Tensorflow simulator backend

Module name: strawberryfields.backends.tfbackend

The TFBackend object implements a simulation of quantum optical circuits using Tensorflow. The primary component of the TFBackend is a Circuit object which is used to simulate a multi-mode quantum optical system. The TFBackend provides the basic API-compatible interface to the simulator, while the Circuit object actually carries out the mathematical simulation.

The Circuit simulator maintains an internal tensor representation of the quantum state of a multi-mode quantum optical system using a (truncated) Fock basis representation. As its various state manipulation methods are called, the quantum state is updated to reflect these changes. The simulator will try to keep the internal state in a pure (vector) representation for as long as possible. Unitary gates will not change the type of representation, while state preparations and measurements will.

A number of factors determine the shape and dimensionality of the state tensor:

  • the underlying state representation being used (either a ket vector or a density matrix)
  • the number of modes \(n\) actively being simulated
  • the cutoff dimension \(D\) for the Fock basis
  • whether the circuit is operating in batched mode (with batch size \(B\))

When not operating in batched mode, the state tensor corresponds to a single multimode quantum system. If the representation is a pure state, the state tensor has shape \((\underbrace{D,...,D}_{n~\text{times}})\). In a mixed state representation, the state tensor has shape \((\underbrace{D,D,...,D,D}_{2n~\text{times}})\). Indices for the same mode appear consecutively. Hence, for a mixed state, the first two indices are for the first mode, the second are for the second mode, etc.

In batched mode, the state tensor simultaneously encodes an ensemble of \(B\) multimode quantum systems (indexed using the first axis of the state tensor). Pure states thus have shape \((B,\underbrace{D,...,D}_{n~\text{times}})\), while mixed states have shape \((B,\underbrace{D,D,...,D,D}_{2n~\text{times}})\).

TFBackend methods

The parameters supplied for these operations can be either numeric (float, complex) values or Tensorflow Variables/Tensors. The Tensorflow objects can either be scalars or vectors. For vectors, they must have the same dimension as the declared batch size of the underlying circuit.

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.
get_cutoff_dim() Returns the Hilbert space cutoff dimension used.
reset([pure]) Reset the circuit so that all the modes are in the vacuum state.
state([modes]) Returns the state of the quantum simulation, restricted to the subsystems defined by modes.
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.
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.
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.
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.
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]) Perform a homodyne measurement on the specified modes.
measure_fock(modes[, shots, select]) Measure the given modes in the Fock basis.
graph Get the Tensorflow Graph object where the current quantum circuit is defined.

Code details

class strawberryfields.backends.tfbackend.TFBackend(graph=None)[source]

TensorFlow backend implementation.

circuit = None

representation of the simulated quantum state

Type:Circuit
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:

num_subsystems (int) – number of modes in the circuit

Keyword Arguments:
 
  • cutoff_dim (int) – Numerical Hilbert space cutoff dimension for the modes. For each mode, the simulator can represent the Fock states \(\ket{0}, \ket{1}, \ldots, \ket{\text{cutoff_dim}-1}\).
  • pure (bool) – If True (default), use a pure state representation (otherwise will use a mixed state representation).
  • batch_size (None or int) – Size of the batch-axis dimension. If None, no batch-axis will be used.
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:

pure (bool) – if True, initialize the circuit in a pure state representation (will use a mixed state representation if pure is False)

Keyword Arguments:
 
  • cutoff_dim (int) – new Hilbert space truncation dimension
  • hard (bool) – Whether to reset the underlying TensorFlow graph. If True (default), then resets the underlying tensor graph as well. If False, then the circuit is reset to its initial state, but ops that have already been declared are still accessible.
get_cutoff_dim()[source]

Returns the Hilbert space cutoff dimension used.

Returns:cutoff dimension
Return type:int
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
Return type:list[int]
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_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.
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
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, restricted to the subsystems defined by modes.

See BaseBackend.state().

Keyword Arguments:
 
  • session (tf.Session) – TensorFlow session
  • feed_dict (Dict) – Dictionary containing the desired numerical values for Tensors for numerically evaluating the state. Used with session.
Returns:

state description

Return type:

FockStateTF

measure_fock(modes, shots=1, select=None, **kwargs)[source]

Measure the given modes in the Fock basis.

See BaseFock.measure_fock().

Keyword Arguments:
 
  • session (tf.Session) – TensorFlow session
  • feed_dict (Dict) – Dictionary containing the desired numerical values for Tensors for numerically evaluating the measurement results. Used with session.
Returns:

measurement outcomes

Return type:

tuple[int] or tuple[Tensor]

