How to use the blueqat.backends.backendbase.Backend function in blueqat

To help you get started, we’ve selected a few blueqat examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github Blueqat / Blueqat / blueqat / backends / _numba_backend_impl.py View on Github external
i0 = _shifted(lower_mask, i)
        qubits[i0] *= sqrtp_inv
        qubits[i0 + (1 << target)] = 0.0


@njit(nogil=True, parallel=True)
def _reduce1(qubits, target, n_qubits, p0):
    sqrtp_inv = 1.0 / math.sqrt(1.0 - p0)
    lower_mask = (1 << _QSMask(target)) - 1
    for i in prange(1 << (_QSMask(n_qubits) - 1)):
        i0 = _shifted(lower_mask, i)
        qubits[i0 + (1 << target)] *= sqrtp_inv
        qubits[i0] = 0.0


class NumbaBackend(Backend):
    """Simulator backend which uses numba."""
    __return_type = {
        "statevector": lambda ctx: ctx.qubits,
        "shots": lambda ctx: ctx.shots_result,
        "statevector_and_shots": lambda ctx: (ctx.qubits, ctx.shots_result),
        "_inner_ctx": lambda ctx: ctx,
    }
    DEFAULT_SHOTS = 1024

    def __init__(self):
        self.cache = None
        self.cache_idx = -1

    def __clear_cache(self):
        self.cache = None
        self.cache_idx = -1
github Blueqat / Blueqat / blueqat / backends / qasm_parser_backend_generator.py View on Github external
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from ..gate import *
from .backendbase import Backend
from .qasm_output_backend import QasmOutputBackend

class QasmParsableBackend(Backend):
    """Backend for third-party library which can read OpenQASM """
    def __init__(self, qasm_runner):
        """Specify qasm_runner which receive OpenQASM text and returns result.

        Args:
            qasm_runner (function (qasm: str, *args, **kwargs) -> Result):
                An function which receives OpenQASM and some arguments and returns a result.
        """
        self.to_qasm = QasmOutputBackend()
        self.qasm_runner = qasm_runner

    def run(self, gates, n_qubits, *args, **kwargs):
        qasm = self.to_qasm.run(gates, n_qubits)
        return self.qasm_runner(qasm, *args, **kwargs)

def generate_backend(qasm_runner):
github Blueqat / Blueqat / blueqat / backends / qgate_backend.py View on Github external
from collections import Counter
from .backendbase import Backend
import blueqat.gate as bqgate
import numpy as np

