# Backend API¶

Module name: strawberryfields.backends.base

This module implements the backend API. It contains the classes

as well as a few methods which apply only to the Gaussian backend.

Note

The backend API is $$\hbar$$ independent. Internally the Strawberry Fields backends use $$\hbar=2$$.

Note

Keyword arguments are denoted **kwargs, and allow additional options to be passed to the backends - these are documented where available. For more details on available keyword arguments, please consult the backends directly.

## BaseBackend¶

 supports(name) Check whether the backend supports the given operating mode. begin_circuit(num_subsystems, **kwargs) Instantiate a quantum circuit. add_mode([n]) Add modes to the circuit. del_mode(modes) Delete modes from the circuit. get_modes() Return a list of the active modes for the circuit. reset([pure]) Reset the circuit so that all the modes are in the vacuum state. state([modes]) Returns the state of the quantum simulation. is_vacuum([tol]) Test whether the current circuit state is vacuum (up to given tolerance). prepare_vacuum_state(mode) Prepare the vacuum state in the specified mode. prepare_coherent_state(alpha, mode) Prepare a coherent state in the specified mode. prepare_squeezed_state(r, phi, mode) Prepare a squeezed vacuum state in the specified mode. prepare_displaced_squeezed_state(alpha, r, …) Prepare a displaced squeezed state in the specified mode. prepare_thermal_state(nbar, mode) Prepare a thermal state in the specified mode. rotation(phi, mode) Apply the phase-space rotation operation to the specified mode. displacement(alpha, mode) Apply the displacement operation to the specified mode. squeeze(z, mode) Apply the squeezing operation to the specified mode. beamsplitter(t, r, mode1, mode2) Apply the beamsplitter operation to the specified modes. loss(T, mode) Perform a loss channel operation on the specified mode. thermal_loss(T, nbar, mode) Perform a thermal loss channel operation on the specified mode. measure_homodyne(phi, mode[, shots, select]) Measure a phase space quadrature of the given mode. measure_fock(modes[, shots, select]) Measure the given modes in the Fock basis.

## Fock backends¶

Some methods are only implemented in the subclass BaseFock, which is the base class for simulators using a Fock-state representation for quantum optical circuits.

 get_cutoff_dim() Returns the Hilbert space cutoff dimension used. prepare_fock_state(n, mode) Prepare a Fock state in the specified mode. prepare_ket_state(state, modes) Prepare the given ket state in the specified modes. prepare_dm_state(state, modes) Prepare the given mixed state in the specified modes. cubic_phase(gamma, mode) Apply the cubic phase operation to the specified mode. kerr_interaction(kappa, mode) Apply the Kerr interaction $$\exp{(i\kappa \hat{n}^2)}$$ to the specified mode. cross_kerr_interaction(kappa, mode1, mode2) Apply the two mode cross-Kerr interaction $$\exp{(i\kappa \hat{n}_1\hat{n}_2)}$$ to the specified modes.

## Gaussian backends¶

Likewise, some methods are only implemented in subclass BaseGaussian, which is the base class for simulators using a Gaussian symplectic representation for quantum optical circuits.

 measure_heterodyne(mode[, shots, select]) Perform a heterodyne measurement on the given mode.

### Code details¶

exception strawberryfields.backends.base.NotApplicableError[source]

Exception raised by the backend when the user attempts an unsupported operation. E.g. measure_fock() on a Gaussian backend. Conceptually different from NotImplementedError (which means “not implemented, but at some point may be”).

class strawberryfields.backends.base.ModeMap(num_subsystems)[source]

Simple internal class for maintaining a map of existing modes.

reset()[source]

reset the modemap to the initial state

remap(modes)[source]

Remaps the mode list

valid(modes)[source]

checks if the mode list is valid

show()[source]

Returns the mapping

delete(modes)[source]

Deletes a mode

add(num_modes)[source]

class strawberryfields.backends.base.BaseBackend[source]

Abstract base class for backends.

short_name = 'base'

short name of the backend

Type: str
circuit_spec = None

Short name of the CircuitSpecs class used to validate Programs for this backend. None if no validation is required.

Type: str, None
supports(name)[source]

Check whether the backend supports the given operating mode.

Currently supported operating modes are:

• “gaussian”: for manipulations in the Gaussian representation using the displacements and covariance matrices
• “fock_basis”: for manipulations in the Fock representation
• “mixed_states”: for representations where the quantum state is mixed
• “batched”: allows for a multiple circuits to be simulated in parallel
Parameters: name (str) – name of the operating mode which we are checking support for True if this backend supports that operating mode. bool
begin_circuit(num_subsystems, **kwargs)[source]

