|
| 1 | +""" |
| 2 | +A Monte Carlo integrator built upon Qibo for quantum integration |
| 3 | +""" |
| 4 | + |
| 5 | +from .monte_carlo import wrapper, sampler |
| 6 | +from .plain import PlainFlow # start building upon a naive idiotic integrator |
| 7 | +from .configflow import run_eager, DTYPE |
| 8 | +import tensorflow as tf |
| 9 | + |
| 10 | + |
| 11 | +class QuantumIntegrator(PlainFlow): |
| 12 | + """ |
| 13 | + Simple Monte Carlo integrator. |
| 14 | + """ |
| 15 | + |
| 16 | + _CAN_RUN_VECTORIAL = False |
| 17 | + |
| 18 | + def __init__(self, *args, **kwargs): |
| 19 | + # This integrator can only run for now in eager mode and needs qibolab to be installed |
| 20 | + run_eager(True) |
| 21 | + |
| 22 | + try: |
| 23 | + from qibolab.instruments.qrng import QRNG |
| 24 | + from serial.serialutil import SerialException |
| 25 | + except ModuleNotFoundError as e: |
| 26 | + raise ModuleNotFoundError("You can do pip install vegasflow[quantum]") from e |
| 27 | + |
| 28 | + try: |
| 29 | + qrng = QRNG(address="/dev/ttyACM0") |
| 30 | + qrng.connect() |
| 31 | + except SerialException as e: |
| 32 | + raise SerialException("No quantum device found") from e |
| 33 | + |
| 34 | + self._quantum_sampler = qrng |
| 35 | + super().__init__(*args, **kwargs) |
| 36 | + |
| 37 | + def run_integration(self, *args, **kwargs): |
| 38 | + ret = super().run_integration(*args, **kwargs) |
| 39 | + self._quantum_sampler.disconnect() |
| 40 | + return ret |
| 41 | + |
| 42 | + def _generate_random_array(self, n_events, *args): |
| 43 | + """ |
| 44 | + Returns |
| 45 | + ------- |
| 46 | + `rnds`: array of (n_events, n_dim) random points |
| 47 | + `idx` : index associated to each random point |
| 48 | + `wgt` : wgt associated to the random point |
| 49 | + """ |
| 50 | + quantum_rnds_raw = self._quantum_sampler.random((n_events, self.n_dim)) |
| 51 | + rnds_raw = tf.cast(quantum_rnds_raw, dtype=DTYPE) |
| 52 | + |
| 53 | + rnds, wgts_raw, *extra = self._digest_random_generation(rnds_raw, *args) |
| 54 | + |
| 55 | + wgts = wgts_raw * self.xjac |
| 56 | + if self._xdelta is not None: |
| 57 | + # Now apply integration limits |
| 58 | + rnds = self._xmin + rnds * self._xdelta |
| 59 | + wgts *= self._xdeltajac |
| 60 | + return rnds, wgts, *extra |
| 61 | + |
| 62 | + |
| 63 | +def quantum_wrapper(*args, **kwargs): |
| 64 | + """Wrapper around QuantumIntegrator""" |
| 65 | + return wrapper(QuantumIntegrator, *args, **kwargs) |
| 66 | + |
| 67 | + |
| 68 | +def quantum_sampler(*args, **kwargs): |
| 69 | + """Wrapper sampler around QuantumIntegrator""" |
| 70 | + return sampler(QuantumIntegrator, *args, **kwargs) |
0 commit comments