Python Examples

ProjectQ examples

A simple example that demonstrates how to use the SDK to create a circuit to create a Bell state, and simulate the circuit on Quantum Inspire.

"""
This example is copied from https://github.com/ProjectQ-Framework/ProjectQ
and is covered under the Apache 2.0 license.
"""
import os

from projectq import MainEngine
from projectq.backends import ResourceCounter
from projectq.ops import CNOT, H, Measure, All
from projectq.setups import restrictedgateset

from quantuminspire.api import QuantumInspireAPI
from quantuminspire.credentials import get_authentication
from quantuminspire.projectq.backend_qx import QIBackend

QI_URL = os.getenv('API_URL', 'https://api.quantum-inspire.com/')


project_name = 'ProjectQ-entangle'
authentication = get_authentication()
qi_api = QuantumInspireAPI(QI_URL, authentication, project_name=project_name)
qi_backend = QIBackend(quantum_inspire_api=qi_api)

compiler_engines = restrictedgateset.get_engine_list(one_qubit_gates=qi_backend.one_qubit_gates,
                                                     two_qubit_gates=qi_backend.two_qubit_gates)
compiler_engines.extend([ResourceCounter()])
engine = MainEngine(backend=qi_backend, engine_list=compiler_engines)

qubits = engine.allocate_qureg(2)
q1 = qubits[0]
q2 = qubits[1]

H | q1
CNOT | (q1, q2)
All(Measure) | qubits

engine.flush()

print('\nMeasured: {0}'.format([int(q) for q in qubits]))
print('Probabilities {0}'.format(qi_backend.get_probabilities(qubits)))

An example that demonstrates how to use the SDK to create a more complex circuit to run Grover’s algorithm and simulate the circuit on Quantum Inspire.

"""
This example is copied from https://github.com/ProjectQ-Framework/ProjectQ
and is covered under the Apache 2.0 license.
"""
import os
import math

from projectq import MainEngine
from projectq.backends import ResourceCounter, Simulator
from projectq.meta import Compute, Control, Loop, Uncompute
from projectq.ops import CNOT, CZ, All, H, Measure, X, Z
from projectq.setups import restrictedgateset

from quantuminspire.api import QuantumInspireAPI
from quantuminspire.credentials import get_authentication
from quantuminspire.projectq.backend_qx import QIBackend

QI_URL = os.getenv('API_URL', 'https://api.quantum-inspire.com/')


def run_grover(eng, n, oracle):
    """
    Runs Grover's algorithm on n qubit using the provided quantum oracle.

    Args:
        eng (MainEngine): Main compiler engine to run Grover on.
        n (int): Number of bits in the solution.
        oracle (function): Function accepting the engine, an n-qubit register,
            and an output qubit which is flipped by the oracle for the correct
            bit string.

    Returns:
        solution (list<int>): Solution bit-string.
    """
    x = eng.allocate_qureg(n)

    # start in uniform superposition
    All(H) | x

    # number of iterations we have to run:
    num_it = int(math.pi / 4. * math.sqrt(1 << n))

    # prepare the oracle output qubit (the one that is flipped to indicate the
    # solution. start in state 1/sqrt(2) * (|0> - |1>) s.t. a bit-flip turns
    # into a (-1)-phase.
    oracle_out = eng.allocate_qubit()
    X | oracle_out
    H | oracle_out

    # run num_it iterations
    with Loop(eng, num_it):
        # oracle adds a (-1)-phase to the solution
        oracle(eng, x, oracle_out)

        # reflection across uniform superposition
        with Compute(eng):
            All(H) | x
            All(X) | x

        with Control(eng, x[0:-1]):
            Z | x[-1]

        Uncompute(eng)

    All(Measure) | x
    Measure | oracle_out

    eng.flush()
    # return result
    return [int(qubit) for qubit in x]


def alternating_bits_oracle(eng, qubits, output):
    """
    Marks the solution string 1,0,1,0,...,0,1 by flipping the output qubit,
    conditioned on qubits being equal to the alternating bit-string.

    Args:
        eng (MainEngine): Main compiler engine the algorithm is being run on.
        qubits (Qureg): n-qubit quantum register Grover search is run on.
        output (Qubit): Output qubit to flip in order to mark the solution.
    """
    with Compute(eng):
        All(X) | qubits[1::2]
    with Control(eng, qubits):
        X | output
    Uncompute(eng)


# Remote Quantum-Inspire backend
authentication = get_authentication()
qi = QuantumInspireAPI(QI_URL, authentication)
qi_backend = QIBackend(quantum_inspire_api=qi)

compiler_engines = restrictedgateset.get_engine_list(one_qubit_gates=qi_backend.one_qubit_gates,
                                                     two_qubit_gates=qi_backend.two_qubit_gates,
                                                     other_gates=qi_backend.three_qubit_gates)
compiler_engines.extend([ResourceCounter()])
qi_engine = MainEngine(backend=qi_backend, engine_list=compiler_engines)

