Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Compute expectation value #4484

Merged
merged 48 commits into from
Jun 17, 2024

Conversation

ludmilaasb
Copy link
Contributor

@ludmilaasb ludmilaasb commented Aug 16, 2023

Context:

It would be nice to have a function to calculate the expectation values of an operator $A$ given a state vector $\vert\psi\rangle$. This can be also used for computing the fidelity between a mixed and a pure state in simple way, avoiding eigendecomposition problems.

Description of the Change:

Added a overlap calculation between state vectors and density matrices

Benefits:

It is faster then computing $\text{Tr}(A \vert\psi\rangle\langle\psi\vert)$. No need for eigendecomposition, therefore, it is a way to avoid issues regarding differentiation as pointed on issue #4373.

Possible Drawbacks:

It does not work if the user pass as input two state vectors or two matrices. It is tailored to first input as (batched) matrices and the second one as (batched) state vectors.

Related GitHub Issues:
#4373

ludmilaasb and others added 10 commits August 14, 2023 17:51
* Change seed setting in spsa_grad.

* Update changelog.

* Adapt tests. Note that lots of tests still set a global seed!

* Update pennylane/gradients/spsa_gradient.py

Co-authored-by: Christina Lee <[email protected]>

* Update pennylane/gradients/spsa_gradient.py

Co-authored-by: Christina Lee <[email protected]>

