merlin.core package

Core quantum layer components.

class merlin.core.AbstractComputationProcess

Bases: ABC

Abstract base class for quantum computation processes.

abstract compute(*args, **kwargs)

Perform the computation.

Args:

*args: Positional arguments for the computation. **kwargs: Keyword arguments for the computation.`

class merlin.core.BeamSplitter(targets, theta_role=ParameterRole.FIXED, theta_value=0.7854, phi_role=ParameterRole.FIXED, phi_value=0.0, theta_name=None, phi_name=None)

Bases: object

Beam splitter description.

get_params()

Describe which phase shifter angles should be exposed as parameters.

Return type:

dict[str, Any]

Returns:

Dict[str, Any]: Parameter placeholders keyed by their symbolic names.

phi_name: Optional[str] = None
phi_role: ParameterRole = 'fixed'
phi_value: float = 0.0
targets: tuple
theta_name: Optional[str] = None
theta_role: ParameterRole = 'fixed'
theta_value: float = 0.7854
class merlin.core.Circuit(n_modes, components=<factory>, metadata=<factory>)

Bases: object

Simple circuit container.

add(component)

Append a component and return the circuit for chained calls.

Return type:

Circuit

Args:

component: Circuit element (rotation, beam splitter, measurement, etc.).

Returns:

Circuit: self to support fluent-style chaining.

clear()

Remove every component and metadata entry from the circuit.

components: list[Any]
property depth: int

Estimate logical depth by summing component depths when available.

get_parameters()

Collect parameter placeholders exposed by each component.

Return type:

dict[str, Any]

Returns:

Dict[str, Any]: Mapping from parameter name to default value (or None).

metadata: dict[str, Any]
n_modes: int
property num_components: int

Return the count of registered components.

class merlin.core.CircuitGenerator

Bases: object

Utility class for generating quantum photonic circuits.

static generate_circuit(circuit_type, n_modes, n_features, reservoir_mode=False)

Generate a quantum circuit based on specified type.

enum merlin.core.CircuitType(value)

Bases: Enum

Quantum circuit topology types.

Valid values are as follows:

PARALLEL_COLUMNS = <CircuitType.PARALLEL_COLUMNS: 'parallel_columns'>
SERIES = <CircuitType.SERIES: 'series'>
PARALLEL = <CircuitType.PARALLEL: 'parallel'>
class merlin.core.Component

Bases: object

Base class for backward compatibility.

class merlin.core.ComputationProcess(circuit, input_state, trainable_parameters, input_parameters, n_photons=None, reservoir_mode=False, dtype=torch.float32, device=None, computation_space=None, no_bunching=None, output_map_func=None)

Bases: AbstractComputationProcess

Handles quantum circuit computation and state evolution.

compute(parameters)

Compute quantum output distribution.

Return type:

Tensor

compute_ebs_simultaneously(parameters, simultaneous_processes=1)

Evaluate a single circuit parametrisation against all superposed input states by chunking them in groups and delegating the heavy work to the TorchScript-enabled batch kernel.

The method converts the trainable parameters into a unitary matrix, normalises the input state (if it is not already normalised), filters out components with zero amplitude, and then queries the simulation graph for batches of Fock states. Each batch feeds SLOSComputeGraph.compute_batch(), producing a tensor that contains the amplitudes of all reachable output states for the selected input components. The partial results are accumulated into a preallocated tensor and finally weighted by the complex coefficients of self.input_state to produce the global output amplitudes.

Return type:

Tensor

Args:
parameters (list[torch.Tensor]): Differentiable parameters that

encode the photonic circuit. They are forwarded to self.converter to build the unitary matrix used during the simulation.

simultaneous_processes (int): Maximum number of non-zero input

components that are propagated in a single call to compute_batch. Tuning this value allows trading memory consumption for wall-clock time on GPU.

Returns:

torch.Tensor: The superposed output amplitudes with shape [batch_size, num_output_states] where batch_size corresponds to the number of independent input batches and num_output_states is the size of self.simulation_graph.mapped_keys.

Raises:

TypeError: If self.input_state is not a torch.Tensor. The simulation graph expects tensor inputs, therefore other sequence types (NumPy arrays, lists, etc.) cannot be used here.

Notes:
  • self.input_state is normalised in place to avoid an extra allocation.

  • Zero-amplitude components are skipped to minimise the number of calls to compute_batch.

  • The method is agnostic to the device: tensors remain on the device they already occupy, so callers should ensure parameters and self.input_state live on the same device.

compute_superposition_state(parameters, *, return_keys=False)
Return type:

Tensor | tuple[list[tuple[int, ...]], Tensor]

compute_with_keys(parameters)

Compute quantum output distribution and return both keys and probabilities.

configure_computation_space(computation_space=ComputationSpace.UNBUNCHED, *, validate_input=True)

Reconfigure the logical basis according to the desired computation space.

Return type:

None

class merlin.core.ComputationProcessFactory

Bases: object

Factory for creating computation processes.

static create(circuit, input_state, trainable_parameters, input_parameters, reservoir_mode=False, computation_space=None, **kwargs)

Create a computation process.

Return type:

ComputationProcess

enum merlin.core.ComputationSpace(value)

Bases: str, Enum

Enumeration of supported computational subspaces.

Member Type:

str

Valid values are as follows:

FOCK = <ComputationSpace.FOCK: 'fock'>
UNBUNCHED = <ComputationSpace.UNBUNCHED: 'unbunched'>
DUAL_RAIL = <ComputationSpace.DUAL_RAIL: 'dual_rail'>

The Enum and its members also have the following methods:

classmethod default(*, no_bunching)

Derive the default computation space from the legacy no_bunching flag.

Return type:

ComputationSpace

classmethod coerce(value)

Normalize user-provided values (enum instances or case-insensitive strings).

Return type:

ComputationSpace

class merlin.core.EntanglingBlock(targets='all', pattern='nearest_neighbor', depth=1, trainable=True, name_prefix=None)

Bases: object

Entangling block description.

depth: int = 1
get_params()

Entangling blocks themselves carry no direct parameters.

Return type:

dict[str, Any]

Returns:

Dict[str, Any]: Always empty because entangling blocks are metadata-only.

name_prefix: Optional[str] = None
pattern: str = 'nearest_neighbor'
targets: str | list[int] = 'all'
trainable: bool = True
class merlin.core.PhotonicBackend(circuit_type, n_modes, n_photons, state_pattern=StatePattern.PERIODIC, use_bandwidth_tuning=False, reservoir_mode=False)

Bases: object

Configuration container for quantum layer experiments.

class merlin.core.Rotation(target, role=ParameterRole.FIXED, value=0.0, axis='z', custom_name=None)

Bases: object

Rotation gate description.

The actual parameter name will be generated by the backend based on role.

axis: str = 'z'
custom_name: Optional[str] = None
get_params()

Return declared parameter placeholders for the rotation.

Non-fixed rotations expose either their custom name or the automatically generated identifier so that downstream tooling can bind data or trainable tensors to the gate.

Return type:

dict[str, Any]

Returns:

Dict[str, Any]: Mapping from parameter name to placeholder value.

role: ParameterRole = 'fixed'
target: int
value: float = 0.0
class merlin.core.StateGenerator

Bases: object

Utility class for generating photonic input states.

static generate_state(n_modes, n_photons, state_pattern)

Generate an input state based on specified pattern.

enum merlin.core.StatePattern(value)

Bases: Enum

Input photon state patterns.

Valid values are as follows:

DEFAULT = <StatePattern.DEFAULT: 'default'>
SPACED = <StatePattern.SPACED: 'spaced'>
SEQUENTIAL = <StatePattern.SEQUENTIAL: 'sequential'>
PERIODIC = <StatePattern.PERIODIC: 'periodic'>

Submodules