Import and export circuits

from mimiqcircuits import *

In this section we introduce different options to import and export circuits. In particular, MIMIQ allows to import circuits in well-known languages such as OpenQASM and Stim, as well as save and import circuits using its own Protobuf structure.

Protobuf

Export Protobuf files from MIMIQ

After building a circuit in MIMIQ you can export it into a Protobuf format using the saveproto() function. You need to give it two arguments, the name of the file to create (pb format) and the circuit to save.

results.saveproto("my_circuit.pb")

The same method allows you to save your simulation results in a Protobuf file.

# get the results
results = conn.get_results(job)
# save the results
results.saveproto("my_results.pb")

Experiments, models and other objects have the same saveproto method and loadproto static method: Hamiltonian, NoiseModel, OptimizationExperiment, SweepExperiment and EquivalenceExperiment. A sweep keeps its symbolic circuit and its whole table of values, and an equivalence experiment keeps both circuits and its method.

Note

Protobuf is a serialized file format developed by google. It is very lightweight and efficient to parse. Check the Protobuf repository for more information.

Note

You can only export a circuit into Protobuf format and cannot export an OpenQASM or Stim file in the current version of MIMIQ.

Import Protobuf file to MIMIQ

MIMIQ allows you to import Protobuf circuit files using the loadproto() function and import Protobuf results file using loadproto(). With this function you can get previously saved circuit or get previous simulation results. You need to give this function the name of the file to parse and the type of object to parse.

# Import circuit from Protobuf to MIMIQ
circuit = Circuit.loadproto("my_circuit.pb")

# Import results from Protobuf to MIMIQ
results = QCSResults.loadproto("my_results.pb")

The circuit imported with loadproto() can be manipulated like any other circuit on MIMIQ to add or insert gates, see circuit page.

OpenQASM

Open Quantum Assembly Language is a programming language designed for describing quantum circuits and algorithms for execution on quantum computers. It is a very convenient middle ground for different quantum computer architectures to interpret and execute circuits.

Execute OpenQASM file in MIMIQ

The remote MIMIQ services can readily process and execute OpenQASM files, thanks to fast and feature-complete Julia and C++ parsers and interpreters.

Here is a simple comprehensive example of executing a QASM file on MIMIQ.

>>> qasm = """
... // Implementation of Deutsch algorithm with two qubits for f(x)=x
... // taken from https://github.com/pnnl/QASMBench/blob/master/small/deutsch_n2/deutsch_n2.qasm
... OPENQASM 2.0;
... include "qelib1.inc";
... qreg q[2];
... creg c[2];
... x q[1];
... h q[0];
... h q[1];
... cx q[0],q[1];
... h q[0];
... measure q[0] -> c[0];
... measure q[1] -> c[1];
... """

# Write the OPENQASM as a file
>>> with open("/tmp/deutsch_n2.qasm", "w") as file:
...     file.write(qasm)
308

# actual execution of the QASM file
>>> job = conn.submit("/tmp/deutsch_n2.qasm", algorithm="statevector")
>>> res = conn.get_result(job)
>>> res.histogram()
{bs"11": 514, bs"10": 486}
>>> from mimiqcircuits.visualization import *

# Visualizing the result
>>> plothistogram(res)
<Figure size 960x720 with 1 Axes>

The result will be plotted as follows:

Alternative Text

For more informations, read the documentation of submit().

Behaviour of include files

A common file used by many QASM files is the qelib1.inc file. This file is not defined as being part of OpenQASM 2.0, but its usage is so widespread that it might be considered as de-facto part of the specifications.

details

We remind the careful reader that OpenQASM 2.0 specifications only define 6 operations: U, CX, measure, reset, barrier and if.

If we were to parse every file together with qelib1.inc, we would have at the end just a list of simple U and CX gates, leaving behind any speed improvement that we would gain by using more complex gates as blocks. For this reason, if you don’t explicitly provide the include files, MIMIQ will not parse the usual qelib1.inc file but will instead use a simplified version of it, where almost all gate definitions are replaced by opaque definitions. These opaque definitions will be converted to the corresponding MIMIQ gates listed in `GATES`().

Another alternative is to use the mimiqlib.inc directly in your file. For now it’s almost a copy of the modified qelib1.inc but in the future it will be extended to contain more gates and operations, diverging from qelib1.inc.

Parse OpenQASM locally

You can parse OpenQASM 2.0 code directly into a MIMIQ Circuit object using the mimiqcircuits.qasm module. This is useful for importing circuits from other tools, analyzing them, or modifying them before execution.

The parsing process involves two steps:

  1. Parsing: Converts the QASM source (string) into an Abstract Syntax Tree (AST) using loads() or load().

  2. Interpretation: Converts the AST into a Circuit.

