コード例 #1
0
ファイル: providers.py プロジェクト: myQLM/myqlm-interop
    def set_backend(self,
                    backend=None,
                    token=None,
                    ibmq_backend='ibmq_qasm_simulator'):
        """
        Sets the backend that will execute circuits.
        If no backend and no token are specified, the backend  will be
        a simulator.

        Args:
            backend: The Backend Qiskit object to be wrapped
            token: Qiskit IBMQ login token. If not supplied, loaded from env
                    variable QISKIT_TOKEN. Only used if backend is None
            ibmq_backend: Name of the IBM Quantum Experience backend, default
                    value is 'ibmq_qasm_simulator', which goes up to 32qubits
        """
        if backend is None:
            if token is None:
                token = os.getenv("QISKIT_TOKEN")
            if token is not None:
                if 'token' not in IBMQ.stored_account().keys() or \
                        IBMQ.stored_account()['token'] != token:
                    IBMQ.save_account(token, overwrite=True)

                provider = IBMQ.load_account()
                self.backend = provider.get_backend(ibmq_backend)
            else:
                self.backend = Aer.get_backend("aer_simulator")
        else:
            self.backend = backend
コード例 #2
0
def load_IBMQ(token, hub, group, project):
    if len(IBMQ.stored_account()) == 0:
        IBMQ.save_account(token)
        IBMQ.load_account()
    elif IBMQ.active_account() == None:
        IBMQ.load_account()
    provider = IBMQ.get_provider(hub=hub, group=group, project=project)
    return provider
コード例 #3
0
ファイル: grover.py プロジェクト: ikhvorost/quantum-computing
def search(N, oracle, provider_name, backend_name, token, shots, draw, file):
    print("Grover's Search Algorithm Tool v.{}".format(__version__))
    print("Params: N = {}, Oracle = {}, Backend = {}/{}, Shots = {}".format(
        N, oracle, provider_name, backend_name, shots))

    controlsCount = math.ceil(math.log2(N))
    controls = QuantumRegister(controlsCount, "c_qb")

    ancilla = QuantumRegister(1, "a_qb")
    target = QuantumRegister(1, "t_qb")

    classical = ClassicalRegister(controlsCount, "c_b")

    iterations = int(math.pi / 4 * math.log2(N))

    print("Quantum circuit: {} qubits, {} iteration(s)".format(
        controlsCount + 2, iterations))

    print("Building...")

    # Create a Quantum Circuit acting on the q register
    circuit = QuantumCircuit(controls, ancilla, target, classical)

    # State preparation

    # Add a H gates to contol qubits
    circuit.h(controls)

    # |-> to target qubit
    circuit.x(target)
    circuit.h(target)

    # Grover iterator
    def grover(circuit, controls, target):
        # Oracle
        binary = format(oracle, "0{}b".format(controlsCount))

        for c, qubit in zip(binary, reversed(controls)):
            if c == '0':
                circuit.x(qubit)

        circuit.mct(controls, target[0], ancilla, mode='advanced')

        for c, qubit in zip(binary, reversed(controls)):
            if c == '0':
                circuit.x(qubit)

        # Diffuser
        circuit.h(controls)
        circuit.x(controls)
        circuit.mct(controls, target[0], ancilla, mode='advanced')
        circuit.x(controls)
        circuit.h(controls)

    # Iterations
    for i in range(iterations):
        grover(circuit, controls, target)

    # Measurement
    circuit.measure(controls, classical)

    # Draw quantum circuit
    if draw:
        if bool(file):
            f = open(file, "w+")
            print(circuit, file=f)
            f.close()
        else:
            print(circuit)

    # Backend

    # Aer
    if provider_name == "Aer":
        backend = Aer.get_backend(backend_name)
    # IBMQ
    elif provider_name == "IBMQ":
        account = IBMQ.stored_account()
        if bool(account):
            provider = IBMQ.load_account()
        else:
            if bool(token):
                provider = IBMQ.enable_account(token)
            else:
                print("Token is not provided!")
                exit()
        backend = provider.get_backend(backend_name)

    # Execute the quantum circuit on the qasm simulator
    print("Executing...")
    job = execute(circuit, backend, shots=shots)

    # Wait results
    i = 0
    while True:
        time.sleep(1)
        status = job.status()
        print("({}) {}".format(i, status))
        i = i + 1

        if status in JOB_FINAL_STATES:
            if status == JobStatus.ERROR:
                print("Error:", job.error_message())
                exit()
            else:
                break

    # Get results from the job
    result = job.result()
    #print("\nResults:", result)

    # Find max counts
    max = 0
    state = ""
    for k, v in result.get_counts(circuit).items():
        if v > max:
            max = v
            state = k

    num = int(state, 2)
    print("Answer: {}, State: '{}', {} times".format(num, state, max))
    return num
