# backends¶

 projectq.backends.CommandPrinter([…]) CommandPrinter is a compiler engine which prints commands to stdout prior to sending them on to the next compiler engine. projectq.backends.CircuitDrawer([…]) CircuitDrawer is a compiler engine which generates TikZ code for drawing quantum circuits. projectq.backends.Simulator([gate_fusion, …]) Simulator is a compiler engine which simulates a quantum computer using C++-based kernels. projectq.backends.ClassicalSimulator() A simple introspective simulator that only permits classical operations. projectq.backends.ResourceCounter() ResourceCounter is a compiler engine which counts the number of gates and max. projectq.backends.IBMBackend([use_hardware, …]) The IBM Backend class, which stores the circuit, transforms it to JSON QASM, and sends the circuit through the IBM API.

## Module contents¶

Contains back-ends for ProjectQ.

This includes:

• a debugging tool to print all received commands (CommandPrinter)
• a circuit drawing engine (which can be used anywhere within the compilation chain)
• a simulator with emulation capabilities
• a resource counter (counts gates and keeps track of the maximal width of the circuit)
• an interface to the IBM Quantum Experience chip (and simulator).
class projectq.backends.CircuitDrawer(accept_input=False, default_measure=0)[source]

CircuitDrawer is a compiler engine which generates TikZ code for drawing quantum circuits.

The circuit can be modified by editing the settings.json file which is generated upon first execution. This includes adjusting the gate width, height, shadowing, line thickness, and many more options.

After initializing the CircuitDrawer, it can also be given the mapping from qubit IDs to wire location (via the set_qubit_locations() function):

circuit_backend = CircuitDrawer()
circuit_backend.set_qubit_locations({0: 1, 1: 0}) # swap lines 0 and 1
eng = MainEngine(circuit_backend)

... # run quantum algorithm on this main engine

print(circuit_backend.get_latex()) # prints LaTeX code


To see the qubit IDs in the generated circuit, simply set the draw_id option in the settings.json file under “gates”:”AllocateQubitGate” to True:

