backends

projectq.backends._aqt

ProjectQ module for supporting the AQT platform

projectq.backends._awsbraket

ProjectQ module for supporting the AWS Braket platform

projectq.backends._azure

ProjectQ module for supporting the Azure Quantum platform.

projectq.backends._circuits

ProjectQ module for exporting/printing quantum circuits

projectq.backends._exceptions

Exception classes for projectq.backends.

projectq.backends._ibm

ProjectQ module for supporting the IBM QE platform

projectq.backends._ionq

ProjectQ module for supporting the IonQ platform

projectq.backends._printer

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

projectq.backends._resource

Contain a compiler engine to calculate resource count used by a quantum circuit.

projectq.backends._sim

ProjectQ module dedicated to simulation

projectq.backends._unitary

Contain a backend that saves the unitary of a quantum circuit.

projectq.backends._utils

Module containing some utility functions.

projectq.backends.AQTBackend([use_hardware, ...])

Backend for building circuits and submitting them to the AQT API.

projectq.backends.AWSBraketBackend(*args, ...)

Dummy class

projectq.backends.AzureQuantumBackend(*args, ...)

Dummy 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([...])

Compiler engine that prints command to the standard output.

projectq.backends.DeviceNotHandledError

Exception raised if a selected device cannot handle the circuit or is not supported by ProjectQ.

projectq.backends.DeviceOfflineError

Raised when a device is required but is currently offline.

projectq.backends.DeviceTooSmall

Raised when a device does not have enough qubits for a desired job.

projectq.backends.IBMBackend([use_hardware, ...])

Define the compiler engine class that handles interactions with the IBM API.

projectq.backends.IonQBackend([...])

Backend for building circuits and submitting them to the IonQ API.

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.

projectq.backends.UnitarySimulator()

Simulator engine aimed at calculating the unitary transformation that represents the current quantum circuit.

Submodules

_aqt

ProjectQ module for supporting the AQT platform

_awsbraket

ProjectQ module for supporting the AWS Braket platform

class projectq.backends._awsbraket.AWSBraketBackend(*args, **kwargs)[source]

Dummy class

_azure

ProjectQ module for supporting the Azure Quantum platform.

class projectq.backends._azure.AzureQuantumBackend(*args, **kwargs)[source]

Dummy class

_circuits

ProjectQ module for exporting/printing quantum circuits

_exceptions

Exception classes for projectq.backends.

exception projectq.backends._exceptions.DeviceNotHandledError[source]

Exception raised if a selected device cannot handle the circuit or is not supported by ProjectQ.

exception projectq.backends._exceptions.DeviceOfflineError[source]

Raised when a device is required but is currently offline.

exception projectq.backends._exceptions.DeviceTooSmall[source]

Raised when a device does not have enough qubits for a desired job.

exception projectq.backends._exceptions.InvalidCommandError[source]

Raised if the backend encounters an invalid command.

exception projectq.backends._exceptions.JobSubmissionError[source]

Raised when the job creation API contains an error of some kind.

exception projectq.backends._exceptions.MidCircuitMeasurementError[source]

Raised when a mid-circuit measurement is detected on a qubit.

exception projectq.backends._exceptions.RequestTimeoutError[source]

Raised if a request to the job creation API times out.

_ibm

ProjectQ module for supporting the IBM QE platform

_ionq

ProjectQ module for supporting the IonQ platform

class projectq.backends._ionq.IonQBackend(use_hardware=False, num_runs=100, verbose=False, token=None, device='ionq_simulator', num_retries=3000, interval=1, retrieve_execution=None)[source]

Backend for building circuits and submitting them to the IonQ API.

get_probabilities(qureg)[source]

Given the provided qubit register, determine the probability of each possible outcome.

Note

This method should only be called after a circuit has been run and its results are available.

Parameters

qureg (Qureg) – A ProjectQ Qureg object.

Returns

A dict mapping of states -> probability.

Return type

dict

get_probability(state, qureg)[source]

Shortcut to get a specific state’s probability.

Parameters
  • state (str) – A state in bit-string format.

  • qureg (Qureg) – A ProjectQ Qureg object.

Returns

The probability for the provided state.

Return type

float

is_available(cmd)[source]

Test if this backend is available to process the provided command.

Parameters

cmd (Command) – A command to process.

Returns

If this backend can process the command.

Return type

bool

receive(command_list)[source]

Receive a command list from the ProjectQ engine pipeline.

If a given command is a “flush” operation, the pending circuit will be submitted to IonQ’s API for processing.

Parameters

command_list (list[Command]) – A list of ProjectQ Command objects.

_printer

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

class projectq.backends._printer.CommandPrinter(accept_input=True, default_measure=False, in_place=False)[source]

Compiler engine that prints command to the standard output.

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

is_available(cmd)[source]

