backends

projectq.backends._aqt
projectq.backends._circuits
projectq.backends._ibm
projectq.backends._json_converter Contains a compiler engine that converts ProjectQ commands to JSON format
projectq.backends._printer Contains a compiler engine which prints commands to stdout prior to sending them on to the next engines (see CommandPrinter).
projectq.backends._resource Contains a compiler engine which counts the number of calls for each type of gate used in a circuit, in addition to the max.
projectq.backends._sim
projectq.backends.AQTBackend([use_hardware, …]) The AQT Backend class, which stores the circuit, transforms it to the appropriate data format, and sends the circuit through the AQT API.
projectq.backends.BasicEngine() Basic compiler engine: All compiler engines are derived from this class.
projectq.backends.CircuitDrawer([…]) CircuitDrawer is a compiler engine which generates TikZ code for drawing quantum circuits.
projectq.backends.CircuitDrawerMatplotlib([…]) CircuitDrawerMatplotlib is a compiler engine which using Matplotlib library for drawing quantum circuits
projectq.backends.ClassicalSimulator() A simple introspective simulator that only permits classical operations.
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.dynamic_import(name)
projectq.backends.IBMBackend([use_hardware, …]) The IBM Backend class, which stores the circuit, transforms it to JSON, and sends the circuit through the IBM API.
projectq.backends.import_module(name[, package]) Import a module.
projectq.backends.JSONBackend() ProjectQ engine to convert a list of commands to JSON format
projectq.backends.pkg_name str(object=’‘) -> str str(bytes_or_buffer[, encoding[, errors]]) -> str
projectq.backends.ResourceCounter() ResourceCounter is a compiler engine which counts the number of gates and max.
projectq.backends.Simulator([gate_fusion, …]) Simulator is a compiler engine which simulates a quantum computer using C++-based kernels.

Submodules

_aqt

_circuits

_ibm

_json_converter

Contains a compiler engine that converts ProjectQ commands to JSON format

class projectq.backends._json_converter.JSONBackend[source]

ProjectQ engine to convert a list of commands to JSON format

json(**kwargs)[source]

Get a JSON representation of the commands processed by this engine as JSON string.

Parameters:**kwargs – Arbitrary keyword arguments (see dumps() function from json module)
write_json(fp, **kwargs)[source]

Write a JSON representation of the commands processed by this engine to a JSON formatted stream.

Parameters:
  • fp (file-like object) – Stream to output JSON to
  • **kwargs – Arbitrary keyword arguments (see dump() function from json module)
class projectq.backends._json_converter.ProjectQJSONEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)[source]

Custom JSON encoder for ProjectQ commands and gates

default(o)[source]

Implement this method in a subclass such that it returns a serializable object for o, or calls the base implementation (to raise a TypeError).

For example, to support arbitrary iterators, you could implement default like this:

def default(self, o):
    try:
        iterable = iter(o)
    except TypeError:
        pass
    else:
        return list(iterable)
    # Let the base class default method raise the TypeError
    return JSONEncoder.default(self, o)
projectq.backends._json_converter.calculate_circuit_depth(command_list)[source]

Calculate the depth of a quantum circuit

Parameters:command_list (list) – List of ProjectQ commands
Returns:Depth of quantum circuit (int)

_printer

Contains a compiler engine which prints commands to stdout prior to sending them on to the next engines (see CommandPrinter).

class projectq.backends._printer.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.

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).
Returns:
True, unless the next engine cannot handle
the Command (if there is a next engine).
Return type: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<Command>) – List of Commands to print (and potentially send on to the next engine).

_resource

Contains a compiler engine which counts the number of calls for each type of gate used in a circuit, in addition to the max. number of active qubits.

class projectq.backends._resource.ResourceCounter[source]

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

gate_counts

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

Type:dict
gate_class_counts

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.

Type:dict
max_width

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

Type:int
Properties:
depth_of_dag (int): It is the longest path in the directed
acyclic graph (DAG) of the program.
depth_of_dag[source]
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).
Returns:
True, unless the next engine cannot handle
the Command (if there is a next engine).
Return type: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<Command>) – List of commands to receive (and count).

