# cengines¶

The ProjectQ compiler engines package.

## Module contents¶

class projectq.cengines.AutoReplacer(decomposition_chooser=<function AutoReplacer.<lambda>>)

The AutoReplacer is a compiler engine which uses engine.is_available in order to determine which commands need to be replaced/decomposed/compiled further. The loaded setup is used to find decomposition rules appropriate for each command (e.g., setups.default).

__init__(decomposition_chooser=<function AutoReplacer.<lambda>>)

Initialize an AutoReplacer.

Parameters: decomposition_chooser (function) – A function which, given the Command to decompose and a list of potential Decomposition objects, determines (and then returns) the ‘best’ decomposition.

The default decomposition chooser simply returns the first list element, i.e., calling

repl = AutoReplacer()


Amounts to

def decomposition_chooser(cmd, decomp_list):
return decomp_list[0]
repl = AutoReplacer(decomposition_chooser)

receive(command_list)

Receive a list of commands from the previous compiler engine and, if necessary, replace/decompose the gates according to the decomposition rules in the loaded setup.

Parameters: command_list (list) – List of commands to handle.
class projectq.cengines.BasicEngine

Basic compiler engine: All compiler engines are derived from this class. It provides basic functionality such as qubit allocation/deallocation and functions that provide information about the engine’s position (e.g., next engine).

This information is provided by the MainEngine, which initializes all further engines.

next_engine

BasicEngine – Next compiler engine (or the back-end).

main_engine

MainEngine – Reference to the main compiler engine.

is_last_engine

bool – True for the last engine, which is the back-end.

__init__()

Initialize the basic engine.

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

allocate_qubit(dirty=False)

Return a new qubit as a list containing 1 qubit object (quantum register of size 1).

Allocates a new qubit by getting a (new) qubit id from the MainEngine, creating the qubit object, and then sending an AllocateQubit command down the pipeline. If dirty=True, the fresh qubit can be replaced by a pre-allocated one (in an unknown, dirty, initial state). Dirty qubits must be returned to their initial states before they are deallocated / freed.

All allocated qubits are added to the MainEngine’s set of active qubits as weak references. This allows proper clean-up at the end of the Python program (using atexit), deallocating all qubits which are still alive. Qubit ids of dirty qubits are registered in MainEngine’s dirty_qubits set.

Parameters: dirty (bool) – If True, indicates that the allocated qubit may be dirty (i.e., in an arbitrary initial state). Qureg of length 1, where the first entry is the allocated qubit.
allocate_qureg(n)

Allocate n qubits and return them as a quantum register, which is a list of qubit objects.

Parameters: n (int) – Number of qubits to allocate Qureg of length n, a list of n newly allocated qubits.
deallocate_qubit(qubit)

Deallocate a qubit (and sends the deallocation command down the pipeline). If the qubit was allocated as a dirty qubit, add DirtyQubitTag() to Deallocate command.

Parameters: qubit (BasicQubit) – Qubit to deallocate.
is_available(cmd)

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.
is_meta_tag_supported(meta_tag)

Check if there is a compiler engine handling the meta tag

Parameters: engine – First engine to check (then iteratively calls getNextEngine) meta_tag – Meta tag class for which to check support True if one of the further compiler engines is a meta tag handler, i.e., engine.is_meta_tag_handler(meta_tag) returns True. supported (bool)
send(command_list)

Forward the list of commands to the next engine in the pipeline.

class projectq.cengines.CommandModifier(cmd_mod_fun)

CommandModifier is a compiler engine which applies a function to all incoming commands, sending on the resulting command instead of the original one.

__init__(cmd_mod_fun)

Initialize the CommandModifier.

Parameters: cmd_mod_fun (function) – Function which, given a command cmd, returns the command it should send instead.

Example

def cmd_mod_fun(cmd):
cmd.tags += [MyOwnTag()]
compiler_engine = CommandModifier(cmd_mod_fun)
...

receive(command_list)

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

Parameters: command_list (list) – List of commands to receive and then (after modification) send on.
class projectq.cengines.CompareEngine

CompareEngine is an engine which saves all commands. It is only intended for testing purposes. Two CompareEngine backends can be compared and return True if they contain the same commmands.

class projectq.cengines.Decomposition(replacement_fun, recogn_fun)

The Decomposition class can be used to register a decomposition rule (by calling register_decomposition)

__init__(replacement_fun, recogn_fun)

Construct the Decomposition object.

Parameters: replacement_fun – Function that, when called with a Command object, decomposes this command. recogn_fun – Function that, when called with a Command object, returns True if and only if the replacement rule can handle this command.

Every Decomposition is registered with the gate class. The Decomposition rule is then potentially valid for all objects which are an instance of that same class (i.e., instance of gate_object.__class__). All other parameters have to be checked by the recogn_fun, i.e., it has to decide whether the decomposition rule can indeed be applied to replace the given Command.