# Run remote Grover search to find a n-bit solution
result_qi = run_grover(qi_engine, 3, alternating_bits_oracle)
print("\nResult from the remote Quantum-Inspire backend: {}".format(result_qi))

# Local ProjectQ simulator backend
compiler_engines = restrictedgateset.get_engine_list(one_qubit_gates="any", two_qubit_gates=(CNOT, CZ))
compiler_engines.append(ResourceCounter())
local_engine = MainEngine(Simulator(), compiler_engines)

# Run local Grover search to find a n-bit solution
result_local = run_grover(local_engine, 3, alternating_bits_oracle)
print("Result from the local ProjectQ simulator backend: {}\n".format(result_local))

Qiskit examples

A simple example that demonstrates how to use the SDK to create a circuit to create a Bell state, and simulate the circuit on Quantum Inspire.

"""Example usage of the Quantum Inspire backend with the Qiskit SDK.

A simple example that demonstrates how to use the SDK to create
a circuit to create a Bell state, and simulate the circuit on
Quantum Inspire.

For documentation on how to use Qiskit we refer to
[https://qiskit.org/](https://qiskit.org/).

Specific to Quantum Inspire is the creation of the QI instance, which is used to set the authentication
of the user and provides a Quantum Inspire backend that is used to execute the circuit.

Copyright 2018-2022 QuTech Delft. Licensed under the Apache License, Version 2.0.
"""
import os

from qiskit import transpile
from qiskit.circuit import QuantumRegister, ClassicalRegister, QuantumCircuit

from quantuminspire.credentials import get_authentication
from quantuminspire.qiskit import QI

QI_URL = os.getenv('API_URL', 'https://api.quantum-inspire.com/')


project_name = 'Qiskit-entangle'
authentication = get_authentication()
QI.set_authentication(authentication, QI_URL, project_name=project_name)
qi_backend = QI.get_backend('QX single-node simulator')

q = QuantumRegister(2)
b = ClassicalRegister(2)
circuit = QuantumCircuit(q, b)

circuit.h(q[0])
circuit.cx(q[0], q[1])
circuit.measure(q, b)

circuit = transpile(circuit, backend=qi_backend)
qi_job = qi_backend.run(circuit, shots=256)
qi_result = qi_job.result()
histogram = qi_result.get_counts(circuit)
print('\nState\tCounts')
[print('{0}\t\t{1}'.format(state, counts)) for state, counts in histogram.items()]
# Print the full state probabilities histogram
probabilities_histogram = qi_result.get_probabilities(circuit)
print('\nState\tProbabilities')
[print('{0}\t\t{1}'.format(state, val)) for state, val in probabilities_histogram.items()]

A simple example that demonstrates how to use the SDK to create a circuit to demonstrate conditional gate execution.

"""Example usage of the Quantum Inspire backend with the Qiskit SDK.

A simple example that demonstrates how to use the SDK to create
a circuit to demonstrate conditional gate execution.

For documentation on how to use Qiskit we refer to
[https://qiskit.org/](https://qiskit.org/).

Specific to Quantum Inspire is the creation of the QI instance, which is used to set the authentication
of the user and provides a Quantum Inspire backend that is used to execute the circuit.

Copyright 2018-2022 QuTech Delft. Licensed under the Apache License, Version 2.0.
"""
import os

from qiskit import transpile
from qiskit.providers.basic_provider import BasicProvider
from qiskit.circuit import QuantumRegister, ClassicalRegister, QuantumCircuit

from quantuminspire.credentials import get_authentication
from quantuminspire.qiskit import QI

QI_URL = os.getenv('API_URL', 'https://api.quantum-inspire.com/')


authentication = get_authentication()
QI.set_authentication(authentication, QI_URL)
qi_backend = QI.get_backend('QX single-node simulator')

q = QuantumRegister(3, "q")
c0 = ClassicalRegister(1, "c0")
c1 = ClassicalRegister(1, "c1")
c2 = ClassicalRegister(1, "c2")
qc = QuantumCircuit(q, c0, c1, c2, name="conditional")

qc.h(q[0])
qc.h(q[1]).c_if(c0, 0)  # h-gate on q[1] is executed
qc.h(q[2]).c_if(c1, 1)  # h-gate on q[2] is not executed

qc.measure(q[0], c0)
qc.measure(q[1], c1)
qc.measure(q[2], c2)

qc = transpile(qc, backend=qi_backend)
qi_job = qi_backend.run(qc, shots=1024)
qi_result = qi_job.result()
histogram = qi_result.get_counts(qc)
print("\nResult from the remote Quantum Inspire backend:\n")
print('State\tCounts')
[print('{0}\t{1}'.format(state, counts)) for state, counts in histogram.items()]

print("\nResult from the local Qiskit simulator backend:\n")
backend = BasicProvider().get_backend(name="basic_simulator")   # qasm_simulator
qc = transpile(qc, backend=backend)
job = backend.run(qc, shots=1024)

result = job.result()
print(result.get_counts(qc))

Back to the main page.