qml.QubitDevice

class QubitDevice(wires=1, shots=1000, analytic=True)[source]

Bases: pennylane._device.Device

Abstract base class for PennyLane qubit devices.

The following abstract method must be defined:

  • apply(): append circuit operations, compile the circuit (if applicable), and perform the quantum computation.

Devices that generate their own samples (such as hardware) may optionally overwrite probabilty(). This method otherwise automatically computes the probabilities from the generated samples, and must overwrite the following method:

  • generate_samples(): Generate samples from the device from the exact or approximate probability distribution.

Analytic devices must overwrite the following method:

This device contains common utility methods for qubit-based devices. These do not need to be overwritten. Utility methods include:

  • expval(), var(), sample(): return expectation values, variances, and samples of observables after the circuit has been rotated into the observable eigenbasis.

Parameters
  • wires (int) – number of subsystems in the quantum state represented by the device

  • shots (int) – number of circuit evaluations/random samples used to estimate expectation values of observables

  • analytic (bool) – If True, the device calculates probability, expectation values, and variances analytically. If False, a finite number of samples set by the argument shots are used to estimate these quantities.

author

The author(s) of the plugin.

circuit_hash

The hash of the circuit upon the last execution.

name

The full name of the device.

obs_queue

The observables to be measured and returned.

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

The current API version that the device plugin was made for.

short_name

Returns the string used to load the device.

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.

version

The current version of the plugin.

author

The author(s) of the plugin.

circuit_hash

The hash of the circuit upon the last execution.

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

name

The full name of the device.

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', 'Hermitian', '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

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

The current API version that the device plugin was made for.

short_name

Returns the string used to load the device.

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.

version

The current version of the plugin.

active_wires(operators)

Returns the wires acted on by a set of operators.

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.

capabilities()

Get the capabilities of the plugin.

check_validity(queue, observables)

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

estimate_probability([wires])

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.

execution_context()

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

expval(observable)

Returns the expectation value of observable on specified wires.

generate_samples()

Returns the computational basis samples generated for all wires.

marginal_prob(prob[, wires])

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

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

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

reset()

Reset the backend state.

sample(observable)

Return a sample of an observable.

sample_basis_states(number_of_states, …)

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

states_to_binary(samples, num_wires)

Convert basis states from base 10 to binary representation.

statistics(observables)

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)

Returns the variance of observable on specified wires.

static active_wires(operators)[source]

Returns the wires acted on by a set of operators.

Parameters

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

Returns

the set of wires activated by the specified operators

Return type

set[int]

analytic_probability(wires=None)[source]

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 (Sequence[int]) – Sequence of wires to return marginal probabilities for. Wires not provided are traced out of the system.

Returns

list of the probabilities

Return type

List[float]

abstract 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 list of 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

classmethod capabilities()[source]

Get the capabilities of the plugin.

Capabilities include:

  • "model" (str): either "qubit" or "CV".

  • "inverse_operations" (bool): True if the device supports applying the inverse of operations. Operations which should be inverted have operation.inverse == True.

  • "tensor_observables" (*bool*): ``True if the device supports expectation values/variance/samples of Tensor observables.

The qubit device class has built-in support for tensor observables. As a result, devices that inherit from this class automatically have the following items in their capabilities dictionary:

  • "model": "qubit"

  • "tensor_observables": True

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

estimate_probability(wires=None)[source]

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

Parameters

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

Returns

list of the probabilities

Return type

List[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 (CircuitGraph) – 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).

expval(observable)[source]

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 (List[int] or List[List[int]]) – subsystems the observable(s) is 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_samples()[source]

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]

marginal_prob(prob, wires=None)[source]

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 strictly increasing, the returned marginal probabilities take this permuation into account.

For example, if wires=[2, 0], then the returned marginal probability vector will take this ‘reversal’ of the two wires into account:

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

  • wires (Sequence[int]) – Sequence of 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]

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

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

If no analytic attributes exists for the device, then return the estimated probability.

Parameters

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

Returns

list of the probabilities

Return type

List[float]

reset()[source]

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

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 (List[int] or List[List[int]]) – subsystems 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 (n, num_wires)

Return type

array[float]

sample_basis_states(number_of_states, state_probability)[source]

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

Returns

the sampled basis states

Return type

List[int]

static states_to_binary(samples, num_wires)[source]

Convert basis states from base 10 to binary representation.

This is an auxiliary method to the generate_samples method.

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

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

Returns

basis states in binary representation

Return type

List[int]

statistics(observables)[source]

Process measurement results from circuit execution and return statistics.

This includes returning expectation values, variance, samples and probabilities.

Parameters

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

Raises

QuantumFunctionError – if the value of return_type is not supported

Returns

the corresponding statistics

Return type

Union[float, List[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 iff supplied operation is supported

Return type

bool

var(observable)[source]

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 (List[int] or List[List[int]]) – subsystems 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

Contents

Using PennyLane

Development

API