_sim

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).
  • an interface to the AQT trapped ion system (and simulator).
class projectq.backends.AQTBackend(use_hardware=False, num_runs=100, verbose=False, token='', device='simulator', num_retries=3000, interval=1, retrieve_execution=None)[source]

The AQT Backend class, which stores the circuit, transforms it to the appropriate data format, and sends the circuit through the AQT API.

__init__(use_hardware=False, num_runs=100, verbose=False, token='', device='simulator', 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 AQT quantum chip (instead of using the AQT simulator)
  • num_runs (int) – Number of runs to collect statistics. (default is 100, max is usually around 200)
  • verbose (bool) – If True, statistics are printed, in addition to the measurement result being registered (at the end of the circuit).
  • token (str) – AQT user API token.
  • device (str) – name of the AQT device to use. simulator By default
  • num_retries (int) – Number of times to retry to obtain results from the AQT API. (default is 3000)
  • interval (float, int) – Number of seconds between successive attempts to obtain results from the AQT 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. If input qureg is a subset of the register used for the experiment, then returns the projected probabilities over the other states. 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<Qubit>) – Quantum register determining the order of the qubits.
Returns:Dictionary mapping n-bit strings to probabilities.
Return type:probability_dict (dict)
Raises: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 AQT ion trap can only do Rx,Ry and Rxx.

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.BasicEngine[source]

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

Next compiler engine (or the back-end).

Type:BasicEngine
main_engine

Reference to the main compiler engine.

Type:MainEngine
is_last_engine

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

Type:bool
__init__()[source]

Initialize the basic engine.

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

allocate_qubit(dirty=False)[source]

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).
Returns:Qureg of length 1, where the first entry is the allocated qubit.
allocate_qureg(n)[source]

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
Returns:Qureg of length n, a list of n newly allocated qubits.
deallocate_qubit(qubit)[source]

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.
Raises:ValueError – Qubit already deallocated. Caller likely has a bug.
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.
Returns:True if the command can be executed.
Raises:LastEngineException – If is_last_engine is True but is_available is not implemented.
is_meta_tag_supported(meta_tag)[source]

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
Returns:

True if one of the further compiler engines is a meta tag handler, i.e., engine.is_meta_tag_handler(meta_tag) returns True.

Return type:

supported (bool)

send(command_list)[source]

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

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"
            "shadow": false,
            "size": 0.1
    },
    "gate_shadow": true, # enable/disable shadows for all gates
    "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(ordered=False, draw_gates_in_parallel=True)[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.

Parameters:
  • ordered (bool) – flag if the gates should be drawn in the order they were added to the circuit
  • draw_gates_in_parallel (bool) – flag if parallel gates should be drawn parallel (True), or not (False)
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).
Returns:True, unless the next engine cannot handle the Command (if there is a next engine).
Return type: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<Command>) – 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.
Raises:RuntimeError – If the mapping has already begun (this function needs be called before any gates have been received).
class projectq.backends.CircuitDrawerMatplotlib(accept_input=False, default_measure=0)[source]

CircuitDrawerMatplotlib is a compiler engine which using Matplotlib library for drawing quantum circuits

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

Initialize a circuit drawing engine(mpl) :param accept_input: If accept_input is true, the printer queries

the user to input measurement results if the CircuitDrawerMPL is the last engine. Otherwise, all measurements yield the result default_measure (0 or 1).
Parameters: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.
draw(qubit_labels=None, drawing_order=None, **kwargs)[source]

Generates and returns the plot of the quantum circuit stored so far

Parameters:
  • qubit_labels (dict) – label for each wire in the output figure. Keys: qubit IDs, Values: string to print out as label for that particular qubit wire.
  • drawing_order (dict) – position of each qubit in the output graphic. Keys: qubit IDs, Values: position of qubit on the qubit line in the graphic.
  • **kwargs (dict) – additional parameters are used to update the default plot parameters
