sf.Program

class Program(num_subsystems, name=None)[source]

Bases: object

Represents a photonic quantum circuit.

The program class provides a context manager for:

  • accessing the quantum register associated with the program, and

  • appending Operations to the program.

Within the context, operations are appended to the program using the Python-embedded Blackbird syntax

ops.GateName(arg1, arg2, ...) | (q[i], q[j], ...)

where ops.GateName is a valid quantum operation, and q is a list of the programs quantum modes. All operations are appended to the program in the order they are listed within the context.

In addition, some ‘meta-operations’ (such as New() and Del) are provided to modify the programs quantum register itself by adding and deleting subsystems.

Note

Two programs can be run successively on the same engine if and only if the number of registers at the end of the first program matches the number of modes at the beginning of the second program.

This can be enforced by constructing the second program as an explicit successor of the first, in which case the registers are directly copied over.

When a Program is run or it obtains a successor, it is locked and no more operations can be appended to it.

Example:

import strawberryfields as sf
from strawberryfields import ops

# create a 3 mode quantum program
prog = sf.Program(3)

with prog.context as q:
    ops.Sgate(0.54) | q[0]
    ops.Sgate(0.54) | q[1]
    ops.Sgate(0.54) | q[2]
    ops.BSgate(0.43, 0.1) | (q[0], q[2])
    ops.BSgate(0.43, 0.1) | (q[1], q[2])
    ops.MeasureFock() | q

The currently active register references can be accessed using the register() method.

Note

The Program equality operation (e.g., prog_1 == prog_2) does not account for logically equivalent programs where the order of operations or modes do not matter. It simply checks that the operations and parameters are identically applied. For a more thorough check, use the Program.equivalence() method instead.

Parameters
  • num_subsystems (int, Program) – Initial number of modes (subsystems) in the quantum register. Alternatively, another Program instance from which to inherit the register state.

  • name (str) – program name (optional)

compile_info

The device specification and the compiler that was used during compilation.

context

Syntactic sugar for defining a Program using the with statement.

has_feed_forward

Indicate if any operation in the program uses feed-forwarding or not.

has_post_selection

Indicate if any operation in the program uses post-selection or not.

num_subsystems

Return the current number of valid quantum modes.

register

Return a tuple of all the currently valid quantum modes.

target

The target specification the program has been compiled against.

compile_info

The device specification and the compiler that was used during compilation.

If the program has not been compiled, this will return None.

Returns

device specification and the short name of the Compiler that was used if compiled, otherwise None

Return type

tuple or None

context

Syntactic sugar for defining a Program using the with statement.

The Program object itself acts as the context manager.

has_feed_forward

Indicate if any operation in the program uses feed-forwarding or not.

Returns

whether feed-forwarding is used anywhere in the circuit

Return type

bool

has_post_selection

Indicate if any operation in the program uses post-selection or not.

Returns

whether post-selection is used anywhere in the circuit

Return type

bool

num_subsystems

Return the current number of valid quantum modes.

Returns

number of currently valid register subsystems

Return type

int

register

Return a tuple of all the currently valid quantum modes.

Returns

valid subsystem references

Return type

tuple[RegRef]

target

The target specification the program has been compiled against.

If the program has not been compiled, this will return None.

Returns

the short name of the target Compiler template if compiled, otherwise None

Return type

str or None

append(op, reg)

Append a command to the program.

assert_modes(device)

Check that the number of modes in the program is valid for the given device.

bind_params(binding)

Binds the free parameters of the program to the given values.

can_follow(prev)

Check whether this program can follow the given program.

compile(*[, device, compiler])

Compile the program given a Strawberry Fields photonic compiler, or hardware device specification.

draw_circuit([tex_dir, write_to_file])

Draw the circuit using the Qcircuit \(\LaTeX\) package.

equivalence(prog, **kwargs)

Checks if two programs are equivalent.

lock()

Finalize the program.

optimize()

Simplify and optimize the program.

params(*args)

Create and access free circuit parameters.

print([print_fn])

Print the program contents using Blackbird syntax.

append(op, reg)[source]

Append a command to the program.

Parameters
  • op (Operation) – quantum operation

  • reg (list[int, RegRef]) – register subsystem(s) to apply it to

Returns

subsystem list as RegRefs

Return type

list[RegRef]

assert_modes(device)[source]

Check that the number of modes in the program is valid for the given device.

Note

device.modes must be an integer with the allowed number of modes for the target, or a dictionary containing the maximum number of allowed measurements for the specified target.

Parameters

device (strawberryfields.Device) – device specification object to use

bind_params(binding)[source]

Binds the free parameters of the program to the given values.

Parameters

binding (dict[Union[str, FreeParameter], Any]) – mapping from parameter names (or the parameters themselves) to parameter values

Raises

ParameterError – tried to bind an unknown parameter

can_follow(prev)[source]

Check whether this program can follow the given program.

This requires that the final RegRef state of the first program matches the initial RegRef state of the second program, i.e., they have the same number number of RegRefs, all with identical indices and activity states.