measure_homodyne(phi, mode, shots=1, select=None, **kwargs)[source]

Perform a homodyne measurement on the specified modes.

See BaseBackend.measure_homodyne().

Keyword Arguments:
 
  • session (tf.Session) – TensorFlow session
  • feed_dict (Dict) – Dictionary containing the desired numerical values for Tensors for numerically evaluating the measurement results. Used with session.
  • num_bins (int) – Number of equally spaced bins for the probability distribution function (pdf) simulating the homodyne measurement (default: 100000).
  • max (float) – The pdf is discretized onto the 1D grid [-max,max] (default: 10).
Returns:

measurement outcome

Return type:

float or tf.Tensor

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
Returns:True iff current state is vacuum up to tolerance tol
Return type:bool
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
add_mode(n=1)[source]

Add modes to the circuit.

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
Returns:indices of the newly added modes
Return type:list[int]
graph

Get the Tensorflow Graph object where the current quantum circuit is defined.

Returns:the circuit’s graph
Return type:tf.Graph

FockStateTF

This class represents the quantum state returned by the Tensorflow backend. It extends BaseFockState with additional functionality unique to the Tensorflow backend. The primary difference between this class and the Base Fock state is that its methods and attributes can return either numerical or symbolic values.

The default representation (numerical or symbolic) is set when creating the state: state = eng.run('backend', eval=True/False). The representation can also be specified on a per-use basis when calling a method, e.g., state.mean_photon(eval=True/False). Along with the boolean eval, acceptable keyword arguments are session (a Tensorflow Session object) and feed_dict (a dictionary mapping Tensorflow objects to numerical values). These will be used when evaluating any Tensors.

ket(**kwargs) Computes the ket representation of the state.
dm(**kwargs) Computes the density matrix representation of the state.
reduced_dm(modes, **kwargs) Computes the reduced density matrix representation of the state.
trace(**kwargs) Computes the trace of the state.
fock_prob(n, **kwargs) Compute the probabilities of a specific Fock-basis matrix element for the state.
all_fock_probs(**kwargs) Compute the probabilities of all possible Fock-basis states for the state.
fidelity(other_state, mode, **kwargs) Compute the fidelity of the reduced state (on the specified mode) with the state.
fidelity_coherent(alpha_list, **kwargs) Compute the fidelity of the state with the coherent states specified by alpha_list.
fidelity_vacuum(**kwargs) Compute the fidelity of the state with the vacuum state.
is_vacuum([tol]) Computes a boolean which indicates whether the state is the vacuum state.
quad_expectation(mode[, phi]) Compute the expectation value of the quadrature operator \(\hat{x}_\phi\) for the reduced state on the specified mode.
mean_photon(mode, **kwargs) Compute the mean photon number for the reduced state on the specified mode.
batched The number of batches.
cutoff_dim The numerical truncation of the Fock space used by the underlying state.
graph The computational graph.

Code details

class strawberryfields.backends.tfbackend.states.FockStateTF(state_data, num_modes, pure, cutoff_dim, graph, batched=False, mode_names=None, eval=True)[source]

Class for the representation of quantum states in the Fock basis using the TFBackend.

Parameters:
  • state_data (array) – the state representation in the Fock basis
  • num_modes (int) – the number of modes in the state
  • pure (bool) – True if the state is a pure state, false if the state is mixed
  • cutoff_dim (int) – the Fock basis truncation size
  • mode_names (Sequence) – (optional) this argument contains a list providing mode names for each mode in the state.
  • eval (bool) – indicates the default return behaviour for the class instance (symbolic when eval=False, numerical when eval=True)
trace(**kwargs)[source]

Computes the trace of the state. May be numerical or symbolic.

Parameters:**kwargs

Optional keyword arguments.

  • If this contains the key eval, then the corresponding argument will be used to determine the return behaviour of this function. When eval=True, the return value is numerical; when eval=False, it is symbolic.
  • If eval is not present in kwargs, then state falls back to the an internal evaluation behaviour, which is specified at initialization.
  • A Tensorflow Session or feed_dict may also be passed via the keys session or feed_dict, respectively. If a Session is supplied, then eval is overriden and the numerical evaluation takes place in the provided Session. If session and/or feed_dict are not given, then a temporary session and/or empty feed_dict will be used.
Returns:the numerical value, or an unevaluated Tensor object, for the trace.
Return type:float/Tensor
fock_prob(n, **kwargs)[source]

Compute the probabilities of a specific Fock-basis matrix element for the state. May be numerical or symbolic.

