Quantum operations¶
Module name: strawberryfields.ops
Note
In the strawberryfields.ops
API we use the convention \(\hbar=2\) by default, however
this can be changed using the global variable strawberryfields.hbar
.
See Conventions and formulas for more details.
This module defines and implements the Pythonembedded quantum programming language for continuousvariable (CV) quantum systems. The syntax is modeled after ProjectQ [42].
Quantum operations (state preparation, unitary gates, measurements, channels) act on register objects using the following syntax:
prog = sf.Program(3)
with prog.context as q:
G(params)  q
F(params)  (q[1], q[6], q[2])
Here prog
is an instance of strawberryfields.program.Program
which defines the context where the commands are stored.
Within each command, the part on the left is an Operation
instance,
quite typically a constructor call for the requested operation class with the relevant parameters.
The vertical bar calls the __or__()
method of the Operation
object,
with the part on the right as the parameter. The part on the right is a single
strawberryfields.engine.RegRef
object or, for multimode gates, a sequence of them.
It is of course also possible to construct gates separately and reuse them several times:
R = Rgate(s)
with prog.context as q:
R  q
Xgate(t)  q
R.H  q
There are six kinds of Operation
objects:
Preparation
operations only manipulate the register state:with prog.context as q: Vac  q[0] All(Coherent(0.4, 0.2))  (q[1], q[2])
Transformations such as
Gate
andChannel
operations only manipulate the register state:with prog.context as q: Dgate(0.3)  q[0] BSgate(0.5)  q[0:2]
Measurement
operations manipulate the register state and produce classical information. The information is directly available only after the program has been run up to the point of measurement:with prog.context as (alice, bob): Measure  alice eng = sf.LocalEngine(backend='fock') eng.run(prog) print(alice.val)
Alternatively one may use a symbolic reference to the register containing the measurement result by supplying registers as the argument to an
Operation
, in which case the measurement may be deferred, i.e., we may symbolically use the measurement result before it exists:with prog.context as (alice, bob): Measure  alice Dgate(alice)  bob
One may also include an arbitrary postprocessing function for the measurement result, to be applied before using it as the argument to another
Operation
. Theconvert()
decorator can be used in Python to convert a userdefined function into a postprocessing function recognized by the engine:@convert def square(q): return q ** 2 with prog.context as q: Measure  q[0] Dgate(square(q[0]))  q[1]
Finally, the lowerlevel
strawberryfields.engine.RegRefTransform
(RR) and an optional lambda function can be used to achieve the same functionality:with prog.context as q: Measure  q[0] Dgate(RR(q[0]))  q[1] Dgate(RR(q[0], lambda q: q ** 2))  q[2]
Modes can be created and deleted during program execution using the function
New()
and the preconstructed objectDel
. Behind the scenes they utilize the metaoperations_New_modes
and_Delete
:with prog.context as (alice,): Sgate(1)  alice bob, charlie = New(2) BSgate(0.5)  (alice, bob) CXgate(1)  (alice, charlie) Del  alice S2gate(0.4)  (charlie, bob)
Finally,
Decomposition
operations are a special case, and can act as either transformations or state preparation, depending on the decomposition used. Decompositions calculate the required elementaryGate
and/orPreparation
objects and parameters in order to decompose specific transformations or states. Examples of objects that are supported by decompositions include covariance matrices, interferometers, and symplectic transformations.
Hierarchy for operations¶
Base classes¶
The abstract base class hierarchy exists to provide the correct semantics for the actual operations that inherit them.
Operation (par) 
Abstract base class for quantum operations acting on one or more subsystems. 
Preparation (par) 
Abstract base class for operations that demolish the previous state of the subsystem entirely. 
Transformation (par) 
Abstract base class for transformations. 
Gate (par) 
Abstract base class for unitary quantum gates. 
Channel (par) 
Abstract base class for quantum channels. 
Measurement (par[, select]) 
Abstract base class for subsystem measurements. 
Decomposition (par[, decomp]) 
Abstract base class for multimode matrix transformations. 
MetaOperation () 
Abstract base class for metaoperations. 
Operation class¶
All Operations have the following methods.
__str__ () 
String representation for the Operation using Blackbird syntax. 
__or__ (reg) 
Apply the operation to a part of a quantum register. 
merge (other) 
Merge the operation with another (acting on the exact same set of subsystems). 
decompose (reg) 
Decompose the operation into elementary operations supported by the backend API. 
apply (reg, backend, **kwargs) 
Ask a local backend to execute the operation on the current register state right away. 
_apply (reg, backend, **kwargs) 
Internal apply method. 
State preparation¶
Vacuum () 
Prepare a mode in the vacuum state. 
Coherent ([a, p]) 
Prepare a mode in a coherent state. 
Squeezed ([r, p]) 
Prepare a mode in a squeezed vacuum state. 
DisplacedSqueezed ([alpha, r, p]) 
Prepare a mode in a displaced squeezed state. 
Thermal ([n]) 
Prepare a mode in a thermal state. 
Fock ([n]) 
Prepare a mode in a Fock basis state. 
Catstate ([alpha, p]) 
Prepare a mode in a cat state. 
Ket (state) 
Prepare mode(s) using the given ket vector(s) in the Fock basis. 
DensityMatrix (state) 
Prepare mode(s) using the given density matrix in the Fock basis. 
Gaussian (V[, r, decomp, tol]) 
Prepare the specified modes in a Gaussian state. 
Measurements¶
MeasureFock ([select]) 
Photon counting measurement: measures a set of modes in the Fock basis. 
MeasureHomodyne (phi[, select]) 
Performs a homodyne measurement, measures one quadrature of a mode. 
MeasureHeterodyne ([select]) 
Performs a heterodyne measurement on a mode. 
Channels¶
LossChannel (T) 
Perform a loss channel operation on the specified mode. 
ThermalLossChannel (T, nbar) 
Perform a thermal loss channel operation on the specified mode. 
Decompositions¶
Interferometer (U[, tol]) 
Apply a linear interferometer to the specified qumodes. 
GraphEmbed (A[, mean_photon_per_mode, …]) 
Embed a graph into an interferometer setup. 
GaussianTransform (S[, vacuum, tol]) 
Apply a Gaussian symplectic transformation to the specified qumodes. 
Gaussian (V[, r, decomp, tol]) 
Prepare the specified modes in a Gaussian state. 
Singlemode gates¶
Dgate (a[, phi]) 
Phase space displacement gate. 
Xgate (x) 
Position displacement gate. 
Zgate (p) 
Momentum displacement gate. 
Sgate (r[, phi]) 
Phase space squeezing gate. 
Rgate (theta) 
Rotation gate. 
Pgate (s) 
Quadratic phase gate. 
Vgate (gamma) 
Cubic phase gate. 
Fouriergate () 
Fourier gate. 
Twomode gates¶
BSgate ([theta, phi]) 
Beamsplitter gate. 
S2gate (r[, phi]) 
Twomode squeezing gate. 
CXgate ([s]) 
Controlled addition or sum gate in the position basis. 
CZgate ([s]) 
Controlled phase gate in the position basis. 
CKgate (kappa) 
CrossKerr gate. 
Metaoperations¶
All (op) 
Metaoperation for applying a singlemode operation to every mode in the register. 
_New_modes ([n]) 
Used internally for adding new modes to the system in a deferred way. 
_Delete () 
Deletes one or more existing modes. 
Operations shortcuts¶
Several of the operation classes described below come with variables that point to preconstructed instances; this is to provide shorthands for operations that accept no arguments, as well as for common variants of operations that do.
Shorthand variable  Operation 
New 
_New_modes 
Del 
_Delete 
Vac 
Vacuum 
Fourier 
Fouriergate 
Measure 
MeasureFock 
MeasureX 
MeasureHomodyne (\(\phi=0\)), \(x\) quadrature measurement 
MeasureP 
MeasureHomodyne (\(\phi=\pi/2\)), \(p\) quadrature measurement 
MeasureHD 
MeasureHeterodyne 
RR 
Alias for RegRefTransform 
Code details¶

