OrquestraDevice

class pennylane_orquestra.OrquestraDevice(wires, shots=None, **kwargs)[source]

Bases: QubitDevice, ABC

The Orquestra base device.

Provides the execute() and batch_execute() methods which allows remote device executions by generating, submitting Orquestra workflows and processing their results.

The batch_execute() method can be utilized to send workflows that contain several circuits which are computed in parallel on a remote device.

The workflow files generated are placed into a user specific data folder specified by the output of appdirs.user_data_dir("pennylane-orquestra", "Xanadu"). By default, such files are removed (see keep_files keyword argument). After each device execution, filenames for the generated workflows are stored in the filenames attribute.

Computing the expectation value of the identity operator does not involve a workflow submission (hence no files are created).

Parameters
  • wires (int, Iterable[Number, str]]) – 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']). Default 1 if not specified.

  • shots (int or list[int]) – Number of circuit evaluations/random samples used to estimate expectation values of observables. If None, the device calculates probability, expectation values, and variances analytically. If an integer, it specifies the number of samples to estimate these quantities. If a list of integers is passed, the circuit evaluations are batched over the list of shots.

Keyword Arguments
  • backend=None (str) – the Orquestra backend device to use for the specific Orquestra backend, if applicable

  • batch_size=10 (int) – the size of each circuit batch when using the batch_execute() method to send multiple workflows

  • keep_files=False (bool) – whether or not the workflow files generated during the circuit execution should be kept or deleted

  • resources=None (dict) – an option for Orquestra, specifies the resources provisioned for the clusters running each workflow step

  • timeout=600 (int) – the maximum time until a job will timeout after getting no response from Orquestra (in seconds)

analytic

Whether shots is None or not.

author

backend_specs

The backend specifications defined for the device.

circuit_hash

The hash of the circuit upon the last execution.

filenames

Returns the names of the workflow files created during device executions.

latest_id

Returns the latest workflow ID that has been executed.

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

op_queue

The operation queue to be applied.

operations

parameters

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

pennylane_requires

qe_component

Device specific Orquestra component name used in the backend specification.

qe_function_name

Device specific Orquestra function name used in the backend specification.

qe_module_name

Device specific Orquestra module name used in the backend specification.

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

state

Returns the state vector of the circuit prior to measurement.

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 = 'Xanadu'
backend_specs

The backend specifications defined for the device.

Returns

the backend specifications represented as a string

Return type

str

circuit_hash

The hash of the circuit upon the last execution.

This can be used by devices in apply() for parametric compilation.

filenames

Returns the names of the workflow files created during device executions.

Returns

the workflow filenames

Return type

list

latest_id

Returns the latest workflow ID that has been executed.

Returns

the ID of the latest workflow that has been submitted

Return type

str

name = 'Orquestra base device for PennyLane'
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 = {'Hadamard', 'Identity', 'PauliX', 'PauliY', 'PauliZ'}
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 = {'BasisState', 'CNOT', 'CRX', 'CRY', 'CRZ', 'CRot', 'CSWAP', 'CY', 'CZ', 'Hadamard', 'MultiRZ', 'PauliX', 'PauliY', 'PauliZ', 'PhaseShift', 'QubitStateVector', 'RX', 'RY', 'RZ', 'Rot', 'S', 'SWAP', 'SX', 'T', 'Toffoli'}
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'
qe_component

Device specific Orquestra component name used in the backend specification.

qe_function_name

Device specific Orquestra function name used in the backend specification.

qe_module_name

Device specific Orquestra module name used in the backend specification.

short_name = 'orquestra.base'
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", wires=2, shots=[3, 1, 2, 2, 2, 2, 6, 1, 1, 5, 12, 10, 10])
>>> dev.shots
57
>>> dev.shot_vector
[ShotTuple(shots=3, copies=1),
 ShotTuple(shots=1, copies=1),
 ShotTuple(shots=2, copies=4),
 ShotTuple(shots=6, copies=1),
 ShotTuple(shots=1, copies=2),
 ShotTuple(shots=5, copies=1),
 ShotTuple(shots=12, copies=1),
 ShotTuple(shots=10, copies=2)]

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

