Core
Основные классы для работы с оптическими симуляциями
from svetlanna import Wavefront, SimulationParameters, ParameterКлассы
Wavefront
Наследует:torch.Tensor
Class that represents wavefront
Свойства
intensityCalculates intensity of the wavefront
max_intensityCalculates maximum intensity of the wavefront
phaseCalculates 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) -> SelfGenerate wavefront of the plane wave
📥 Параметры
| Параметр | Тип | Описание |
|---|---|---|
simulation_parameters | SimulationParameters | simulation parameters |
distance | float, optional | free wave propagation distance, by default 0. |
wave_direction | Any, optional | three 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_phase | float, optional | additional 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) -> SelfGenerates the Gaussian beam.
📥 Параметры
| Параметр | Тип | Описание |
|---|---|---|
simulation_parameters | SimulationParameters | simulation parameters |
waist_radius | float | Waist radius of the beam |
distance | float, optional | free wave propagation distance, by default 0. |
dx | float, optional | Horizontal position of the beam center, by default 0. |
dy | float, optional | Horizontal 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) -> SelfGenerate wavefront of the spherical wave
📥 Параметры
| Параметр | Тип | Описание |
|---|---|---|
simulation_parameters | SimulationParameters | simulation parameters |
distance | float | distance between the source and the oXY plane. |
initial_phase | float, optional | additional phase to the resulting field, by default 0. |
dx | float, optional | Horizontal position of the spherical wave center, by default 0. |
dy | float, optional | Horizontal 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
Свойства
namesNon-scalar axes’ names
Методы
__init__ constructor
__init__(self, axes: dict[str, torch.Tensor]) -> Noneindex
index(self, name: str) -> intIndex of specific axis in the tensor. The index is negative.
📥 Параметры
| Параметр | Тип | Описание |
|---|---|---|
name | str | name 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]) -> Nonemeshgrid
meshgrid(self, x_axis: str, y_axis: str)Returns a meshgrid for a selected pair of axes. …
📥 Параметры
| Параметр | Тип | Описание |
|---|---|---|
x_axis, y_axis | str | Axis 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.SizeReturns a size of axes in specified order.
📥 Параметры
| Параметр | Тип | Описание |
|---|---|---|
axs | Iterable[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)📥 Параметры
| Параметр | Тип | Описание |
|---|---|---|
data | Any | parameter tensor |
requires_grad | bool, optional | if the parameter requires gradient, by default True |
ConstrainedParameter
Наследует:Parameter
Constrained parameter
Свойства
valueParameter 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)📥 Параметры
| Параметр | Тип | Описание |
|---|---|---|
data | Any | parameter tensor |
min_value | Any | minimum value tensor |
max_value | Any | maximum value tensor |
bound_func | Callable[[torch.Tensor], torch.Tensor], optional | function that map \\mathbb{R}\to[0,1], by default torch.sigmoid |
inv_bound_func | Callable[[torch.Tensor], torch.Tensor], optional | inverse function of bound_func |
requires_grad | bool, optional | if 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📥 Параметры
| Параметр | Тип | Описание |
|---|---|---|
elements | Iterable[Element] | A set of optical elements which make up a setup. |
forward
forward(self, input_wavefront: Tensor) -> TensorA forward function for a network assembled from elements.
📥 Параметры
| Параметр | Тип | Описание |
|---|---|---|
input_wavefront | torch.Tensor | A 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_wavefront | torch.Tensor | A 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) -> Tensorto_specs
to_specs(self) -> Iterable[ParameterSpecs | SubelementSpecs]Clerk
Наследует:Generic[ConditionsType]
Методы
__init__ constructor
__init__(self, experiment_directory: str) -> NoneA 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_directory | str | The 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.
📥 Параметры
| Параметр | Тип | Описание |
|---|---|---|
None | conditions : Any | Any data that can be serialized into JSON. For example, a dict with string keys. |
load_conditions
load_conditions(self) -> ConditionsTypeRead 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.
📥 Параметры
| Параметр | Тип | Описание |
|---|---|---|
targets | dict[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) -> SelfConfigure the clerk for a new context.
📥 Параметры
| Параметр | Тип | Описание |
|---|---|---|
resume | bool, optional | If 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_checkpoint | bool, optional | If 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_checkpoint | bool, optional | If 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.
📥 Параметры
| Параметр | Тип | Описание |
|---|---|---|
tag | str | The tag for the data. The name of the log file will be based on this tag: <tag>.jsonl. |
data | dict | The data to be logged. It should be serializable into JSON. |
None | flush: bool | If 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 | `object | None, optional` |
load_checkpoint
load_checkpoint(self, index: str | int, targets: dict[str, StatefulTorchClass] | None = None, weights_only: bool = True) -> object | NoneLoad 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 | `str | int` |
targets | `dict[str, StatefulTorchClass] | None, optional` |
weights_only | bool | See 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.
📥 Параметры
| Параметр | Тип | Описание |
|---|---|---|
tag | str | The 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.
📥 Параметры
| Параметр | Тип | Описание |
|---|---|---|
tag | str | The 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_parameters | SimulationParameters | Simulation parameters for a further optical network. |
func | str | A 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.TensorMethod 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_field | Wavefront | A 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.
📥 Параметры
| Параметр | Тип | Описание |
|---|---|---|
wf | Wavefront | wavefront |
b | Any | tensor |
b_axis | `str | Iterable[str]` |
sim_params | `SimulationParameters | None, optional` |
📤 Возвращает
Wavefront
product result