Parameters:
  • n (Sequence[int]) – the Fock state \(\ket{\vec{n}}\) that we want to measure the probability of
  • **kwargs

    Optional keyword arguments.

    • If this contains the key eval, then the corresponding argument will be used to determine the return behaviour of this function. When eval=True, the return value is numerical; when eval=False, it is symbolic.
    • If eval is not present in kwargs, then state falls back to the an internal evaluation behaviour, which is specified at initialization.
    • A Tensorflow Session or feed_dict may also be passed via the keys session or feed_dict, respectively. If a Session is supplied, then eval is overriden and the numerical evaluation takes place in the provided Session. If session and/or feed_dict are not given, then a temporary session and/or empty feed_dict will be used.
Returns:

the numerical values, or an unevaluated Tensor object, for the Fock-state probabilities.

Return type:

float/Tensor

all_fock_probs(**kwargs)[source]

Compute the probabilities of all possible Fock-basis states for the state. May be numerical or symbolic.

For example, in the case of 3 modes, this method allows the Fock state probability \(|\braketD{0,2,3}{\psi}|^2\) to be returned via

probs = state.all_fock_probs()
probs[0,2,3]
Parameters:**kwargs

Optional keyword arguments.

  • If this contains the key eval, then the corresponding argument will be used to determine the return behaviour of this function. When eval=True, the return value is numerical; when eval=False, it is symbolic.
  • If eval is not present in kwargs, then state falls back to the an internal evaluation behaviour, which is specified at initialization.
  • A Tensorflow Session or feed_dict may also be passed via the keys session or feed_dict, respectively. If a Session is supplied, then eval is overriden and the numerical evaluation takes place in the provided Session. If session and/or feed_dict are not given, then a temporary session and/or empty feed_dict will be used.
Returns:the numerical values, or an unevaluated Tensor object, for the Fock-basis probabilities.
Return type:array/Tensor
fidelity(other_state, mode, **kwargs)[source]

Compute the fidelity of the reduced state (on the specified mode) with the state. May be numerical or symbolic.

Parameters:
  • other_state (array) – state vector (ket) to compute the fidelity with respect to
  • mode (int) – which subsystem to use for the fidelity computation
  • **kwargs

    Optional keyword arguments.

    • If this contains the key eval, then the corresponding argument will be used to determine the return behaviour of this function. When eval=True, the return value is numerical; when eval=False, it is symbolic.
    • If eval is not present in kwargs, then state falls back to the an internal evaluation behaviour, which is specified at initialization.
    • A Tensorflow Session or feed_dict may also be passed via the keys session or feed_dict, respectively. If a Session is supplied, then eval is overriden and the numerical evaluation takes place in the provided Session. If session and/or feed_dict are not given, then a temporary session and/or empty feed_dict will be used.
Returns:

the numerical value, or an unevaluated Tensor object, for the fidelity.

Return type:

float/Tensor

fidelity_coherent(alpha_list, **kwargs)[source]

Compute the fidelity of the state with the coherent states specified by alpha_list. May be numerical or symbolic.

Parameters:
  • alpha_list (Sequence[complex]) – list of coherence parameter values, one for each mode
  • **kwargs

    Optional keyword arguments.

    • If this contains the key eval, then the corresponding argument will be used to determine the return behaviour of this function. When eval=True, the return value is numerical; when eval=False, it is symbolic.
    • If eval is not present in kwargs, then state falls back to the an internal evaluation behaviour, which is specified at initialization.
    • A Tensorflow Session or feed_dict may also be passed via the keys session or feed_dict, respectively. If a Session is supplied, then eval is overriden and the numerical evaluation takes place in the provided Session. If session and/or feed_dict are not given, then a temporary session and/or empty feed_dict will be used.
Returns:

the numerical value, or an unevaluated Tensor object, for the fidelity \(\bra{\vec{\alpha}}\rho\ket{\vec{\alpha}}\).

Return type:

float/Tensor

fidelity_vacuum(**kwargs)[source]

Compute the fidelity of the state with the vacuum state. May be numerical or symbolic.

Parameters:**kwargs

Optional keyword arguments.

  • If this contains the key eval, then the corresponding argument will be used to determine the return behaviour of this function. When eval=True, the return value is numerical; when eval=False, it is symbolic.
  • If eval is not present in kwargs, then state falls back to the an internal evaluation behaviour, which is specified at initialization.
  • A Tensorflow Session or feed_dict may also be passed via the keys session or feed_dict, respectively. If a Session is supplied, then eval is overriden and the numerical evaluation takes place in the provided Session. If session and/or feed_dict are not given, then a temporary session and/or empty feed_dict will be used.