Type

list[.ShotTuple[int, int]]

shots

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

state

Returns the state vector of the circuit prior to measurement.

Note

Only state vector simulators support this property. Please see the plugin documentation for more details.

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.23.0-dev'
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

access_state([wires])

Check that the device has access to an internal state and return it if available.

active_wires(operators)

Returns the wires acted on by a set of operators.

adjoint_jacobian(tape[, starting_state, ...])

Implements the adjoint method outlined in Jones and Gacon to differentiate an input tape.

analytic_probability([wires])

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

apply(operations, **kwargs)

Apply quantum operations, rotate the circuit into the measurement basis, and compile and execute the quantum circuit.

batch_execute(circuits, **kwargs)

Execute a batch of quantum circuits on the device.

batch_execute_new(circuits)

Temporary batch execute function, waiting for QNode execution of the new return types.

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.

classical_shadow(obs, circuit)

Returns the measured bits and recipes in the classical shadow protocol.

create_backend_specs()

Create the backend specifications as a dictionary based on the device options.

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.

density_matrix(wires)

Returns the reduced density matrix over the given wires.

estimate_probability([wires, shot_range, ...])

Return the estimated probability of each computational basis state using the generated samples.

execute(circuit, **kwargs)

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.

execute_new(circuit, **kwargs)

New execute (update of return type) function, it executes a queue of quantum operations on the device and then measure the given observables.

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[, shot_range, bin_size])

Returns the expectation value of observable on specified wires.

generate_basis_states(num_wires[, dtype])

Generates basis states in binary representation according to the number of wires specified.

generate_samples()

Returns the computational basis samples generated for all wires.

gradients(circuits[, method])

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

insert_identity_res_batch(results, ...)

An auxiliary function for inserting values which were not computed using workflows into batch results.

map_wires(wires)

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

marginal_prob(prob[, wires])

Return the marginal probability of the computational basis states by summing the probabiliites on the non-specified wires.

multi_step_execute(circuits, file_id, **kwargs)

Creates a multi-step workflow for executing a batch of circuits.

multiple_steps_results(workflow_id)

Extracts the results of multiple steps obtained for a workflow.

mutual_info(wires0, wires1, log_base)

Returns the mutual information prior to measurement:

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.

pauliz_operator_string(wires)

Creates an OpenFermion operator string based on the measured wires that can be passed when creating an openfermion.IsingOperator.

post_apply()

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

post_measure()

Called during execute() after the individual observables have been measured.

pre_apply()

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

pre_measure()

Called during execute() before the individual observables are measured.

probability([wires, shot_range, bin_size])

Return either the analytic probability or estimated probability of each computational basis state.

process_observables(observables)

Processes the observables provided with the circuits.

qubit_operator_string(observable)

Serializes a PennyLane observable to a string compatible with the openfermion.QubitOperator class.

reset()

Reset the backend state.

sample(observable[, shot_range, bin_size, ...])

Return samples of an observable.

sample_basis_states(number_of_states, ...)

Sample from the computational basis states based on the state probability.

serialize_circuit(circuit)

Serializes the circuit before submission according to the backend specified.

serialize_operator(observable)

Serialize the observable specified for the circuit as an OpenFermion operator.

shadow_expval(obs, circuit)

Compute expectation values using classical shadows in a differentiable manner.

shot_vec_statistics(circuit)

Process measurement results from circuit execution using a device with a shot vector and return statistics.

single_step_results(workflow_id)

Extracts the results of a single step obtained for a workflow.

states_to_binary(samples, num_wires[, dtype])

Convert basis states from base 10 to binary representation.

statistics(observables[, shot_range, ...])

Process measurement results from circuit execution and return statistics.

statistics_new(observables[, shot_range, ...])

Process measurement results from circuit execution and return statistics.

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[, shot_range, bin_size])

Returns the variance of observable on specified wires.

vn_entropy(wires, log_base)

Returns the Von Neumann entropy prior to measurement.

access_state(wires=None)

Check that the device has access to an internal state and return it if available.

Parameters

wires (Wires) – wires of the reduced system

Raises

QuantumFunctionError – if the device is not capable of returning the state