Parameters

prev (Program) – preceding program fragment

Returns

True if the Program can follow prev

Return type

bool

compile(*, device=None, compiler=None, **kwargs)[source]

Compile the program given a Strawberry Fields photonic compiler, or hardware device specification.

The compilation process can involve up to three stages:

  1. Validation: Validates properties of the program, including number of modes and allowed operations, making sure all the Operations used are accepted by the compiler.

  2. Decomposition: Once the program has been validated, decomposition are performed, transforming certain gates into sequences of simpler gates.

  3. General compilation: Finally, the compiler might specify bespoke compilation logic for transforming the quantum circuit into an equivalent circuit which can be executed by the target device.

Example:

The gbs compile target will compile a circuit consisting of Gaussian operations and Fock measurements into canonical Gaussian boson sampling form.

>>> prog2 = prog.compile(compiler="gbs")

For a hardware device a Device object, and optionally a specified compile strategy, must be supplied. If no compile strategy is supplied the default compiler from the device specification is used.

>>> eng = sf.RemoteEngine("X8")
>>> device = eng.device_spec
>>> prog2 = prog.compile(device=device, compiler="Xcov")
Parameters
  • device (Device) – device specification object to use for program compilation

  • compiler (str, Compiler) – Compiler name or compile strategy to use. If a device is specified, this overrides the compile strategy specified by the hardware Device.

Keyword Arguments
  • optimize (bool) – If True, try to optimize the program by merging and canceling gates. The default is False.

  • warn_connected (bool) – If True, the user is warned if the quantum circuit is not weakly connected. The default is True.

  • shots (int) – Number of times the program measurement evaluation is repeated. Passed along to the compiled program’s run_options.

Returns

compiled program

Return type

Program

draw_circuit(tex_dir='./circuit_tex', write_to_file=True)[source]

Draw the circuit using the Qcircuit \(\LaTeX\) package.

This will generate the LaTeX code required to draw the quantum circuit diagram corresponding to the Program.

The drawing of the following Xanadu supported operations are currently supported:

Gate type

Supported gates

Single mode gates

Dgate, Xgate, Zgate, Sgate, Rgate, Pgate, Vgate, Kgate, Fouriergate

Two mode gates

BSgate, S2gate, CXgate, CZgate, CKgate

Note

Measurement operations MeasureHomodyne, MeasureHeterodyne, and MeasureFock are not currently supported.

Parameters
  • tex_dir (str) – relative directory for latex document output

  • write_to_file (bool) – if False, no output file is created

Returns

filename of the written tex document and the written tex content

Return type

list[str]

equivalence(prog, **kwargs)[source]

Checks if two programs are equivalent.

This function converts the program lists into directed acyclic graphs, and runs the NetworkX is_isomorphic graph function in order to determine if the two programs are equivalent.

Note

This method is a convenience method, wrapping the program_equivalence() function in the program utils module.

Parameters

prog (strawberryfields.program.Program) – quantum program to check equivalence with

Keyword Arguments
  • compare_params (bool) – Set to False to turn of comparing program parameters; equivalency will only take into account the operation order.

  • atol (float) – the absolute tolerance parameter for checking quantum operation parameter equality

  • rtol (float) – the relative tolerance parameter for checking quantum operation parameter equality

Returns

returns True if two quantum programs are equivalent

Return type

bool

lock()[source]

Finalize the program.

When a Program is locked, no more Commands can be appended to it. The locking happens when the program is run, compiled, or a successor Program is constructed, in order to ensure that the RegRef state of the Program does not change anymore.

optimize()[source]

Simplify and optimize the program.

The simplifications are based on the algebraic properties of the gates, e.g., combining two consecutive gates of the same gate family.

Returns a copy of the program, sharing RegRefs with the original.

See optimize_circuit().

Returns

optimized copy of the program

Return type

Program

params(*args)[source]

Create and access free circuit parameters.

Returns the named free parameters. If a parameter does not exist yet, it is created and returned.

Parameters

*args (tuple[str]) – name(s) of the free parameters to access

Returns

requested parameter(s)

Return type

FreeParameter, list[FreeParameter]

print(print_fn=<built-in function print>)[source]

Print the program contents using Blackbird syntax.

Example:

# create a 3 mode quantum program
prog = sf.Program(3)

with prog.context as q:
    ops.Sgate(0.54) | q[0]
    ops.Sgate(0.54) | q[1]
    ops.Sgate(0.54) | q[2]
    ops.BSgate(0.43, 0.1) | (q[0], q[2])
    ops.BSgate(0.43, 0.1) | (q[1], q[2])
    ops.MeasureFock() | q
>>> prog.print()
Sgate(0.54, 0) | (q[0])
Sgate(0.54, 0) | (q[1])
Sgate(0.54, 0) | (q[2])
BSgate(0.43, 0.1) | (q[0], q[2])
BSgate(0.43, 0.1) | (q[1], q[2])
MeasureFock | (q[0], q[1], q[2])
Parameters

print_fn (function) – optional custom function to use for string printing