Пример #1
0
def check_and_load_accounts():
    if IBMQ.active_account() is None:
        # try loading account
        IBMQ.load_account()
        if IBMQ.active_account() is None:
            # try grabbing token from environment
            logger.debug("Using token: {}".format(os.environ['QE_TOKEN']))
            IBMQ.enable_account(os.environ['QE_TOKEN'])
def run_grover(algorithm,oracle_type,oracle_method):
    # Run the algorithm on a simulator, printing the most frequently occurring result

    backend = Aer.get_backend('qasm_simulator')
    result = algorithm.run(backend)
    print("Oracle method:",oracle_method)
    print("Oracle for:", oracle_type)
    print("Aer Result:",result['top_measurement'])
    display(plot_histogram(result['measurement']))
    
    # Run the algorithm on an IBM Q backend, printing the most frequently occurring result
    print("Getting provider...")
    if not IBMQ.active_account():
        IBMQ.load_account()
    provider = IBMQ.get_provider()
    from qiskit.providers.ibmq import least_busy
    
    filtered_backend = least_busy(provider.backends(n_qubits=5, operational=True, simulator=False))
        
    result = algorithm.run(filtered_backend)

    print("Oracle method:",oracle_method)
    print("Oracle for:", oracle_type)
    print("IBMQ "+filtered_backend.name()+" Result:",result['top_measurement'])
    display(plot_histogram(result['measurement']))

    print(result)
Пример #3
0
def _get_provider():
    if IBMQ.active_account() is None:
        ibmq_token = os.environ["IBMQ_TOKEN"]
        provider = IBMQ.enable_account(ibmq_token)
    else:
        provider = IBMQ.get_provider(hub="ibm-q", group="open", project="main")

    return provider
Пример #4
0
def login_IBMQ_okay() -> bool:
    ibmq_token = os.environ.get("IBMQ_TOKEN", "")

    if ibmq_token:
        QiskitIBMQ.enable_account(ibmq_token)
    else:
        QiskitIBMQ.load_account()
    return bool(QiskitIBMQ.active_account())
Пример #5
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
Пример #6
0
 def save_IBMQ_account(self, token, url):
     print('update IBMQ account now.')
     IBMQ.save_account(token, url, overwrite=True)
     IBMQ.load_account()
     IBMQ.enable_account(token, url)
     if self.outputTestLog:
         print('The actived account:')
         print(IBMQ.active_account())
Пример #7
0
def connect(kwargs):
    """Function that allows connection to IBMQ.

    Args:
        kwargs(dict): dictionary that contains the token and the url"""

    token = kwargs.get("ibmqx_token", None) or os.getenv("IBMQX_TOKEN")
    url = kwargs.get("ibmqx_url", None) or os.getenv("IBMQX_URL")

    # TODO: remove "no cover" when #173 is resolved
    if token is not None:  # pragma: no cover
        # token was provided by the user, so attempt to enable an
        # IBM Q account manually
        def login():
            ibmq_kwargs = {"url": url} if url is not None else {}
            IBMQ.enable_account(token, **ibmq_kwargs)

        active_account = IBMQ.active_account()
        if active_account is None:
            login()
        else:
            # There is already an active account:
            # If the token is the same, do nothing.
            # If the token is different, authenticate with the new account.
            if active_account["token"] != token:
                IBMQ.disable_account()
                login()
    else:
        # check if an IBM Q account is already active.
        #
        # * IBMQ v2 credentials stored in active_account().
        #   If no accounts are active, it returns None.

        if IBMQ.active_account() is None:
            # no active account
            try:
                # attempt to load a v2 account stored on disk
                IBMQ.load_account()
            except IBMQAccountError:
                # attempt to enable an account manually using
                # a provided token
                raise IBMQAccountError(
                    "No active IBM Q account, and no IBM Q token provided."
                ) from None
Пример #8
0
 def find_least_busy_backend_from_open(cls, n):
     if account_details.account_token_open is None:
         account_token = input("Insert your account token: ")
     else:
         account_token = account_details.account_token_open
     if IBMQ.active_account() is None:
         IBMQ.enable_account(account_token)
     provider = IBMQ.get_provider(hub='ibm-q')
     return least_busy(
         provider.backends(filters=lambda x: x.configuration().n_qubits >=
                           (n + 1) and not x.configuration(
                           ).simulator and x.status().operational == True))
Пример #9
0
    def __init__(self,
                 wires,
                 provider=None,
                 backend="ibmq_qasm_simulator",
                 shots=1024,
                 **kwargs):
        token = os.getenv("IBMQX_TOKEN") or kwargs.get("ibmqx_token", None)
        url = os.getenv("IBMQX_URL") or kwargs.get("ibmqx_url", None)

        # Specify a single hub, group and project
        hub = kwargs.get("hub", "ibm-q")
        group = kwargs.get("group", "open")
        project = kwargs.get("project", "main")

        if token is not None:
            # token was provided by the user, so attempt to enable an
            # IBM Q account manually
            ibmq_kwargs = {"url": url} if url is not None else {}
            IBMQ.enable_account(token, **ibmq_kwargs)
        else:
            # check if an IBM Q account is already active.
            #
            # * IBMQ v2 credentials stored in active_account().
            #   If no accounts are active, it returns None.

            if IBMQ.active_account() is None:
                # no active account
                try:
                    # attempt to load a v2 account stored on disk
                    IBMQ.load_account()
                except IBMQAccountError:
                    # attempt to enable an account manually using
                    # a provided token
                    raise IBMQAccountError(
                        "No active IBM Q account, and no IBM Q token provided."
                    ) from None

        # IBM Q account is now enabled

        # get a provider
        p = provider or IBMQ.get_provider(
            hub=hub, group=group, project=project)

        super().__init__(wires=wires,
                         provider=p,
                         backend=backend,
                         shots=shots,
                         **kwargs)