Returns

the state or the density matrix of the device

Return type

array or tensor

static active_wires(operators)

Returns the wires acted on by a set of operators.

Parameters

operators (list[Operation]) – operators for which we are gathering the active wires

Returns

wires activated by the specified operators

Return type

Wires

adjoint_jacobian(tape, starting_state=None, use_device_state=False)

Implements the adjoint method outlined in Jones and Gacon to differentiate an input tape.

After a forward pass, the circuit is reversed by iteratively applying inverse (adjoint) gates to scan backwards through the circuit.

Note

The adjoint differentiation method has the following restrictions:

  • As it requires knowledge of the statevector, only statevector simulator devices can be used.

  • Only expectation values are supported as measurements.

  • Does not work for parametrized observables like Hamiltonian or Hermitian.

Parameters

tape (.QuantumTape) – circuit that the function takes the gradient of

Keyword Arguments
  • starting_state (tensor_like) – post-forward pass state to start execution with. It should be complex-valued. Takes precedence over use_device_state.

  • use_device_state (bool) – use current device state to initialize. A forward pass of the same circuit should be the last thing the device has executed. If a starting_state is provided, that takes precedence.

Returns

the derivative of the tape with respect to trainable parameters. Dimensions are (len(observables), len(trainable_params)).

Return type

array

Raises

QuantumFunctionError – if the input tape has measurements that are not expectation values or contains a multi-parameter operation aside from Rot

analytic_probability(wires=None)

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

PennyLane uses the convention \(|q_0,q_1,\dots,q_{N-1}\rangle\) where \(q_0\) is the most significant bit.

If no wires are specified, then all the basis states representable by the device are considered and no marginalization takes place.

Note

marginal_prob() may be used as a utility method to calculate the marginal probability distribution.

Parameters

wires (Iterable[Number, str], Number, str, Wires) – wires to return marginal probabilities for. Wires not provided are traced out of the system.

Returns

list of the probabilities

Return type

array[float]

apply(operations, **kwargs)[source]

Apply quantum operations, rotate the circuit into the measurement basis, and compile and execute the quantum circuit.

This method receives a list of quantum operations queued by the QNode, and should be responsible for:

  • Constructing the quantum program

  • (Optional) Rotating the quantum circuit using the rotation operations provided. This diagonalizes the circuit so that arbitrary observables can be measured in the computational basis.

  • Compile the circuit

  • Execute the quantum circuit

Both arguments are provided as lists of PennyLane Operation instances. Useful properties include name, wires, and parameters, and inverse:

>>> op = qml.RX(0.2, wires=[0])
>>> op.name # returns the operation name
"RX"
>>> op.wires # returns a Wires object representing the wires that the operation acts on
<Wires = [0]>
>>> op.parameters # returns a list of parameters
[0.2]
>>> op.inverse # check if the operation should be inverted
False
>>> op = qml.RX(0.2, wires=[0]).inv
>>> op.inverse
True
Parameters

operations (list[Operation]) – operations to apply to the device

Keyword Arguments
  • rotations (list[Operation]) – operations that rotate the circuit pre-measurement into the eigenbasis of the observables.

  • hash (int) – the hash value of the circuit constructed by CircuitGraph.hash

batch_execute(circuits, **kwargs)[source]

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[.tapes.QuantumTape]) – circuits to execute on the device

Returns

list of measured value(s)

Return type

list[array[float]]

batch_execute_new(circuits)

Temporary batch execute function, waiting for QNode execution of the new return types. 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[.tapes.QuantumTape]) – circuits to execute on the device

Returns

list of measured value(s)

Return type

list[array[float]]

batch_transform(circuit)

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

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_inverse_operations=False,
        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. Includes checks for inverse operations.

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

classical_shadow(obs, circuit)

Returns the measured bits and recipes in the classical shadow protocol.

The protocol is described in detail in the classical shadows paper. This measurement process returns the randomized Pauli measurements (the recipes) that are performed for each qubit and snapshot as an integer:

  • 0 for Pauli X,

  • 1 for Pauli Y, and

  • 2 for Pauli Z.