Instantiate a quantum circuit.

Instantiates a representation of a quantum optical state with num_subsystems modes. The state is initialized to vacuum.

The modes in the circuit are indexed sequentially using integers, starting from zero. Once an index is assigned to a mode, it can never be re-assigned to another mode. If the mode is deleted its index becomes invalid. An operation acting on an invalid or unassigned mode index raises an IndexError exception.

Parameters: Keyword Arguments: num_subsystems (int) – number of modes in the circuit cutoff_dim (int) – Hilbert space truncation dimension (for Fock basis backends only) batch_size (int) – (optional) batch-axis dimension, enables batched operation if > 1 (for the TF backend only)
add_mode(n=1)[source]

The new modes are initialized to the vacuum state. They are assigned mode indices sequentially, starting from the first unassigned index.

Parameters: n (int) – number of modes to add indices of the newly added modes list[int]
del_mode(modes)[source]

Delete modes from the circuit.

The deleted modes are traced out. As a result the state may have to be described using a density matrix.

The indices of the deleted modes become invalid for the lifetime of the circuit object. They will never be reassigned to other modes. Deleting a mode that has already been deleted raises an IndexError exception.

Parameters: modes (Sequence[int]) – mode numbers to delete
get_modes()[source]

Return a list of the active modes for the circuit.

A mode is active if it has been created and has not been deleted.

Returns: sorted list of active (assigned, not invalid) mode indices list[int]
reset(pure=True, **kwargs)[source]

Reset the circuit so that all the modes are in the vacuum state.

After the reset the circuit is in the same state as it was after the last begin_circuit() call. It will have the original number of modes, all initialized in the vacuum state. Some circuit parameters may be changed during the reset, see the keyword args below.

Parameters: Keyword Arguments: pure (bool) – if True, initialize the circuit in a pure state representation (will use a mixed state representation if pure is False) cutoff_dim (int) – new Hilbert space truncation dimension (for Fock basis backends only)
prepare_vacuum_state(mode)[source]

Prepare the vacuum state in the specified mode.

The requested mode is traced out and replaced with the vacuum state. As a result the state may have to be described using a density matrix.

Parameters: mode (int) – which mode to prepare the vacuum state in
prepare_coherent_state(alpha, mode)[source]

Prepare a coherent state in the specified mode.

The requested mode is traced out and replaced with the coherent state $$\ket{\alpha}$$. As a result the state may have to be described using a density matrix.

Parameters: alpha (complex) – coherent state displacement parameter mode (int) – which mode to prepare the coherent state in
prepare_squeezed_state(r, phi, mode)[source]

Prepare a squeezed vacuum state in the specified mode.

The requested mode is traced out and replaced with the squeezed state $$\ket{z}$$, where $$z=re^{i\phi}$$. As a result the state may have to be described using a density matrix.

Parameters: r (float) – squeezing amplitude phi (float) – squeezing angle mode (int) – which mode to prepare the squeezed state in
prepare_displaced_squeezed_state(alpha, r, phi, mode)[source]

Prepare a displaced squeezed state in the specified mode.

The requested mode is traced out and replaced with the displaced squeezed state state $$\ket{\alpha, z}$$, where $$z=re^{i\phi}$$. As a result the state may have to be described using a density matrix.

Parameters: alpha (complex) – displacement parameter r (float) – squeezing amplitude phi (float) – squeezing angle mode (int) – which mode to prepare the squeezed state in
prepare_thermal_state(nbar, mode)[source]

Prepare a thermal state in the specified mode.

The requested mode is traced out and replaced with the thermal state $$\rho(nbar)$$. As a result the state may have to be described using a density matrix.

Parameters: nbar (float) – thermal population (mean photon number) of the mode mode (int) – which mode to prepare the thermal state in
rotation(phi, mode)[source]

Apply the phase-space rotation operation to the specified mode.

Parameters: phi (float) – rotation angle mode (int) – which mode to apply the rotation to
displacement(alpha, mode)[source]

Apply the displacement operation to the specified mode.

Parameters: alpha (complex) – displacement parameter mode (int) – which mode to apply the displacement to
squeeze(z, mode)[source]

Apply the squeezing operation to the specified mode.

Parameters: z (complex) – squeezing parameter mode (int) – which mode to apply the squeeze to
beamsplitter(t, r, mode1, mode2)[source]

Apply the beamsplitter operation to the specified modes.