def test_tketautopass() -> None:
    backends = [
        Aer.get_backend("statevector_simulator"),
        Aer.get_backend("qasm_simulator"),
        Aer.get_backend("unitary_simulator"),
    ]
    if not skip_remote_tests:
        if not IBMQ.active_account():
            IBMQ.load_account()
        provider = IBMQ.providers()[0]
        backends.append(provider.get_backend("ibmq_santiago"))
    for back in backends:
        for o_level in range(3):
            tkpass = TketAutoPass(back, o_level)
            qc = get_test_circuit(True)
            pm = PassManager(passes=tkpass)
            pm.run(qc)
Пример #11
0
def test_process_characterisation() -> None:
    if not IBMQ.active_account():
        IBMQ.load_account()

    provider = IBMQ.providers(hub="ibm-q", group="open")[0]
    back = provider.get_backend("ibmq_santiago")

    char = process_characterisation(back)
    dev = Device(
        char.get("NodeErrors", {}),
        char.get("EdgeErrors", {}),
        char.get("Architecture", Architecture([])),
    )

    assert len(dev.nodes) == 5
    assert len(dev.errors_by_node) == 5
    assert len(dev.coupling) == 8
Пример #12
0
    def __init__(self, wires, provider=None, backend="ibmq_qasm_simulator", shots=1024, **kwargs):
        token = os.getenv("IBMQX_TOKEN") or kwargs.get("ibmqx_token", None)
        url = os.getenv("IBMQX_URL") or kwargs.get("ibmqx_url", None)

        if token is not None:
            # token was provided by the user, so attempt to enable an
            # IBM Q account manually
            ibmq_kwargs = {"url": url} if url is not None else {}
            IBMQ.enable_account(token, **ibmq_kwargs)
        else:
            # turn off deprecation warnings
            # TODO: remove IBM Q v1 API calls when fully deprecated
            with warnings.catch_warnings():
                warnings.filterwarnings("ignore", category=DeprecationWarning)

                # check if an IBM Q account is already active.
                #
                # * IBMQ v1 credentials stored in active_accounts().
                #   If no accounts are active, it returns []
                #
                # * IBMQ v2 credentials stored in active_account().
                #   If no accounts are active, it returns None.

                if IBMQ.active_account() is None and not IBMQ.active_accounts():
                    # no active account
                    try:
                        # attempt to load a v1 account stored on disk
                        IBMQ.load_accounts()
                    except IBMQAccountError:
                        try:
                            # attempt to load a v2 account stored on disk
                            IBMQ.load_account()
                        except IBMQAccountError:
                            # attempt to enable an account manually using
                            # a provided token
                            raise IBMQAccountError(
                                "No active IBM Q account, and no IBM Q token provided."
                            ) from None

        # IBM Q account is now enabled

        # get a provider
        p = provider or IBMQ.get_provider()

        super().__init__(wires=wires, provider=p, backend=backend, shots=shots, **kwargs)
Пример #13
0
def run_qasm(qasm,
             backend_to_run="qasm_simulator",
             api_token=None,
             shots=1024,
             memory=False):
    active_account = IBMQ.active_account()
    if api_token:
        if active_account is None:
            IBMQ.enable_account(api_token)
        elif active_account['token'] != api_token:
            IBMQ.enable_account(api_token)

    qc = QuantumCircuit.from_qasm_str(qasm)
    backend = Aer.get_backend(backend_to_run)
    job_sim = execute(qc, backend, shots=shots, memory=memory)
    sim_result = job_sim.result()
    if memory:
        return sim_result.get_memory(qc)
    else:
        return sim_result.get_counts(qc)
def run_shor(N):
    if N <= 64:  #Arbitrarily set upper limit for local simulator
        print("Getting local simulator backend...")
        backend = Aer.get_backend('qasm_simulator')
    else:
        print("Getting provider...")
        if not IBMQ.active_account():
            IBMQ.load_account()
        provider = IBMQ.get_provider()
        print("Getting IBM Q simulator backend...")
        backend = provider.get_backend('ibmq_qasm_simulator')
    print("Running Shor's algorithm for", str(N), "on", backend, "...")
    results = Shor(N=N).run(backend)
    print("\nResults:")
    if results['factors'] == []:
        print("No prime factors: ", str(N), "=", str(N))
    elif isinstance(results['factors'][0], int):
        print("Prime factors: ", str(N), "=", results['factors'][0], "^ 2")
    else:
        print("Prime factors: ", str(N), "=", results['factors'][0][0], "*",
              results['factors'][0][1])
Пример #15
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created Nov 2020

@author: hassi
"""

print("Ch 7: IBM Q simulators and how they are used")
print("--------------------------------------------")

# Import Qiskit and load account
from qiskit import Aer, IBMQ

print("Getting provider...")
if not IBMQ.active_account():
    IBMQ.load_account()
provider = IBMQ.get_provider()

# Load backends
backends = Aer.backends()
print("\nAer backends:\n\n", backends)

# Collect Aer simulators
simulators = []
for sim in range(0, len(backends)):
    backend = Aer.get_backend(str(backends[sim]))
    simulators.append(backend.configuration())

# Add IBM Q simulator
ibmq_simulator = provider.backends(simulator=True)
Пример #16
0
import qiskit
from qiskit import IBMQ

# Load account from disk:
provider = IBMQ.load_account()
# list the account currently in the session
print(IBMQ.active_account())
# list all available providers
print(IBMQ.providers())
print(provider.backends())

Пример #17
0
    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