class
strawberryfields.ops.
Vacuum
[source]¶ Prepare a mode in the vacuum state.
Can be accessed via the shortcut variable
Vac
.

class
strawberryfields.ops.
Coherent
(a=0.0, p=0.0)[source]¶ Prepare a mode in a coherent state.
The gate is parameterized so that a user can specify a single complex number \(a=\alpha\) or use the polar form \(a = r, p=\phi\) and still get the same result.
Parameters:  a (complex) – displacement parameter \(\alpha\)
 p (float) – phase angle \(\phi\)

class
strawberryfields.ops.
Squeezed
(r=0.0, p=0.0)[source]¶ Prepare a mode in a squeezed vacuum state.
Parameters:  r (float) – squeezing magnitude
 p (float) – squeezing angle \(\phi\)

class
strawberryfields.ops.
DisplacedSqueezed
(alpha=0.0, r=0.0, p=0.0)[source]¶ Prepare a mode in a displaced squeezed state.
A displaced squeezed state is prepared by squeezing a vacuum state, and then applying a displacement operator.
\[\ket{\alpha,z} = D(\alpha)\ket{0,z} = D(\alpha)S(z)\ket{0},\]where the squeezing parameter \(z=re^{i\phi}\).
Parameters:  alpha (complex) – displacement parameter
 r (float) – squeezing magnitude
 p (float) – squeezing angle \(\phi\)