It is assumed that $$|r|^2+|t|^2 = t^2+|r|^2=1$$, i.e that t is real.

Parameters: t (float) – transmitted amplitude r (complex) – reflected amplitude (with phase) mode1 (int) – first mode that beamsplitter acts on mode2 (int) – second mode that beamsplitter acts on
loss(T, mode)[source]

Perform a loss channel operation on the specified mode.

Parameters: T (float) – loss parameter, $$0\leq T\leq 1$$. mode (int) – index of mode where operation is carried out
thermal_loss(T, nbar, mode)[source]

Perform a thermal loss channel operation on the specified mode.

Parameters: T (float) – loss parameter, $$0\leq T\leq 1$$. nbar (float) – mean photon number of the environment thermal state mode (int) – index of mode where operation is carried out
measure_homodyne(phi, mode, shots=1, select=None, **kwargs)[source]

Measure a phase space quadrature of the given mode.

For the measured mode, samples the probability distribution $$f(q) = \bra{q_\phi} \rho \ket{q_\phi}$$ and returns the sampled value. Here $$\ket{q_\phi}$$ is the eigenstate of the operator

$\hat{q}_\phi = \sqrt{2/\hbar}(\cos(\phi)\hat{x} +\sin(\phi)\hat{p}) = e^{-i\phi} \hat{a} +e^{i\phi} \hat{a}^\dagger.$

Note

This method is $$\hbar$$ independent. The returned values can be converted to conventional position/momentum eigenvalues by multiplying them with $$\sqrt{\hbar/2}$$.

Updates the current state such that the measured mode is reset to the vacuum state. This is because we cannot represent exact position or momentum eigenstates in any of the backends, and experimentally the photons are destroyed in a homodyne measurement.

Parameters: phi (float) – phase angle of the quadrature to measure (x: $$\phi=0$$, p: $$\phi=\pi/2$$) mode (int) – which mode to measure shots (int) – number of measurement samples to obtain select (None or float) – If not None: desired value of the measurement result. Enables post-selection on specific measurement results instead of random sampling.

Keyword arguments can be used to pass additional parameters to the backend. Options for such arguments will be documented in the respective subclasses.

Returns: measured value float
measure_fock(modes, shots=1, select=None, **kwargs)[source]

Measure the given modes in the Fock basis.

..note::
When :code:shots == 1, updates the current system state to the conditional state of that measurement result. When :code:shots > 1, the system state is not updated.
Parameters: modes (Sequence[int]) – which modes to measure shots (int) – number of measurement samples to obtain select (None or Sequence[int]) – If not None: desired values of the measurement results. Enables post-selection on specific measurement results instead of random sampling. len(select) == len(modes) is required. measurement results tuple[int]
is_vacuum(tol=0.0, **kwargs)[source]

Test whether the current circuit state is vacuum (up to given tolerance).

Returns True iff $$|\bra{0} \rho \ket{0} -1| \le$$ tol, i.e., the fidelity of the current circuit state with the vacuum state is within the given tolerance from 1.

Parameters: tol (float) – numerical tolerance True iff current state is vacuum up to tolerance tol bool
state(modes=None, **kwargs)[source]

Returns the state of the quantum simulation.

Parameters: modes (int or Sequence[int] or None) – Specifies the modes to restrict the return state to. None returns the state containing all the modes. The returned state contains the requested modes in the given order, i.e., modes=[3,0] results in a two mode state being returned with the first mode being subsystem 3 and the second mode being subsystem 0. state description, specific child class depends on the backend BaseState
class strawberryfields.backends.base.BaseFock[source]

Abstract base class for backends capable of Fock state manipulation.

get_cutoff_dim()[source]

Returns the Hilbert space cutoff dimension used.

Returns: cutoff dimension int
prepare_fock_state(n, mode)[source]

Prepare a Fock state in the specified mode.

The requested mode is traced out and replaced with the Fock state $$\ket{n}$$. As a result the state may have to be described using a density matrix.

Parameters: n (int) – Fock state to prepare mode (int) – which mode to prepare the Fock state in
prepare_ket_state(state, modes)[source]

Prepare the given ket state in the specified modes.

The requested modes are traced out and replaced with the given ket state (in the Fock basis). As a result the state may have to be described using a density matrix.

