Skip to content

Commit

Permalink
Merge branch 'devel' into visualize
Browse files Browse the repository at this point in the history
  • Loading branch information
kottmanj authored Sep 14, 2023
2 parents 1ac6a5e + 521e3ce commit 054cf21
Show file tree
Hide file tree
Showing 43 changed files with 3,383 additions and 344 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/ci_chemistry_pyscf.yml
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,6 @@ jobs:
python -m pip install 'h5py <= 3.1'
cd tests
ls
pytest test_chemistry.py -m "not dependencies"
pytest test_chemistry.py test_TrotErr.py -m "not dependencies"
pytest test_adapt.py -m "not dependencies"
cd ../
4 changes: 2 additions & 2 deletions .github/workflows/ci_pyquil.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ on:
push:
branches: [ master, devel ]
pull_request:
branches: [ master, devel ]
branches: []

jobs:

Expand All @@ -31,7 +31,7 @@ jobs:
pip install -r requirements.txt
pip install "pyquil<3.0"
pip install -e .
docker pull rigetti/qvm
docker pull rigetti/qvm:edge
docker pull rigetti/quilc
docker run --rm -itd -p 5555:5555 rigetti/quilc -R
docker run --rm -itd -p 5000:5000 rigetti/qvm -S
Expand Down
165 changes: 61 additions & 104 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,88 +1,26 @@
[![License: MIT](https://img.shields.io/badge/License-MIT-lightgrey.svg)](LICENCE) [![DOI](https://zenodo.org/badge/259718912.svg)](https://zenodo.org/badge/latestdoi/259718912) [![PyPI version](https://badge.fury.io/py/tequila-basic.svg)](https://badge.fury.io/py/tequila-basic) ![CI](https://github.com/tequilahub/tequila/actions/workflows/ci_basic.yml/badge.svg)

![Image](docs/all_in_one_example.png)

# Tequila

Tequila is an abstraction framework for (variational) quantum algorithms.
It operates on abstract data structures allowing the formulation, combination, automatic differentiation and optimization of generalized objectives.
Tequila can execute the underlying quantum expectation values on state of the art simulators as well as on real quantum devices.

Check out this small overview to get a glimpse on [what tequila is,](https://kottmanj.github.io/tequila-in-a-nutshell/#/)
or, get an overview through different slides and recordings of talks on different level of detail: See [here](https://kottmanj.github.io/talks_and_material/).

Get started with our [BasicUsage](https://nbviewer.org/github/tequilahub/tequila-tutorials/blob/main/BasicUsage.ipynb) Tutorial or find more in the [Tutorial collection](https://github.com/aspuru-guzik-group/tequila-tutorials)

or checkout our [overview article](https://arxiv.org/abs/2011.03057)

# Quantum Backends
Currently supported
- [Qulacs](https://github.com/qulacs/qulacs)
- [Qibo](https://github.com/Quantum-TII/qibo) -- currently needs to be qibo==0.1.1
- [Qiskit](https://github.com/qiskit/qiskit)
- [Cirq](https://github.com/quantumlib/cirq)
- [PyQuil](https://github.com/rigetti/pyquil)
- [QLM](https://atos.net/en/solutions/quantum-learning-machine) (works also whith [myQLM](https://myqlm.github.io/index.html))

Tequila detects backends automatically if they are installed on your systems.
All of them are available over standard pip installation like for example `pip install qulacs`.
For best performance it is recommended to have `qulacs` installed.
- [overview article](https://arxiv.org/abs/2011.03057)
- [tequila in a nutshell](https://kottmanj.github.io/tequila-in-a-nutshell/#/)
- [getting started](https://jakobkottmann.com/posts/tq-get-started/)
- [circuits in tequila](https://jakobkottmann.com/posts/tq-circuits/)
- [notebook collection](https://github.com/tequilahub/tequila-tutorials)
- [talks and slides](https://kottmanj.github.io/talks_and_material/)

# QuantumChemistry:
Currently supported
## [Psi4](https://github.com/psi4/psi4).
In a conda environment this can be installed with
```bash
conda install psi4 -c psi4
```
Here is a small [tutorial](https://nbviewer.org/github/tequilahub/tequila-tutorials/blob/main/chemistry/ChemistryModule.ipynb) that illustrates the usage.
# Installation
Recommended Python version is 3.8-3.9.
Tequila supports linux, osx and windows. However, not all optional dependencies are supported on windows.

## [Madness](https://github.com/kottmanj/madness)
In a conda environment this can be installed with
```bash
conda install madtequila -c kottmann
```
This installs a modified version of madness ready to use with tequila.
Alternatively it can be compiled from the sources provided in this [fork](https://github.com/kottmanj/madness) (follow readme instructions there).
Here is a small [tutorial](https://nbviewer.org/github/tequilahub/tequila-tutorials/blob/main/chemistry/MadnessInterface.ipynb) that illustrates the usage.

## [PySCF](https://github.com/pyscf/pyscf)
Install with
```bash
pip install pyscf
```
Works similar as Psi4. Classical methods are also integrated in the madness interface allowing to use them in a basis-set-free representation.

# Install from source
## Install from PyPi
**Do not** install like this: (Minecraft lovers excluded)
<strike>`pip install tequila`</strike>

We recommend installing in editable mode with
```bash
git clone https://github.com/tequilahub/tequila.git
cd tequila
pip install -e .
```

You can install `tequila` directly with pip over:
```bash
pip install git+https://github.com/tequilahub/tequila.git
```
Install from devel branch (most recent updates):
```bash
pip install git+https://github.com/tequilahub/tequila.git@devel
```

Recommended Python version is 3.7.
Python 3.8 works, but not all (optional) dependencies support it yet (e.g. Psi4).
Python 3.6 works, but some (optional) dependencies might have issues with numpy >= 1.20.

# Install from PyPi
**Do not** install like this:
<strike>`pip install tequila`</strike>

this will install a Minecraft server manager (might be useful for other things, but probably not what you are looking for).

You can install tequila from PyPi as:
```bash
pip install tequila-basic
Expand All @@ -97,22 +35,15 @@ pip install tequila-basic
pip install qulacs
```

# Install with Windows
## Install from github
You can install `tequila` directly with pip over:
```bash
pip install git+https://github.com/tequilahub/tequila.git
```
Install from devel branch (most recent updates):
```bash
pip install git+https://github.com/tequilahub/tequila.git@windows
pip install git+https://github.com/tequilahub/tequila.git@devel
```
See also the troubleshooting below if you want to tweak things manually.
The command above will not install the qulacs simulator.
You can install it on windows OS, but you need to have cmake and c++ compilers ready (can be installed for example over visual studio).
Of course you can also use one of the other backends (see above).

# Getting Started
We have a collection of [*tutorials*](https://github.com/tequilahub/tequila-tutorials) covering basic usage of tequila as well as cutting edge research content:
- Tutorial on [Basic Usage](https://nbviewer.org/github/tequilahub/tequila-tutorials/blob/main/BasicUsage.ipynb)
- Chemistry tutorial with psi4: see [here](https://nbviewer.org/github/tequilahub/tequila-tutorials/blob/main/chemistry/ChemistryModule.ipynb)
- Chemistry tutorial with madness: see [here](https://nbviewer.org/github/tequilahub/tequila-tutorials/blob/main/chemistry/MadnessInterface.ipynb)
- check the list of research projects below for links to specific examples.
- all tutorials: [github/tequilahub/tequila-tutorials](https://github.com/tequilahub/tequila-tutorials).

## Tequila Hello World
```python
Expand All @@ -137,13 +68,8 @@ result.history.plot("angles")
result.history.plot("gradients")
```

## Chemistry Hello World (Madness backend)
Install backend as
```bash
conda install madtequila -c kottmann
```
or see above for more.
more info [here](https://nbviewer.org/github/tequilahub/tequila-tutorials/blob/main/chemistry/MadnessInterface.ipynb)
## Chemistry Hello World (Madness backend)
see below for installation of dependencies
```python
import tequila as tq

Expand All @@ -164,7 +90,7 @@ E = tq.ExpectationValue(H=H, U=U)
result = tq.minimize(E)

# optional:compute classical reference energies
# needs pyscf
# needs pyscf as well
cisd = mol.compute_energy("cisd")
fci = mol.compute_energy("fci")

Expand All @@ -175,23 +101,17 @@ print("FCI : {:+2.8}f".format(fci))
```

## Chemistry Hello World (Psi4 or PySCF backend)
install backends with
```bash
pip install pyscf
# and/or
conda install psi4 -c psi4
```
more info [here](https://nbviewer.org/github/tequilahub/tequila-tutorials/blob/main/chemistry/ChemistryModule.ipynb)
see below for installation of dependencies
```python
# define a molecule within an active space
active = {"a1": [1], "b1":[0]}
active_orbitals=[1,2,5]
molecule = tq.quantumchemistry.Molecule(geometry="lih.xyz", basis_set='6-31g', active_orbitals=active, transformation="bravyi-kitaev")

# get the qubit hamiltonian
H = molecule.make_hamiltonian()

# create an k-UpCCGSD circuit of order k
U = molecule.make_upccgsd_ansatz(order=1, include_singles=True)
U = molecule.make_ansatz(name="UpCCGSD")

# define the expectationvalue
E = tq.ExpectationValue(H=H, U=U)
Expand All @@ -204,7 +124,6 @@ cisd = molecule.compute_energy("detci", options={"detci__ex_level": 2})
result = tq.minimize(objective=E, method="BFGS", initial_values=0.0)

print("VQE : {:+2.8}f".format(result.energy))
print("CISD: {:+2.8}f".format(cisd))
print("FCI : {:+2.8}f".format(fci))
```

Expand Down Expand Up @@ -319,6 +238,44 @@ Currently those are: [Phoenics](https://github.com/aspuru-guzik-group/phoenics)
and [GPyOpt](https://sheffieldml.github.io/GPyOpt/).
Quantum backends are treated in the same way.

## Quantum Backends
Currently supported
- [Qulacs](https://github.com/qulacs/qulacs) (recommended)
- [Qibo](https://github.com/Quantum-TII/qibo) -- currently needs to be qibo==0.1.1
- [Qiskit](https://github.com/qiskit/qiskit)
- [Cirq](https://github.com/quantumlib/cirq)
- [PyQuil](https://github.com/rigetti/pyquil)
- [QLM](https://atos.net/en/solutions/quantum-learning-machine) (works also whith [myQLM](https://myqlm.github.io/index.html))

Tequila detects backends automatically if they are installed on your systems.
All of them are available over standard pip installation like for example `pip install qulacs`.
For best performance it is recommended to have `qulacs` installed.

## QuantumChemistry:
Currently supported
### [Psi4](https://github.com/psi4/psi4).
In a conda environment this can be installed with
```bash
conda install psi4 -c psi4
```
Here is a small [tutorial](https://nbviewer.org/github/tequilahub/tequila-tutorials/blob/main/chemistry/ChemistryModule.ipynb) that illustrates the usage.

### [Madness](https://github.com/kottmanj/madness)
In a conda environment this can be installed with
```bash
conda install madtequila -c kottmann
```
This installs a modified version of madness ready to use with tequila.
Alternatively it can be compiled from the sources provided in this [fork](https://github.com/kottmanj/madness) (follow readme instructions there).
Here is a small [tutorial](https://nbviewer.org/github/tequilahub/tequila-tutorials/blob/main/chemistry/MadnessInterface.ipynb) that illustrates the usage. For fast performance it is recommended to not use the conda package.

### [PySCF](https://github.com/pyscf/pyscf)
Install with
```bash
pip install pyscf
```
Works similar as Psi4. Classical methods are also integrated in the madness interface allowing to use them in a basis-set-free representation.

# Documentation
You can build the documentation by navigating to `docs` and entering `make html`.
Open the documentation with a browser over like `firefox docs/build/html/index.html`
Expand Down
10 changes: 5 additions & 5 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
# necessary
numpy
scipy >= 1.5 # can in principle be smaller, we recommend >= 1.5 for consistency with our tutorials (numerical gradients mostly)
scipy < 1.11 # for now, until issues with scipy/pyscf are fixed # can in principle be smaller, we recommend >= 1.5 for consistency with our tutorials (numerical gradients mostly)
sympy
jax
jaxlib
# autograd # use if jaxlib gives you trouble (e.g. on Windows), make sure jax and jaxlib are uninstalled and install autograd
#jax
#jaxlib
autograd # autograd works better on OSX-ARM64 (M1 and M2) and Windows, feel free to try jax however (no big differences)
setuptools
pytest
openfermion ~= 1.0 # can not be smaller than 1.0
#cmake # needed by qulacs, can be removed otherwise, now in qulacs requirements
qulacs < 0.5.0 # default simulator (best integration), remove if the installation gives you trouble and just install one of the other supported backend. Version restriction only for noise models, otherwise the new version is fine
qulacs # default simulator (best integration), remove if the installation gives you trouble and just install one of the other supported backend. Version restriction only for noise models, otherwise the new version is fine

#optional quantum backends
#cirq >= 0.9.2 #
Expand Down
4 changes: 2 additions & 2 deletions src/tequila/apps/robustness/interval.py
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,7 @@ def _compute_interval(self) -> Tuple[float, float]:
pauli_lower_bound = pauli_upper_bound = 1.0
else:
expec_normalized = np.clip(2 * (p_expec - min_eigval) / (max_eigval - min_eigval) - 1, -1, 1,
dtype=np.float64)
dtype=float)

pauli_lower_bound = (max_eigval - min_eigval) / 2.0 * (
1 + self._calc_lower_bound(expec_normalized, self.fidelity)) + min_eigval
Expand Down Expand Up @@ -337,7 +337,7 @@ def _compute_bound_grouped(self) -> float:
for eigvals, expec, variance in zip(self._pauligroups_eigenvalues, self._pauligroups_expectations,
self._pauligroups_variances):
min_eigval = min(eigvals)
expec_pos = np.clip(expec - min_eigval, 0, None, dtype=np.float)
expec_pos = np.clip(expec - min_eigval, 0, None, dtype=float)
bound += min_eigval + self._calc_lower_bound(expec_pos, variance, self.fidelity)

return bound
Expand Down
28 changes: 27 additions & 1 deletion src/tequila/autograd_imports.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
# make sure to use the jax/autograd numpy
# will import either jax or autograd, depending on what is available on the system
from tequila.utils.exceptions import TequilaException

__AUTOGRAD__BACKEND__ = None
Expand All @@ -7,11 +8,36 @@
from jax import numpy
jax.config.update('jax_platform_name', 'cpu')
__AUTOGRAD__BACKEND__ = "jax"
except ImportError:
except:
# will pick autograd if jax is not installed
# or if there are errors on import (like on M2 chips or when jax/jaxlib are not matching
try:
import autograd as jax
from autograd import numpy

__AUTOGRAD__BACKEND__ = "autograd"
except ImportError:
raise TequilaException("Neither jax nor autograd found on your system")

def change_classical_differentiation_backend(name:str):
if name.lower() == "jax":
try:
import jax
from jax import numpy
except:
raise TequilaException("failed to load jax as classical differentiation backend")
elif name.lower() == "autograd":
try:
import autograd as jax
from autograd import numpy
except:
raise TequilaException("failed to load autograd as classical differentiation backend")

else:
raise TequilaException("unknown differentiation backend: {}, try jax or autograd".format(name))

return True

def status():
print("currently loaded autodiff numpy: {}, {}".format(numpy.__name__, numpy))
print("currently loaded autodiff library: {}, {}".format(jax.__name__, jax))
6 changes: 3 additions & 3 deletions src/tequila/circuit/_gates_impl.py
Original file line number Diff line number Diff line change
Expand Up @@ -180,18 +180,18 @@ def parameter(self, other):

def __init__(self, name, parameter: UnionParam, target: UnionList, control: UnionList = None,
generator: QubitHamiltonian = None):
super().__init__(name=name, target=target, control=control, generator=generator)
# failsafe
if hasattr(parameter, "shape") and parameter.shape not in [tuple()]: # take care of new numpy conventions where scalars have shape ()
self._parameter=None
raise TequilaException("parameter has to be a scalar. Received {}\n{}\n{}".format(repr(parameter), type(parameter), str(parameter)))
self._parameter = assign_variable(variable=parameter)
super().__init__(name=name, target=target, control=control, generator=generator)

def __str__(self):
result = str(self.name) + "(target=" + str(self.target)
if not self.is_single_qubit_gate():
result += ", control=" + str(self.control)

result += ", parameter=" + repr(self._parameter)
result += ", parameter=" + repr(self.parameter)
result += ")"
return result

Expand Down
Loading

0 comments on commit 054cf21

Please sign in to comment.