"gates": {
"AllocateQubitGate": {
"draw_id": True,
"height": 0.15,
"width": 0.2,
"pre_offset": 0.1,
"offset": 0.1
},
...


The settings.json file has the following structure:

{
"control": { # settings for control "circle"
"size": 0.1
},
"gates": {
"GateClassString": {
GATE_PROPERTIES
}
"GateClassString2": {
...
},
"lines": { # settings for qubit lines
"double_classical": true, # draw double-lines for
# classical bits
"double_lines_sep": 0.04, # gap between the two lines
# for double lines
"init_quantum": true, # start out with quantum bits
"style": "very thin" # line style
}
}


All gates (except for the ones requiring special treatment) support the following properties:

"GateClassString": {
"height": GATE_HEIGHT,
"width": GATE_WIDTH
"pre_offset": OFFSET_BEFORE_PLACEMENT,
"offset": OFFSET_AFTER_PLACEMENT,
},

__init__(accept_input=False, default_measure=0)[source]

Initialize a circuit drawing engine.

The TikZ code generator uses a settings file (settings.json), which can be altered by the user. It contains gate widths, heights, offsets, etc.

Parameters: accept_input (bool) – If accept_input is true, the printer queries the user to input measurement results if the CircuitDrawer is the last engine. Otherwise, all measurements yield the result default_measure (0 or 1). default_measure (bool) – Default value to use as measurement results if accept_input is False and there is no underlying backend to register real measurement results.
get_latex()[source]

Return the latex document string representing the circuit.

Simply write this string into a tex-file or, alternatively, pipe the output directly to, e.g., pdflatex:

python3 my_circuit.py | pdflatex


where my_circuit.py calls this function and prints it to the terminal.

is_available(cmd)[source]

Specialized implementation of is_available: Returns True if the CircuitDrawer is the last engine (since it can print any command).

Parameters: cmd (Command) – Command for which to check availability (all Commands can be printed). True, unless the next engine cannot handle the Command (if there is a next engine). availability (bool)
receive(command_list)[source]

Receive a list of commands from the previous engine, print the commands, and then send them on to the next engine.

Parameters: command_list (list) – List of Commands to print (and potentially send on to the next engine).
set_qubit_locations(id_to_loc)[source]

Sets the qubit lines to use for the qubits explicitly.

To figure out the qubit IDs, simply use the setting draw_id in the settings file. It is located in “gates”:”AllocateQubitGate”. If draw_id is True, the qubit IDs are drawn in red.

Parameters: id_to_loc (dict) – Dictionary mapping qubit ids to qubit line numbers. RuntimeError – If the mapping has already begun (this function needs be called before any gates have been received).
class projectq.backends.ClassicalSimulator[source]

A simple introspective simulator that only permits classical operations.

Allows allocation, deallocation, measuring (no-op), flushing (no-op), controls, NOTs, and any BasicMathGate. Supports reading/writing directly from/to bits and registers of bits.

__init__()[source]

Initialize the basic engine.

Initializes local variables such as _next_engine, _main_engine, etc. to None.

is_available(cmd)[source]

Default implementation of is_available: Ask the next engine whether a command is available, i.e., whether it can be executed by the next engine(s).

Parameters: cmd (Command) – Command for which to check availability. True if the command can be executed. LastEngineException – If is_last_engine is True but is_available is not implemented.
read_bit(qubit)[source]

Note

If there is a mapper present in the compiler, this function automatically converts from logical qubits to mapped qubits for the qureg argument.

Parameters: qubit (projectq.types.Qubit) – The bit to read. 0 if the target bit is off, 1 if it’s on. int
read_register(qureg)[source]

Reads a group of bits as a little-endian integer.

Note

If there is a mapper present in the compiler, this function automatically converts from logical qubits to mapped qubits for the qureg argument.

Parameters: qureg (projectq.types.Qureg) – The group of bits to read, in little-endian order. Little-endian register value. int
write_bit(qubit, value)[source]

Resets/sets a bit to the given value.

Note

If there is a mapper present in the compiler, this function automatically converts from logical qubits to mapped qubits for the qureg argument.

Parameters: qubit (projectq.types.Qubit) – The bit to write. value (bool|int) – Writes 1 if this value is truthy, else 0.
write_register(qureg, value)[source]

Sets a group of bits to store a little-endian integer value.

Note

If there is a mapper present in the compiler, this function automatically converts from logical qubits to mapped qubits for the qureg argument.

Parameters: qureg (projectq.types.Qureg) – The bits to write, in little-endian order. value (int) – The integer value to store. Must fit in the register.
class projectq.backends.CommandPrinter(accept_input=True, default_measure=False, in_place=False)[source]

CommandPrinter is a compiler engine which prints commands to stdout prior to sending them on to the next compiler engine.

__init__(accept_input=True, default_measure=False, in_place=False)[source]

Initialize a CommandPrinter.

Parameters: accept_input (bool) – If accept_input is true, the printer queries the user to input measurement results if the CommandPrinter is the last engine. Otherwise, all measurements yield default_measure. default_measure (bool) – Default measurement result (if accept_input is False). in_place (bool) – If in_place is true, all output is written on the same line of the terminal.
is_available(cmd)[source]

Specialized implementation of is_available: Returns True if the CommandPrinter is the last engine (since it can print any command).

Parameters: cmd (Command) – Command of which to check availability (all Commands can be printed). True, unless the next engine cannot handle the Command (if there is a next engine). availability (bool)
receive(command_list)[source]

Receive a list of commands from the previous engine, print the commands, and then send them on to the next engine.

Parameters: command_list (list) – List of Commands to print (and potentially send on to the next engine).
class projectq.backends.IBMBackend(use_hardware=False, num_runs=1024, verbose=False, user=None, password=None, device='ibmqx4', num_retries=3000, interval=1, retrieve_execution=None)[source]

The IBM Backend class, which stores the circuit, transforms it to JSON QASM, and sends the circuit through the IBM API.

__init__(use_hardware=False, num_runs=1024, verbose=False, user=None, password=None, device='ibmqx4', num_retries=3000, interval=1, retrieve_execution=None)[source]

Initialize the Backend object.

Parameters: use_hardware (bool) – If True, the code is run on the IBM quantum chip (instead of using the IBM simulator) num_runs (int) – Number of runs to collect statistics. (default is 1024) verbose (bool) – If True, statistics are printed, in addition to the measurement result being registered (at the end of the circuit). user (string) – IBM Quantum Experience user name password (string) – IBM Quantum Experience password device (string) – Device to use (‘ibmqx4’, or ‘ibmqx5’) if use_hardware is set to True. Default is ibmqx4. num_retries (int) – Number of times to retry to obtain results from the IBM API. (default is 3000) interval (float, int) – Number of seconds between successive attempts to obtain results from the IBM API. (default is 1) retrieve_execution (int) – Job ID to retrieve instead of re- running the circuit (e.g., if previous run timed out).
get_probabilities(qureg)[source]

Return the list of basis states with corresponding probabilities.

The measured bits are ordered according to the supplied quantum register, i.e., the left-most bit in the state-string corresponds to the first qubit in the supplied quantum register.

Warning

Only call this function after the circuit has been executed!

Parameters: qureg (list) – Quantum register determining the order of the qubits. Dictionary mapping n-bit strings to probabilities. probability_dict (dict) RuntimeError – If no data is available (i.e., if the circuit has not been executed). Or if a qubit was supplied which was not present in the circuit (might have gotten optimized away).
is_available(cmd)[source]

Return true if the command can be executed.

The IBM quantum chip can do X, Y, Z, T, Tdag, S, Sdag, rotation gates, barriers, and CX / CNOT.

Parameters: cmd (Command) – Command for which to check availability
receive(command_list)[source]

Receives a command list and, for each command, stores it until completion.

Parameters: command_list – List of commands to execute
class projectq.backends.ResourceCounter[source]

ResourceCounter is a compiler engine which counts the number of gates and max. number of active qubits.

gate_counts

dict – Dictionary of gate counts. The keys are tuples of the form (cmd.gate, ctrl_cnt), where ctrl_cnt is the number of control qubits.

gate_class_counts

dict – Dictionary of gate class counts. The keys are tuples of the form (cmd.gate.__class__, ctrl_cnt), where ctrl_cnt is the number of control qubits.

max_width

int – Maximal width (=max. number of active qubits at any given point).

Properties:
depth_of_dag (int): It is the longest path in the directed
acyclic graph (DAG) of the program.
__init__()[source]

Initialize a resource counter engine.

Sets all statistics to zero.

is_available(cmd)[source]

Specialized implementation of is_available: Returns True if the ResourceCounter is the last engine (since it can count any command).

Parameters: cmd (Command) – Command for which to check availability (all Commands can be counted). True, unless the next engine cannot handle the Command (if there is a next engine). availability (bool)
receive(command_list)[source]

Receive a list of commands from the previous engine, increases the counters of the received commands, and then send them on to the next engine.

Parameters: command_list (list) – List of commands to receive (and count).
class projectq.backends.Simulator(gate_fusion=False, rnd_seed=None)[source]

Simulator is a compiler engine which simulates a quantum computer using C++-based kernels.

OpenMP is enabled and the number of threads can be controlled using the OMP_NUM_THREADS environment variable, i.e.

export OMP_NUM_THREADS=4 # use 4 threads

__init__(gate_fusion=False, rnd_seed=None)[source]

Construct the C++/Python-simulator object and initialize it with a random seed.

Parameters: gate_fusion (bool) – If True, gates are cached and only executed once a certain gate-size has been reached (only has an effect for the c++ simulator). rnd_seed (int) – Random seed (uses random.randint(0, 4294967295) by default).

Example of gate_fusion: Instead of applying a Hadamard gate to 5 qubits, the simulator calculates the kronecker product of the 1-qubit gate matrices and then applies one 5-qubit gate. This increases operational intensity and keeps the simulator from having to iterate through the state vector multiple times. Depending on the system (and, especially, number of threads), this may or may not be beneficial.

Note

If the C++ Simulator extension was not built or cannot be found, the Simulator defaults to a Python implementation of the kernels. While this is much slower, it is still good enough to run basic quantum algorithms.

If you need to run large simulations, check out the tutorial in the docs which gives futher hints on how to build the C++ extension.

apply_qubit_operator(qubit_operator, qureg)[source]

Apply a (possibly non-unitary) qubit_operator to the current wave function represented by the supplied quantum register.

Parameters: qubit_operator (projectq.ops.QubitOperator) – Operator to apply. qureg (list[Qubit],Qureg) – Quantum bits to which to apply the operator. Exception – If qubit_operator acts on more qubits than present in the qureg argument.

Warning

This function allows applying non-unitary gates and it will not re-normalize the wave function! It is for numerical experiments only and should not be used for other purposes.

Note

Make sure all previous commands (especially allocations) have passed through the compilation chain (call main_engine.flush() to make sure).

Note

If there is a mapper present in the compiler, this function automatically converts from logical qubits to mapped qubits for the qureg argument.

cheat()[source]

Access the ordering of the qubits and the state vector directly.

This is a cheat function which enables, e.g., more efficient evaluation of expectation values and debugging.

Returns: A tuple where the first entry is a dictionary mapping qubit indices to bit-locations and the second entry is the corresponding state vector.

Note

Make sure all previous commands have passed through the compilation chain (call main_engine.flush() to make sure).

Note

If there is a mapper present in the compiler, this function DOES NOT automatically convert from logical qubits to mapped qubits.

collapse_wavefunction(qureg, values)[source]

Collapse a quantum register onto a classical basis state.

Parameters: qureg (Qureg|list[Qubit]) – Qubits to collapse. values (list[bool|int]|string[0|1]) – Measurement outcome for each of the qubits in qureg. RuntimeError – If an outcome has probability (approximately) 0 or if unknown qubits are provided (see note).

Note

Make sure all previous commands have passed through the compilation chain (call main_engine.flush() to make sure).

Note

If there is a mapper present in the compiler, this function automatically converts from logical qubits to mapped qubits for the qureg argument.

get_amplitude(bit_string, qureg)[source]

Return the probability amplitude of the supplied bit_string. The ordering is given by the quantum register qureg, which must contain all allocated qubits.

Parameters: bit_string (list[bool|int]|string[0|1]) – Computational basis state qureg (Qureg|list[Qubit]) – Quantum register determining the ordering. Must contain all allocated qubits. Probability amplitude of the provided bit string.

Note

Make sure all previous commands (especially allocations) have passed through the compilation chain (call main_engine.flush() to make sure).

Note

If there is a mapper present in the compiler, this function automatically converts from logical qubits to mapped qubits for the qureg argument.

get_expectation_value(qubit_operator, qureg)[source]

Get the expectation value of qubit_operator w.r.t. the current wave function represented by the supplied quantum register.

Parameters: qubit_operator (projectq.ops.QubitOperator) – Operator to measure. qureg (list[Qubit],Qureg) – Quantum bits to measure. Expectation value

Note

Make sure all previous commands (especially allocations) have passed through the compilation chain (call main_engine.flush() to make sure).

Note

If there is a mapper present in the compiler, this function automatically converts from logical qubits to mapped qubits for the qureg argument.

Raises: Exception – If qubit_operator acts on more qubits than present in the qureg argument.
get_probability(bit_string, qureg)[source]

Return the probability of the outcome bit_string when measuring the quantum register qureg.

Parameters: bit_string (list[bool|int]|string[0|1]) – Measurement outcome. qureg (Qureg|list[Qubit]) – Quantum register. Probability of measuring the provided bit string.

Note

Make sure all previous commands (especially allocations) have passed through the compilation chain (call main_engine.flush() to make sure).

Note

If there is a mapper present in the compiler, this function automatically converts from logical qubits to mapped qubits for the qureg argument.

is_available(cmd)[source]

Specialized implementation of is_available: The simulator can deal with all arbitrarily-controlled gates which provide a gate-matrix (via gate.matrix) and acts on 5 or less qubits (not counting the control qubits).

Parameters: cmd (Command) – Command for which to check availability (single- qubit gate, arbitrary controls) True if it can be simulated and False otherwise.
receive(command_list)[source]

Receive a list of commands from the previous engine and handle them (simulate them classically) prior to sending them on to the next engine.

Parameters: command_list (list) – List of commands to execute on the simulator.
set_wavefunction(wavefunction, qureg)[source]

Set the wavefunction and the qubit ordering of the simulator.

The simulator will adopt the ordering of qureg (instead of reordering the wavefunction).

Parameters: wavefunction (list[complex]) – Array of complex amplitudes describing the wavefunction (must be normalized). qureg (Qureg|list[Qubit]) – Quantum register determining the ordering. Must contain all allocated qubits.

Note

Make sure all previous commands (especially allocations) have passed through the compilation chain (call main_engine.flush() to make sure).

Note

If there is a mapper present in the compiler, this function automatically converts from logical qubits to mapped qubits for the qureg argument.