Test whether a Command is supported by a compiler engine.

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.

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

Contain a compiler engine to calculate resource count used by a quantum circuit.

A resrouce counter compiler engine 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.

property depth_of_dag[source]

Return the depth of the DAG.

is_available(cmd)[source]

Test whether a Command is supported by a compiler engine.

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.

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

ProjectQ module dedicated to simulation

_unitary

Contain a backend that saves the unitary of a quantum circuit.

class projectq.backends._unitary.UnitarySimulator[source]

Simulator engine aimed at calculating the unitary transformation that represents the current quantum circuit.

unitary[source]

Current unitary representing the quantum circuit being processed so far.

Type

np.ndarray

history[source]

List of previous quantum circuit unitaries.

Type

list<np.ndarray>

Note

The current implementation of this backend resets the unitary after the first gate that is neither a qubit deallocation nor a measurement occurs after one of those two aforementioned gates.

The old unitary call be accessed at anytime after such a situation occurs via the history property.

eng = MainEngine(backend=UnitarySimulator(), engine_list=[])
qureg = eng.allocate_qureg(3)
All(X) | qureg

eng.flush()
All(Measure) | qureg
eng.deallocate_qubit(qureg[1])

X | qureg[0]  # WARNING: appending gate after measurements or deallocations resets the unitary
property history[source]

Access all previous unitary matrices.

The current unitary matrix is appended to this list once a gate is received after either a measurement or a qubit deallocation has occurred.

Returns

A list where the elements are all previous unitary matrices representing the circuit, separated by measurement/deallocate gates.

is_available(cmd)[source]

Test whether a Command is supported by a compiler engine.

Specialized implementation of is_available: The unitary simulator can deal with all arbitrarily-controlled gates which provide a gate-matrix (via gate.matrix).

Parameters

cmd (Command) – Command for which to check availability (single- qubit gate, arbitrary controls)

Returns

True if it can be simulated and False otherwise.

measure_qubits(ids)[source]

Measure the qubits with IDs ids and return a list of measurement outcomes (True/False).

Parameters

ids (list<int>) – List of qubit IDs to measure.

Returns

List of measurement results (containing either True or False).

receive(command_list)[source]

Receive a list of commands.

Receive a list of commands from the previous engine and handle them:
  • update the unitary of the quantum circuit

  • update the internal quantum state if a measurement or a qubit deallocation occurs

prior to sending them on to the next engine.

Parameters

command_list (list<Command>) – List of commands to execute on the simulator.

property unitary[source]

Access the last unitary matrix directly.

Returns

A numpy array which is the unitary matrix of the circuit.

_utils

Module containing some utility functions.

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).

  • an interface to the AWS Braket service decives (and simulators)

  • an interface to the Azure Quantum service devices (and simulators)

  • an interface to the IonQ trapped ionq hardware (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]

Backend for building circuits and submitting them to the AQT API.

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 probability of the outcome bit_string when measuring the quantum register qureg.

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]

Receive a list of commands.

Receive a command list and, for each command, stores it until completion. Upon flush, send the data to the AQT API.

Parameters

command_list – List of commands to execute

class projectq.backends.AWSBraketBackend(*args, **kwargs)[source]

Dummy class

__init__(*args, **kwargs)[source]
class projectq.backends.AzureQuantumBackend(*args, **kwargs)[source]

Dummy class

__init__(*args, **kwargs)[source]
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": {"shadow": false, "size": 0.1},  # settings for control "circle"
    "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]

Test whether a Command is supported by a compiler engine.

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.

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]

Set 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).

Parameters
  • accept_input (bool) – 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).

  • 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]

Generate 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]

Test whether a Command is supported by a compiler engine.

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.

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 a ClassicalSimulator object.

is_available(cmd)[source]

Test whether a Command is supported by a compiler engine.

read_bit(qubit)[source]

Read 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]

Read 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]

Receive a list of commands.

This implementation simply forwards all commands to the next engine.

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]

Set 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]

Compiler engine that prints command to the standard output.

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]

Test whether a Command is supported by a compiler engine.

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.

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).

exception projectq.backends.DeviceNotHandledError[source]

Exception raised if a selected device cannot handle the circuit or is not supported by ProjectQ.

exception projectq.backends.DeviceOfflineError[source]

Raised when a device is required but is currently offline.

exception projectq.backends.DeviceTooSmall[source]

Raised when a device does not have enough qubits for a desired job.

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]

Define the compiler engine class that handles interactions with the IBM API.

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 probability of the outcome bit_string when measuring the quantum register qureg.

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]

Receive a list of commands.

Receive a command list and, for each command, stores it until completion. Upon flush, send the data to the IBM QE API.

Parameters

command_list – List of commands to execute

