Make a Blueqat backend ~ Part 1

Blueqat library for easy quantum programming

Is developing. https://github.com/Blueqat/Blueqat

Blueqat backend?

Blueqat has a numpy simulator,

――I want to run a faster simulator ――I want to move the actual machine instead of the simulator ――I want to do something different --Get the unitary matrix of the circuit --Output the circuit in OpenQ ASM format

It is designed so that functions can be added in the form of "back end" so that it can be used for such purposes.

In some cases, such as "I made a simulator myself, but it is troublesome to make an interface", it may be convenient to make an appropriate backend.

This time, I will explain how to create a backend for a simulator that can accept OpenQ ASM input. OpenQASM input may be rarely accepted, but if possible, backend creation will be significantly easier.

A backend that takes OpenQASM input and returns the result

If your own simulator accepts OpenQ ASM input, this is the easiest way to create it. Just pass the function that receives OpenQASM and returns the result to the blueqat.backends.qasm_parser_backend_generator.generate_backend function.

Let's take a look at the IBM Q backend, which creates the backend that way. https://github.com/Blueqat/Blueqat/blob/master/blueqat/backends/ibmq_backend.py

First of all, take a quick look at everything


def _qasm_runner_qiskit(qasm, qiskit_backend=None, shots=None, returns=None, **kwargs):
    if returns is None:
        returns = "shots"
    elif returns not in ("shots", "draw", "_exception",
                         "qiskit_circuit", "qiskit_job", "qiskit_result"):
        raise ValueError("`returns` shall be None, 'shots', 'draw', " +
                         "'qiskit_circuit', 'qiskit_job', 'qiskit_result' or '_exception'")

    import_error = None
    try:
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            from qiskit import Aer, QuantumCircuit, execute
    except Exception as e:
        import_error = e

    if import_error:
        if returns == "_exception":
            return e
        if isinstance(import_error, ImportError):
            raise ImportError("Cannot import qiskit. To use this backend, please install qiskit." +
                              " `pip install qiskit`.")
        else:
            raise ValueError("Unknown error raised when importing qiskit. To get exception, " +
                             'run this backend with arg `returns="_exception"`')
    else:
        if returns == "_exception":
            return None
        qk_circuit = QuantumCircuit.from_qasm_str(qasm)
        if returns == "qiskit_circuit":
            return qk_circuit
        if returns == "draw":
            return qk_circuit.draw(**kwargs)
        if shots is None:
            shots = 1024
        if qiskit_backend is None:
            qiskit_backend = Aer.get_backend("qasm_simulator")
        job = execute(qk_circuit, backend=qiskit_backend, shots=shots, **kwargs)
        if returns == "qiskit_job":
            return job
        result = job.result()
        if returns == "qiskit_result":
            return result
        counts = Counter({bits[::-1]: val for bits, val in result.get_counts().items()})
        return counts

ibmq_backend = generate_backend(_qasm_runner_qiskit)

If you write like Circuit (). h [0] .m [:] .run (backend ='ibmq', qiskit_backend = ..., ...), it is _qasm_runner_qiskit (the circuit is converted to OpenQASM). , qiskit_backend = ..., ...) is called. Let's see how it behaves when called.

    if returns is None:
        returns = "shots"
    elif returns not in ("shots", "draw", "_exception",
                         "qiskit_circuit", "qiskit_job", "qiskit_result"):
        raise ValueError("`returns` shall be None, 'shots', 'draw', " +
                         "'qiskit_circuit', 'qiskit_job', 'qiskit_result' or '_exception'")

This area is processing the received arguments. Blueqat backends often accept an argument called returns, where you can specify what type of result you want to return.

In the default numpy backend, you can select the state vector or the measurement result, and in ibmq, you can get the measurement result, the circuit in Qiskit, the Job object, and so on. You can also return an object that is used internally for debugging. However, it is highly recommended to provide the default behavior so that it works without returns.

    import_error = None
    try:
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            from qiskit import Aer, QuantumCircuit, execute
    except Exception as e:
        import_error = e

    if import_error:
        if returns == "_exception":
            return e
        if isinstance(import_error, ImportError):
            raise ImportError("Cannot import qiskit. To use this backend, please install qiskit." +
                              " `pip install qiskit`.")
        else:
            raise ValueError("Unknown error raised when importing qiskit. To get exception, " +
                             'run this backend with arg `returns="_exception"`')