It also returns the measurement results (the bits); 0 if the 1 eigenvalue is sampled, and 1 if the -1 eigenvalue is sampled.

The device shots are used to specify the number of snapshots. If T is the number of shots and n is the number of qubits, then both the measured bits and the Pauli measurements have shape (T, n).

This implementation is device-agnostic and works by executing single-shot tapes containing randomized Pauli observables. Devices should override this if they can offer cleaner or faster implementations.

See also

classical_shadow()

Parameters
  • obs (ShadowMeasurementProcess) – The classical shadow measurement process

  • circuit (QuantumTape) – The quantum tape that is being executed

Returns

A tensor with shape (2, T, n), where the first row represents the measured bits and the second represents the recipes used.

Return type

tensor_like[int]

create_backend_specs()[source]

Create the backend specifications as a dictionary based on the device options.

Backend specifications are dictionaries submitted in a serialized json string format to Orquestra to specify which QuantumBackend to run quantum circuits on. Data specified include details such as the name of the external framework, the exact device to be used when several availabe, the number of samples to obtain (if not exact computation).

Returns

the backend specifications represented as a dictionary

Return type

dict

custom_expand(fn)

Register a custom expansion function for the device.

Example

dev = qml.device("default.qubit", 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:

  • 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]>)])
density_matrix(wires)

Returns the reduced density matrix over the given wires.

Parameters

wires (Wires) – wires of the reduced system

Returns

complex array of shape (2 ** len(wires), 2 ** len(wires)) representing the reduced density matrix of the state prior to measurement.

Return type

array[complex]

estimate_probability(wires=None, shot_range=None, bin_size=None)

Return the estimated probability of each computational basis state using the generated samples.

Parameters
  • wires (Iterable[Number, str], Number, str, Wires) – wires to calculate marginal probabilities for. Wires not provided are traced out of the system.

  • shot_range (tuple[int]) – 2-tuple of integers specifying the range of samples to use. If not specified, all samples are used.

  • bin_size (int) – Divides the shot range into bins of size bin_size, and returns the measurement statistic separately over each bin. If not provided, the entire shot range is treated as a single bin.

Returns

list of the probabilities

Return type

array[float]

execute(circuit, **kwargs)[source]

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

Additional keyword arguments may be passed to the this method that can be utilised by apply(). An example would be passing the QNode hash that can be used later for parametric compilation.

Parameters

circuit (QuantumTape) – circuit to execute on the device

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

execute_new(circuit, **kwargs)

New execute (update of return type) function, it executes a queue of quantum operations on the device and then measure the given observables. More case will be added in future PRs, for the moment it only supports measurements without shots.

For plugin developers: instead of overwriting this, consider implementing a suitable subset of

Additional keyword arguments may be passed to the this method that can be utilised by apply(). An example would be passing the QNode hash that can be used later for parametric compilation.

Parameters

circuit (QuantumTape) – circuit to execute on the device

Raises

QuantumFunctionError – if the value of return_type is not supported

Returns

measured value(s)

Return type

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 Device.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, shot_range=None, bin_size=None)

Returns the expectation value of observable on specified wires.

Note: all arguments accept _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) are to be measured on

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

Returns

expectation value \(\expect{A} = \bra{\psi}A\ket{\psi}\)

Return type

float

generate_basis_states(num_wires, dtype=<class 'numpy.uint32'>)

Generates basis states in binary representation according to the number of wires specified.

The states_to_binary method creates basis states faster (for larger systems at times over x25 times faster) than the approach using itertools.product, at the expense of using slightly more memory.

Due to the large size of the integer arrays for more than 32 bits, memory allocation errors may arise in the states_to_binary method. Hence we constraint the dtype of the array to represent unsigned integers on 32 bits. Due to this constraint, an overflow occurs for 32 or more wires, therefore this approach is used only for fewer wires.

For smaller number of wires speed is comparable to the next approach (using itertools.product), hence we resort to that one for testing purposes.

Parameters
  • num_wires (int) – the number wires

  • dtype=np.uint32 (type) – the data type of the arrays to use

Returns

the sampled basis states

Return type

array[int]

generate_samples()

Returns the computational basis samples generated for all wires.

