Skip to Content

Core

Основные классы для работы с оптическими симуляциями

from svetlanna import Wavefront, SimulationParameters, Parameter

Классы

Wavefront

Наследует: torch.Tensor

Class that represents wavefront

Свойства

intensity

Calculates intensity of the wavefront

max_intensity

Calculates maximum intensity of the wavefront

phase

Calculates phase of the wavefront

Фабричные методы

plane_wave classmethod

plane_wave(cls, simulation_parameters: SimulationParameters, distance: float = 0.0, wave_direction: Any = None, initial_phase: float = 0.0) -> Self

Generate wavefront of the plane wave

📥 Параметры

ПараметрТипОписание
simulation_parametersSimulationParameterssimulation parameters
distancefloat, optionalfree wave propagation distance, by default 0.
wave_directionAny, optionalthree component tensor-like vector with x,y,z coordinates. The resulting field propagates along the vector, by default the wave propagates along z direction.
initial_phasefloat, optionaladditional phase to the resulting field, by default 0.

📤 Возвращает

Wavefront

plane wave field.

gaussian_beam classmethod

gaussian_beam(cls, simulation_parameters: SimulationParameters, waist_radius: float, distance: float = 0.0, dx: float = 0.0, dy: float = 0.0) -> Self

Generates the Gaussian beam.

📥 Параметры

ПараметрТипОписание
simulation_parametersSimulationParameterssimulation parameters
waist_radiusfloatWaist radius of the beam
distancefloat, optionalfree wave propagation distance, by default 0.
dxfloat, optionalHorizontal position of the beam center, by default 0.
dyfloat, optionalHorizontal position of the beam center, by default 0.

📤 Возвращает

Wavefront

Beam field in the plane oXY propagated over the distance

spherical_wave classmethod

spherical_wave(cls, simulation_parameters: SimulationParameters, distance: float, initial_phase: float = 0.0, dx: float = 0.0, dy: float = 0.0) -> Self

Generate wavefront of the spherical wave

📥 Параметры

ПараметрТипОписание
simulation_parametersSimulationParameterssimulation parameters
distancefloatdistance between the source and the oXY plane.
initial_phasefloat, optionaladditional phase to the resulting field, by default 0.
dxfloat, optionalHorizontal position of the spherical wave center, by default 0.
dyfloat, optionalHorizontal position of the spherical wave center, by default 0.

📤 Возвращает

Wavefront

Beam field

Методы

fwhm

fwhm(self, simulation_parameters: SimulationParameters) -> tuple[float, float]

Calculates full width at half maximum of the wavefront

📤 Возвращает

tuple[float, float]

full width at half maximum along x and y axes

Axes

Axes storage

Свойства

names

Non-scalar axes’ names

Методы

__init__ constructor

__init__(self, axes: dict[str, torch.Tensor]) -> None

index

index(self, name: str) -> int

Index of specific axis in the tensor. The index is negative.

📥 Параметры

ПараметрТипОписание
namestrname of the axis

📤 Возвращает

int

index of the axis

SimulationParameters

A class which describes characteristic parameters of the system

Свойства

device

Методы

__init__ constructor

__init__(self, axes: dict[str, torch.Tensor | float]) -> None

meshgrid

meshgrid(self, x_axis: str, y_axis: str)

Returns a meshgrid for a selected pair of axes. …

📥 Параметры

ПараметрТипОписание
x_axis, y_axisstrAxis names to compose a meshgrid.

📤 Возвращает

x_grid, y_grid: torch.Tensor

A torch.meshgrid of selected axis. Comment: indexing=‘xy’ the first dimension corresponds to the cardinality of the second axis (y_axis) and the second dimension corresponds to the cardinality of the first axis (x_axis).

axes_size

axes_size(self, axs: Iterable[str]) -> torch.Size

Returns a size of axes in specified order.

📥 Параметры

ПараметрТипОписание
axsIterable[str]An order of axis.

📤 Возвращает

torch.Size()

Size of axes in a specified order.

to

to(self, device: str | torch.device | int) -> 'SimulationParameters'

