merlin.core package
Core quantum layer components.
- class merlin.core.AbstractComputationProcess
Bases:
ABCAbstract 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:
objectBeam 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:
objectSimple circuit container.
- add(component)
Append a component and return the circuit for chained calls.
- Return type:
- Args:
component: Circuit element (rotation, beam splitter, measurement, etc.).
- Returns:
Circuit:
selfto support fluent-style chaining.
- clear()
Remove every component and metadata entry from the circuit.
- 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).
-
n_modes:
int
- property num_components: int
Return the count of registered components.
- class merlin.core.Component
Bases:
objectBase class for backward compatibility.
- class merlin.core.ComputationProcess(circuit, input_state, trainable_parameters, input_parameters, n_photons=None, dtype=torch.float32, device=None, computation_space=None, no_bunching=None, output_map_func=None)
Bases:
AbstractComputationProcessHandles quantum circuit computation and state evolution.
- 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 ofself.input_stateto produce the global output amplitudes.- Return type:
- Args:
- parameters (list[torch.Tensor]): Differentiable parameters that
encode the photonic circuit. They are forwarded to
self.converterto 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]wherebatch_sizecorresponds to the number of independent input batches andnum_output_statesis the size ofself.simulation_graph.mapped_keys.- Raises:
TypeError: If
self.input_stateis not atorch.Tensor. The simulation graph expects tensor inputs, therefore other sequence types (NumPy arrays, lists, etc.) cannot be used here.- Notes:
self.input_stateis 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
parametersandself.input_statelive on the same device.
- compute_superposition_state(parameters, *, return_keys=False)
- compute_with_keys(parameters)
Compute quantum output distribution and return both keys and probabilities.
- class merlin.core.ComputationProcessFactory
Bases:
objectFactory for creating computation processes.
- static create(circuit, input_state, trainable_parameters, input_parameters, computation_space=None, **kwargs)
Create a computation process.
- Return type:
- enum merlin.core.ComputationSpace(value)
Bases:
str,EnumEnumeration 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
Enumand its members also have the following methods:- classmethod default(*, no_bunching)
Derive the default computation space from the legacy no_bunching flag.
- Return type:
- classmethod coerce(value)
Normalize user-provided values (enum instances or case-insensitive strings).
- Return type:
- class merlin.core.EntanglingBlock(targets='all', pattern='nearest_neighbor', depth=1, trainable=True, name_prefix=None)
Bases:
objectEntangling 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
-
depth:
- class merlin.core.ProbabilityDistribution(tensor, n_modes, n_photons, computation_space=ComputationSpace.FOCK, logical_performance=None, _custom_basis=None)
Bases:
objectProbability tensor bundled with Fock metadata and post-filter tracking.
Parameters
- tensor:
Dense or sparse probabilities; leading dimensions are treated as batch axes.
- n_modes:
Number of modes in the Fock space.
- n_photons:
Total photon number represented by the distribution.
- computation_space:
Basis enumeration used to order amplitudes (
fock,unbunched,dual_rail).- logical_performance:
Optional per-batch scalar tracking kept/total probability after filtering.
Notes
Instances are normalized on construction; arithmetic-style temporary unnormalized states are not supported (unlike
StateVector). Onlyshape,device,dtype, andrequires_gradare delegated to the underlyingtorch.Tensor; tensor-like helpersto,clone,detach, andrequires_grad_mirror tensor semantics while keeping metadata and logical performance aligned. Layout-changing tensor operations should be done ontensordirectly, then wrapped again viafrom_tensorto maintain a consistent basis.- property basis: Combinadics | FilteredBasis | tuple[tuple[int, ...], ...]
- property basis_size: int
- clone()
Return a cloned
ProbabilityDistributionwith metadata and logical performance copied.- Return type:
-
computation_space:
ComputationSpace= 'fock'
- detach()
Return a detached
ProbabilityDistributionsharing data without gradients.- Return type:
- filter(rule)
Apply post-selection filter and renormalize probabilities.
logical_performance records kept_mass / original_mass per batch.
- Return type:
Parameters
- rule:
Computation space alias (
fock,unbunched,dual_rail), a predicate, an explicit iterable of allowed states, or a tuple(space, predicate)to combine a computation-space constraint with an additional predicate.
Returns
- ProbabilityDistribution
A new, normalized distribution; may shrink its basis when filtering to
unbunchedordual_railin the dense case.
Raises
- ValueError
If
dual_railis selected with incompatiblen_modes/n_photonsor an unknown computation space is requested.
- classmethod from_perceval(distribution, *, dtype=None, device=None, sparse=None)
Construct from a Perceval
BSDistribution.Validates that all entries share the same photon number and mode count.
- Return type:
Parameters
- distribution:
Input Perceval distribution.
- dtype / device:
Optional overrides for output tensor placement and precision.
- sparse:
Force dense or sparse output; default auto-selects based on fill ratio.
Raises
- ValueError
If the distribution is empty or inconsistent in shape/photon number.
- classmethod from_state_vector(state_vector, *, dtype=None, device=None, computation_space=None)
Convert a
StateVectorto a probability distribution.- Return type:
Parameters
- state_vector:
Source amplitudes; must expose
to_dense,n_modes, andn_photons.- dtype / device:
Optional overrides for output tensor placement and precision.
- computation_space:
Optional basis scheme; defaults to
fock.
- classmethod from_tensor(tensor, *, n_modes, n_photons, computation_space=None, dtype=None, device=None)
Build a distribution from an explicit probability tensor.
- Return type:
Parameters
- tensor:
Dense or sparse probability tensor; last dimension must match the basis size.
- n_modes / n_photons:
Metadata for basis construction.
- computation_space:
Optional basis scheme; defaults to
fock.- dtype / device:
Optional overrides for output tensor placement and precision.
Raises
- ValueError
If the last dimension does not match the expected basis size.
- property is_normalized: bool
- property is_sparse: bool
- memory_bytes()
Return the tensor’s approximate memory footprint in bytes.
- Return type:
int
-
n_modes:
int
-
n_photons:
int
- normalize()
In-place normalization; safe for zero-mass batches.
- Return type:
Returns
- ProbabilityDistribution
The same instance, normalized along the basis dimension.
- probabilities()
Alias for
to_dense()for readability.- Return type:
- requires_grad_(requires_grad=True)
Set
requires_gradon underlying tensors and return self.- Return type:
- to(*args, **kwargs)
Return a new
ProbabilityDistributionwith tensor (and logical_performance) moved/cast viatorch.Tensor.to.- Return type:
- to_perceval()
Convert to Perceval
BSDistribution(single) or list for batches.
- class merlin.core.Rotation(target, role=ParameterRole.FIXED, value=0.0, axis='z', custom_name=None)
Bases:
objectRotation 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
-
axis:
- enum merlin.core.StatePattern(value)
Bases:
str,EnumInput photon state patterns.
- Member Type:
str
Valid values are as follows:
- DEFAULT = <StatePattern.DEFAULT: 'default'>
- SPACED = <StatePattern.SPACED: 'spaced'>
- SEQUENTIAL = <StatePattern.SEQUENTIAL: 'sequential'>
- PERIODIC = <StatePattern.PERIODIC: 'periodic'>
- class merlin.core.StateVector(tensor, n_modes, n_photons, _normalized=False)
Bases:
objectAmplitude tensor bundled with its Fock metadata.
Keeps
n_modes/n_photonsand combinadics basis ordering alongside the underlying PyTorch tensor (dense or sparse).Parameters
- tensor:
Dense or sparse amplitude tensor; leading dimensions (if any) are treated as batch axes.
- n_modes:
Number of modes in the Fock space.
- n_photons:
Total photon number represented by the state.
- _normalized:
Internal flag tracking whether the stored tensor is normalized.
Notes
This is a thin wrapper over a
torch.Tensor: onlyshape,device,dtype, andrequires_gradare delegated automatically, and tensor-like helpersto,clone,detach, andrequires_grad_are provided to mirror common tensor workflows while preserving metadata. Layout-changing operations (e.g.,reshape/view) are intentionally not exposed; perform those ontensorexplicitly if needed and rebuild viafrom_tensor.- property basis: Combinadics
Lazy combinadics basis for
(n_modes, n_photons)in Fock ordering.
- property basis_size: int
Return the number of basis states for
(n_modes, n_photons).
- clone()
Return a cloned
StateVectorwith identical metadata and normalization flag.- Return type:
- detach()
Return a detached
StateVectorsharing data without gradients.- Return type:
- classmethod from_basic_state(state, *, dtype=None, device=None, sparse=True)
Create a one-hot state from a Fock occupation list/BasicState.
- Return type:
- Args:
state: Occupation numbers per mode. dtype: Optional target dtype. device: Optional target device. sparse: Build sparse layout when True.
- Returns:
StateVector: One-hot state.
- classmethod from_perceval(state_vector, *, dtype=None, device=None, sparse=None)
Build from a
pcvl.StateVector.- Return type:
- Args:
state_vector: Perceval state to wrap. dtype: Optional target dtype. device: Optional target device. sparse: Force sparse/dense; if None use density heuristic (<=30%).
- Returns:
StateVector: Merlin wrapper with metadata and preserved amplitudes.
- Raises:
ValueError: If the Perceval state is empty or has inconsistent photon/mode counts.
- classmethod from_tensor(tensor, *, n_modes, n_photons, dtype=None, device=None)
Wrap an existing tensor with explicit metadata.
- Return type:
- Args:
tensor: Dense or sparse amplitude tensor. n_modes: Number of modes. n_photons: Total photons. dtype: Optional target dtype. device: Optional target device.
- Returns:
StateVector: Wrapped tensor.
- Raises:
ValueError: If the last dimension does not match the basis size.
- index(state)
Return basis index for the given Fock state.
- Return type:
Optional[int]
- Args:
state: Occupation list or BasicState.
- Returns:
int | None: Basis index, or None if not present (or zero in sparse tensor).
- property is_normalized: bool
- property is_sparse: bool
Return True if the underlying tensor uses a sparse layout.
- memory_bytes()
Approximate memory footprint (bytes) of the underlying tensor data.
- Return type:
int
-
n_modes:
int
-
n_photons:
int
- normalize()
Normalize this state in-place and return self.
- Return type:
- normalized_str()
Human-friendly string of the normalized state (forces normalization for display).
- Return type:
str
- requires_grad_(requires_grad=True)
Set
requires_gradon the underlying tensor and return self.- Return type:
- tensor_product(other, *, sparse=None)
Tensor product of two states with metadata propagation.
If any operand is dense, the result is dense. Supports one-hot fast path. The resulting state is normalized before returning.
- Return type:
- Args:
other: Another StateVector or a BasicState/occupation list. sparse: Override sparsity of the result; default keeps dense if any input dense.
- Returns:
StateVector: Combined state with summed modes/photons (normalized).
- Raises:
ValueError: If tensors are not 1D.
- to(*args, **kwargs)
Return a new
StateVectorwith the tensor moved/cast viatorch.Tensor.to.- Return type:
- to_perceval()
Convert to
pcvl.StateVector.- Return type:
StateVector|list[StateVector]
- Args:
None
- Returns:
pcvl.StateVector | list[pcvl.StateVector]: A Perceval state for 1D tensors, or a list for batched tensors, with amplitudes preserved (no extra renormalization).
- merlin.core.generate_state(n_modes, n_photons, state_pattern=StatePattern.DEFAULT)
Generate a Perceval Fock input state as a
BasicState.- Return type:
BasicState
- Args:
n_modes: Number of photonic modes. n_photons: Total number of photons. state_pattern: Placement strategy for the photons.
- Returns:
A
perceval.BasicStateinstance.- Raises:
ValueError: If the inputs are inconsistent or the pattern is unknown.
Submodules
- merlin.core.base module
- merlin.core.state module
- merlin.core.state_vector
- StateVector
StateVectorStateVector.tensorStateVector.n_modesStateVector.n_photonsStateVector.is_normalizedStateVector.basisStateVector.is_sparseStateVector.basis_sizeStateVector.to()StateVector.clone()StateVector.detach()StateVector.requires_grad_()StateVector.memory_bytes()StateVector.to_perceval()StateVector.from_perceval()StateVector.from_basic_state()StateVector.from_tensor()StateVector.tensor_product()StateVector.index()StateVector.to_dense()StateVector.normalize()StateVector.normalized_str()
- Notes and Examples
- StateVector
- merlin.core.probability_distribution
- ProbabilityDistribution
ProbabilityDistributionProbabilityDistribution.tensorProbabilityDistribution.n_modesProbabilityDistribution.n_photonsProbabilityDistribution.computation_spaceProbabilityDistribution.logical_performanceProbabilityDistribution.basisProbabilityDistribution.basis_sizeProbabilityDistribution.to()ProbabilityDistribution.clone()ProbabilityDistribution.detach()ProbabilityDistribution.requires_grad_()ProbabilityDistribution.is_sparseProbabilityDistribution.is_normalizedProbabilityDistribution.memory_bytes()ProbabilityDistribution.normalize()ProbabilityDistribution.to_dense()ProbabilityDistribution.probabilities()ProbabilityDistribution.from_tensor()ProbabilityDistribution.from_state_vector()ProbabilityDistribution.from_perceval()ProbabilityDistribution.to_perceval()ProbabilityDistribution.filter()
- Notes and Examples
- ProbabilityDistribution
- merlin.core.process module
- merlin.core.components module
- merlin.core.partial_measurement
- PartialMeasurementBranch
- PartialMeasurement
PartialMeasurementPartialMeasurement.verify_branches_order()PartialMeasurement.reorder_branches()PartialMeasurement.probability_tensor_shapePartialMeasurement.n_measured_modesPartialMeasurement.n_unmeasured_modesPartialMeasurement.tensorPartialMeasurement.probabilitiesPartialMeasurement.amplitudesPartialMeasurement.outcomesPartialMeasurement.set_grouping()PartialMeasurement.from_detector_transform_output()
- Notes and Examples
- MerlinProcessor API Reference