Skip to content

Commit 044ffe8

Browse files
mudit2812AmintorDuskogithub-actions[bot]vincentmralbi3ro
authored
Add support for LinearCombination (#649)
* update jax config import * Auto update version * trigger CI * update state vector class and tests for improved coverage * update measurement class tests * update dev version * add cpp binary available variable * remove device definition * update dev version * Auto update version * reduce dependency on DefaultQubit for tests * update LightningQubit2 * clean test_measurements_class.py * isort+black * review suggestion * fix docs * Add qml.var support. * Add probs support. * increase tolerance * Auto update version * isort * Add double-obs tests. * Pin pytest version (#624) * update dev version * update changelog * pin pytest version in requirement files * add a requirements file for tests against Pennylane master * update wheels' workflows * Version Bump (#626) * post release version bump * trigger CI --------- Co-authored-by: AmintorDusko <[email protected]> Co-authored-by: AmintorDusko <[email protected]> * increase tolerance * Introduce isort. (#623) * Introduce isort. * Auto update version * Update changelog * Auto update version * Update changelog. * trigger ci --------- Co-authored-by: Dev version update bot <github-actions[bot]@users.noreply.github.com> * Auto update version * isort * Add qml.var support. * Add probs support. * Add measurement tests with wires. * review suggestions * remove unused imports * Introduce _new_API and fix/skip few tests. * Fix few more tests. * Skip shots, adjoint, vjp with new API. * remove diagonalization gate application from state vector * pytest.skip tests * Auto update version * Fix format * Fix no-bin interface. * WIP * Initial shots support + fix test_measurement tests. * update * adding tests from add-simulate branch * merge conflicts * create state vector on initialization * remove import of modifier from lightning * Update pennylane_lightning/lightning_qubit/lightning_qubit2.py * minor test updates * register with setup.py, state vector fixes * add LightningQubit2 to init and format * add cpp binary available variable * reduce dependency on DefaultQubit for tests * update LightningQubit2 * Fixing rebase artifacts * Add fewLQ2 tests. * remove adjoint diff support from supports derivatives * Remove print from test_apply * Add expval/var tests. * Remove duplicate class data. * Include LQ2 in linux ests. * Add _group_measurements support. * --cov-append * Add mcmc capability + tests. * Auto update version * update dev version * add LightningAdjointJacobian class * add unit tests for the LightningAdjointJacobian class * format * add changelog for PR #613 * [skip ci] Added skeleton file for LQ2 unit tests * update changelog * update adjoint Jacobian * Auto update version * codefactor * Add shots tests and fix bugs in LQ, LQ2. * Lightning qubit2 upgrade api (#628) * update * adding tests from add-simulate branch * merge conflicts * create state vector on initialization * remove import of modifier from lightning * Update pennylane_lightning/lightning_qubit/lightning_qubit2.py * minor test updates * register with setup.py, state vector fixes * add LightningQubit2 to init and format * add cpp binary available variable * Auto update version * reduce dependency on DefaultQubit for tests * update LightningQubit2 * Introduce _new_API and fix/skip few tests. * Fix few more tests. * Skip shots, adjoint, vjp with new API. * Fix no-bin interface. * Remove duplicate class data. * Include LQ2 in linux ests. * --cov-append --------- Co-authored-by: albi3ro <[email protected]> Co-authored-by: AmintorDusko <[email protected]> Co-authored-by: Dev version update bot <github-actions[bot]@users.noreply.github.com> * fix processing_fn_expval * make a proper new_tape * Added init tests; Added skeleton tests for helpers * Fix more bug with shots. * trigger CI * Change pennylane branch for CI. * Update .github/CHANGELOG.md Co-authored-by: Vincent Michaud-Rioux <[email protected]> * Update pennylane_lightning/lightning_qubit/_adjoint_jacobian.py Co-authored-by: Vincent Michaud-Rioux <[email protected]> * Update pennylane_lightning/lightning_qubit/_adjoint_jacobian.py Co-authored-by: Vincent Michaud-Rioux <[email protected]> * Add probs support. * Add double-obs tests. * Add qml.var support. * Add probs support. * Add measurement tests with wires. * pytest.skip tests * Fix format * update * adding tests from add-simulate branch * merge conflicts * create state vector on initialization * remove import of modifier from lightning * Update pennylane_lightning/lightning_qubit/lightning_qubit2.py * minor test updates * register with setup.py, state vector fixes * add LightningQubit2 to init and format * add cpp binary available variable * reduce dependency on DefaultQubit for tests * update LightningQubit2 * Fixing rebase artifacts * remove adjoint diff support from supports derivatives * [skip ci] Added skeleton file for LQ2 unit tests * Lightning qubit2 upgrade api (#628) * update * adding tests from add-simulate branch * merge conflicts * create state vector on initialization * remove import of modifier from lightning * Update pennylane_lightning/lightning_qubit/lightning_qubit2.py * minor test updates * register with setup.py, state vector fixes * add LightningQubit2 to init and format * add cpp binary available variable * Auto update version * reduce dependency on DefaultQubit for tests * update LightningQubit2 * Introduce _new_API and fix/skip few tests. * Fix few more tests. * Skip shots, adjoint, vjp with new API. * Fix no-bin interface. * Remove duplicate class data. * Include LQ2 in linux ests. * --cov-append --------- Co-authored-by: albi3ro <[email protected]> Co-authored-by: AmintorDusko <[email protected]> Co-authored-by: Dev version update bot <github-actions[bot]@users.noreply.github.com> * Added init tests; Added skeleton tests for helpers * Resolving rebase artifacts * Refactor shots test. * Added tests; integrated jacobian * Update pennylane_lightning/lightning_qubit/lightning_qubit2.py Co-authored-by: Amintor Dusko <[email protected]> * Auto update version * Small update to simulate_and_jacobian * Auto update version * Rerun isort. * Uncomment integration tests. * Reformat * Delete symlink * Fix pylint. * Run linux tests in parallel (when possible). * Run double obs tests with shots. * Revert linux tests * Fix bg in diag_gates. * Call isort/black with python -m * update dev version * Add docstrings, rm C_DTYPE. * Auto update version * comment isort check * trigger ci * Update tests/test_expval.py Co-authored-by: Amintor Dusko <[email protected]> * Init mcmc params to None in measurements. * Reformat with python3.11 * Reformat black * Auto update version * update QuantumScriptSerializer * remove LightningQubit2 from init * update setup.py * remove lightning.qubit2 from tests configuration * remove extra tests for lightning.qubit2 * migrate lightning.qubit2 to lightning.qubit on tests * make lightning.qubit2 the new lightning.qubit * add device name (necessary for pl-device-test) * Add _measure_hamiltonian_with_samples _measure_sum_with_samples * fix tests without binary * check for jac size before reshaping * remove obsolete tests * organize tests * fix test for Windows wheels * Adding LC to supported obs list for all devices * Updating serialization * Trying out test changes * Updated PL dependency * Running isort * Update CPP layer for observable accessible functions * Auto update version * Allow output from TP CPP layer * Fixed serialize tests * Added legacy fixture to failing tests * Updated requirements with debug branch * Trigger CI * Auto update version * Trigger CI * Trigger CI * Added recursive logic to find projectors * format * mark tests to be dual tested and some small fixes * example of test failing * remove print and move ham to tape scope * Fixed expval test; isort * Auto update version * isort * Updated device tests; changelog entry * Update mpitests/test_apply.py * Auto update version * Fix terms in ham serialization. * Use requirements-dev.txt to install black/isort. * Mark test_single_return_value flaky. Add comment on split_obs. * Apply suggestions from code review Co-authored-by: Ali Asadi <[email protected]> Co-authored-by: Vincent Michaud-Rioux <[email protected]> * Auto update version * Auto update version * Trigger CI * Fix format * Updated PL branch in reqs-dev * Update requirements * Added fix for prod with overlapping wires * Formatting * Point requirements to PL master * Pinning cmake * Pinned cmake in workflows * Pinned cmake in more workflows * Trigger CI * Apply suggestions from code review Co-authored-by: Ali Asadi <[email protected]> * [skip ci] Apply suggestions from code review Co-authored-by: Ali Asadi <[email protected]> * Trigger CI * Fix indent. * Fix workflow files indentation * Comment triggers. (#662) * Comment triggers. * pytest -x * trigger ci * Do not skip comp for LQ. * Revert triggers * Revert changes --------- Co-authored-by: AmintorDusko <[email protected]> Co-authored-by: Amintor Dusko <[email protected]> Co-authored-by: Dev version update bot <github-actions[bot]@users.noreply.github.com> Co-authored-by: Vincent Michaud-Rioux <[email protected]> Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: AmintorDusko <[email protected]> Co-authored-by: Vincent Michaud-Rioux <[email protected]> Co-authored-by: albi3ro <[email protected]> Co-authored-by: Lee J. O'Riordan <[email protected]> Co-authored-by: Ali Asadi <[email protected]> Co-authored-by: Lee James O'Riordan <[email protected]>
1 parent 7e77c5d commit 044ffe8

24 files changed

+413
-199
lines changed

.github/CHANGELOG.md

+3
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,9 @@
2424
[(#607)](https://github.com/PennyLaneAI/pennylane-lightning/pull/607)
2525
[(#628)](https://github.com/PennyLaneAI/pennylane-lightning/pull/628)
2626

27+
* Add support for using new operator arithmetic as the default.
28+
[(#649)](https://github.com/PennyLaneAI/pennylane-lightning/pull/649)
29+
2730
### Breaking changes
2831

2932
* Migrate `lightning.qubit` to the new device API.

.github/workflows/tests_gpu_cuda.yml

+6-2
Original file line numberDiff line numberDiff line change
@@ -119,7 +119,9 @@ jobs:
119119
120120
- name: Install required packages
121121
run: |
122-
python -m pip install ninja cmake custatevec-cu${{ matrix.cuda_version }}
122+
# Omitting the installation of cmake v3.29.0 due to
123+
# https://github.com/scikit-build/cmake-python-distributions/pull/474
124+
python -m pip install ninja "cmake!=3.29.0" custatevec-cu${{ matrix.cuda_version }}
123125
sudo apt-get -y -q install liblapack-dev
124126
125127
- name: Build and run unit tests
@@ -241,7 +243,9 @@ jobs:
241243
run: |
242244
cd main
243245
python -m pip install -r requirements-dev.txt
244-
python -m pip install cmake custatevec-cu${{ matrix.cuda_version }} openfermionpyscf
246+
# Omitting the installation of cmake v3.29.0 due to
247+
# https://github.com/scikit-build/cmake-python-distributions/pull/474
248+
python -m pip install "cmake!=3.29.0" custatevec-cu${{ matrix.cuda_version }} openfermionpyscf
245249
246250
- name: Checkout PennyLane for release build
247251
if: inputs.pennylane-version == 'release'

.github/workflows/tests_linux_x86_mpi_gpu.yml

+4-2
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,9 @@ jobs:
9494
- name: Install required packages
9595
run: |
9696
python -m pip install -r requirements-dev.txt
97-
python -m pip install cmake custatevec-cu12
97+
# Omitting the installation of cmake v3.29.0 due to
98+
# https://github.com/scikit-build/cmake-python-distributions/pull/474
99+
python -m pip install "cmake!=3.29.0" custatevec-cu12
98100
sudo apt-get -y -q install liblapack-dev
99101
100102
- name: Validate GPU version and installed compiler and modules
@@ -240,7 +242,7 @@ jobs:
240242
source /etc/profile.d/modules.sh && module use /opt/modules/ && module load ${{ matrix.mpilib }}/cuda-${{ matrix.cuda_version_maj }}.${{ matrix.cuda_version_min }}
241243
python -m pip install -r requirements-dev.txt
242244
python -m pip install custatevec-cu${{ matrix.cuda_version_maj }} mpi4py openfermionpyscf
243-
SKIP_COMPILATION=True PL_BACKEND=lightning_qubit python -m pip install -e . -vv
245+
PL_BACKEND=lightning_qubit python -m pip install -e . -vv
244246
245247
- name: Checkout PennyLane for release build
246248
if: inputs.pennylane-version == 'release'

.github/workflows/wheel_macos_x86_64.yml

+3-1
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,9 @@ jobs:
6868
run: |
6969
mkdir -p ${{ github.workspace}}/Kokkos_install/${{ matrix.exec_model }}
7070
cd kokkos
71-
python -m pip install cmake ninja
71+
# Omitting the installation of cmake v3.29.0 due to
72+
# https://github.com/scikit-build/cmake-python-distributions/pull/474
73+
python -m pip install "cmake!=3.29.0" ninja
7274
7375
cmake -BBuild . -DCMAKE_INSTALL_PREFIX=${{ github.workspace}}/Kokkos_install/${{ matrix.exec_model }} \
7476
-DKokkos_ENABLE_COMPLEX_ALIGN=OFF \

.github/workflows/wheel_noarch.yml

+3-1
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,9 @@ jobs:
4444
4545
- name: Install CMake and ninja
4646
run: |
47-
python -m pip install --upgrade cmake ninja
47+
# Omitting the installation of cmake v3.29.0 due to
48+
# https://github.com/scikit-build/cmake-python-distributions/pull/474
49+
python -m pip install --upgrade "cmake!=3.29.0" ninja
4850
4951
- name: Build wheels
5052
if: ${{ matrix.pl_backend == 'lightning_qubit'}}

.github/workflows/wheel_win_x86_64.yml

+3-1
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,9 @@ jobs:
6464
- name: Install dependencies
6565
if: steps.kokkos-cache.outputs.cache-hit != 'true'
6666
run: |
67-
python -m pip install cmake build
67+
# Omitting the installation of cmake v3.29.0 due to
68+
# https://github.com/scikit-build/cmake-python-distributions/pull/474
69+
python -m pip install "cmake!=3.29.0" build
6870
6971
- name: Build Kokkos core library
7072
if: steps.kokkos-cache.outputs.cache-hit != 'true'

mpitests/test_apply.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -450,7 +450,7 @@ def test_dev_reset(self, tol, dev_mpi):
450450
comm.Scatter(state_vector, local_state_vector, root=0)
451451
dev_cpu = qml.device("lightning.qubit", wires=num_wires, c_dtype=c_dtype)
452452

453-
dev_cpu.reset()
453+
dev_cpu._statevector.reset_state()
454454

455455
def circuit():
456456
qml.PauliX(wires=[0])
@@ -556,7 +556,7 @@ def circuit():
556556

557557
cpu_qnode = qml.QNode(circuit, dev_cpu)
558558
expected_output_cpu = cpu_qnode()
559-
comm.Bcast(expected_output_cpu, root=0)
559+
comm.Bcast(np.array(expected_output_cpu), root=0)
560560

561561
mpi_qnode = qml.QNode(circuit, dev_mpi)
562562
expected_output_mpi = mpi_qnode()

pennylane_lightning/core/_serialize.py

+27-12
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
r"""
1515
Helper functions for serializing quantum tapes.
1616
"""
17-
from typing import List, Tuple
17+
from typing import List, Sequence, Tuple
1818

1919
import numpy as np
2020
from pennylane import (
@@ -34,6 +34,7 @@
3434
)
3535
from pennylane.math import unwrap
3636
from pennylane.operation import Tensor
37+
from pennylane.ops import Prod, SProd, Sum
3738
from pennylane.tape import QuantumTape
3839

3940
pauli_name_map = {
@@ -183,19 +184,22 @@ def _named_obs(self, observable, wires_map: dict = None):
183184

184185
def _hermitian_ob(self, observable, wires_map: dict = None):
185186
"""Serializes a Hermitian observable"""
186-
assert not isinstance(observable, Tensor)
187187

188188
wires = [wires_map[w] for w in observable.wires] if wires_map else observable.wires.tolist()
189189
return self.hermitian_obs(matrix(observable).ravel().astype(self.ctype), wires)
190190

191191
def _tensor_ob(self, observable, wires_map: dict = None):
192192
"""Serialize a tensor observable"""
193-
assert isinstance(observable, Tensor)
194-
return self.tensor_obs([self._ob(obs, wires_map) for obs in observable.obs])
193+
obs = observable.obs if isinstance(observable, Tensor) else observable.operands
194+
return self.tensor_obs([self._ob(o, wires_map) for o in obs])
195195

196196
def _hamiltonian(self, observable, wires_map: dict = None):
197-
coeffs = np.array(unwrap(observable.coeffs)).astype(self.rtype)
198-
terms = [self._ob(t, wires_map) for t in observable.ops]
197+
coeffs, ops = observable.terms()
198+
coeffs = np.array(unwrap(coeffs)).astype(self.rtype)
199+
terms = [self._ob(t, wires_map) for t in ops]
200+
# TODO: This is in case `_hamiltonian` is called recursively which would cause a list
201+
# to be passed where `_ob` expects an observable.
202+
terms = [t[0] if isinstance(t, Sequence) and len(t) == 1 else t for t in terms]
199203

200204
if self.split_obs:
201205
return [self.hamiltonian_obs([c], [t]) for (c, t) in zip(coeffs, terms)]
@@ -254,23 +258,33 @@ def _pauli_sentence(self, observable, wires_map: dict = None):
254258
terms = [self._pauli_word(pw, wires_map) for pw in pwords]
255259
coeffs = np.array(coeffs).astype(self.rtype)
256260

261+
# TODO: Add this
262+
# if len(terms) == 1 and coeffs[0] == 1.0:
263+
# return terms[0]
264+
257265
if self.split_obs:
258266
return [self.hamiltonian_obs([c], [t]) for (c, t) in zip(coeffs, terms)]
259267
return self.hamiltonian_obs(coeffs, terms)
260268

261-
# pylint: disable=protected-access
269+
# pylint: disable=protected-access, too-many-return-statements
262270
def _ob(self, observable, wires_map: dict = None):
263271
"""Serialize a :class:`pennylane.operation.Observable` into an Observable."""
264-
if isinstance(observable, Tensor):
272+
if isinstance(observable, (Prod, Sum, SProd)) and observable.pauli_rep is not None:
273+
return self._pauli_sentence(observable.pauli_rep, wires_map)
274+
if isinstance(observable, Tensor) or (
275+
isinstance(observable, Prod) and not observable.has_overlapping_wires
276+
):
265277
return self._tensor_ob(observable, wires_map)
266-
if observable.name == "Hamiltonian":
278+
if observable.name in ("Hamiltonian", "LinearCombination"):
267279
return self._hamiltonian(observable, wires_map)
268280
if observable.name == "SparseHamiltonian":
269281
return self._sparse_hamiltonian(observable, wires_map)
270282
if isinstance(observable, (PauliX, PauliY, PauliZ, Identity, Hadamard)):
271283
return self._named_obs(observable, wires_map)
272-
if observable._pauli_rep is not None:
273-
return self._pauli_sentence(observable._pauli_rep, wires_map)
284+
if observable.pauli_rep is not None:
285+
return self._pauli_sentence(observable.pauli_rep, wires_map)
286+
# if isinstance(observable, (Prod, Sum)):
287+
# return self._hamiltonian(observable, wires_map)
274288
return self._hermitian_ob(observable, wires_map)
275289

276290
def serialize_observables(self, tape: QuantumTape, wires_map: dict = None) -> List:
@@ -282,7 +296,8 @@ def serialize_observables(self, tape: QuantumTape, wires_map: dict = None) -> Li
282296
283297
Returns:
284298
list(ObsStructC128 or ObsStructC64): A list of observable objects compatible with
285-
the C++ backend
299+
the C++ backend. For unsupported observables, the observable matrix is used
300+
to create a :class:`~pennylane.Hermitian` to be used for serialization.
286301
"""
287302

288303
serialized_obs = []

pennylane_lightning/core/_version.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -16,4 +16,4 @@
1616
Version number (major.minor.patch[-label])
1717
"""
1818

19-
__version__ = "0.36.0-dev18"
19+
__version__ = "0.36.0-dev19"

pennylane_lightning/core/lightning_base.py

+56-4
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,9 @@
2323
import pennylane as qml
2424
from pennylane import BasisState, QubitDevice, StatePrep
2525
from pennylane.devices import DefaultQubitLegacy
26-
from pennylane.measurements import MeasurementProcess
27-
from pennylane.operation import Operation
26+
from pennylane.measurements import Expectation, MeasurementProcess, State
27+
from pennylane.operation import Operation, Tensor
28+
from pennylane.ops import Prod, Projector, SProd, Sum
2829
from pennylane.wires import Wires
2930

3031
from ._serialize import QuantumScriptSerializer
@@ -306,18 +307,69 @@ def _process_jacobian_tape(
306307
"obs_idx_offsets": obs_idx_offsets,
307308
}
308309

310+
@staticmethod
311+
def _assert_adjdiff_no_projectors(observable):
312+
"""Helper function to validate that an observable is not or does not contain
313+
Projectors
314+
315+
Args:
316+
observable (~pennylane.operation.Operator): Observable to check
317+
318+
Raises:
319+
~pennylane.QuantumFunctionError: if a ``Projector`` is found.
320+
"""
321+
if isinstance(observable, Tensor):
322+
if any(isinstance(o, Projector) for o in observable.non_identity_obs):
323+
raise qml.QuantumFunctionError(
324+
"Adjoint differentiation method does not support the Projector observable"
325+
)
326+
327+
elif isinstance(observable, Projector):
328+
raise qml.QuantumFunctionError(
329+
"Adjoint differentiation method does not support the Projector observable"
330+
)
331+
332+
elif isinstance(observable, SProd):
333+
LightningBase._assert_adjdiff_no_projectors(observable.base)
334+
335+
elif isinstance(observable, (Sum, Prod)):
336+
for obs in observable:
337+
LightningBase._assert_adjdiff_no_projectors(obs)
338+
309339
# pylint: disable=unnecessary-pass
310340
@staticmethod
311341
def _check_adjdiff_supported_measurements(measurements: List[MeasurementProcess]):
312-
"""Check whether given list of measurement is supported by adjoint_differentiation.
342+
"""Check whether given list of measurements is supported by adjoint_differentiation.
313343
314344
Args:
315345
measurements (List[MeasurementProcess]): a list of measurement processes to check.
316346
317347
Returns:
318348
Expectation or State: a common return type of measurements.
349+
350+
Raises:
351+
~pennylane.QuantumFunctionError: if a measurement is unsupported with adjoint
352+
differentiation.
319353
"""
320-
pass
354+
if not measurements:
355+
return None
356+
357+
if len(measurements) == 1 and measurements[0].return_type is State:
358+
# return State
359+
raise qml.QuantumFunctionError(
360+
"Adjoint differentiation does not support State measurements."
361+
)
362+
363+
# The return_type of measurement processes must be expectation
364+
if any(m.return_type is not Expectation for m in measurements):
365+
raise qml.QuantumFunctionError(
366+
"Adjoint differentiation method does not support expectation return type "
367+
"mixed with other return types"
368+
)
369+
370+
for measurement in measurements:
371+
LightningBase._assert_adjdiff_no_projectors(measurement.obs)
372+
return Expectation
321373

322374
@staticmethod
323375
def _adjoint_jacobian_processing(jac):

pennylane_lightning/core/src/bindings/Bindings.hpp

+8
Original file line numberDiff line numberDiff line change
@@ -350,6 +350,8 @@ void registerBackendAgnosticObservables(py::module_ &m) {
350350
.def("__repr__", &HermitianObs<StateVectorT>::getObsName)
351351
.def("get_wires", &HermitianObs<StateVectorT>::getWires,
352352
"Get wires of observables")
353+
.def("get_matrix", &HermitianObs<StateVectorT>::getMatrix,
354+
"Get matrix representation of Hermitian operator")
353355
.def(
354356
"__eq__",
355357
[](const HermitianObs<StateVectorT> &self,
@@ -373,6 +375,8 @@ void registerBackendAgnosticObservables(py::module_ &m) {
373375
.def("__repr__", &TensorProdObs<StateVectorT>::getObsName)
374376
.def("get_wires", &TensorProdObs<StateVectorT>::getWires,
375377
"Get wires of observables")
378+
.def("get_ops", &TensorProdObs<StateVectorT>::getObs,
379+
"Get operations list")
376380
.def(
377381
"__eq__",
378382
[](const TensorProdObs<StateVectorT> &self,
@@ -401,6 +405,10 @@ void registerBackendAgnosticObservables(py::module_ &m) {
401405
.def("__repr__", &Hamiltonian<StateVectorT>::getObsName)
402406
.def("get_wires", &Hamiltonian<StateVectorT>::getWires,
403407
"Get wires of observables")
408+
.def("get_ops", &Hamiltonian<StateVectorT>::getObs,
409+
"Get operations contained by Hamiltonian")
410+
.def("get_coeffs", &Hamiltonian<StateVectorT>::getCoeffs,
411+
"Get Hamiltonian coefficients")
404412
.def(
405413
"__eq__",
406414
[](const Hamiltonian<StateVectorT> &self,

pennylane_lightning/lightning_gpu/lightning_gpu.py

+3-48
Original file line numberDiff line numberDiff line change
@@ -77,17 +77,8 @@
7777
from typing import List, Union
7878

7979
import pennylane as qml
80-
from pennylane import (
81-
BasisState,
82-
DeviceError,
83-
Projector,
84-
QuantumFunctionError,
85-
Rot,
86-
StatePrep,
87-
math,
88-
)
89-
from pennylane.measurements import Expectation, MeasurementProcess, State
90-
from pennylane.operation import Tensor
80+
from pennylane import BasisState, DeviceError, QuantumFunctionError, Rot, StatePrep, math
81+
from pennylane.measurements import Expectation, State
9182
from pennylane.ops.op_math import Adjoint
9283
from pennylane.wires import Wires
9384

@@ -196,6 +187,7 @@ def _mebibytesToBytes(mebibytes):
196187
"Hadamard",
197188
"SparseHamiltonian",
198189
"Hamiltonian",
190+
"LinearCombination",
199191
"Hermitian",
200192
"Identity",
201193
"Sum",
@@ -583,43 +575,6 @@ def apply(self, operations, rotations=None, **kwargs):
583575

584576
self.apply_lightning(operations)
585577

586-
@staticmethod
587-
def _check_adjdiff_supported_measurements(measurements: List[MeasurementProcess]):
588-
"""Check whether given list of measurement is supported by adjoint_diff.
589-
Args:
590-
measurements (List[MeasurementProcess]): a list of measurement processes to check.
591-
Returns:
592-
Expectation or State: a common return type of measurements.
593-
"""
594-
if not measurements:
595-
return None
596-
597-
if len(measurements) == 1 and measurements[0].return_type is State:
598-
# return State
599-
raise QuantumFunctionError(
600-
"Adjoint differentiation does not support State measurements."
601-
)
602-
603-
# The return_type of measurement processes must be expectation
604-
if any(m.return_type is not Expectation for m in measurements):
605-
raise QuantumFunctionError(
606-
"Adjoint differentiation method does not support expectation return type "
607-
"mixed with other return types"
608-
)
609-
610-
for measurement in measurements:
611-
if isinstance(measurement.obs, Tensor):
612-
if any(isinstance(o, Projector) for o in measurement.obs.non_identity_obs):
613-
raise QuantumFunctionError(
614-
"Adjoint differentiation method does not support the "
615-
"Projector observable"
616-
)
617-
elif isinstance(measurement.obs, Projector):
618-
raise QuantumFunctionError(
619-
"Adjoint differentiation method does not support the Projector observable"
620-
)
621-
return Expectation
622-
623578
@staticmethod
624579
def _check_adjdiff_supported_operations(operations):
625580
"""Check Lightning adjoint differentiation method support for a tape.

0 commit comments

Comments
 (0)