Above, in order to make Blueqat itself work even if qiskit is not installed, I am trying to import it when calling a function. Also, for a while, when I imported qiskit, a warning was issued, so I am also working to suppress it.

    else:
        if returns == "_exception":
            return None
        qk_circuit = QuantumCircuit.from_qasm_str(qasm)
        if returns == "qiskit_circuit":
            return qk_circuit
        if returns == "draw":
            return qk_circuit.draw(**kwargs)
        if shots is None:
            shots = 1024
        if qiskit_backend is None:
            qiskit_backend = Aer.get_backend("qasm_simulator")

While preparing to run the Qiskit simulator, some returns are returning results before running the simulator.

        job = execute(qk_circuit, backend=qiskit_backend, shots=shots, **kwargs)
        if returns == "qiskit_job":
            return job

I'm running a Qiskit simulator. If you specified returns to return a Qiskit job, it will return the job.

        result = job.result()
        if returns == "qiskit_result":
            return result
        counts = Counter({bits[::-1]: val for bits, val in result.get_counts().items()})
        return counts

It takes the result from the job, formats it into the format used by other Blueqat backends, and returns the result.

ibmq_backend = generate_backend(_qasm_runner_qiskit)

Pass in the function we saw above to create the backend.

Backend registration and use

The created backend cannot be used with Blueqat unless it is registered.

Backend registration


from blueqat import BlueqatGlobalSetting
# BlueqatGlobalSetting.register_backend(Backend name,Back end)
BlueqatGlobalSetting.register_backend(”myibmq”, ibmq_backend)

I was able to register a backend with the name myibmq.

Use the back end


Circuit().h[0].m[:].run_with_myibmq()
#Or
Circuit().h[0].m[:].run(backend=”myibmq”)

You can use the one registered in the form of run_with_ backend name ().

Set the backend to default


BlueqatGlobalSetting.set_default_backend(”myibmq”)

I was able to set the registered backend as the default.

Summary

It turns out that a simulator that accepts OpenQASM as input can support Blueqat quite easily.

Blueqat can be implemented with a little effort even if it is not. We will look at that in the future.

Recommended Posts

Make a Blueqat backend ~ Part 1
Make a Blueqat backend ~ Part 2
Let's make a Backend plugin for Errbot
Make a squash game
Make a function decorator
Make a distance matrix
I'll make a password!
Make a Nyan button
Make a Tetris-style game!
Make a Base64 decoder
How to make a shooting game with toio (Part 1)
Let's make a Discord Bot.
Make a tky2jgd plugin with no practicality in QGIS Part 2
How to make a hacking lab-Kali Linux (2020.1) VirtualBox 64-bit Part 2-
Make a tky2jgd plugin with no practicality in QGIS Part 1
[Django] Make a pull-down menu
Make a LINE BOT (chat)
Let's make Splatoon AI! part.1
Make a bookmarklet in Python
Make a fortune with Python
Make Responder a daemon (service)
Let's make a rock-paper-scissors game
Make a fire with kdeplot
Make a math drill print
Let's make a WEB application for phone book with flask Part 1
Make a cat detector with Google Colabratory (Part 2) [Python] ~ Use OpenCV ~
Let's make a WEB application for phone book with flask Part 2
Make a thermometer with Raspberry Pi and make it viewable with a browser Part 4
How to make a unit test Part.1 Design pattern for introduction
Let's make a WEB application for phone book with flask Part 3
Let's make a WEB application for phone book with flask Part 4
Let's make a remote rumba [Hardware]
How to make a Japanese-English translation
Make a Santa classifier from a Santa image
Play with a turtle with turtle graphics (Part 1)
Let's make a remote rumba [Software]
Make a Tweet box for Pepper
Let's make a GUI with python.
Make a sound with Jupyter notebook
Let's make a spot sale service 2
Make a face recognizer using TensorFlow
How to make a slack bot
Let's make a breakout with wxPython
Let's make a spot sale service 1
How to make a crawler --Advanced
How to make a recursive function
Make C compilation a little easier
python / Make a dict from a list.
[Python] Make the function a lambda function
Make a recommender system with python
How to make a deadman's switch
[Blender] How to make a Blender plugin
Make Flask a Cloud Native application
Make a filter with a django template
[LINE bot] I'm a ranger! Part 2
Let's make a graph with python! !!
Let's make a supercomputer with xCAT
How to make a crawler --Basic
Make a model iterator with PySide
Make a nice graph with plotly
Make a curtain generator in Blender