Note that PennyLane uses the convention \(|q_0,q_1,\dots,q_{N-1}\rangle\) where \(q_0\) is the most significant bit.

Warning

This method should be overwritten on devices that generate their own computational basis samples, with the resulting computational basis samples stored as self._samples.

Returns

array of samples in the shape (dev.shots, dev.num_wires)

Return type

array[complex]

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

static insert_identity_res_batch(results, empty_obs_list, identity_indices)[source]

An auxiliary function for inserting values which were not computed using workflows into batch results.

Computations involving the identity observable are given by theoretical values rather than as part of a workflow. Therefore, such values need to be inserted into the results later.

Parameters
  • results (list) – workflow results of the batched execution

  • empty_obs_list (list) – list of indices where every observable is the identity

  • identity_indices (dict) – maps the index of a sublist to the the list of indices where the observable is an identity

Returns

list of results

Return type

list

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

marginal_prob(prob, wires=None)

Return the marginal probability of the computational basis states by summing the probabiliites on the non-specified wires.

If no wires are specified, then all the basis states representable by the device are considered and no marginalization takes place.

Note

If the provided wires are not in the order as they appear on the device, the returned marginal probabilities take this permutation into account.

For example, if the addressable wires on this device are Wires([0, 1, 2]) and this function gets passed wires=[2, 0], then the returned marginal probability vector will take this ‘reversal’ of the two wires into account:

\[\mathbb{P}^{(2, 0)} = \left[ |00\rangle, |10\rangle, |01\rangle, |11\rangle \right]\]
Parameters
  • prob – The probabilities to return the marginal probabilities for

  • wires (Iterable[Number, str], Number, str, Wires) – wires to return marginal probabilities for. Wires not provided are traced out of the system.

Returns

array of the resulting marginal probabilities.

Return type

array[float]

multi_step_execute(circuits, file_id, **kwargs)[source]

Creates a multi-step workflow for executing a batch of circuits.

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

  • file_id (str) – the file id to be used for naming the workflow file

Returns

list of measured value(s) for the batch

Return type

list[array[float]]

multiple_steps_results(workflow_id)[source]

Extracts the results of multiple steps obtained for a workflow.

This method assumes that the workflow had multiple steps and that the structure of the result corresponds to results sent by Orquestra API v1.0.0.

Orquestra doesn’t necessarily execute parallel steps in the order they were defined in a workflow file. Therefore, due to parallel execution, results might have been written in any order, so results are sorted by the step name.

Parameters

workflow_id (str) – the ID of the workflow to extract results for

Returns

a list of workflow results for each step

Return type

results (list)

mutual_info(wires0, wires1, log_base)

Returns the mutual information prior to measurement:

\[I(A, B) = S(\rho^A) + S(\rho^B) - S(\rho^{AB})\]

where \(S\) is the von Neumann entropy.

Parameters
  • wires0 (Wires) – wires of the first subsystem

  • wires1 (Wires) – wires of the second subsystem

  • log_base (float) – base to use in the logarithm

Returns

the mutual information

Return type

float

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)

static pauliz_operator_string(wires)[source]

Creates an OpenFermion operator string based on the measured wires that can be passed when creating an openfermion.IsingOperator.

This method is used if rotations are needed for the backend specified. In such a case a string that represents measuring PauliZ on each of the affected wires is used.

Example

>>> dev = QeQiskitDevice(wires=2)
>>> wires = [0, 1, 2]
>>> op_str = dev.pauliz_operator_string(wires)
>>> print(op_str)
[Z0 Z1 Z2]
>>> print(openfermion.IsingOperator(op_str))
1.0 [Z0 Z1 Z2]
Parameters

wires (Wires) – the wires the observable of the quantum function acts on

Returns

the openfermion.IsingOperator string representation

Return type

str

post_apply()

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

post_measure()

Called during execute() after the individual observables have been measured.

pre_apply()

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

pre_measure()

Called during execute() before the individual observables are measured.

probability(wires=None, shot_range=None, bin_size=None)

Return either the analytic probability or estimated probability of each computational basis state.

Devices that require a finite number of shots always return the estimated probability.

Parameters