Parameters: state (array) – Ket state in the Fock basis. The state can be given in either vector form, with one index, or tensor form, with one index per mode. For backends supporting batched mode, state can be a batch of such vectors or tensors. modes (int or Sequence[int]) – Modes to prepare the state in. If modes is not ordered this is taken into account when preparing the state, i.e., when a two mode state is prepared in modes=[3,1], then the first mode of state goes into mode 3 and the second mode goes into mode 1 of the simulator.
prepare_dm_state(state, modes)[source]

Prepare the given mixed state in the specified modes.

The requested modes are traced out and replaced with the given density matrix state (in the Fock basis). As a result the state will be described using a density matrix.

Parameters: state (array) – Density matrix in the Fock basis. The state can be given in either matrix form, with two indices, or tensor form, with two indices per mode. For backends supporting batched mode, state can be a batch of such matrices or tensors. modes (int or Sequence[int]) – which mode to prepare the state in If modes is not ordered this is take into account when preparing the state, i.e., when a two mode state is prepared in modes=[3,1], then the first mode of state goes into mode 3 and the second mode goes into mode 1 of the simulator.
cubic_phase(gamma, mode)[source]

Apply the cubic phase operation to the specified mode.

Applies the operation

$\exp\left(i \frac{\gamma}{6} (\hat{a} +\hat{a}^\dagger)^3\right)$

to the specified mode.

Note

This method is $$\hbar$$ independent. The usual definition of the cubic phase gate is $$\hbar$$ dependent:

$V(\gamma') = \exp\left(i \frac{\gamma'}{3\hbar} \hat{x}^3\right) = \exp\left(i \frac{\gamma' \sqrt{\hbar/2}}{6} (\hat{a} +\hat{a}^\dagger)^3\right).$

Hence the cubic phase gate $$V(\gamma')$$ is executed on a backend by scaling the $$\gamma'$$ parameter by $$\sqrt{\hbar/2}$$ and then passing it to this method, much in the way the $$\hbar$$ dependent X and Z gates are implemented through the $$\hbar$$ independent displacement() method.

Warning

The cubic phase gate can suffer heavily from numerical inaccuracies due to finite-dimensional cutoffs in the Fock basis. The gate implementation in Strawberry Fields is unitary, but it does not implement an exact cubic phase gate. The Kerr gate provides an alternative non-Gaussian gate.

Parameters: gamma (float) – scaled cubic phase shift, $$\gamma = \gamma' \sqrt{\hbar/2}$$ mode (int) – which mode to apply it to
kerr_interaction(kappa, mode)[source]

Apply the Kerr interaction $$\exp{(i\kappa \hat{n}^2)}$$ to the specified mode.

Parameters: kappa (float) – strength of the interaction mode (int) – which mode to apply it to
cross_kerr_interaction(kappa, mode1, mode2)[source]

Apply the two mode cross-Kerr interaction $$\exp{(i\kappa \hat{n}_1\hat{n}_2)}$$ to the specified modes.

Parameters: kappa (float) – strength of the interaction mode1 (int) – first mode that cross-Kerr interaction acts on mode2 (int) – second mode that cross-Kerr interaction acts on
state(modes=None, **kwargs)[source]

Returns the state of the quantum simulation.

Returns: state description BaseFockState
class strawberryfields.backends.base.BaseGaussian[source]

Abstract base class for backends that are only capable of Gaussian state manipulation.

measure_heterodyne(mode, shots=1, select=None)[source]

Perform a heterodyne measurement on the given mode.

Updates the current state of the circuit such that the measured mode is reset to the vacuum state.

Parameters: mode (int) – which mode to measure shots (int) – number of measurement samples to obtain select (None or complex) – If not None: desired value of the measurement result. Enables post-selection on specific measurement results instead of random sampling. measured value complex
prepare_gaussian_state(r, V, modes)[source]

Prepare a Gaussian state.

The specified modes are traced out and replaced with a Gaussian state provided via a vector of means and a covariance matrix.

Note

This method is $$\hbar$$ independent. The input arrays are the means and covariance of the $$a+a^\dagger$$ and $$-i(a-a^\dagger)$$ operators. They are obtained by dividing the xp means by $$\sqrt{\hbar/2}$$ and the xp covariance by $$\hbar/2$$.

Parameters: r (array) – vector of means in xp ordering V (array) – covariance matrix in xp ordering modes (int or Sequence[int]) – Which modes to prepare the state in. If the modes are not sorted, this is taken into account when preparing the state. I.e., when a two mode state is prepared with modes=[3,1], the first mode of the given state goes into mode 3 and the second mode goes into mode 1.
state(modes=None, **kwargs)[source]

Returns the state of the quantum simulation.

Returns: state description BaseGaussianState