>>> from mimiqcircuits.qasm import loads
>>> qasm_source = """
... OPENQASM 2.0;
... include "qelib1.inc";
... qreg q[2];
... h q[0];
... cx q[0], q[1];
... """
>>> circuit = loads(qasm_source)
>>> print(f"Circuit with {circuit.num_qubits()} qubits") # compact print for doctest
Circuit with 2 qubits

You can also load directly from a file:

from mimiqcircuits.qasm import load
circuit = load("my_circuit.qasm")

Export to OpenQASM

Any MIMIQ Circuit can be exported back to OpenQASM 2.0 format. This supports standard gates as well as custom gate definitions.

  • dumps(): Returns the QASM representation of the circuit as a string.

  • dump(): Writes the QASM representation directly to a file.

>>> from mimiqcircuits.qasm import dumps
>>> qasm_out = dumps(circuit)
>>> print(qasm_out)
OPENQASM 2.0;
include "qelib1.inc";
qreg q[2];
h q[0];
cx q[0],q[1];

Relations between OpenQASM registers and MIMIQ indices

During the parsing of the QASM file, we will assign a unique index to each qubit and classical bit. This index will be used to identify the qubit or bit in the MIMIQ-CIRC service.

The indices are assigned in the following way:

  • The first qubit is assigned index 0 (Python), the second 1, and so on.

  • All registers retain the same ordering as in the QASM file.

  • Qubits and classical bits behave similarly but have they have each other its own sequence from indices, starting from 0.

A simple example will clarify this behaviour:

OPENQASM 2.0;
qreg q[2];
creg m[10];
qreg a[10];
creg g[2];

Will be parsed as:

QASM name

MIMIQ Qubit index

MIMIQ Bit index

q[0]

0

q[1]

1

a[0]

2

a[1]

3

...

...

...

a[9]

11

m[0]

0

m[1]

1

...

...

...

m[9]

0

g[0]

10

g[1]

11

Stim

Execute Stim file on MIMIQ

Stim is a fast stabilizer circuit simulator commonly used for Clifford circuit simulation. Stim allows users to export their circuit to a text format usually with the stim extention. The remote MIMIQ services can readily process and execute Stim files as follows:

job = conn.submit("my_stim_circuit.stim")

Warning

The support of Stim is still in progress and some of the most specific Stim features are not supported. For instance, detectors will be completely ignored by MIMIQ at exectution time.

The results of the simulation can be accessed as usual on MIMIQ, see remote execution page.

Reference

saveproto(self, file)

Save the circuit to a protobuf (binary) file.

Symbolic parameters are saved as expressions. Read the file back with loadproto().

Parameters:

file – A file path or a binary file-like object to write to.

Returns:

The number of bytes written.

Return type:

int

Examples

>>> from mimiqcircuits import *
>>> from symengine import *
>>> import tempfile
>>> x, y = symbols("x y")
>>> c = Circuit()
>>> c.push(GateH(), 0)
1-qubit circuit with 1 instruction:
└── H @ q[0]

>>> c.push(GateXXplusYY(x**2, y),0,1)
2-qubit circuit with 2 instructions:
├── H @ q[0]
└── XXplusYY(x**2, y) @ q[0:1]

>>> c.push(Measure(),0,0)
2-qubit, 1-bit circuit with 3 instructions:
├── H @ q[0]
├── XXplusYY(x**2, y) @ q[0:1]
└── M @ q[0], c[0]

>>> # a temporary file keeps the example self-contained; any path works
>>> tmpfile = tempfile.NamedTemporaryFile(suffix=".pb", delete=True)
>>> c.saveproto(tmpfile.name)
64
>>> Circuit.loadproto(tmpfile.name)
2-qubit, 1-bit circuit with 3 instructions:
├── H @ q[0]
├── XXplusYY(x**2, y) @ q[0:1]
└── M @ q[0], c[0]
loadproto(file)

Load a circuit from a protobuf (binary) file written by saveproto().

Parameters:

file – A file path or a binary file-like object to read from.

Returns:

The loaded circuit.

Return type:

Circuit

Raises:

ValueError – If the file cannot be parsed.

See also

saveproto(), which has an example of saving and loading.

saveproto(self, file)

Save the results to a protobuf file.

Parameters:

file (str or file-like) – A path, or a binary file object with a write method.

Returns:

The number of bytes written.

Return type:

int

Raises:

ValueError – If the file cannot be written.

Examples

>>> from mimiqcircuits import *
>>> import os, tempfile
>>> res = QCSResults(
...     simulator="MIMIQ-StateVector",
...     version="1.0",
...     cstates=[BitString("01"), BitString("01"), BitString("10")],
... )

Write the results to a file, then read them back with the static method loadproto().

>>> path = os.path.join(tempfile.mkdtemp(), "results.pb")
>>> nbytes = res.saveproto(path)
>>> loaded = QCSResults.loadproto(path)
>>> loaded.histogram() == res.histogram()
True
loadproto(file)

Load results from a protobuf file written by saveproto().

This is a static method: call it on the class.

Parameters:

file (str or file-like) – A path, or a binary file object with a read method.

