ProjectQIBMBackend

class ProjectQIBMBackend(wires=1, shots=1024, **kwargs)[source]

Bases: _ProjectQDevice

A PennyLane projectq.ibm device for the ProjectQ IBMBackend backend.

Note

This device computes expectation values by averaging over a finite number of runs of the quantum circuit. Irrespective of whether this is done on real quantum hardware, or on the IBM simulator, this means that expectation values (and therefore also gradients) will have a finite accuracy and fluctuate from run to run.

Parameters

wires – Number of subsystems represented by the device, or iterable that contains unique labels for the subsystems as numbers (i.e., [-1, 0, 2]) or strings (['ancilla', 'q1', 'q2']).

Keyword Arguments
  • 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). Is equivalent to but takes preference over the shots parameter.

  • token (string) – IBM Quantum Experience API token

  • device (string) – IBMQ backend to use (ibmq_16_melbourne’, ‘ibmqx2’, ‘ibmq_rome’ ‘ibmq_qasm_simulator’) if use_hardware is set to True. Default is ‘‘ibmqx5’’.

  • retrieve_execution (int) – Job ID to retrieve instead of re-running a circuit (e.g., if previous run timed out).

  • verbose (bool) – If True, log messages are printed and exceptions are more verbose.

This device can, for example, be instantiated from PennyLane as follows:

import pennylane as qml
dev = qml.device('projectq.ibm', wires=XXX, token="XXX")

To avoid leaking your user name and password when sharing code, it is better to specify the user name and password in your PennyLane configuration file.

Supported PennyLane Operations:

pennylane.PauliX, pennylane.PauliY, pennylane.PauliZ, pennylane.CNOT, pennylane.CZ, pennylane.SWAP, pennylane.RX, pennylane.RY, pennylane.RZ, pennylane.PhaseShift, pennylane.Hadamard, pennylane.Rot, pennylane.BasisState

Supported PennyLane observables:

pennylane.PauliX, pennylane.PauliY, pennylane.PauliZ, pennylane.Hadamard, pennylane.Identity

Note

The observables pennylane.PauliY, pennylane.PauliZ, and pennylane.Hadamard, cannot be natively measured on the hardware device. They are implemented by executing a few additional gates on the respective wire before the final measurement, which is always performed in the pennylane.PauliZ basis. These measurements may thus be slightly more noisy than native pennylane.PauliZ measurement.

Extra Operations:

pennylane_pq.S, pennylane_pq.T, pennylane_pq.SqrtX, pennylane_pq.SqrtSwap,

analytic

Whether shots is None or not.

author

name

num_executions

Number of times this device is executed by the evaluation of QNodes running on this device

obs_queue

The observables to be measured and returned.

observables

Get the supported set of observables.

op_queue

The operation queue to be applied.

operations

Get the supported set of operations.

parameters

Mapping from free parameter index to the list of Operations in the device queue that depend on it.

pennylane_requires

plugin_version

short_name

shot_vector

Returns the shot vector, a sparse representation of the shot sequence used by the device when evaluating QNodes.

shots

Number of circuit evaluations/random samples used to estimate expectation values of observables

stopping_condition

Returns the stopping condition for the device.

version

wire_map

Ordered dictionary that defines the map from user-provided wire labels to the wire labels used on this device

wires

All wires that can be addressed on this device

analytic

Whether shots is None or not. Kept for backwards compatability.

author = 'Christian Gogolin and Xanadu'
name = 'ProjectQ PennyLane plugin'
num_executions

Number of times this device is executed by the evaluation of QNodes running on this device

Returns

number of executions

Return type

int

obs_queue

The observables to be measured and returned.

Note that this property can only be accessed within the execution context of execute().

Raises

ValueError – if outside of the execution context

Returns

list[~.operation.Observable]

observables

Get the supported set of observables.

Returns

the set of PennyLane observable names the device supports

Return type

set[str]

op_queue

The operation queue to be applied.

Note that this property can only be accessed within the execution context of execute().

Raises

ValueError – if outside of the execution context

Returns

list[~.operation.Operation]

operations

Get the supported set of operations.

Returns

the set of PennyLane operation names the device supports

Return type

set[str]

parameters

Mapping from free parameter index to the list of Operations in the device queue that depend on it.

Note that this property can only be accessed within the execution context of execute().

Raises

ValueError – if outside of the execution context

Returns

the mapping

Return type

dict[int->list[ParameterDependency]]

pennylane_requires = '>=0.15.0'
plugin_version = '0.34.0'
short_name = 'projectq.ibm'
shot_vector