Returns:the numerical value, or an unevaluated Tensor object, for the fidelity \(\bra{\vec{0}}\rho\ket{\vec{0}}\).
Return type:float/Tensor
is_vacuum(tol=0.0, **kwargs)[source]

Computes a boolean which indicates whether the state is the vacuum state. May be numerical or symbolic.

Parameters:
  • tol – numerical tolerance. If the state has fidelity with vacuum within tol, then this method returns True.
  • **kwargs

    Optional keyword arguments.

    • If this contains the key eval, then the corresponding argument will be used to determine the return behaviour of this function. When eval=True, the return value is numerical; when eval=False, it is symbolic.
    • If eval is not present in kwargs, then state falls back to the an internal evaluation behaviour, which is specified at initialization.
    • A Tensorflow Session or feed_dict may also be passed via the keys session or feed_dict, respectively. If a Session is supplied, then eval is overriden and the numerical evaluation takes place in the provided Session. If session and/or feed_dict are not given, then a temporary session and/or empty feed_dict will be used.
Returns:

the boolean value, or an unevaluated Tensor object, for whether the state is in vacuum.

Return type:

bool/Tensor

reduced_dm(modes, **kwargs)[source]

Computes the reduced density matrix representation of the state. May be numerical or symbolic.

Parameters:
  • modes (int or Sequence[int]) – specifies the mode(s) to return the reduced density matrix for.
  • **kwargs

    Optional keyword arguments.

    • If this contains the key eval, then the corresponding argument will be used to determine the return behaviour of this function. When eval=True, the return value is numerical; when eval=False, it is symbolic.
    • If eval is not present in kwargs, then state falls back to the an internal evaluation behaviour, which is specified at initialization.
    • A Tensorflow Session or feed_dict may also be passed via the keys session or feed_dict, respectively. If a Session is supplied, then eval is overriden and the numerical evaluation takes place in the provided Session. If session and/or feed_dict are not given, then a temporary session and/or empty feed_dict will be used.
Returns:

the numerical value, or an unevaluated Tensor object, for the density matrix.

Return type:

array/Tensor

quad_expectation(mode, phi=0.0, **kwargs)[source]

Compute the expectation value of the quadrature operator \(\hat{x}_\phi\) for the reduced state on the specified mode. May be numerical or symbolic.

Parameters:
  • mode (int) – which subsystem to take the expectation value of
  • phi (float) – rotation angle for the quadrature operator
  • **kwargs

    Optional keyword arguments.

    • If this contains the key eval, then the corresponding argument will be used to determine the return behaviour of this function. When eval=True, the return value is numerical; when eval=False, it is symbolic.
    • If eval is not present in kwargs, then state falls back to the an internal evaluation behaviour, which is specified at initialization.
    • A Tensorflow Session or feed_dict may also be passed via the keys session or feed_dict, respectively. If a Session is supplied, then eval is overriden and the numerical evaluation takes place in the provided Session. If session and/or feed_dict are not given, then a temporary session and/or empty feed_dict will be used.
Returns:

the numerical value, or an unevaluated Tensor object, for the expectation value

Return type:

float/Tensor

mean_photon(mode, **kwargs)[source]

Compute the mean photon number for the reduced state on the specified mode. May be numerical or symbolic.

Parameters:
  • mode (int) – which subsystem to take the mean photon number of
  • **kwargs

    Optional keyword arguments.

    • If this contains the key eval, then the corresponding argument will be used to determine the return behaviour of this function. When eval=True, the return value is numerical; when eval=False, it is symbolic.
    • If eval is not present in kwargs, then state falls back to the an internal evaluation behaviour, which is specified at initialization.
    • A Tensorflow Session or feed_dict may also be passed via the keys session or feed_dict, respectively. If a Session is supplied, then eval is overriden and the numerical evaluation takes place in the provided Session. If session and/or feed_dict are not given, then a temporary session and/or empty feed_dict will be used.
Returns:

tuple containing the numerical value, or an unevaluated Tensor object, for the mean photon number and variance.

Return type:

tuple(float/Tensor)

ket(**kwargs)[source]

Computes the ket representation of the state. May be numerical or symbolic.

Parameters:**kwargs

Optional keyword arguments.

  • If this contains the key eval, then the corresponding argument will be used to determine the return behaviour of this function. When eval=True, the return value is numerical; when eval=False, it is symbolic.
  • If eval is not present in kwargs, then state falls back to the an internal evaluation behaviour, which is specified at initialization.
  • A Tensorflow Session or feed_dict may also be passed via the keys session or feed_dict, respectively. If a Session is supplied, then eval is overriden and the numerical evaluation takes place in the provided Session. If session and/or feed_dict are not given, then a temporary session and/or empty feed_dict will be used.