Returns:

The loaded results.

Return type:

QCSResults

Raises:

ValueError – If the file cannot be read or parsed.

See also

saveproto(), which has an example.

load(filename, includedirs=None)[source]

Read an OpenQASM 2.0 program from a file.

Same as loads() on the file’s content, with the file’s own directory added to the front of includedirs.

Parameters:
  • filename (str) – The path of the file.

  • includedirs (List[str]) – Extra directories to search for included files. Defaults to None.

Returns:

The circuit described by the program.

Return type:

Circuit

Raises:
  • FileNotFoundError – If the file does not exist.

  • ParseError – If the source is not valid OpenQASM 2.0 syntax or an included file is not found.

  • QASMError – If the program cannot be interpreted.

Examples

Write a circuit to a file with dump() and read it back.

>>> from mimiqcircuits import *
>>> from mimiqcircuits import qasm
>>> import os, tempfile
>>> c = Circuit()
>>> c.push(GateH(), 0)
1-qubit circuit with 1 instruction:
└── H @ q[0]

>>> path = os.path.join(tempfile.mkdtemp(), "circuit.qasm")
>>> qasm.dump(c, path)
>>> qasm.load(path)
1-qubit circuit with 1 instruction:
└── H @ q[0]
loads(s, includedirs=None)[source]

Read an OpenQASM 2.0 program from a string.

Quantum registers are laid out one after the other on the circuit’s qubits in order of declaration, and classical registers likewise on its bits. include files are looked up in the current directory, then in the directory of files bundled with the package (which provides qelib1.inc), then in includedirs.

Parameters:
  • s (str) – The OpenQASM 2.0 source.

  • includedirs (List[str]) – Extra directories to search for included files. Defaults to None.

Returns:

The circuit described by the program.

Return type:

Circuit

Raises:
  • ParseError – If the source is not valid OpenQASM 2.0 syntax or an included file is not found.

  • QASMError – If the program cannot be interpreted, for example because it uses an undeclared gate or register (see the subclasses in mimiqcircuits.qasm).

Examples

>>> from mimiqcircuits import *
>>> from mimiqcircuits import qasm

A Bell-state program using gates from qelib1.inc.

>>> src = '''
... OPENQASM 2.0;
... include "qelib1.inc";
... qreg q[2];
... creg c[2];
... h q[0];
... cx q[0],q[1];
... measure q -> c;
... '''
>>> qasm.loads(src)
2-qubit, 2-bit circuit with 4 instructions:
├── H @ q[0]
├── CX @ q[0], q[1]
├── M @ q[0], c[0]
└── M @ q[1], c[1]
dump(c, filename, decompose_wrappers=False, sanitize_names=True)[source]

Write a circuit as an OpenQASM 2.0 program to a file.

The file is overwritten, unless serialization fails. See dumps() for how the circuit is written; load() reads the file back.

Parameters:
  • c (Circuit) – The circuit to write.

  • filename (str) – The path of the file.

  • decompose_wrappers (bool) – Not used.

  • sanitize_names (bool) – If True, rewrite gate declaration names into valid OpenQASM identifiers. Defaults to True.

Raises:
dumps(c, decompose_wrappers=False, sanitize_names=True)[source]

Write a circuit as an OpenQASM 2.0 program.

Operations that OpenQASM 2.0 cannot express directly are decomposed into qelib1.inc gates, and gate declarations (GateDecl) become gate definitions. All qubits go in one register q and all bits in one register c.

Parameters:
  • c (Circuit) – The circuit to write.

  • decompose_wrappers (bool) – Not used.

  • sanitize_names (bool) – If True, rewrite gate declaration names into valid OpenQASM identifiers. If False, an invalid name raises QASMSerializationError. Defaults to True.

Returns:

The OpenQASM 2.0 source.

Return type:

str

Raises:
  • DecompositionError – If an operation cannot be decomposed into the OpenQASM 2.0 basis, such as a noise channel or a classical or z-variable operation.

  • QASMSerializationError – If a name or an IfStatement condition cannot be expressed in OpenQASM 2.0.

Examples

>>> from mimiqcircuits import *
>>> from mimiqcircuits import qasm
>>> c = Circuit()
>>> c.push(GateH(), 0)
1-qubit circuit with 1 instruction:
└── H @ q[0]

>>> c.push(GateCX(), 0, 1)
2-qubit circuit with 2 instructions:
├── H @ q[0]
└── CX @ q[0], q[1]

>>> c.push(Measure(), range(2), range(2))
2-qubit, 2-bit circuit with 4 instructions:
├── H @ q[0]
├── CX @ q[0], q[1]
├── M @ q[0], c[0]
└── M @ q[1], c[1]

>>> print(qasm.dumps(c))
OPENQASM 2.0;
include "qelib1.inc";
qreg q[2];
creg c[2];
h q[0];
cx q[0],q[1];
measure q[0] -> c[0];
measure q[1] -> c[1];