class
strawberryfields.ops.
Fock
(n=0)[source]¶ Prepare a mode in a Fock basis state.
The prepared mode is traced out and replaced with the Fock state \(\ket{n}\). As a result the state of the other subsystems may have to be described using a density matrix.
Parameters: n (int) – Fock state to prepare

class
strawberryfields.ops.
Catstate
(alpha=0, p=0)[source]¶ Prepare a mode in a cat state.
A cat state is the coherent superposition of two coherent states,
\[\ket{\text{cat}(\alpha)} = \frac{1}{N} (\ket{\alpha} +e^{i\phi} \ket{\alpha}),\]where \(N = \sqrt{2 (1+\cos(\phi)e^{2\alpha^2})}\) is the normalization factor.
Parameters:  alpha (complex) – displacement parameter
 p (float) – parity, where \(\phi=p\pi\).
p=0
corresponds to an even cat state, andp=1
an odd cat state.

class
strawberryfields.ops.
Ket
(state)[source]¶ Prepare mode(s) using the given ket vector(s) in the Fock basis.
The prepared modes are traced out and replaced with the given ket state (in the Fock basis). As a result the state of the other subsystems may have to be described using a density matrix.
The provided kets must be each be of length
cutoff_dim
, matching the cutoff dimension used in calls toeng.run
.Parameters: state (array or BaseFockState) – state vector in the Fock basis. This can be provided as either:
 a single ket vector, for single mode state preparation
 a multimode ket, with one array dimension per mode
 a
BaseFockState
state object.

class
strawberryfields.ops.
DensityMatrix
(state)[source]¶ Prepare mode(s) using the given density matrix in the Fock basis.
The prepared modes are traced out and replaced with the given state (in the Fock basis). As a result, the overall state of system will also have to be described using a density matrix.
The provided density matrices must be of size
[cutoff_dim, cutoff_dim]
, matching the cutoff dimension used in calls toeng.run
.Parameters: state (array or BaseFockState) – density matrix in the Fock basis. This can be provided as either:
 a single mode twodimensional matrix \(\rho_{ij}\),
 a multimode tensor \(\rho_{ij,kl,\dots,mn}\), with two indices per mode,
 a
BaseFockState
state object.

class
strawberryfields.ops.
Thermal
(n=0)[source]¶ Prepare a mode in a thermal state.
The requested mode is traced out and replaced with the thermal state \(\rho(\bar{n})\). As a result the state will be described using a density matrix.
Parameters: n (float) – mean thermal population of the mode

class
strawberryfields.ops.
MeasureFock
(select=None)[source]¶ Photon counting measurement: measures a set of modes in the Fock basis.
Also accessible via the shortcut variable
Measure
.After measurement, the modes are reset to the vacuum state.

class
strawberryfields.ops.
MeasureHomodyne
(phi, select=None)[source]¶ Performs a homodyne measurement, measures one quadrature of a mode.
 Position basis measurement: \(\phi = 0\)
