Skip to content

Commit

Permalink
[Docs] Add circuit example to tutorial (#4)
Browse files Browse the repository at this point in the history
  • Loading branch information
dominikandreasseitz authored Nov 17, 2023
1 parent ab99161 commit dbb49cb
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 1 deletion.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# horqrux

**horqrux** is a [JAX](https://jax.readthedocs.io/en/latest/)-based state vector simulator designed for quantum machine learning.
It acts as the a backend for [`Qadence`](https://github.com/pasqal-io/qadence), a digital-analog quantum programming interface.
It acts as a backend for [`Qadence`](https://github.com/pasqal-io/qadence), a digital-analog quantum programming interface.

## Installation

Expand Down
35 changes: 35 additions & 0 deletions docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,3 +72,38 @@ state = prepare_state(2, '11')
param_value = 1 / 4 * jnp.pi
new_state = apply_gate(state, Rx(param_value, target_qubit, control_qubit))
```

A fully differentiable variational circuit is simply a sequence of gates which are applied to a state.

```python exec="on" source="material-block"
import jax
import jax.numpy as jnp
from horqrux import gates
from horqrux.utils import prepare_state, overlap
from horqrux.ops import apply_gate

n_qubits = 2
state = prepare_state(2, '00')
# Lets define a sequence of rotations
ops = [gates.Rx, gates.Ry, gates.Rx]
# Create random initial values for the parameters
key = jax.random.PRNGKey(0)
params = jax.random.uniform(key, shape=(n_qubits * len(ops),))

def circ(state) -> jax.Array:
for qubit in range(n_qubits):
for gate,param in zip(ops, params):
state = apply_gate(state, gate(param, qubit))
state = apply_gate(state,gates.NOT(1, 0))
projection = apply_gate(state, gates.Z(0))
return overlap(state, projection)

# Let's compute both values and gradients for a set of parameters and compile the circuit.
circ = jax.jit(jax.value_and_grad(circ))
# Run it on a state.
expval_and_grads = circ(state)
expval = expval_and_grads[0]
grads = expval_and_grads[1:]
print(f'Expval: {expval};'
f'Grads: {grads}')
```
4 changes: 4 additions & 0 deletions horqrux/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,3 +67,7 @@ def equivalent_state(state: Array, reference_state: str) -> bool:
n_qubits = state.ndim
ref_state = prepare_state(n_qubits, reference_state)
return jnp.allclose(state, ref_state) # type: ignore[no-any-return]


def overlap(state: Array, projection: Array) -> Array:
return jnp.real(jnp.dot(jnp.conj(state.flatten()), projection.flatten()))

0 comments on commit dbb49cb

Please sign in to comment.