Parameter

Наследует: torch.Tensor

torch.Parameter replacement. Added for further feature enrichment.

Методы

__init__ constructor

__init__(self, data: Any, requires_grad: bool = True)

📥 Параметры

ПараметрТипОписание
dataAnyparameter tensor
requires_gradbool, optionalif the parameter requires gradient, by default True

ConstrainedParameter

Наследует: Parameter

Constrained parameter

Свойства

value

Parameter value

Методы

__init__ constructor

__init__(self, data: Any, min_value: Any, max_value: Any, bound_func: Callable[[torch.Tensor], torch.Tensor] = torch.sigmoid, inv_bound_func: Callable[[torch.Tensor], torch.Tensor] = sigmoid_inv, requires_grad: bool = True)

📥 Параметры

ПараметрТипОписание
dataAnyparameter tensor
min_valueAnyminimum value tensor
max_valueAnymaximum value tensor
bound_funcCallable[[torch.Tensor], torch.Tensor], optionalfunction that map \\mathbb{R}\to[0,1], by default torch.sigmoid
inv_bound_funcCallable[[torch.Tensor], torch.Tensor], optionalinverse function of bound_func
requires_gradbool, optionalif the parameter requires gradient, by default True

LinearOpticalSetup

Наследует: nn.Module

A linear optical network composed of Element’s

Методы

__init__ constructor

__init__(self, elements: Iterable[Element]) -> None

📥 Параметры

ПараметрТипОписание
elementsIterable[Element]A set of optical elements which make up a setup.

forward

forward(self, input_wavefront: Tensor) -> Tensor

A forward function for a network assembled from elements.

📥 Параметры

ПараметрТипОписание
input_wavefronttorch.TensorA wavefront that enters the optical network.

📤 Возвращает

torch.Tensor

A wavefront after the last element of the network (output of the network).

stepwise_forward

stepwise_forward(self, input_wavefront: Tensor)

Function that consistently applies forward method of each element to an input wavefront.

📥 Параметры

ПараметрТипОписание
input_wavefronttorch.TensorA wavefront that enters the optical network.

📤 Возвращает

str

A string that represents a scheme of a propagation through a setup.

list(torch.Tensor)

A list of an input wavefront evolution during a propagation through a setup.

reverse

reverse(self, Ein: Tensor) -> Tensor

to_specs

to_specs(self) -> Iterable[ParameterSpecs | SubelementSpecs]

Clerk

Наследует: Generic[ConditionsType]

Методы

__init__ constructor

__init__(self, experiment_directory: str) -> None

A lightweight alternative to TensorBoard and other logging frameworks for tracking the training process, storing experiment metadata, and handling checkpoints.

The Clerk is not a new concept but a minimal implementation included in the framework to start training models without any dependencies.

📥 Параметры

ПараметрТипОписание
experiment_directorystrThe directory where experiment data will be stored.

save_conditions

save_conditions(self, conditions: ConditionsType)

Save the experiment conditions. The conditions are stored in the experiment directory in the file conditions.json.

📥 Параметры

ПараметрТипОписание
Noneconditions : AnyAny data that can be serialized into JSON. For example, a dict with string keys.

load_conditions

load_conditions(self) -> ConditionsType

Read and return the experiment conditions.

📤 Возвращает

Any

The experiment conditions.

set_checkpoint_targets

set_checkpoint_targets(self, targets: dict[str, StatefulTorchClass])

Set the targets with state dict to be saved in the checkpoint. The same targets will be automatically used when loading from the checkpoint.

📥 Параметры

ПараметрТипОписание
targetsdict[str, StatefulTorchClass]Targets with unique keys. The same keys should be used when loading the checkpoint.

begin

begin(self, resume: bool = False, resume_load_last_checkpoint: bool = True, autosave_checkpoint: bool = False) -> Self

Configure the clerk for a new context.

📥 Параметры