Returns:the numerical value, or an unevaluated Tensor object, for the ket.
Return type:array/Tensor
dm(**kwargs)[source]

Computes the density matrix representation of the state. May be numerical or symbolic.

Parameters:**kwargs

Optional keyword arguments.

  • If this contains the key eval, then the corresponding argument will be used to determine the return behaviour of this function. When eval=True, the return value is numerical; when eval=False, it is symbolic.
  • If eval is not present in kwargs, then state falls back to the an internal evaluation behaviour, which is specified at initialization.
  • A Tensorflow Session or feed_dict may also be passed via the keys session or feed_dict, respectively. If a Session is supplied, then eval is overriden and the numerical evaluation takes place in the provided Session. If session and/or feed_dict are not given, then a temporary session and/or empty feed_dict will be used.
Returns:the numerical value, or an unevaluated Tensor object, for the density matrix.
Return type:array/Tensor
wigner(mode, xvec, pvec)[source]

Calculates the discretized Wigner function of the specified mode.

Warning

Calculation of the Wigner function is currently only supported if eval=True and batched=False.

Note

This code is a modified version of the ‘iterative’ method of the wigner function provided in QuTiP, which is released under the BSD license, with the following copyright notice:

Copyright (C) 2011 and later, P.D. Nation, J.R. Johansson, A.J.G. Pitchford, C. Granade, and A.L. Grimsmo. All rights reserved.

Parameters:
  • mode (int) – the mode to calculate the Wigner function for
  • xvec (array) – array of discretized \(x\) quadrature values
  • pvec (array) – array of discretized \(p\) quadrature values
Returns:

2D array of size [len(xvec), len(pvec)], containing reduced Wigner function values for specified x and p values.

Return type:

array

poly_quad_expectation(A, d=None, k=0, phi=0, **kwargs)[source]

The multi-mode expectation values and variance of arbitrary 2nd order polynomials of quadrature operators.

Warning

Calculation of multi-mode quadratic expectation values is currently only supported if eval=True and batched=False.

An arbitrary 2nd order polynomial of quadrature operators over $N$ modes can always be written in the following form:

\[P(\mathbf{r}) = \mathbf{r}^T A\mathbf{r} + \mathbf{r}^T \mathbf{d} + k I\]

where:

  • \(A\in\mathbb{R}^{2N\times 2N}\) is a symmetric matrix representing the quadratic coefficients,
  • \(\mathbf{d}\in\mathbb{R}^{2N}\) is a real vector representing the linear coefficients,
  • \(k\in\mathbb{R}\) represents the constant term, and
  • \(\mathbf{r} = (\x_1,\dots,\x_N,\p_1,\dots,\p_N)\) is the vector of quadrature operators in \(xp\)-ordering.

This method returns the expectation value of this second-order polynomial,

\[\langle P(\mathbf{r})\rangle,\]

as well as the variance

\[\Delta P(\mathbf{r})^2 = \langle P(\mathbf{r})^2\rangle - \braket{P(\mathbf{r})}^2\]
Parameters:
  • A (array) – a real symmetric 2Nx2N NumPy array, representing the quadratic coefficients of the second order quadrature polynomial.
  • d (array) – a symmetric length-2N NumPy array, representing the linear coefficients of the second order quadrature polynomial. Defaults to the zero vector.
  • k (float) – the constant term. Default 0.
  • phi (float) – quadrature angle, clockwise from the positive \(x\) axis. If provided, the vector of quadrature operators \(\mathbf{r}\) is first rotated by angle \(\phi\) in the phase space.
  • **kwargs

    Optional keyword arguments.

    • If this contains the key eval, then the corresponding argument will be used to determine the return behaviour of this function. When eval=True, the return value is numerical; when eval=False, it is symbolic.
    • If eval is not present in kwargs, then state falls back to the an internal evaluation behaviour, which is specified at initialization.
    • A Tensorflow Session or feed_dict may also be passed via the keys session or feed_dict, respectively. If a Session is supplied, then eval is overriden and the numerical evaluation takes place in the provided Session. If session and/or feed_dict are not given, then a temporary session and/or empty feed_dict will be used.
Returns:

expectation value and variance

Return type:

tuple (float, float)

batched

The number of batches.

graph

The computational graph.

strawberryfields.backends.tfbackend.excepthook(type, value, traceback)[source]

Exception hook to suppress superfluous exceptions