# pennylane_forest.QVMDevice¶

class QVMDevice(device, *, wires=None, shots=1000, noisy=False, **kwargs)[source]

Bases: pennylane_forest.device.ForestDevice

Forest QVM device for PennyLane.

This device supports both the Rigetti Lisp QVM, as well as the built-in pyQuil pyQVM. If using the pyQVM, the qvm_url QVM server url keyword argument does not need to be set.

Parameters: Keyword Arguments: device (Union[str, nx.Graph]) – the name or topology of the device to initialise. Nq-qvm: for a fully connected/unrestricted N-qubit QVM 9q-square-qvm: a $$9\times 9$$ lattice. Nq-pyqvm or 9q-square-pyqvm, for the same as the above but run via the built-in pyQuil pyQVM device. Any other supported Rigetti device architecture. Graph topology representing the device architecture. shots (None, int, 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. wires (Iterable[Number, str]) – Iterable that contains unique labels for the qubits as numbers or strings (i.e., ['q1', ..., 'qN']). The number of labels must match the number of qubits accessible on the backend. If not provided, qubits are addressed as consecutive integers [0, 1, …], and their number is inferred from the backend. noisy (bool) – set to True to add noise models to your QVM. forest_url (str) – the Forest URL server. Can also be set by the environment variable FOREST_SERVER_URL, or in the ~/.qcs_config configuration file. Default value is "https://forest-server.qcs.rigetti.com". qvm_url (str) – the QVM server URL. Can also be set by the environment variable QVM_URL, or in the ~/.forest_config configuration file. Default value is "http://127.0.0.1:5000". compiler_url (str) – the compiler server URL. Can also be set by the environment variable COMPILER_URL, or in the ~/.forest_config configuration file. Default value is "http://127.0.0.1:6000". timeout (int) – number of seconds to wait for a response from the client. parametric_compilation (bool) – a boolean value of whether or not to use parametric compilation.
 analytic Whether shots is None or not. author cache Number of device executions to store in a cache to speed up subsequent executions. circuit_hash The hash of the circuit upon the last execution. compiled_program Returns the latest program that was compiled for running. map_wires Map the wire labels of wires using this device’s wire map. 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 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 program View the last evaluated Quil program 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. 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 = 'Rigetti Computing Inc.'
cache

Number of device executions to store in a cache to speed up subsequent executions. If set to zero, no caching occurs.

Type: int
circuit_hash

The hash of the circuit upon the last execution.

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

compiled_program

Returns the latest program that was compiled for running.

If parametric compilation is turned on, this will be a parametric program.

The pyquil.ExecutableDesignator.program attribute stores the pyquil.Program instance. If no program was compiled yet, this property returns None.

Returns: the latest compiled program Union[None, pyquil.ExecutableDesignator]
map_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 wires with new labels Wires
name = 'Forest QVM Device'
num_executions

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

Returns: number of executions 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 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 list[~.operation.Operation]
operations

Get the supported set of operations.

Returns: the set of PennyLane operation names the device supports 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 the mapping dict[int->list[ParameterDependency]]
pennylane_requires = '>=0.17'
program

View the last evaluated Quil program

short_name = 'forest.qvm'
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.

version = '0.17.0'
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) Run the QVM apply_parametric_program(operations, **kwargs) Applies a parametric program by applying parametric operation with symbolic parameters. apply_rotations(rotations) Apply the circuit rotations. batch_execute(circuits) Execute a batch of quantum circuits on the device. 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. 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 prior to measurement. 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. execution_context() The device execution context used during calls to execute(). 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. marginal_prob(prob[, wires]) Return the marginal probability of the computational basis states by summing the probabiliites on the non-specified wires. mat_vec_product(mat, vec, device_wire_labels) Apply multiplication of a matrix to subsystems of the quantum state. 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. reset() Resets the device after the previous run. sample(observable[, shot_range, bin_size]) 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[, dtype]) Convert basis states from base 10 to binary representation. statistics(observables[, shot_range, bin_size]) 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.
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 QuantumFunctionError – if the device is not capable of returning the state the state or the density matrix of the device 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 wires activated by the specified operators 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. This method is similar to the reversible method, but has a lower time overhead and a similar memory overhead.

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.
Parameters: Keyword Arguments: tape (QuantumTape) – circuit that the function takes the gradient of 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. the derivative of the tape with respect to trainable parameters. Dimensions are (len(observables), len(trainable_params)). array 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.

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

Warning

This method will have to be redefined for hardware devices, since it uses the device._state attribute. This attribute might not be available for such devices.

Parameters: wires (Iterable[Number, str], Number, str, Wires) – wires to return marginal probabilities for. Wires not provided are traced out of the system. list of the probabilities List[float]
apply(operations, **kwargs)[source]

Run the QVM

apply_parametric_program(operations, **kwargs)[source]

Applies a parametric program by applying parametric operation with symbolic parameters.

apply_rotations(rotations)

Apply the circuit rotations.

This method serves as an auxiliary method to apply().

Parameters: rotations (List[pennylane.Operation]) – operations that rotate into the measurement basis the pyquil Program that specifies the corresponding rotations pyquil.Program
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[tapes.QuantumTape]) – circuits to execute on the device list of measured value(s) list[array[float]]
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_inverse_operations=False,
supports_a_new_capability=True,
)
return capabilities

Returns: results 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 DeviceError – if there are operations in the queue or observables that the device does not support
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 dictionary specifying the wire map 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 prior to measurement.

Note

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

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. list of the probabilities 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 (CircuitGraph) – circuit to execute on the device QuantumFunctionError – if the value of return_type is not supported measured value(s) 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, 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) expectation value $$\expect{A} = \bra{\psi}A\ket{\psi}$$ float
static 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 the sampled basis states array[int]
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) array[complex]
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. array of the resulting marginal probabilities. array[float]
mat_vec_product(mat, vec, device_wire_labels)

Apply multiplication of a matrix to subsystems of the quantum state.

Parameters: mat (array) – matrix to multiply vec (array) – state vector to multiply device_wire_labels (Sequence[int]) – labels of device subsystems output vector after applying mat to input vec on specified subsystems array
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. list of the probabilities array[float]
reset()[source]

Resets the device after the previous run.

Note

The _compiled_program and the _compiled_program_dict attributes are not reset such that these can be used upon multiple device execution.

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

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) NotImplementedError – if the device does not support sampling samples in an array of dimension (shots,) array[float]
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 the sampled basis states array[int]
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. basis states in binary representation array[int]
statistics(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. QuantumFunctionError – if the value of return_type is not supported the corresponding statistics 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 ValueError – if observable is not a Observable class or string True iff supplied observable is supported bool
supports_operation(operation)

Checks if an operation is supported by this device.

Parameters: operation (type or str) – operation to be checked ValueError – if operation is not a Operation class or string True iff supplied operation is supported 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) NotImplementedError – if the device does not support variance computation variance $$\mathrm{var}(A) = \bra{\psi}A^2\ket{\psi} - \bra{\psi}A\ket{\psi}^2$$ float