Skip to content

Commit

Permalink
added first attempt at quantump integrator
Browse files Browse the repository at this point in the history
  • Loading branch information
scarlehoff committed Jan 29, 2025
1 parent af24b27 commit dfd534b
Show file tree
Hide file tree
Showing 3 changed files with 108 additions and 0 deletions.
35 changes: 35 additions & 0 deletions examples/quantum_mc.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
"""
Run integration with qibo as the backend
"""

from vegasflow.quantum import quantum_wrapper
from vegasflow import float_me
import time
import numpy as np
import tensorflow as tf


# MC integration setup
dim = 2
ncalls = int(1e2)
n_iter = 5


def symgauss(xarr):
"""symgauss test function"""
n_dim = xarr.shape[-1]
a = float_me(0.1)
n100 = float_me(100 * n_dim)
pref = tf.pow(1.0 / a / np.sqrt(np.pi), n_dim)
coef = tf.reduce_sum(tf.range(n100 + 1))
coef += tf.reduce_sum(tf.square((xarr - 1.0 / 2.0) / a), axis=1)
coef -= (n100 + 1) * n100 / 2.0
return pref * tf.exp(-coef)


if __name__ == "__main__":
"""Testing several different integrations"""
print(f"VEGAS MC, ncalls={ncalls}:")
start = time.time()
result = quantum_wrapper(symgauss, dim, n_iter, ncalls)
end = time.time()
3 changes: 3 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -43,3 +43,6 @@ distribute = [
'distributed',
'dask-jobqueue',
]
quantum = [
"qibolab[qrng] @ git+https://github.com/qiboteam/qibolab@qrng"
]
70 changes: 70 additions & 0 deletions src/vegasflow/quantum.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
"""
A Monte Carlo integrator built upon Qibo for quantum integration
"""

from .monte_carlo import wrapper, sampler
from .plain import PlainFlow # start building upon a naive idiotic integrator
from .configflow import run_eager, DTYPE
import tensorflow as tf


class QuantumIntegrator(PlainFlow):
"""
Simple Monte Carlo integrator.
"""

_CAN_RUN_VECTORIAL = False

def __init__(self, *args, **kwargs):
# This integrator can only run for now in eager mode and needs qibolab to be installed
run_eager(True)

try:
from qibolab.instruments.qrng import QRNG
from serial.serialutil import SerialException
except ModuleNotFoundError as e:
raise ModuleNotFoundError("You can do pip install vegasflow[quantum]") from e

try:
qrng = QRNG(address="/dev/ttyACM0")
qrng.connect()
except SerialException as e:
raise SerialException("No quantum device found") from e

self._quantum_sampler = qrng
super().__init__(*args, **kwargs)

def run_integration(self, *args, **kwargs):
ret = super().run_integration(*args, **kwargs)
self._quantum_sampler.disconnect()
return ret

def _generate_random_array(self, n_events, *args):
"""
Returns
-------
`rnds`: array of (n_events, n_dim) random points
`idx` : index associated to each random point
`wgt` : wgt associated to the random point
"""
quantum_rnds_raw = self._quantum_sampler.random((n_events, self.n_dim))
rnds_raw = tf.cast(quantum_rnds_raw, dtype=DTYPE)

rnds, wgts_raw, *extra = self._digest_random_generation(rnds_raw, *args)

wgts = wgts_raw * self.xjac
if self._xdelta is not None:
# Now apply integration limits
rnds = self._xmin + rnds * self._xdelta
wgts *= self._xdeltajac
return rnds, wgts, *extra


def quantum_wrapper(*args, **kwargs):
"""Wrapper around QuantumIntegrator"""
return wrapper(QuantumIntegrator, *args, **kwargs)


def quantum_sampler(*args, **kwargs):
"""Wrapper sampler around QuantumIntegrator"""
return sampler(QuantumIntegrator, *args, **kwargs)

0 comments on commit dfd534b

Please sign in to comment.