* use Shots class in gradients module (PennyLaneAI#4152)

* linting

* add num_copies property to shots

* change gradients to use new Shots class

* fix missing update in vjp

* fix stacking and single-shots in shot_adaptive

* remove unneeded cast to tuple

* type-hints and touch-ups

* code review feedback

* changelog

---------

Co-authored-by: Romain Moyard <[email protected]>

* Qutrit Rotations PennyLaneAI#2 (TRY) (PennyLaneAI#2846)

* Adding tests for tensor observables

* Added tests for tensor sample

* Updated tests

* Apply suggestions from code review

* Partition device apply ops test case.

* Run black

* Fix pylint

* Update pennylane/devices/default_qutrit.py

* black and pylint

* Update pennylane/devices/default_qutrit.py

Co-authored-by: Olivia Di Matteo <[email protected]>

* Update tests/ops/qutrit/test_qutrit_non_parametric_ops.py

Co-authored-by: Olivia Di Matteo <[email protected]>

* Updated test_default_qutrit.py

* Updated _apply_tadd documentation

* Added eigvals method for TSWAP

* Reverted TSWAP eigval changes

* Update tests/devices/test_default_qutrit.py

Co-authored-by: Olivia Di Matteo <[email protected]>

* Update pennylane/devices/default_qutrit.py

Co-authored-by: Jay Soni <[email protected]>

* Added TSWAP eigvals

* Updated changelog-dev.md to include GellMannObs

* Removed empty file

* Added linting comments

* Updated tests to use gate_data

* Updated test parameter names to be more accurate

* Remove unused file

* Updated GellMannObs doc-string

* Update changelog-dev.md

* Update tests/devices/test_default_qutrit.py

Co-authored-by: Olivia Di Matteo <[email protected]>

* Update tests/devices/test_default_qutrit.py

Co-authored-by: Olivia Di Matteo <[email protected]>

* Update tests/devices/test_default_qutrit.py

Co-authored-by: Olivia Di Matteo <[email protected]>

* Update pennylane/ops/qutrit/observables.py

Co-authored-by: Olivia Di Matteo <[email protected]>

* Added changes to GellMann to address PR comments

* Updated test

* Reformatting

* Trying out changes to Gell-Mann docstring

* Updated Changelog

* Update pennylane/ops/qutrit/observables.py

Co-authored-by: Olivia Di Matteo <[email protected]>

* Testing LaTeX align

* Added non-diag tests

* Added diag, complex case for tensor sample

* Added example to doc string

* Fixed label test

* Update pennylane/ops/qutrit/observables.py

Co-authored-by: Olivia Di Matteo <[email protected]>

* Update pennylane/ops/qutrit/observables.py

Co-authored-by: Olivia Di Matteo <[email protected]>

* Update tests/devices/test_default_qutrit.py

Co-authored-by: Olivia Di Matteo <[email protected]>

* Update tests/devices/test_default_qutrit.py

Co-authored-by: Olivia Di Matteo <[email protected]>

* Added tests for controlled qutrit unitary

* Fix broadcasting, finish tests for CQutritUnitary

* Added TRX and created skeleton files

* Adding tests for TRX

* Fixed broadcasting issue in controlled qutrit unitary

* Fixed broadcasting issue with ControlledQutritUnitary

* Fixed broadcasting issue in TRX

* Updated TRX documentation

* Added tests

* Added tests for TRX

* Removed unused imports

* Removed unused imports, linting changes

* Added TRX parameter frequencies

* Updated matrix dtype for TRX generator

* Added test for param frequencies

* Added param-shift capability for qutrit devices

* Updated changelog

* Update changelog

* Added change for TRX generator

* Updated utils.py to support higher dimensions

* Added tests for updated utils.sparse_hamiltonian

* Added Identity as supported obs

* Updated TRX docstring

* Update tests/ops/qutrit/test_qutrit_non_parametric_ops.py

Co-authored-by: Jay Soni <[email protected]>

* Update pennylane/ops/qutrit/observables.py

Co-authored-by: Jay Soni <[email protected]>

* Update pennylane/ops/qutrit/observables.py

Co-authored-by: Jay Soni <[email protected]>

* Added ControlledQutritUnitary

* Update changelog-dev.md

* Removed empty files

* Update tests/ops/qutrit/test_qutrit_matrix_ops.py

Co-authored-by: Olivia Di Matteo <[email protected]>

* Update tests/ops/qutrit/test_qutrit_matrix_ops.py

Co-authored-by: Olivia Di Matteo <[email protected]>

* Update tests/ops/qutrit/test_qutrit_matrix_ops.py

Co-authored-by: Olivia Di Matteo <[email protected]>

* Update tests/ops/qutrit/test_qutrit_matrix_ops.py

Co-authored-by: Olivia Di Matteo <[email protected]>

* Updated to address PR

* Fixed uncommented lines in test suite

* Added complex values to state

* Updated test_mixed_polarity_controls

* Fixed QutritUnitary._controlled

* Updated test_controlled for matrix ops

* Updated ControlledQutritUnitary._controlled

* Reformatting

* Update pennylane/ops/qutrit/matrix_ops.py

Co-authored-by: Olivia Di Matteo <[email protected]>

* Updated ControlledQutritUnitary and tests

* Addressing PR review

* Updated sparse_hamiltonian, fixed TRX docstring

* Addressing PR review

* Refactoring

* Fixed changelog

* Update pennylane/devices/default_qutrit.py

Co-authored-by: Olivia Di Matteo <[email protected]>

* Update pennylane/ops/qutrit/parametric_ops.py

Co-authored-by: Olivia Di Matteo <[email protected]>

* Update pennylane/ops/qutrit/parametric_ops.py

Co-authored-by: Olivia Di Matteo <[email protected]>

* Update pennylane/ops/qutrit/parametric_ops.py

Co-authored-by: Olivia Di Matteo <[email protected]>

* Update pennylane/ops/qutrit/parametric_ops.py

Co-authored-by: Olivia Di Matteo <[email protected]>

* Update tests/ops/qutrit/test_qutrit_parametric_ops.py

Co-authored-by: Olivia Di Matteo <[email protected]>

* Update tests/ops/qutrit/test_qutrit_parametric_ops.py

Co-authored-by: Olivia Di Matteo <[email protected]>

* Update tests/ops/qutrit/test_qutrit_parametric_ops.py

Co-authored-by: Olivia Di Matteo <[email protected]>

* Update tests/ops/qutrit/test_qutrit_parametric_ops.py

Co-authored-by: Olivia Di Matteo <[email protected]>

* Update tests/test_qnode.py

Co-authored-by: Olivia Di Matteo <[email protected]>

* Reverted changes to sparse_hamiltonian

* Fixed sparse_hamiltonian test

* Updated changelog

* Updated TRX documentation

* Fixed generator

* Adding levels to sparse_hamiltonian

* Updated test sparse hamiltonian

* Fixed sparse hamiltonian test

* Fixed constant level kwarg

* Updated changelog, added test coverage

* Fixed coverage

* Updated test suite

* Updated files to address PR review

* Updated tests to include subspace error tests

* Added TRX tests for parameter shift

* Update doc/releases/changelog-dev.md

Co-authored-by: Olivia Di Matteo <[email protected]>

* Update pennylane/utils.py

Co-authored-by: Olivia Di Matteo <[email protected]>

* Update utils.py to remove trailing whitespace

* Updated to address PR review

* Fixed class/object confusion bug

* Testing changes to adjust lines changed in PR

* Fixing changes

* Fixing changes

* Resetting problem files

* Fixing changes

* updated TRX docs

* Fixed TRX docs

* Updated TRX docs

* Fixed PR too many lines changed issue

* Updated subspace error tests

* Tweaked THadamard docs to fix rendering

* Test dos2unix

* Fixed subspace testing

* Merge changes

* Started adding tests for grad

* Updated tests to parametrize diff-method

* Linted tests

* Fiex tests using in-place inversion

* Added diff tests

* Update pennylane/ops/qutrit/parametric_ops.py

Co-authored-by: Olivia Di Matteo <[email protected]>

* Update tests/ops/qutrit/test_qutrit_parametric_ops.py

Co-authored-by: Olivia Di Matteo <[email protected]>

* Update tests/ops/qutrit/test_qutrit_parametric_ops.py

Co-authored-by: Olivia Di Matteo <[email protected]>

* Update tests/ops/qutrit/test_qutrit_parametric_ops.py

Co-authored-by: Olivia Di Matteo <[email protected]>

* Update tests/ops/qutrit/test_qutrit_parametric_ops.py

Co-authored-by: Olivia Di Matteo <[email protected]>

* Update tests/ops/qutrit/test_qutrit_parametric_ops.py

Co-authored-by: Olivia Di Matteo <[email protected]>

* Update tests/ops/qutrit/test_qutrit_parametric_ops.py

Co-authored-by: Olivia Di Matteo <[email protected]>

* Update tests/ops/qutrit/test_qutrit_parametric_ops.py

Co-authored-by: Olivia Di Matteo <[email protected]>

* Fixed formatting

* Update pennylane/utils.py

Co-authored-by: Olivia Di Matteo <[email protected]>

* Updated TRY and tests

* Updated utils.py

* Fixed TRX generator

* Updated generator TRY

* Updated subspace validation for TRY

* Updated subspace validation

* Update pennylane/ops/qutrit/parametric_ops.py

Co-authored-by: Christina Lee <[email protected]>

* Update pennylane/ops/qutrit/parametric_ops.py

Co-authored-by: Matthew Silverman <[email protected]>

* Update pennylane/ops/qutrit/parametric_ops.py

Co-authored-by: Matthew Silverman <[email protected]>

* Reverted `validate_subspace` changes

* Updated test

* Added parameter shift test

* Fixed test

* Update doc/releases/changelog-dev.md

* Update changelog

* Updated grad tests

* Apply suggestions from code review

Co-authored-by: Olivia Di Matteo <[email protected]>

* Updated subspace docstring

---------

Co-authored-by: Olivia Di Matteo <[email protected]>
Co-authored-by: Olivia Di Matteo <[email protected]>
Co-authored-by: Jay Soni <[email protected]>
Co-authored-by: Christina Lee <[email protected]>
Co-authored-by: Matthew Silverman <[email protected]>

* jax integration for for DefaultQubit2 (PennyLaneAI#4137)

* copy-paste autograd test file

* port to jax in tests; update shots in jax interface

* add argnums when needed; skip tests that do not work with jax

* use pytest imports to skip

* pylint tests

* changelog

* take shots change from Christina's PR

* Update doc/releases/changelog-dev.md

Co-authored-by: Mudit Pandey <[email protected]>

* copy changes to autograd as well

* rename to indicate bool; slight autograd fixup

---------

Co-authored-by: Mudit Pandey <[email protected]>

* Treat identities as equivalent in `pauli.are_identical_pauli_words` (PennyLaneAI#4161)

* fix hamiltonian grouping indices bug

* Update doc/releases/changelog-dev.md

* Take wire ordering in the `wires` argument to `qml.density_matrix` into account (PennyLaneAI#4072)

* include wire ordering, test for that, raise error for broadcasting, test for that

* reduce

* changelog

* add test for qinfo transform

* more tests for math module

* lint math tests

* lint

* black

* introduce, use and test input_is_dm kwarg to reduced_dm

* tmp

* reverting

* seed fix

---------

Co-authored-by: Edward Jiang <[email protected]>

* CY inherits from ControlledOp (PennyLaneAI#4116)

`qml.CY` has been moved from `qml.ops.qubit.non_parametric_ops` to `qml.ops.op_math.controlled_ops`
  and now inherits from `qml.ops.op_math.ControlledOp`.
---------
Co-authored-by: Matthew Silverman <[email protected]>
Co-authored-by: Christina Lee <[email protected]>

* Empty hamiltonians are compatible with `qml.pauli_sentence()` (PennyLaneAI#4171)

* fix ps rep for empty hamiltonian

* changelog

* Update doc/releases/changelog-dev.md

Co-authored-by: Utkarsh <[email protected]>

---------

Co-authored-by: Utkarsh <[email protected]>

* Update tests/interfaces/test_torch_qnode.py

Co-authored-by: Christina Lee <[email protected]>

* Python 3.8 compatibility and increase num_directions, since spsa_grad, with num_directions=1, fails sometimes, depending on the seed.

* Fix failing tests

* Fix docs.

* Fix unsupported NoneType import

* Undo irrelevant change.

* Fix failing tests. Still not reliable.

* Fix tolerance issue with SPSA second derivative.

* Increase tolerance. This test has also been failing spontaneously on the master branch 3468885

* Switch to sampler_rng kwarg and fix tolerance issues.

* More migration to sampler_rng

* Migrate more tests to sampler_rng

* Migrate legacy tests to sampler_rng

* black

* Deprecated the sampler_seed argument

* black

* Increase tolerance for test_hamiltonian_expansion_finite_shots tests.

* Fix tol

* Pin autoray for CI

* Set num_directions=20 in all hamiltonian_expansion_finite_shots tests.

* Make black and pylint happy

* Set device seed for DQ2 tests.

* Add tests for new return type system.

* Fix bug

* Adapt dq2 tests for spsa

* Remove qml.disable_return()

* Change DQ2 tests to new seed setting system.

* Fix bug

* Fix failing tests. TF tests pass locally. Not sure what the problem is.

* Fix missing grad_kwarg

* black

* Increase tol

* Increase num_directions

* Apply suggestions from code review

Co-authored-by: David Wierichs <[email protected]>

* Update pennylane/gradients/spsa_gradient.py

Co-authored-by: David Wierichs <[email protected]>

* Copy TestRademacherSampler into new tests

* Make docs more precise and add tests for rng kwarg of samplers.

* black

* black

* Fix error message in _spsa_grad_legacy

* pylint

* Update changelog-dev.md

* black

* Increase num_directions for Hessian test.

---------

Co-authored-by: Christina Lee <[email protected]>
Co-authored-by: Matthew Silverman <[email protected]>
Co-authored-by: Romain Moyard <[email protected]>
Co-authored-by: Mudit Pandey <[email protected]>
Co-authored-by: Olivia Di Matteo <[email protected]>
Co-authored-by: Olivia Di Matteo <[email protected]>
Co-authored-by: Jay Soni <[email protected]>
Co-authored-by: Christina Lee <[email protected]>
Co-authored-by: Matthew Silverman <[email protected]>
Co-authored-by: David Wierichs <[email protected]>
Co-authored-by: Edward Jiang <[email protected]>
Co-authored-by: Utkarsh <[email protected]>
Copy link
Contributor

@dwierichs dwierichs left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for this addition @ludmilaasb 🎉 💯

I left a number of comments regarding minor nitpicky stuff, a good part coming from porting functionality/docs over from other functions. Sorry if you were about to change those anyways, still!

One open question to me personally is whether we want to restrict to Hermitian matrices or not, and--connected to that--what output data type we want (real or complex).
This topic comes up repeatedly in the context of QNode expectation values of Hamiltonians, as far as I know, so it might deserve some discussion.
Once this is decided, I would suggest to add tests that

  • test the return dtype
  • test for some "more random" inputs and outputs. Maybe just adding a random matrix and state vector test would be a nice addition :)

pennylane/math/quantum.py Outdated Show resolved Hide resolved
pennylane/math/quantum.py Outdated Show resolved Hide resolved
pennylane/math/quantum.py Outdated Show resolved Hide resolved
pennylane/math/quantum.py Outdated Show resolved Hide resolved
pennylane/math/quantum.py Outdated Show resolved Hide resolved
tests/math/test_expectation_value_math.py Outdated Show resolved Hide resolved
tests/math/test_expectation_value_math.py Outdated Show resolved Hide resolved
tests/math/test_expectation_value_math.py Outdated Show resolved Hide resolved
tests/math/test_expectation_value_math.py Outdated Show resolved Hide resolved
tests/math/test_expectation_value_math.py Outdated Show resolved Hide resolved
@trbromley
Copy link
Contributor

One open question to me personally is whether we want to restrict to Hermitian matrices or not, and--connected to that--what output data type we want (real or complex).
This topic comes up repeatedly in the context of QNode expectation values of Hamiltonians, as far as I know, so it might deserve some discussion.

Could we not have the Hermitian restriction, but also have a qml.math.real_if_close that wraps the return?

@dwierichs
Copy link
Contributor

Could we not have the Hermitian restriction, but also have a qml.math.real_if_close that wraps the return?

data types have been causing quite a bit of headaches in the past, so having them be changed automatically scares me personally a little bit. Also, we get value dependent type changes that might not go well with JITting?

ludmilaasb and others added 2 commits August 17, 2023 11:52
@ludmilaasb
Copy link
Contributor Author

Thank you for the careful review! 😄

So, about the Hermitian matrices, it depends on what kind of operators you would like to work with. For instance, if the goal is exclusive "physically measurable quantities", i.e., observables and POVMs, then yes, they need to be Hermitian.

On the other side, if you consider things like annihilation and creation operators, they are non-hermitian. But I don't know if you guys want to go in this direction. 🤔

@dwierichs
Copy link
Contributor

On the other side, if you consider things like annihilation and creation operators, they are non-hermitian. But I don't know if you guys want to go in this direction.

Good point. I can't judge what's needed here... We could also have "a physicist's expectation" as default, expecting a Hermitian and returning a real value. Then there could be a keyword argument is_hermitian that can be switched off to allow non-Hermitian obs.

@codecov
Copy link

codecov bot commented Aug 23, 2023

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 99.67%. Comparing base (94adc17) to head (3d2210c).
Report is 246 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff             @@
##           master    #4484      +/-   ##
==========================================
- Coverage   99.68%   99.67%   -0.01%     
==========================================
  Files         421      421              
  Lines       40435    40161     -274     
==========================================
- Hits        40306    40031     -275     
- Misses        129      130       +1     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

Copy link
Contributor

@lillian542 lillian542 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looking good, thanks @ludmilaasb! 🚀 I left a couple of comments about tests and examples :)

pennylane/math/quantum.py Outdated Show resolved Hide resolved
pennylane/math/quantum.py Outdated Show resolved Hide resolved
tests/math/test_expectation_value.py Show resolved Hide resolved
@trbromley
Copy link
Contributor

[sc-43438]

@ludmilaasb ludmilaasb marked this pull request as ready for review January 29, 2024 13:51
@Alex-Preciado Alex-Preciado removed request for lillian542 and a team February 16, 2024 19:51
@Alex-Preciado Alex-Preciado removed the request for review from timmysilv March 6, 2024 22:56
@astralcai astralcai added this to the v0.37 milestone Jun 17, 2024
Copy link
Contributor

@mudit2812 mudit2812 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just one comment, otherwise I'm ready to approve.

pennylane/math/quantum.py Outdated Show resolved Hide resolved
Copy link
Contributor

@PietropaoloFrisoni PietropaoloFrisoni left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is great, Thanks @ludmilaasb!

Just a few comments about documentation from me

doc/releases/changelog-dev.md Outdated Show resolved Hide resolved
pennylane/math/quantum.py Outdated Show resolved Hide resolved
tests/math/test_expectation_value.py Outdated Show resolved Hide resolved
pennylane/math/quantum.py Outdated Show resolved Hide resolved
@astralcai astralcai merged commit fb06ce8 into PennyLaneAI:master Jun 17, 2024
40 checks passed
@trbromley
Copy link
Contributor

Thanks everyone for getting this merged!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
WIP 🚧 Work-in-progress
Projects
None yet
Development

Successfully merging this pull request may close these issues.