Returns the shot vector, a sparse representation of the shot sequence used by the device when evaluating QNodes.

Example

>>> dev = qml.device("default.qubit.legacy", wires=2, shots=[3, 1, 2, 2, 2, 2, 6, 1, 1, 5, 12, 10, 10])
>>> dev.shots
57
>>> dev.shot_vector
[ShotCopies(3 shots x 1),
 ShotCopies(1 shots x 1),
 ShotCopies(2 shots x 4),
 ShotCopies(6 shots x 1),
 ShotCopies(1 shots x 2),
 ShotCopies(5 shots x 1),
 ShotCopies(12 shots x 1),
 ShotCopies(10 shots x 2)]

The sparse representation of the shot sequence is returned, where tuples indicate the number of times a shot integer is repeated.

Type

list[ShotCopies]

shots

Number of circuit evaluations/random samples used to estimate expectation values of observables

stopping_condition

Returns the stopping condition for the device. The returned function accepts a queuable object (including a PennyLane operation and observable) and returns True if supported by the device.

Type

.BooleanFn

version = '0.4.2'
wire_map

Ordered dictionary that defines the map from user-provided wire labels to the wire labels used on this device

wires

All wires that can be addressed on this device

apply(operation, wires, par)

Apply a quantum operation.

batch_execute(circuits)

Execute a batch of quantum circuits on the device.

batch_transform(circuit)

Apply a differentiable batch transform for preprocessing a circuit prior to execution.

capabilities()

Get the capabilities of this device class.

check_validity(queue, observables)

Checks whether the operations and observables in queue are all supported by the device.

custom_expand(fn)

Register a custom expansion function for the device.

default_expand_fn(circuit[, max_expansion])

Method for expanding or decomposing an input circuit.

define_wire_map(wires)

Create the map from user-provided wire labels to the wire labels used by the device.

execute(queue, observables[, parameters])

Execute a queue of quantum operations on the device and then measure the given observables.

execute_and_gradients(circuits[, method])

Execute a batch of quantum circuits on the device, and return both the results and the gradients.

execution_context()

The device execution context used during calls to execute().

expand_fn(circuit[, max_expansion])

Method for expanding or decomposing an input circuit.

expval(observable, wires, par)

Retrieve the requested observable expectation value.

filter_kwargs_for_backend(kwargs)

Filter the given kwargs for those relevant for the respective device/backend.

gradients(circuits[, method])

Return the gradients of a batch of quantum circuits on the device.

map_wires(wires)

Map the wire labels of wires using this device's wire map.

order_wires(subset_wires)

Given some subset of device wires return a Wires object with the same wires; sorted according to the device wire map.

post_apply()

Called during execute() after the individual operations have been executed.

post_measure()

Deallocate the qubits after expectation values have been retrieved.

pre_apply()

Called during execute() before the individual operations are executed.

pre_measure()

Rotate qubits to the right basis before measurement, apply a measure all operation and flush the device before retrieving expectation values.

probability([wires])

Return the (marginal) probability of each computational basis state from the last run of the device.

reset()

Reset/initialize the device by initializing the backend and engine, and allocating qubits.

sample(observable, wires, par)

Return a sample of an observable.

supports_observable(observable)

Checks if an observable is supported by this device. Raises a ValueError,

supports_operation(operation)

Checks if an operation is supported by this device.

var(observable, wires, par)

Retrieve the requested observable variance.

apply(operation, wires, par)

Apply a quantum operation.

For plugin developers: this function should apply the operation on the device.

Parameters
  • operation (str) – name of the operation

  • wires (Sequence[int]) – subsystems the operation is applied on

  • par (tuple) – parameters for the operation

batch_execute(circuits)

Execute a batch of quantum circuits on the device.

The circuits are represented by tapes, and they are executed one-by-one using the device’s execute method. The results are collected in a list.

For plugin developers: This function should be overwritten if the device can efficiently run multiple circuits on a backend, for example using parallel and/or asynchronous executions.

Parameters

circuits (list[.tape.QuantumTape]) – circuits to execute on the device

Returns

list of measured value(s)

Return type

list[array[float]]

batch_transform(circuit: QuantumTape)

Apply a differentiable batch transform for preprocessing a circuit prior to execution. This method is called directly by the QNode, and should be overwritten if the device requires a transform that generates multiple circuits prior to execution.

By default, this method contains logic for generating multiple circuits, one per term, of a circuit that terminates in expval(H), if the underlying device does not support Hamiltonian expectation values, or if the device requires finite shots.