As an example, consider recognizing the Toffoli gate, which is a Pauli-X gate with 2 control qubits. The recognizer function would then be:

def recogn_toffoli(cmd):
# can be applied if the gate is an X-gate with 2 control qubits:
return len(cmd.control_qubits) == 2


and, given a replacement function replace_toffoli, the decomposition rule can be registered as

register_decomposition(X.__class__, decompose_toffoli, recogn_toffoli)


Note

See projectq.setups.decompositions for more example codes.

get_inverse_decomposition()

Return the Decomposition object which handles the inverse of the original command.

This simulates the user having added a decomposition rule for the inverse as well. Since decomposing the inverse of a command can be achieved by running the original decomposition inside a with Dagger(engine): statement, this is not necessary (and will be done automatically by the framework).

Returns: Decomposition handling the inverse of the original command.
class projectq.cengines.DummyEngine(save_commands=False)

DummyEngine used for testing.

The DummyEngine forwards all commands directly to next engine. If self.is_last_engine == True it just discards all gates. By setting save_commands == True all commands get saved as a list in self.received_commands. Elements are appended to this list so they are ordered according to when they are received.

__init__(save_commands=False)

Initialize DummyEngine

Parameters: save_commands (default = False) – If True, commands are saved in self.received_commands.
class projectq.cengines.ForwarderEngine(engine, cmd_mod_fun=None)

A ForwarderEngine is a trivial engine which forwards all commands to the next engine.

It is mainly used as a substitute for the MainEngine at lower levels such that meta operations still work (e.g., with Compute).

__init__(engine, cmd_mod_fun=None)

Initialize a ForwarderEngine.

Parameters: engine (BasicEngine) – Engine to forward all commands to. cmd_mod_fun (function) – Function which is called before sending a command. Each command cmd is replaced by the command it returns when getting called with cmd.
receive(command_list)

Forward all commands to the next engine.

class projectq.cengines.IBMCNOTMapper

CNOT mapper for the IBM backend.

Transforms CNOTs such that all CNOTs within the circuit have the same target qubit (required by IBM backend). If necessary, it will flip around the CNOT gate by first applying Hadamard gates to both qubits, then CNOT with swapped control and target qubit, and finally Hadamard gates to both qubits.

Note

The mapper has to be run once on the entire circuit. Else, an Exception will be raised (if, e.g., several measurements are performed without re- initializing the mapper).

Warning

If the provided circuit cannot be mapped to the hardware layout without performing Swaps, the mapping procedure raises an Exception.

__init__()

Initialize an IBM CNOT Mapper compiler engine.

Resets the mapping.

is_available(cmd)

Check if the IBM backend can perform the Command cmd and return True if so.

Parameters: cmd (Command) – The command to check
receive(command_list)

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

Parameters: command_list (list of Command objects) – list of commands to receive. Exception – If mapping the CNOT gates to 1 qubit would require Swaps. The current version only supports remapping of CNOT gates without performing any Swaps due to the large costs associated with Swapping given the CNOT constraints.
class projectq.cengines.InstructionFilter(filterfun)

The InstructionFilter is a compiler engine which changes the behavior of is_available according to a filter function. All commands are passed to this function, which then returns whether this command can be executed (True) or needs replacement (False).

__init__(filterfun)

Constructor: The provided filterfun returns True for all commands which do not need replacement and False for commands that do.

Parameters: filterfun (function) – Filter function which returns True for available commands, and False otherwise. filterfun will be called as filterfun(self, cmd).
is_available(cmd)

Specialized implementation of BasicBackend.is_available: Forwards this call to the filter function given to the constructor.

Parameters: cmd (Command) – Command for which to check availability.
receive(command_list)

Forward all commands to the next engine.

Parameters: command_list (list) – List of commands to receive.
exception projectq.cengines.LastEngineException(engine)

Exception thrown when the last engine tries to access the next one. (Next engine does not exist)

The default implementation of isAvailable simply asks the next engine whether the command is available. An engine which legally may be the last engine, this behavior needs to be adapted (see BasicEngine.isAvailable).

class projectq.cengines.LocalOptimizer(m=5)

LocalOptimizer is a compiler engine which optimizes locally (merging rotations, cancelling gates with their inverse) in a local window of user- defined size.

It stores all commands in a list of lists, where each qubit has its own gate pipeline. After adding a gate, it tries to merge / cancel successive gates using the get_merged and get_inverse functions of the gate (if available). For examples, see BasicRotationGate. Once a list corresponding to a qubit contains >=m gates, the pipeline is sent on to the next engine.

__init__(m=5)

Initialize a LocalOptimizer object.

Parameters: m (int) – Number of gates to cache per qubit, before sending on the first gate.
receive(command_list)

Receive commands from the previous engine and cache them. If a flush gate arrives, the entire buffer is sent on.