class QgateBackend(Backend) :

    def __init__(self) :
        import sys
        this = sys.modules[__name__]
        if not hasattr(this, 'qgate') :
            import qgate
            this.qgate = qgate
            this.model = qgate.model
            this.gtype = qgate.model.gate_type

            QgateBackend.gatetypes = {
                'i' : (gtype.ID, 0, 1),
                'x' : (gtype.X, 0, 1), 'y' : (gtype.Y, 0, 1), 'z' : (gtype.Z, 0, 1),
                'h' : (gtype.H, 0, 1), 't' : (gtype.T, 0, 1), 's' : (gtype.S, 0, 1),
                # adjoint
                'tdg' : (gtype.T, 0, 1), 'sdg' : (gtype.S, 0, 1),
github Blueqat / Blueqat / blueqat / backends / qasm_output_backend.py View on Github external
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import math
import random
import numpy as np
from ..gate import *
from .backendbase import Backend

class QasmOutputBackend(Backend):
    """Backend for OpenQASM output."""
    def _preprocess_run(self, gates, n_qubits, args, kwargs):
        def _parse_run_args(output_prologue=True, **_kwargs):
            return { 'output_prologue': output_prologue }

        args = _parse_run_args(*args, **kwargs)
        if args['output_prologue']:
            qasmlist = [
                "OPENQASM 2.0;",
                'include "qelib1.inc";',
                f"qreg q[{n_qubits}];",
                f"creg c[{n_qubits}];",
            ]
        else:
            qasmlist = []
        return gates, (qasmlist, n_qubits)
github Blueqat / Blueqat / blueqat / backends / binary_backend.py View on Github external
from itertools import product
from .backendbase import Backend

class _BinaryBackendContext:
    def __init__(self, n_bits, ibits, ilabels, obits, olabels, disp):
        self.n_bits = n_bits
        self.ops = []
        self.ibits = ibits
        self.ilabels = ilabels
        self.obits = obits
        self.olabels = olabels
        self.disp = disp


class BinaryBackend(Backend):
    def __parse_runargs(self, n_bits, inputs=None, outputs=None, display=True):
        # Parse inputs. {'label': n, ...} or [n, m, ...] or None.
        if inputs is None:
            inputs = list(range(n_bits))
            inputs_label = [f'{i}' for i in range(n_bits)]
        if isinstance(inputs, dict):
            inputs_label = list(inputs.keys())
            inputs = list(inputs.values())
            if len(set(inputs)) != len(inputs):
                raise ValueError('Duplicate input bits!')
        else:
            inputs = list(inputs)
            inputs_label = [f'{i}' for i in inputs]
            if len(set(inputs)) != len(inputs):
                raise ValueError('Duplicate input bits!')
        # Parse outputs. {'label': n, ...} or [n, m, ...] or None.
github Blueqat / Blueqat / blueqat / backends / mqc_backend.py View on Github external
self.err_msg = err.read().decode(encoding="utf-8", errors="backslashreplace")
            try:
                self.err_json = json.loads(self.err_msg)
            except json.JSONDecodeError:
                pass
        else:
            self.err_msg = str(err)

    def __str__(self):
        s = self.err_type + ", "
        if self.statuscode is not None:
            s += "Status Code: " + str(self.statuscode) + ", "
        s += self.err_msg
        return s

class MQCBackend(Backend):
    """Backend for MDR Quantum Cloud."""
    def _preprocess_run(self, gates, n_qubits, args, kwargs):
        def _parse_args(token, shots=1024, returns="shots", url=DEFAULT_URL, **_kwargs):
            if returns not in ("shots", "_res", "_urllib_req", "_urllib_res", "_urllib_req_res"):
                raise ValueError(f"Unknown returns type '{returns}'")
            return token, shots, returns, url
        token, shots, returns, url = _parse_args(*args, **kwargs)
        return gates, _MQCContext([], n_qubits, token, shots, returns, url)

    def _postprocess_run(self, ctx):
        req = urllib.request.Request(
            ctx.url,
            json.dumps({
                "access_token": ctx.token,
                "command": "createTask",
                "payload": {
github Blueqat / Blueqat / blueqat / backends / numpy_backend.py View on Github external
if cache is not None:
            np.copyto(self.qubits, cache)
        else:
            self.qubits.fill(0.0)
            self.qubits[0] = 1.0
        self.cregs = [0] * self.n_qubits

    def store_shot(self):
        """Store current cregs to shots_result"""
        def to_str(cregs):
            return ''.join(str(b) for b in cregs)
        key = to_str(self.cregs)
        self.shots_result[key] = self.shots_result.get(key, 0) + 1


class NumPyBackend(Backend):
    """Simulator backend which uses numpy. This backend is Blueqat's default backend."""
    __return_type = {
        "statevector": lambda ctx: ctx.qubits,
        "shots": lambda ctx: ctx.shots_result,
        "statevector_and_shots": lambda ctx: (ctx.qubits, ctx.shots_result),
        "_inner_ctx": lambda ctx: ctx,
    }
    DEFAULT_SHOTS = 1024

    def __init__(self):
        self.cache = None
        self.cache_idx = -1

    def __clear_cache(self):
        self.cache = None
        self.cache_idx = -1
github Blueqat / Blueqat / blueqat / backends / sympy_backend.py View on Github external
if isinstance(ang, float):
        nsimp = sympy.nsimplify(ang / np.pi)
        numer, denom = nsimp.as_numer_denom()
        if denom < 1e12:
            return pi * numer / denom
    return ang


class _SympyBackendContext:
    def __init__(self, n_qubits, ignore_global):
        self.n_qubits = n_qubits
        self.matrix_of_circuit = eye(2 ** n_qubits)
        self.ignore_global = ignore_global


class SympyBackend(Backend):

    def __init__(self):
        try:
            lazy_import()
        except ImportError:
            raise ImportError('sympy_unitary requires sympy. Please install before call this option.')
        theta, phi, lambd = symbols('theta phi lambd')
        self.theta = theta
        self.phi = phi
        self.lambd = lambd
        self.SYMPY_GATE = {
            '_C0': Matrix([[1, 0], [0, 0]]),
            '_C1': Matrix([[0, 0], [0, 1]]),
            'X': sympy_gate.X(0).get_target_matrix(),
            'Y': sympy_gate.Y(0).get_target_matrix(),
            'Z': sympy_gate.Z(0).get_target_matrix(),