(also accessible via the shortcut variable
MeasureX
).  Momentum basis measurement: \(\phi = \pi/2\).
(also accessible via the shortcut variable
MeasureP
)
The measured mode is reset to the vacuum state.
Parameters:  phi (float) – measurement angle \(\phi\)
 select (None, float) – (Optional) desired values of measurement result. Allows the postselection of specific measurement results instead of randomly sampling.
 Position basis measurement: \(\phi = 0\)
(also accessible via the shortcut variable

class
strawberryfields.ops.
MeasureHeterodyne
(select=None)[source]¶ Performs a heterodyne measurement on a mode.
Also accessible via the shortcut variable
MeasureHD
.Samples the joint Husimi distribution \(Q(\vec{\alpha}) = \frac{1}{\pi}\bra{\vec{\alpha}}\rho\ket{\vec{\alpha}}\). The measured mode is reset to the vacuum state.
Parameters: select (None, complex) – (Optional) desired values of measurement result. Allows the postselection of specific measurement results instead of randomly sampling.

class
strawberryfields.ops.
LossChannel
(T)[source]¶ Perform a loss channel operation on the specified mode.
This channel couples mode \(\a\) to another bosonic mode \(\hat{b}\) prepared in the vacuum state using the following transformation:
\[\a \mapsto \sqrt{T} a+\sqrt{1T} \hat{b}\]Parameters: T (float) – the loss parameter \(0\leq T\leq 1\).

class
strawberryfields.ops.
ThermalLossChannel
(T, nbar)[source]¶ Perform a thermal loss channel operation on the specified mode.
This channel couples mode \(\a\) to another bosonic mode \(\hat{b}\) prepared in a thermal state with mean photon number \(\bar{n}\), using the following transformation:
\[\a \mapsto \sqrt{T} a+\sqrt{1T} \hat{b}\]Parameters:  T (float) – the loss parameter \(0\leq T\leq 1\).
 nbar (float) – mean photon number of the environment thermal state

class
strawberryfields.ops.
Dgate
(a, phi=0.0)[source]¶ Phase space displacement gate.
\[D(\alpha) = \exp(\alpha a^\dagger \alpha^* a) = \exp\left(i\sqrt{2}(\re(\alpha) \hat{p} \im(\alpha) \hat{x})/\sqrt{\hbar}\right)\]where \(\alpha = r e^{i\phi}\) has magnitude \(r\geq 0\) and phase \(\phi\).
The gate is parameterized so that a user can specify a single complex number \(a=\alpha\) or use the polar form \(a = r, \phi\) and still get the same result.
Parameters:  a (complex) – displacement parameter \(\alpha\)
 phi (float) – extra (optional) phase angle \(\phi\)

class
strawberryfields.ops.
Xgate
(x)[source]¶ Position displacement gate.
\[X(x) = e^{i x \hat{p}/\hbar}\]Parameters: x (float) – position displacement

class
strawberryfields.ops.
Zgate
(p)[source]¶ Momentum displacement gate.
\[Z(p) = e^{i p \hat{x}/\hbar}\]Parameters: p (float) – momentum displacement

class
strawberryfields.ops.
Sgate
(r, phi=0.0)[source]¶ Phase space squeezing gate.
\[S(z) = \exp\left(\frac{1}{2}(z^* a^2 z {a^\dagger}^2)\right)\]where \(z = r e^{i\phi}\).
Parameters:  r (float) – squeezing amount
 phi (float) – squeezing phase angle \(\phi\)

class
strawberryfields.ops.
Pgate
(s)[source]¶ Quadratic phase gate.
\[P(s) = e^{i \frac{s}{2} \hat{x}^2/\hbar}\]Parameters: s (float) – parameter

class
strawberryfields.ops.
Vgate
(gamma)[source]¶ Cubic phase gate.
\[V(\gamma) = e^{i \frac{\gamma}{3 \hbar} \hat{x}^3}\]Warning
The cubic phase gate has lower accuracy than the Kerr gate at the same cutoff dimension.
Parameters: gamma (float) – parameter

class
strawberryfields.ops.
Kgate
(kappa)[source]¶ Kerr gate.
\[K(\kappa) = e^{i \kappa \hat{n}^2}\]Parameters: kappa (float) – parameter

class
strawberryfields.ops.
Rgate
(theta)[source]¶ Rotation gate.
\[R(\theta) = e^{i \theta a^\dagger a}\]Parameters: theta (float) – rotation angle \(\theta\).

class
strawberryfields.ops.
BSgate
(theta=pi/4, phi=0.)[source]¶ Beamsplitter gate.
\[B(\theta,\phi) = \exp\left(\theta (e^{i \phi} a^\dagger b e^{i \phi}a b^\dagger) \right)\]Parameters:  theta (float) – Transmittivity angle \(\theta\). The transmission amplitude of the beamsplitter is \(t = \cos(\theta)\). The value \(\theta=\pi/4\) gives the 5050 beamsplitter (default).
 phi (float) – Phase angle \(\phi\). The reflection amplitude of the beamsplitter is \(r = e^{i\phi}\sin(\theta)\). The value \(\phi = \pi/2\) gives the symmetric beamsplitter.

class
strawberryfields.ops.
S2gate
(r, phi=0.0)[source]¶ Twomode squeezing gate.
\[S_2(z) = \exp\left(z^* ab z a^\dagger b^\dagger \right) = \exp\left(r (e^{i\phi} ab e^{i\phi} a^\dagger b^\dagger \right)\]where \(z = r e^{i\phi}\).
Parameters:  r (float) – squeezing amount
 phi (float) – squeezing phase angle \(\phi\)

class
strawberryfields.ops.
CXgate
(s=1)[source]¶ Controlled addition or sum gate in the position basis.
\[\text{CX}(s) = \int dx \ket{x}\bra{x} \otimes D\left({\frac{1}{\sqrt{2\hbar}}}s x\right) = e^{i s \: \hat{x} \otimes \hat{p}/\hbar}\]In the position basis it maps \(\ket{x_1, x_2} \mapsto \ket{x_1, s x_1 +x_2}\).
Parameters: s (float) – addition multiplier

class
strawberryfields.ops.
CZgate
(s=1)[source]¶ Controlled phase gate in the position basis.
\[\text{CZ}(s) = \iint dx dy \: e^{i sxy/\hbar} \ket{x,y}\bra{x,y} = e^{i s \: \hat{x} \otimes \hat{x}/\hbar}\]In the position basis it maps \(\ket{x_1, x_2} \mapsto e^{i s x_1 x_2/\hbar} \ket{x_1, x_2}\).
Parameters: s (float) – phase shift multiplier

class
strawberryfields.ops.
CKgate
(kappa)[source]¶ CrossKerr gate.
\[CK(\kappa) = e^{i \kappa \hat{n}_1\hat{n}_2}\]Parameters: kappa (float) – parameter

class
strawberryfields.ops.
Fouriergate
[source]¶ Fourier gate.
Also accessible via the shortcut variable
Fourier
.A special case of the
phase space rotation gate
, where \(\theta=\pi/2\).\[F = R(\pi/2) = e^{i (\pi/2) a^\dagger a}\]

strawberryfields.ops.
New
(n=1)[source]¶ Adds new subsystems to the quantum register.
The new modes are prepared in the vacuum state.
Must only be called in a
Program
context.Parameters: n (int) – number of subsystems to add Returns: tuple of the newly added subsystem references Return type: tuple[RegRef]

class
strawberryfields.ops.
All
(op)[source]¶ Metaoperation for applying a singlemode operation to every mode in the register.
Parameters: op (Operation) – singlemode operation to apply 
op
= None¶ onesubsystem operation to apply
Type: Operation


class
strawberryfields.ops.
Interferometer
(U, tol=1e11)[source]¶ Apply a linear interferometer to the specified qumodes.
This operation uses the Clements decomposition to decompose a linear interferometer into a sequence of beamsplitters and rotation gates.
Parameters:  U (array[complex]) – an \(N\times N\) unitary matrix
 tol (float) – the tolerance used when checking if the matrix is unitary: \(UU^\daggerI \leq\) tol

class
strawberryfields.ops.
GraphEmbed
(A, mean_photon_per_mode=1.0, make_traceless=False, tol=1e06)[source]¶ Embed a graph into an interferometer setup.
This operation uses the Takagi decomposition to decompose an adjacency matrix into a sequence of squeezers and beamsplitters and rotation gates.
Parameters:  A (array) – an \(N\times N\) complex or real symmetric matrix
 mean_photon_per_mode (float) – guarantees that the mean photon number in the pure Gaussian state
representing the graph satisfies \(\frac{1}{N}\sum_{i=1}^N sinh(r_{i})^2 ==\) :code:
mean_photon
 make_traceless (boolean) – Removes the trace of the input matrix, by performing the transformation \(\tilde{A} = A\mathrm{tr}(A) \I/n\). This may reduce the amount of squeezing needed to encode the graph but will lead to different photon number statistics for events with more than one photon in any mode.
 tol (float) – the tolerance used when checking if the input matrix is symmetric: \(AA^T <\) tol

class
strawberryfields.ops.
GaussianTransform
(S, vacuum=False, tol=1e10)[source]¶ Apply a Gaussian symplectic transformation to the specified qumodes.
This operation uses the BlochMessiah decomposition to decompose a symplectic matrix \(S\):
\[S = O_1 R O_2\]where \(O_1\) and \(O_2\) are two orthogonal symplectic matrices (and thus passive Gaussian transformations), and \(R\) is a squeezing transformation in the phase space (\(R=\text{diag}(e^{z},e^z)\)).
The symplectic matrix describing the Gaussian transformation on \(N\) modes must satisfy
\[\begin{split}S\Omega S^T = \Omega, ~~\Omega = \begin{bmatrix}0&I\\I&0\end{bmatrix}\end{split}\]where \(I\) is the \(N\times N\) identity matrix, and \(0\) is the zero matrix.
The two orthogonal symplectic unitaries describing the interferometers are then further decomposed via the
Interferometer
operator and the Clements decomposition:\[U_i = X_i + iY_i\]where
\[\begin{split}O_i = \begin{bmatrix}X&Y\\Y&X\end{bmatrix}\end{split}\]Parameters:  S (array[float]) – a \(2N\times 2N\) symplectic matrix describing the Gaussian transformation.
 vacuum (bool) – set to True if acting on a vacuum state. In this case, \(O_2 V O_2^T = I\), and the unitary associated with orthogonal symplectic \(O_2\) will be ignored.
 tol (float) – the tolerance used when checking if the matrix is symplectic: \(S^T\Omega S\Omega \leq\) tol

vacuum
= None¶ if True, ignore the first unitary matrix when applying the gate
Type: bool

active
= None¶ S is an active symplectic transformation
Type: bool

U1
= None¶ unitary matrix corresponding to O_1
Type: array[complex]

U2
= None¶ unitary matrix corresponding to O_2
Type: array[complex]

Sq
= None¶ diagonal vector of the squeezing matrix R
Type: array[complex]

class
strawberryfields.ops.
Gaussian
(V, r=None, decomp=True, tol=1e06)[source]¶ Prepare the specified modes in a Gaussian state.
This operation uses the Williamson decomposition to prepare quantum modes into a given Gaussian state, specified by a vector of means and a covariance matrix.
The Williamson decomposition decomposes the Gaussian state into a Gaussian transformation (represented by a symplectic matrix) acting on
Thermal
states. The Gaussian transformation is then further decomposed into an array of beamsplitters and local squeezing and rotation gates, by way of theGaussianTransform
andInterferometer
decompositions.Alternatively, the decomposition can be explicitly turned off, and the backend can be explicitly prepared in the Gaussian state provided. This is only supported by backends using the Gaussian representation.
Parameters:  V (array[float]) – an \(2N\times 2N\) (real and positive definite) covariance matrix
 r (array[float] or None) – Length \(2N\) vector of means, of the form \((\x_0,\dots,\x_{N1},\p_0,\dots,\p_{N1})\). If None, it is assumed that \(r=0\).
 decomp (bool) – Should the operation be decomposed into a sequence of elementary gates? If False, the state preparation is performed directly via the backend API.
 tol (float) – the tolerance used when checking if the matrix is symmetric: \(VV^T \leq\) tol

strawberryfields.ops.
RR
¶