class projectq.cengines.MainEngine(backend=None, engine_list=None)

The MainEngine class provides all functionality of the main compiler engine.

It initializes all further compiler engines (calls, e.g., .next_engine=...) and keeps track of measurement results and active qubits (and their IDs).

next_engine

BasicEngine – Next compiler engine (or the back-end).

main_engine

MainEngine – Self.

active_qubits

WeakSet – WeakSet containing all active qubits

dirty_qubits

Set – Containing all dirty qubit ids

backend

BasicEngine – Access the back-end.

__init__(backend=None, engine_list=None)

Initialize the main compiler engine and all compiler engines.

Sets ‘next_engine’- and ‘main_engine’-attributes of all compiler engines and adds the back-end as the last engine.

Parameters: backend (BasicEngine) – Backend to send the circuit to. engine_list (list) – List of engines / backends to use as compiler engines.

Example

from projectq import MainEngine
eng = MainEngine() # will load default setup using Simulator backend


Alternatively, one can specify all compiler engines explicitly, e.g.,

Example

from projectq.cengines import TagRemover,AutoReplacer,LocalOptimizer
from projectq.backends import Simulator
from projectq import MainEngine
engines = [AutoReplacer(), TagRemover(), LocalOptimizer(3)]
eng = MainEngine(Simulator(), engines)

flush(deallocate_qubits=False)

Flush the entire circuit down the pipeline, clearing potential buffers (of, e.g., optimizers).

Parameters: deallocate_qubits (bool) – If True, deallocates all qubits that are still alive (invalidating references to them by setting their id to -1)
get_measurement_result(qubit)

Return the classical value of a measured qubit, given that an engine registered this result previously (see setMeasurementResult).

Parameters: qubit (BasicQubit) – Qubit of which to get the measurement result.

Example

from projectq.ops import H, Measure
from projectq import MainEngine
eng = MainEngine()
qubit = eng.allocate_qubit() # quantum register of size 1
H | qubit
Measure | qubit
eng.get_measurement_result(qubit[0]) == int(qubit)

get_new_qubit_id()

Returns a unique qubit id to be used for the next qubit allocation.

Returns: New unique qubit id. new_qubit_id (int)
receive(command_list)

Forward the list of commands to the first engine.

Parameters: command_list (list) – List of commands to receive (and then send on)
set_measurement_result(qubit, value)

Register a measurement result

The engine being responsible for measurement results needs to register these results with the master engine such that they are available when the user calls an int() or bool() conversion operator on a measured qubit.

Parameters: qubit (BasicQubit) – Qubit for which to register the measurement result. value (bool) – Boolean value of the measurement outcome (True / False = 1 / 0 respectively)
class projectq.cengines.TagRemover(tags=[<class 'projectq.meta._compute.ComputeTag'>, <class 'projectq.meta._compute.UncomputeTag'>])

TagRemover is a compiler engine which removes temporary command tags (see the tag classes such as LoopTag in projectq.meta._loop).

Removing tags is important (after having handled them if necessary) in order to enable optimizations across meta-function boundaries (compute/action/ uncompute or loops after unrolling)

__init__(tags=[<class 'projectq.meta._compute.ComputeTag'>, <class 'projectq.meta._compute.UncomputeTag'>])

Construct the TagRemover.

Parameters: tags – A list of meta tag classes (e.g., [ComputeTag, UncomputeTag]) denoting the tags to remove
receive(command_list)

Receive a list of commands from the previous engine, remove all tags which are an instance of at least one of the meta tags provided in the constructor, and then send them on to the next compiler engine.

Parameters: command_list (list) – List of commands to receive and then (after removing tags) send on.
projectq.cengines.register_decomposition(gate_class, gate_decomposer, gate_recognizer=None)

Add a decomposition rule for compiling ‘gate’ to the global setup.

The decomposition rule is a Decomposition object (see _decomposition.py) and consists of a function which recognizes a command (i.e., determines whether it can handle it) and a function which executes the decomposition. The gate_class parameter determines the gate class for which the decomposition is valid (keeps the number of calls to recognize functions lower).

Parameters: gate_class – Gate class for which the decomposition should be applicable; this parameter is only used to enable binary search on gate_object.__class__. If your class is defined as class MyGate(BasicGate): pass  Then you supply gate_class=MyGate However, if MyGate is overridden as often is the case when MyGate = MyGate() # Because it allows the syntax MyGate | qubit  then gate_class = MyGate.__class__ gate_decomposer (function) – Function which, given the command to decompose, applies a sequence of gates corresponding to the high-level function of a gate of type gate_class. gate_recognizer (function) – Optional function which, given the command to decompose, returns whether the decomposition supports the given command. E.g., rotation gates may be rewritten using one decomposition for some angles, and another one for other angles. If no such function is provided, the decomposition rule will be valid for all gates of type gate_class.