ПараметрТипОписание
resumebool, optionalIf True, logs will continue to append to the files if they already exist, and the number of checkpoints will continue to grow. By default, False.
resume_load_last_checkpointbool, optionalIf True, the very last checkpoint (if available) will be used to load checkpoint targets’ states before entering the context. By default, True. This mechanism works only if resume=True. The last checkpoint is identified in checkpoints.txt and has the largest index.
autosave_checkpointbool, optionalIf True, a backup checkpoint will be saved in case the clerk context exits unexpectedly. By default, False.

📤 Возвращает

Self

The clerk.

write_log

write_log(self, tag: str, data: dict, flush: bool = False)

Write new data to a log file with a specific tag. The data should be a dictionary that can be serialized into JSON.

📥 Параметры

ПараметрТипОписание
tagstrThe tag for the data. The name of the log file will be based on this tag: <tag>.jsonl.
datadictThe data to be logged. It should be serializable into JSON.
Noneflush: boolIf flush is true, the underlying stream is forcibly flushed.

write_checkpoint

write_checkpoint(self, metadata: object | None = None)

Write the states of selected targets into a new checkpoint file.

📥 Параметры

ПараметрТипОписание
metadata`objectNone, optional`

load_checkpoint

load_checkpoint(self, index: str | int, targets: dict[str, StatefulTorchClass] | None = None, weights_only: bool = True) -> object | None

Load the checkpoint with a specific index and apply state dicts to checkpoint targets. If the targets are not provided, the checkpoint targets are obtained from the clerk settings.

If the index is integer, that the checkpoint <index>.pt is used. Otherwise, index is used as a filename.

📥 Параметры

ПараметрТипОписание
index`strint`
targets`dict[str, StatefulTorchClass]None, optional`
weights_onlyboolSee torch.load function docs, by default True.

📤 Возвращает

object | None

The checkpoint metadata, if it exists.

load_logs

load_logs(self, tag: str) -> Generator[dict, None, None]

Load logs from the file specified by the tag.

📥 Параметры

ПараметрТипОписание
tagstrThe tag for the data. The name of the log file will be read is <tag>.jsonl.

Yields

  • Generator[dict, None, None] — Log data with the specific tag.

load_logs_to_pandas

load_logs_to_pandas(self, tag: str) -> 'pandas.DataFrame'

Load logs from the file specified by the tag and return them as a pandas DataFrame.

📥 Параметры

ПараметрТипОписание
tagstrThe tag for the data. The name of the log file will be read is <tag>.jsonl.

📤 Возвращает

pd.DataFrame

Log data with the specific tag.

clean_checkpoints

clean_checkpoints(self)

Remove checkpoints that are not listed in checkpoints.txt. If checkpoints.txt does not exist, then remove all <n>.pt files, where <n> is an integer.

clean_backup_checkpoints

clean_backup_checkpoints(self)

Remove checkpoints that are matches backup checkpoints name pattern.

Detector

Наследует: Element

Object that plays a role of a physical detector in an optical system: (1) func=‘intensity’ transforms incident field to intensities for further image analysis (2) …

Методы

__init__ constructor

__init__(self, simulation_parameters: SimulationParameters, func = 'intensity')

📥 Параметры

ПараметрТипОписание
simulation_parametersSimulationParametersSimulation parameters for a further optical network.
funcstrA parameter that defines a function that will be applied to an incident field to obtain a detector image. (1) func=‘intensity’ – detector returns intensities (2) …

forward

forward(self, input_field: Wavefront) -> torch.Tensor

Method that returns the image obtained from the incident field by a detector using self.func. in the simplest case the image on a detector is an intensities image) …

📥 Параметры

ПараметрТипОписание
input_fieldWavefrontA tensor (Wavefront) of an incident field on a detector.

📤 Возвращает

detector_output : torch.Tensor

The image on a detector (according to self.func).

Функции

mul(wf: Wavefront, b: Any, b_axis: str | Iterable[str], sim_params: SimulationParameters | None = None) -> Wavefront

Multiplication of the wavefront and tensor.

📥 Параметры

ПараметрТипОписание
wfWavefrontwavefront
bAnytensor
b_axis`strIterable[str]`
sim_params`SimulationParametersNone, optional`

📤 Возвращает

Wavefront

product result