Returns:

A tuple containing the matplotlib figure and axes objects

Note

Additional keyword arguments can be passed to this function in order to further customize the figure output by matplotlib (default value in parentheses):

  • fontsize (14): Font size in pt
  • column_spacing (.5): Vertical spacing between two neighbouring gates (roughly in inches)
  • control_radius (.015): Radius of the circle for controls
  • labels_margin (1): Margin between labels and begin of wire (roughly in inches)
  • linewidth (1): Width of line
  • not_radius (.03): Radius of the circle for X/NOT gates
  • gate_offset (.05): Inner margins for gates with a text representation
  • mgate_width (.1): Width of the measurement gate
  • swap_delta (.02): Half-size of the SWAP gate
  • x_offset (.05): Absolute X-offset for drawing within the axes
  • wire_height (1): Vertical spacing between two qubit wires (roughly in inches)
is_available(cmd)[source]

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

Parameters:cmd (Command) – Command for which to check availability (all Commands can be printed).
Returns:True, unless the next engine cannot handle the Command (if there is a next engine).
Return type: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<Command>) – List of Commands to print (and potentially send on to the next engine).
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.
Returns:True if the command can be executed.
Raises:LastEngineException – If is_last_engine is True but is_available is not implemented.
read_bit(qubit)[source]

Reads a bit.

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.
Returns:0 if the target bit is off, 1 if it’s on.
Return type: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.
Returns:Little-endian register value.
Return type:int
receive(command_list)[source]
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).
Returns:
True, unless the next engine cannot handle
the Command (if there is a next engine).
Return type: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<Command>) – 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, token='', device='ibmq_essex', num_retries=3000, interval=1, retrieve_execution=None)[source]

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

__init__(use_hardware=False, num_runs=1024, verbose=False, token='', device='ibmq_essex', 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).
  • token (str) – IBM quantum experience user password.
  • device (str) – name of the IBM device to use. ibmq_essex By default
  • 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. If input qureg is a subset of the register used for the experiment, then returns the projected probabilities over the other states.

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<Qubit>) – Quantum register determining the order of the qubits.
Returns:
Dictionary mapping n-bit strings to
probabilities.
Return type:probability_dict (dict)
Raises: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).
get_qasm()[source]

Return the QASM representation of the circuit sent to the backend. Should be called AFTER calling the ibm device

is_available(cmd)[source]

Return true if the command can be executed.

The IBM quantum chip can only do U1,U2,U3,barriers, and CX / CNOT. Conversion implemented for Rotation gates and H gates.

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.JSONBackend[source]

ProjectQ engine to convert a list of commands to JSON format

__init__()[source]

Initialize DummyEngine

Parameters:save_commands (default = False) – If True, commands are saved in self.received_commands.
json(**kwargs)[source]

Get a JSON representation of the commands processed by this engine as JSON string.

Parameters:**kwargs – Arbitrary keyword arguments (see dumps() function from json module)
write_json(fp, **kwargs)[source]

Write a JSON representation of the commands processed by this engine to a JSON formatted stream.

Parameters:
  • fp (file-like object) – Stream to output JSON to
  • **kwargs – Arbitrary keyword arguments (see dump() function from json module)
class projectq.backends.ResourceCounter[source]

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

gate_counts

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

Type:dict
gate_class_counts

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.

Type:dict
max_width

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

Type:int
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.

depth_of_dag[source]
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).
Returns:
True, unless the next engine cannot handle
the Command (if there is a next engine).
Return type: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<Command>) – 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
export OMP_PROC_BIND=spread # bind threads to processors by spreading
__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:
Raises:

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.
Raises:

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.
Returns:

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:
Returns:

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.
Returns:

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)
Returns: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<Command>) – 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.

projectq.backends.dynamic_import(name)[source]
projectq.backends.import_module(name, package=None)[source]

Import a module.

The ‘package’ argument is required when performing a relative import. It specifies the package to use as the anchor point from which to resolve the relative import to an absolute import.