コード例 #4
0
ファイル: ibm.py プロジェクト: ayazskhan/pytket-extensions
    def __init__(
        self,
        backend_name: str,
        hub: Optional[str] = None,
        group: Optional[str] = None,
        project: Optional[str] = None,
        monitor: bool = True,
    ):
        """A backend for running circuits on remote IBMQ devices.

        :param backend_name: Name of the IBMQ device, e.g. `ibmqx4`,
         `ibmq_16_melbourne`.
        :type backend_name: str
        :param hub: Name of the IBMQ hub to use for the provider.
         If None, just uses the first hub found. Defaults to None.
        :type hub: Optional[str], optional
        :param group: Name of the IBMQ group to use for the provider. Defaults to None.
        :type group: Optional[str], optional
        :param project: Name of the IBMQ project to use for the provider.
         Defaults to None.
        :type project: Optional[str], optional
        :param monitor: Use the IBM job monitor. Defaults to True.
        :type monitor: bool, optional
        :raises ValueError: If no IBMQ account is loaded and none exists on the disk.
        """
        super().__init__()
        if not IBMQ.active_account():
            if IBMQ.stored_account():
                IBMQ.load_account()
            else:
                raise NoIBMQAccountError()
        provider_kwargs = {}
        if hub:
            provider_kwargs["hub"] = hub
        if group:
            provider_kwargs["group"] = group
        if project:
            provider_kwargs["project"] = project

        try:
            if provider_kwargs:
                provider = IBMQ.get_provider(**provider_kwargs)
            else:
                provider = IBMQ.providers()[0]
        except qiskit.providers.ibmq.exceptions.IBMQProviderError as err:
            logging.warn(
                ("Provider was not specified enough, specify hub,"
                 "group and project correctly (check your IBMQ account)."))
            raise err
        self._backend: "_QiskIBMQBackend" = provider.get_backend(backend_name)
        self._config: "QasmBackendConfiguration" = self._backend.configuration(
        )
        self._gate_set: Set[OpType]
        # simulator i.e. "ibmq_qasm_simulator" does not have `supported_instructions`
        # attribute
        self._gate_set = _tk_gate_set(self._backend)

        self._mid_measure = self._config.simulator or self._config.multi_meas_enabled

        self._legacy_gateset = OpType.V not in self._gate_set

        if self._legacy_gateset:
            if not self._gate_set >= {
                    OpType.U1, OpType.U2, OpType.U3, OpType.CX
            }:
                raise NotImplementedError(
                    f"Gate set {self._gate_set} unsupported")
            self._rebase_pass = RebaseIBM()
        else:
            if not self._gate_set >= {
                    OpType.X, OpType.V, OpType.Rz, OpType.CX
            }:
                raise NotImplementedError(
                    f"Gate set {self._gate_set} unsupported")
            self._rebase_pass = RebaseCustom(
                {OpType.CX},
                Circuit(2).CX(0, 1),
                {OpType.X, OpType.V, OpType.Rz},
                _tk1_to_x_v_rz,
            )

        if hasattr(self._config, "max_experiments"):
            self._max_per_job = self._config.max_experiments
        else:
            self._max_per_job = 1

        self._characterisation: Dict[str, Any] = process_characterisation(
            self._backend)
        self._device = Device(
            self._characterisation.get("NodeErrors", {}),
            self._characterisation.get("EdgeErrors", {}),
            self._characterisation.get("Architecture", Architecture([])),
        )
        self._monitor = monitor

        self._MACHINE_DEBUG = False
コード例 #5
0
 def __init__(self, factor):
     self.factor = factor
     storedAccount = IBMQ.stored_account()
     if storedAccount == None or storedAccount == {}:
         IBMQ.save_account(token)
     self.__provider = IBMQ.load_account()
コード例 #6
0
from qiskit.circuit.library import RYGate, MCMT  # type: ignore
from pytket.circuit import (  # type: ignore
    Circuit, CircBox, Unitary2qBox, OpType, Qubit, Bit, CustomGateDef, reg_eq,
)
from pytket.extensions.qiskit import tk_to_qiskit, qiskit_to_tk
from pytket.extensions.qiskit.qiskit_convert import _gate_str_2_optype
from pytket.extensions.qiskit.tket_pass import TketPass, TketAutoPass
from pytket.extensions.qiskit.result_convert import (
    qiskit_result_to_backendresult,
    backendresult_to_qiskit_resultdata,
)
from sympy import Symbol  # type: ignore
from pytket.passes import USquashIBM, DecomposeBoxes, FullPeepholeOptimise  # type: ignore
from pytket.utils.results import compare_statevectors

skip_remote_tests: bool = (not IBMQ.stored_account()
                           or os.getenv("PYTKET_RUN_REMOTE_TESTS") is None)


def get_test_circuit(measure: bool, reset: bool = True) -> QuantumCircuit:
    qr = QuantumRegister(4)
    cr = ClassicalRegister(4)
    qc = QuantumCircuit(qr, cr, name="test_circuit")
    qc.h(qr[0])
    qc.cx(qr[1], qr[0])
    qc.h(qr[0])
    qc.cx(qr[0], qr[3])
    qc.barrier(qr[3])
    if reset:
        qc.reset(qr[3])
    qc.rx(pi / 2, qr[3])
コード例 #7
0
from pytket.extensions.qiskit import qiskit_to_tk, process_characterisation
from pytket.utils.expectations import (
    get_pauli_expectation_value,
    get_operator_expectation_value,
)
from pytket.utils.operators import QubitPauliOperator
from pytket.utils.results import compare_unitaries
from qiskit import IBMQ  # type: ignore
from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister
from qiskit.providers.aer.noise.noise_model import NoiseModel  # type: ignore
from qiskit.providers.aer.noise.errors import depolarizing_error, pauli_error  # type: ignore
import pytest

# TODO add tests for `get_operator_expectation_value`

skip_remote_tests: bool = (not IBMQ.stored_account()
                           or os.getenv("PYTKET_RUN_REMOTE_TESTS") is None)


def circuit_gen(measure: bool = False) -> Circuit:
    c = Circuit(2, 2)
    c.H(0)
    c.CX(0, 1)
    if measure:
        c.measure_all()
    return c


def get_test_circuit(measure: bool) -> QuantumRegister:
    qr = QuantumRegister(5)
    cr = ClassicalRegister(5)
コード例 #8
0
import os
from qiskit import IBMQ, __version__
from dotenv import load_dotenv

# Load environment variables.
load_dotenv()

# Login to IBM Quantum.
if IBMQ.stored_account().get('token') == None:
    IBMQ.save_account(os.environ['IBMQ_TOKEN'])
    print('You are now logged in...')

print(__version__)