wires (Iterable[Number, str], Number, str, Wires) – wires to return marginal probabilities for. Wires not provided are traced out of the system.

Returns

list of the probabilities

Return type

array[float]

process_observables(observables)[source]

Processes the observables provided with the circuits.

If the observable defined is the identity, then no serialization happens. Instead, the index of the observable is saved.

Parameters

observables (list) – a list of observables to process

Returns

  • the serialized non-identity operators

  • the indices of the identity operators

Return type

tuple

qubit_operator_string(observable)[source]

Serializes a PennyLane observable to a string compatible with the openfermion.QubitOperator class.

This method decomposes an observable into a sum of Pauli terms and identities, if needed.

Example

>>> dev = QeQiskitDevice(wires=2)
>>> obs = qml.PauliZ(0)
>>> op_str = dev.qubit_operator_string(obs)
>>> print(op_str)
1 [Z0]
>>> obs = qml.Hadamard(0)
>>> op_str = dev.qubit_operator_string(obs)
>>> print(op_str)
0.7071067811865475 [X0] + 0.7071067811865475 [Z0]
Parameters

observable (pennylane.operation.Observable) – the observable to serialize

Returns

the openfermion.QubitOperator string representation

Return type

str

reset()

Reset the backend state.

After the reset, the backend should be as if it was just constructed. Most importantly the quantum state is reset to its initial value.

sample(observable, shot_range=None, bin_size=None, counts=False)

Return samples of an observable.

Parameters
  • observable (Observable) – the observable to sample

  • shot_range (tuple[int]) – 2-tuple of integers specifying the range of samples to use. If not specified, all samples are used.

  • bin_size (int) – Divides the shot range into bins of size bin_size, and returns the measurement statistic separately over each bin. If not provided, the entire shot range is treated as a single bin.

  • counts (bool) – whether counts (True) or raw samples (False) should be returned

Raises

EigvalsUndefinedError – if no information is available about the eigenvalues of the observable

Returns

samples in an array of dimension (shots,) or counts

Return type

Union[array[float], dict, list[dict]]

sample_basis_states(number_of_states, state_probability)

Sample from the computational basis states based on the state probability.

This is an auxiliary method to the generate_samples method.

Parameters
  • number_of_states (int) – the number of basis states to sample from

  • state_probability (array[float]) – the computational basis probability vector

Returns

the sampled basis states

Return type

array[int]

serialize_circuit(circuit)[source]

Serializes the circuit before submission according to the backend specified.

The circuit is represented as an OpenQASM 2.0 program. Measurement instructions are removed from the program as the operator is passed separately.

Parameters

circuit (QuantumTape) – circuit to serialize

Returns

OpenQASM 2.0 representation of the circuit without any measurement instructions

Return type

str

serialize_operator(observable)[source]

Serialize the observable specified for the circuit as an OpenFermion operator.

Parameters

observable (pennylane.operation.Observable) – the observable to get the operator representation for

Returns

string representation of terms making up the observable

Return type

str

shadow_expval(obs, circuit)

Compute expectation values using classical shadows in a differentiable manner.

Please refer to shadow_expval() for detailed documentation.

Parameters
  • obs (ShadowMeasurementProcess) – The classical shadow expectation value measurement process

  • circuit (QuantumTape) – The quantum tape that is being executed

Returns

expectation value estimate.

Return type

float

shot_vec_statistics(circuit)

Process measurement results from circuit execution using a device with a shot vector and return statistics.

This is an auxiliary method of execute_new and uses statistics_new.

When using shot vectors, measurement results for each item of the shot vector are contained in a tuple.

Parameters

circuit (QuantumTape) – circuit to execute on the device

Raises

QuantumFunctionError – if the value of return_type is not supported

Returns

stastics for each shot item from the shot vector

Return type

tuple

single_step_results(workflow_id)[source]

Extracts the results of a single step obtained for a workflow.

This method assumes that the workflow had a single step and that the structure of the result corresponds to results sent by Orquestra API v1.0.0.

Parameters

workflow_id (str) – the ID of the workflow to extract results for

Returns

a list of workflow results

Return type

results (list)