Warning

This method will be tracked by autodifferentiation libraries, such as Autograd, JAX, TensorFlow, and Torch. Please make sure to use qml.math for autodiff-agnostic tensor processing if required.

Parameters

circuit (.QuantumTape) – the circuit to preprocess

Returns

Returns a tuple containing the sequence of circuits to be executed, and a post-processing function to be applied to the list of evaluated circuit results.

Return type

tuple[Sequence[.QuantumTape], callable]

classmethod capabilities()

Get the capabilities of this device class.

Inheriting classes that change or add capabilities must override this method, for example via

@classmethod
def capabilities(cls):
    capabilities = super().capabilities().copy()
    capabilities.update(
        supports_a_new_capability=True,
    )
    return capabilities
Returns

results

Return type

dict[str->*]

check_validity(queue, observables)

Checks whether the operations and observables in queue are all supported by the device.

Parameters
  • queue (Iterable[Operation]) – quantum operation objects which are intended to be applied on the device

  • observables (Iterable[Observable]) – observables which are intended to be evaluated on the device

Raises

DeviceError – if there are operations in the queue or observables that the device does not support

custom_expand(fn)

Register a custom expansion function for the device.

Example

dev = qml.device("default.qubit.legacy", wires=2)

@dev.custom_expand
def my_expansion_function(self, tape, max_expansion=10):
    ...
    # can optionally call the default device expansion
    tape = self.default_expand_fn(tape, max_expansion=max_expansion)
    return tape

The custom device expansion function must have arguments self (the device object), tape (the input circuit to transform and execute), and max_expansion (the number of times the circuit should be expanded).

The default default_expand_fn() method of the original device may be called. It is highly recommended to call this before returning, to ensure that the expanded circuit is supported on the device.

default_expand_fn(circuit, max_expansion=10)

Method for expanding or decomposing an input circuit. This method should be overwritten if custom expansion logic is required.

By default, this method expands the tape if:

  • state preparation operations are called mid-circuit,

  • nested tapes are present,

  • any operations are not supported on the device, or

  • multiple observables are measured on the same wire.

Parameters
  • circuit (.QuantumTape) – the circuit to expand.

  • max_expansion (int) – The number of times the circuit should be expanded. Expansion occurs when an operation or measurement is not supported, and results in a gate decomposition. If any operations in the decomposition remain unsupported by the device, another expansion occurs.

Returns

The expanded/decomposed circuit, such that the device will natively support all operations.

Return type

.QuantumTape

define_wire_map(wires)

Create the map from user-provided wire labels to the wire labels used by the device.

The default wire map maps the user wire labels to wire labels that are consecutive integers.

However, by overwriting this function, devices can specify their preferred, non-consecutive and/or non-integer wire labels.

Parameters

wires (Wires) – user-provided wires for this device

Returns

dictionary specifying the wire map

Return type

OrderedDict

Example

>>> dev = device('my.device', wires=['b', 'a'])
>>> dev.wire_map()
OrderedDict( [(<Wires = ['a']>, <Wires = [0]>), (<Wires = ['b']>, <Wires = [1]>)])
execute(queue, observables, parameters=None, **kwargs)

Execute a queue of quantum operations on the device and then measure the given observables.

For plugin developers: Instead of overwriting this, consider implementing a suitable subset of pre_apply(), apply(), post_apply(), pre_measure(), expval(), var(), sample(), post_measure(), and execution_context().

Parameters
  • queue (Iterable[Operation]) – operations to execute on the device

  • observables (Iterable[Observable]) – observables to measure and return

  • parameters (dict[int, list[ParameterDependency]]) – Mapping from free parameter index to the list of Operations (in the queue) that depend on it.

Keyword Arguments

return_native_type (bool) – If True, return the result in whatever type the device uses internally, otherwise convert it into array[float]. Default: False.

Raises

QuantumFunctionError – if the value of return_type is not supported

Returns

measured value(s)

Return type

array[float]

execute_and_gradients(circuits, method='jacobian', **kwargs)

Execute a batch of quantum circuits on the device, and return both the results and the gradients.

The circuits are represented by tapes, and they are executed one-by-one using the device’s execute method. The results and the corresponding Jacobians are collected in a list.

For plugin developers: This method should be overwritten if the device can efficiently run multiple circuits on a backend, for example using parallel and/or asynchronous executions, and return both the results and the Jacobians.