class projectq.backends.IonQBackend(use_hardware=False, num_runs=100, verbose=False, token=None, device='ionq_simulator', num_retries=3000, interval=1, retrieve_execution=None)[source]

Backend for building circuits and submitting them to the IonQ API.

__init__(use_hardware=False, num_runs=100, verbose=False, token=None, device='ionq_simulator', num_retries=3000, interval=1, retrieve_execution=None)[source]

Initialize an IonQBackend object.

Parameters
  • use_hardware (bool, optional) – Whether or not to use real IonQ hardware or just a simulator. If False, the ionq_simulator is used regardless of the value of device. Defaults to False.

  • num_runs (int, optional) – Number of times to run circuits. Defaults to 100.

  • verbose (bool, optional) – If True, print statistics after job results have been collected. Defaults to False.

  • token (str, optional) – An IonQ API token. Defaults to None.

  • device (str, optional) – Device to run jobs on. Supported devices are 'ionq_qpu' or 'ionq_simulator'. Defaults to 'ionq_simulator'.

  • num_retries (int, optional) – Number of times to retry fetching a job after it has been submitted. Defaults to 3000.

  • interval (int, optional) – Number of seconds to wait inbetween result fetch retries. Defaults to 1.

  • retrieve_execution (str, optional) – An IonQ API Job ID. If provided, a job with this ID will be fetched. Defaults to None.

get_probabilities(qureg)[source]

Given the provided qubit register, determine the probability of each possible outcome.

Note

This method should only be called after a circuit has been run and its results are available.

Parameters

qureg (Qureg) – A ProjectQ Qureg object.

Returns

A dict mapping of states -> probability.

Return type

dict

get_probability(state, qureg)[source]

Shortcut to get a specific state’s probability.

Parameters
  • state (str) – A state in bit-string format.

  • qureg (Qureg) – A ProjectQ Qureg object.

Returns

The probability for the provided state.

Return type

float

is_available(cmd)[source]

Test if this backend is available to process the provided command.

Parameters

cmd (Command) – A command to process.

Returns

If this backend can process the command.

Return type

bool

receive(command_list)[source]

Receive a command list from the ProjectQ engine pipeline.

If a given command is a “flush” operation, the pending circuit will be submitted to IonQ’s API for processing.

Parameters

command_list (list[Command]) – A list of ProjectQ Command objects.

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.

property depth_of_dag[source]

Return the depth of the DAG.

is_available(cmd)[source]

Test whether a Command is supported by a compiler engine.

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.

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 a 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]

Return the expectation value of a qubit operator.

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]

Test whether a Command is supported by a compiler engine.

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.

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.

class projectq.backends.UnitarySimulator[source]

Simulator engine aimed at calculating the unitary transformation that represents the current quantum circuit.

unitary[source]

Current unitary representing the quantum circuit being processed so far.

Type

np.ndarray

history[source]

List of previous quantum circuit unitaries.

Type

list<np.ndarray>

Note

The current implementation of this backend resets the unitary after the first gate that is neither a qubit deallocation nor a measurement occurs after one of those two aforementioned gates.

The old unitary call be accessed at anytime after such a situation occurs via the history property.

eng = MainEngine(backend=UnitarySimulator(), engine_list=[])
qureg = eng.allocate_qureg(3)
All(X) | qureg

eng.flush()
All(Measure) | qureg
eng.deallocate_qubit(qureg[1])

X | qureg[0]  # WARNING: appending gate after measurements or deallocations resets the unitary
__init__()[source]

Initialize a UnitarySimulator object.

property history[source]

Access all previous unitary matrices.

The current unitary matrix is appended to this list once a gate is received after either a measurement or a qubit deallocation has occurred.

Returns

A list where the elements are all previous unitary matrices representing the circuit, separated by measurement/deallocate gates.

is_available(cmd)[source]

Test whether a Command is supported by a compiler engine.

Specialized implementation of is_available: The unitary simulator can deal with all arbitrarily-controlled gates which provide a gate-matrix (via gate.matrix).

Parameters

cmd (Command) – Command for which to check availability (single- qubit gate, arbitrary controls)

Returns

True if it can be simulated and False otherwise.

measure_qubits(ids)[source]

Measure the qubits with IDs ids and return a list of measurement outcomes (True/False).

Parameters

ids (list<int>) – List of qubit IDs to measure.

Returns

List of measurement results (containing either True or False).

receive(command_list)[source]

Receive a list of commands.

Receive a list of commands from the previous engine and handle them:
  • update the unitary of the quantum circuit

  • update the internal quantum state if a measurement or a qubit deallocation occurs

prior to sending them on to the next engine.

Parameters

command_list (list<Command>) – List of commands to execute on the simulator.

property unitary[source]

Access the last unitary matrix directly.

Returns

A numpy array which is the unitary matrix of the circuit.