static states_to_binary(samples, num_wires, dtype=<class 'numpy.int64'>)

Convert basis states from base 10 to binary representation.

This is an auxiliary method to the generate_samples method.

Parameters
  • samples (array[int]) – samples of basis states in base 10 representation

  • num_wires (int) – the number of qubits

  • dtype (type) – Type of the internal integer array to be used. Can be important to specify for large systems for memory allocation purposes.

Returns

basis states in binary representation

Return type

array[int]

statistics(observables, shot_range=None, bin_size=None, circuit=None)

Process measurement results from circuit execution and return statistics.

This includes returning expectation values, variance, samples, probabilities, states, and density matrices.

Parameters
  • observables (List[.Observable]) – the observables to be measured

  • shot_range (tuple[int]) – 2-tuple of integers specifying the range of samples to use. If not specified, all samples are used.

  • bin_size (int) – Divides the shot range into bins of size bin_size, and returns the measurement statistic separately over each bin. If not provided, the entire shot range is treated as a single bin.

  • circuit (QuantumTape) – the quantum tape currently being executed

Raises

QuantumFunctionError – if the value of return_type is not supported

Returns

the corresponding statistics

Return type

Union[float, List[float]]

The shot_range and bin_size arguments allow for the statistics to be performed on only a subset of device samples. This finer level of control is accessible from the main UI by instantiating a device with a batch of shots.

For example, consider the following device:

>>> dev = qml.device("my_device", shots=[5, (10, 3), 100])

This device will execute QNodes using 135 shots, however measurement statistics will be coarse grained across these 135 shots:

  • All measurement statistics will first be computed using the first 5 shots — that is, shots_range=[0, 5], bin_size=5.

  • Next, the tuple (10, 3) indicates 10 shots, repeated 3 times. We will want to use shot_range=[5, 35], performing the expectation value in bins of size 10 (bin_size=10).

  • Finally, we repeat the measurement statistics for the final 100 shots, shot_range=[35, 135], bin_size=100.

statistics_new(observables, shot_range=None, bin_size=None)

Process measurement results from circuit execution and return statistics.

This includes returning expectation values, variance, samples, probabilities, states, and density matrices.

Parameters
  • observables (List[.Observable]) – the observables to be measured

  • shot_range (tuple[int]) – 2-tuple of integers specifying the range of samples to use. If not specified, all samples are used.

  • bin_size (int) – Divides the shot range into bins of size bin_size, and returns the measurement statistic separately over each bin. If not provided, the entire shot range is treated as a single bin.

Raises

QuantumFunctionError – if the value of return_type is not supported

Returns

the corresponding statistics

Return type

Union[float, List[float]]

The shot_range and bin_size arguments allow for the statistics to be performed on only a subset of device samples. This finer level of control is accessible from the main UI by instantiating a device with a batch of shots.

For example, consider the following device:

>>> dev = qml.device("my_device", shots=[5, (10, 3), 100])

This device will execute QNodes using 135 shots, however measurement statistics will be course grained across these 135 shots:

  • All measurement statistics will first be computed using the first 5 shots — that is, shots_range=[0, 5], bin_size=5.

  • Next, the tuple (10, 3) indicates 10 shots, repeated 3 times. We will want to use shot_range=[5, 35], performing the expectation value in bins of size 10 (bin_size=10).

  • Finally, we repeat the measurement statistics for the final 100 shots, shot_range=[35, 135], bin_size=100.

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 iff supplied operation is supported

Return type

bool

var(observable, shot_range=None, bin_size=None)

Returns the variance of observable on specified wires.

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 variance computation

Returns

variance \(\mathrm{var}(A) = \bra{\psi}A^2\ket{\psi} - \bra{\psi}A\ket{\psi}^2\)

Return type

float

vn_entropy(wires, log_base)

Returns the Von Neumann entropy prior to measurement.

\[S( \rho ) = -\text{Tr}( \rho \log ( \rho ))\]
Parameters
  • wires (Wires) – Wires of the considered subsystem.

  • log_base (float) – Base for the logarithm, default is None the natural logarithm is used in this case.

Returns

returns the Von Neumann entropy

Return type

float

Contents