Parameters
  • circuits (list[.tape.QuantumTape]) – circuits to execute on the device

  • method (str) – the device method to call to compute the Jacobian of a single circuit

  • **kwargs – keyword argument to pass when calling method

Returns

Tuple containing list of measured value(s) and list of Jacobians. Returned Jacobians should be of shape (output_shape, num_params).

Return type

tuple[list[array[float]], list[array[float]]]

execution_context()

The device execution context used during calls to execute().

You can overwrite this function to return a context manager in case your quantum library requires that; all operations and method calls (including apply() and expval()) are then evaluated within the context of this context manager (see the source of execute() for more details).

expand_fn(circuit, max_expansion=10)

Method for expanding or decomposing an input circuit. Can be the default or a custom expansion method, see Device.default_expand_fn() and Device.custom_expand() for more details.

Parameters
  • circuit (.QuantumTape) – the circuit to expand.

  • max_expansion (int) – The number of times the circuit should be expanded. Expansion occurs when an operation or measurement is not supported, and results in a gate decomposition. If any operations in the decomposition remain unsupported by the device, another expansion occurs.

Returns

The expanded/decomposed circuit, such that the device will natively support all operations.

Return type

.QuantumTape

expval(observable, wires, par)[source]

Retrieve the requested observable expectation value.

filter_kwargs_for_backend(kwargs)

Filter the given kwargs for those relevant for the respective device/backend.

gradients(circuits, method='jacobian', **kwargs)

Return the gradients of a batch of quantum circuits on the device.

The gradient method method is called sequentially for each circuit, and the corresponding Jacobians are collected in a list.

For plugin developers: This method should be overwritten if the device can efficiently compute the gradient of multiple circuits on a backend, for example using parallel and/or asynchronous executions.

Parameters
  • circuits (list[.tape.QuantumTape]) – circuits to execute on the device

  • method (str) – the device method to call to compute the Jacobian of a single circuit

  • **kwargs – keyword argument to pass when calling method

Returns

List of Jacobians. Returned Jacobians should be of shape (output_shape, num_params).

Return type

list[array[float]]

map_wires(wires)

Map the wire labels of wires using this device’s wire map.

Parameters

wires (Wires) – wires whose labels we want to map to the device’s internal labelling scheme

Returns

wires with new labels

Return type

Wires

order_wires(subset_wires)

Given some subset of device wires return a Wires object with the same wires; sorted according to the device wire map.

Parameters

subset_wires (Wires) – The subset of device wires (in any order).

Raises

ValueError – Could not find some or all subset wires subset_wires in device wires device_wires.

Returns

a new Wires object containing the re-ordered wires set

Return type

ordered_wires (Wires)

post_apply()

Called during execute() after the individual operations have been executed.

post_measure()

Deallocate the qubits after expectation values have been retrieved.

pre_apply()

Called during execute() before the individual operations are executed.

pre_measure()[source]

Rotate qubits to the right basis before measurement, apply a measure all operation and flush the device before retrieving expectation values.

probability(wires=None)

Return the (marginal) probability of each computational basis state from the last run of the device.

Parameters

wires (Sequence[int]) – Sequence of wires to return marginal probabilities for. Wires not provided are traced out of the system.

Returns

Dictionary mapping a tuple representing the state to the resulting probability. The dictionary should be sorted such that the state tuples are in lexicographical order.

Return type

OrderedDict[tuple, float]

reset()[source]

Reset/initialize the device by initializing the backend and engine, and allocating qubits.

sample(observable, wires, par)

Return a sample of an observable.

The number of samples is determined by the value of Device.shots, which can be directly modified.

Note: all arguments support _lists_, which indicate a tensor product of observables.

Parameters
  • observable (str or list[str]) – name of the observable(s)

  • wires (Wires) – wires the observable(s) is to be measured on

  • par (tuple or list[tuple]]) – parameters for the observable(s)

Raises

NotImplementedError – if the device does not support sampling

Returns

samples in an array of dimension (shots,)

Return type

array[float]

supports_observable(observable)
Checks if an observable is supported by this device. Raises a ValueError,

if not a subclass or string of an Observable was passed.

Parameters

observable (type or str) – observable to be checked

Raises

ValueError – if observable is not a Observable class or string

Returns

True iff supplied observable is supported

Return type

bool

supports_operation(operation)

Checks if an operation is supported by this device.

Parameters

operation (type or str) – operation to be checked

Raises

ValueError – if operation is not a Operation class or string

Returns

True if supplied operation is supported

Return type

bool

var(observable, wires, par)[source]

Retrieve the requested observable variance.