svetlanna

Subpackages

Submodules

svetlanna.axes_math module

svetlanna.axes_math.cast_tensor(a: Tensor, axes: tuple[str, ...], new_axes: tuple[str, ...]) Tensor

Cast tensor a with axes (…, a, b, c) to (…, *new_axes). new_axes should contain all axes presented in axes.

Parameters

atorch.Tensor

a tensor to cast

axestuple[str, …]

last axes of the tensor

new_axestuple[str, …]

last axes of the resulting tensor

Returns

torch.Tensor

tensor with new_axes as last axes

svetlanna.axes_math.is_scalar(a: Tensor | float) bool

Check if the value scalar, meaning 0-dimensional tensor or float

Parameters

atorch.Tensor | float

value to check

Returns

bool

test result

svetlanna.axes_math.tensor_dot(a: Tensor | float, b: Tensor | float, a_axis: str | Iterable[str], b_axis: str | Iterable[str], preserve_a_axis: bool = False) tuple[Tensor, tuple[str, ...]]

Perform tensor dot product.

Parameters

atorch.Tensor | float

first tensor

btorch.Tensor | float

second tensor

a_axisstr | Iterable[str]

axis name of the first tensor

b_axisstr | Iterable[str]

axis name of the second tensor

preserve_a_axisbool, optional

check if the resulting tensor axes are coincide with the a tensor axes, by default False

Returns

tuple[torch.Tensor, tuple[str, …]]

Product result and its axes names

svetlanna.clerk module

class svetlanna.clerk.Clerk(experiment_directory: str)

Bases: Generic[ConditionsType]

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

Configure the clerk for a new context.

Parameters

resumebool, 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_checkpointbool, 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_checkpointbool, optional

If True, a backup checkpoint will be saved in case the clerk context exits unexpectedly. By default, False.

Returns

Self

The clerk.

clean_backup_checkpoints()

Remove checkpoints that are matches backup checkpoints name pattern.

clean_checkpoints()

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.

load_checkpoint(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.

Parameters

indexstr | int

The checkpoint index.

targetsdict[str, StatefulTorchClass] | None, optional

Targets with unique keys, by default None. See the set_checkpoint_targets method.

weights_onlybool

See torch.load function docs, by default True.

Returns

object | None

The checkpoint metadata, if it exists.

load_conditions() ConditionsType

Read and return the experiment conditions.

Returns

Any

The experiment conditions.

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

Load logs from the file specified by the tag.

Parameters

tagstr

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(tag: str) pandas.DataFrame

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

Parameters

tagstr

The tag for the data. The name of the log file will be read is <tag>.jsonl.

Returns

pd.DataFrame

Log data with the specific tag.

save_conditions(conditions: ConditionsType)

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

conditionsAny

Any data that can be serialized into JSON. For example, a dict with string keys.

set_checkpoint_targets(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.

Parameters

targetsdict[str, StatefulTorchClass]

Targets with unique keys. The same keys should be used when loading the checkpoint.

write_checkpoint(metadata: object | None = None)

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

Parameters

metadataobject | None, optional

The metadata for the new checkpoint, by default None.

write_log(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.

Parameters

tagstr

The tag for the data. The name of the log file will be based on this tag: <tag>.jsonl.

datadict

The data to be logged. It should be serializable into JSON.

flush: bool

If flush is true, the underlying stream is forcibly flushed.

class svetlanna.clerk.ClerkMode(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)

Bases: StrEnum

An internal class used to distinguish clerk modes.

The new_run mode indicates that all log files should be rewritten along with all checkpoints. In contrast, the resume mode means that new logs will be appended to existing log files, and checkpoint indices will continue to increment.

new_run = 'new_run'
resume = 'resume'
class svetlanna.clerk.StatefulTorchClass(*args, **kwargs)

Bases: Protocol

A protocol for PyTorch objects that have a state dictionary, such as modules and optimizers.

load_state_dict(*args, **kwargs) Any
state_dict(*args, **kwargs) dict[str, Any]

svetlanna.detector module

class svetlanna.detector.Detector(simulation_parameters: SimulationParameters, func='intensity')

Bases: 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

forward(input_field: Wavefront) 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) …

Parameters

input_fieldWavefront

A tensor (Wavefront) of an incident field on a detector.

Returns

detector_outputtorch.Tensor

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

class svetlanna.detector.DetectorProcessorClf(num_classes: int, simulation_parameters: SimulationParameters, segmented_detector: Tensor | None = None, segments_weights: Tensor | None = None, segments_zone_size: Size | None = None, segmentation_type: str = 'strips', device: str | device = device(type='cpu'))

Bases: Module

The necessary layer to solve a classification task. Must be placed after a detector. This layer process an image from the detector and calculates probabilities of belonging to classes.

batch_forward(batch_detector_data: Tensor) Tensor

Calculates probabilities of belonging to classes for a batch of detector images. …

Parameters

batch_detector_datatorch.Tensor

A batch of images from a detector. shape=(batch_size, … ‘H’, ‘W’).

Returns

torch.Tensor

A tensor of probabilities of element belonging to classes for further calculation of loss. shape=(batch_size, self.num_classes)

batch_zone_integral(batch_detector_data: Tensor, ind_class: int) Tensor

Returns an integral (sum) of a detector data over a selected zone (ind_class). …

Parameters

batch_detector_datatorch.Tensor

A batch of images from a detector.

ind_classint

Index of a class.

Returns

torch.Tensor

Sum of intensities over the selected zone for a batch. Sze of a tensor = [batch_size]

detector_segmentation(detector_shape: Size) Tensor

Function that markups a detector area by classes zones. …

Parameters

detector_shapetorch.Size

Shape of a detector.

Returns

detector_markuptorch.Tensor(dtype=torch.int32)

A tensor of the same shape as detector, where 1) each pixel in the mask is marked by a class number from 0 to self.num_classes; 2) if pixel is marked as -1 it is not belonging to any class during a computation of probabilities; 3) each class zone can be highlighted as torch.where(detector_markup == ind_class, 1, 0).

property device: str | device | int
forward(detector_data: Tensor) Tensor

Calculates probabilities of belonging to classes by detector image. …

Parameters

detector_datatorch.Tensor

A tensor that represents an image on a detector.

Returns

torch.Tensor

A tensor of probabilities of element belonging to classes for further calculation of loss. shape=(1, self.num_classes)

to(device: str | device | int) DetectorProcessorClf

Move and/or cast the parameters and buffers.

This can be called as

to(device=None, dtype=None, non_blocking=False)
to(dtype, non_blocking=False)
to(tensor, non_blocking=False)
to(memory_format=torch.channels_last)

Its signature is similar to torch.Tensor.to(), but only accepts floating point or complex dtypes. In addition, this method will only cast the floating point or complex parameters and buffers to dtype (if given). The integral parameters and buffers will be moved device, if that is given, but with dtypes unchanged. When non_blocking is set, it tries to convert/move asynchronously with respect to the host if possible, e.g., moving CPU Tensors with pinned memory to CUDA devices.

See below for examples.

Note

This method modifies the module in-place.

Args:
device (torch.device): the desired device of the parameters

and buffers in this module

dtype (torch.dtype): the desired floating point or complex dtype of

the parameters and buffers in this module

tensor (torch.Tensor): Tensor whose dtype and device are the desired

dtype and device for all parameters and buffers in this module

memory_format (torch.memory_format): the desired memory

format for 4D parameters and buffers in this module (keyword only argument)

Returns:

Module: self

Examples:

>>> # xdoctest: +IGNORE_WANT("non-deterministic")
>>> linear = nn.Linear(2, 2)
>>> linear.weight
Parameter containing:
tensor([[ 0.1913, -0.3420],
        [-0.5113, -0.2325]])
>>> linear.to(torch.double)
Linear(in_features=2, out_features=2, bias=True)
>>> linear.weight
Parameter containing:
tensor([[ 0.1913, -0.3420],
        [-0.5113, -0.2325]], dtype=torch.float64)
>>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA1)
>>> gpu1 = torch.device("cuda:1")
>>> linear.to(gpu1, dtype=torch.half, non_blocking=True)
Linear(in_features=2, out_features=2, bias=True)
>>> linear.weight
Parameter containing:
tensor([[ 0.1914, -0.3420],
        [-0.5112, -0.2324]], dtype=torch.float16, device='cuda:1')
>>> cpu = torch.device("cpu")
>>> linear.to(cpu)
Linear(in_features=2, out_features=2, bias=True)
>>> linear.weight
Parameter containing:
tensor([[ 0.1914, -0.3420],
        [-0.5112, -0.2324]], dtype=torch.float16)

>>> linear = nn.Linear(2, 2, bias=None).to(torch.cdouble)
>>> linear.weight
Parameter containing:
tensor([[ 0.3741+0.j,  0.2382+0.j],
        [ 0.5593+0.j, -0.4443+0.j]], dtype=torch.complex128)
>>> linear(torch.ones(3, 2, dtype=torch.cdouble))
tensor([[0.6122+0.j, 0.1150+0.j],
        [0.6122+0.j, 0.1150+0.j],
        [0.6122+0.j, 0.1150+0.j]], dtype=torch.complex128)
weight_segments() Tensor

Calculates weights for segments if segments having different areas. Comment: weight_i * area_i = const …

Returns

torch.Tensor

A tensor of weights for further calculation of integrals. shape=(1, self.num_classes)

svetlanna.logging module

svetlanna.logging.agr_short_description(arg: Any) str

Create short description string based on arg type

Parameters

argAny

argument value

Returns

str

description

svetlanna.logging.forward_logging_hook(module, input, output) None

Global debug forward hook for all elements

svetlanna.logging.log_message(message: str)
svetlanna.logging.register_logging_hook(module, name, value, type: Literal['Parameter', 'Buffer', 'Module']) None
svetlanna.logging.set_debug_logging(mode: bool, type: Literal['logging', 'print'] = 'print')

Enables and disables debug logging. If type is ‘print’, then messages are printed using print, if type is ‘logging’ the messages are written in the logger named svetlanna.logging.

Parameters

modebool

flag whether to enable debug logging

type: Literal[‘logging’, ‘print’]

type of logging messages output

svetlanna.parameters module

class svetlanna.parameters.ConstrainedParameter(*args, **kwargs)

Bases: Parameter

Constrained parameter

property value: Tensor

Parameter value

Returns

torch.Tensor

Constrained parameter value computed with bound_func

class svetlanna.parameters.InnerParameterStorageModule(params_to_store: dict[str, Tensor | Parameter])

Bases: Module

expand(params_to_store: dict[str, Tensor | Parameter])

Add more parameters to the storage

Parameters

params_to_storedict[str, torch.Tensor | torch.nn.Parameter]

parameters to store

class svetlanna.parameters.Parameter(*args, **kwargs)

Bases: Tensor

torch.Parameter replacement. Added for further feature enrichment.

svetlanna.parameters.sigmoid_inv(x: Tensor) Tensor

Inverse sigmoid function

Parameters

xtorch.Tensor

the input tensor

Returns

torch.Tensor

the output tensor

svetlanna.setup module

class svetlanna.setup.LinearOpticalSetup(elements: Iterable[Element])

Bases: Module

A linear optical network composed of Element’s

forward(input_wavefront: Tensor) Tensor

A forward function for a network assembled from elements.

Parameters

input_wavefronttorch.Tensor

A wavefront that enters the optical network.

Returns

torch.Tensor

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

reverse(Ein: Tensor) Tensor
stepwise_forward(input_wavefront: Tensor)

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

Parameters

input_wavefronttorch.Tensor

A wavefront that enters the optical network.

Returns

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.

to_specs() Iterable[ParameterSpecs | SubelementSpecs]

svetlanna.simulation_parameters module

class svetlanna.simulation_parameters.Axes(axes: dict[str, Tensor])

Bases: object

Axes storage

index(name: str) int

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

Parameters

namestr

name of the axis

Returns

int

index of the axis

property names: tuple[str, ...]

Non-scalar axes’ names

exception svetlanna.simulation_parameters.AxisNotFound

Bases: Exception

class svetlanna.simulation_parameters.SimulationParameters(axes: dict[str, Tensor | float])

Bases: object

A class which describes characteristic parameters of the system

axes_size(axs: str | Iterable[str]) Size

Returns a size of axes in specified order.

Parameters

axsstr | Iterable[str]

An order of axis.

Returns

torch.Size()

Size of axes in a specified order.

property device: str | device | int
meshgrid(x_axis: str, y_axis: str)

Returns a meshgrid for a selected pair of axes. …

Parameters

x_axis, y_axisstr

Axis names to compose a meshgrid.

Returns

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).

to(device: str | device | int) SimulationParameters

svetlanna.transforms module

class svetlanna.transforms.GaussModulation(sim_params: SimulationParameters, fwhm_x, fwhm_y, peak_x=0.0, peak_y=0.0)

Bases: Module

Multiplies an amplitude of a Wavefront on a gaussian.

forward(wf: Wavefront) Wavefront

Multiplies an input wavefront on a gauss. …

Parameters

wfWavefront

An input wavefront of a shape corresponding to simulation parameters.

Returns

wf_gaussWavefront

A gaussian distribution in a 2D plane.

get_gauss()

Generates a gaussian according to simulation parameters! …

Returns

gauss_2dtorch.Tensor

A gaussian distribution in a 2D plane.

class svetlanna.transforms.ToWavefront(modulation_type=None)

Bases: Module

Transformation of a Tensor to a Wavefront. Three types of transform:
  1. modulation_type=’amp’ tensor values transforms to amplitude, phase = 0

  2. modulation_type=’phase’ tensor values transforms to phases (from 0 to 2pi - eps), amp = const

  3. modulation_type=’amp&phase’ (any other str) tensor values transforms to amplitude and phase simultaneously

forward(img_tensor: Tensor) Wavefront

Function that transforms Tensor to Wavefront. …

Parameters

img_tensortorch.Tensor

A Tensor (of shape [C, H, W] in the range [0, 1]) to be transformed to a Wavefront.

Returns

img_wavefrontWavefront

A resulted Wavefront obtained via one of modulation types (self.modulation_type).

svetlanna.units module

class svetlanna.units.ureg(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)

Bases: Enum

Unit registry. To use it one should multiply variable by the units: .. code-block:: python

var = 10 assert var * ureg.mm == 10*1e-2

GHz = 1000000000.0
Gm = 1000000000.0
Gs = 1000000000.0
Hz = 1
MHz = 1000000.0
Mm = 1000000.0
Ms = 1000000.0
cHz = 0.01
cm = 0.01
cs = 0.01
dHz = 0.1
dm = 0.1
ds = 0.1
fs = 1e-15
kHz = 1000.0
km = 1000.0
ks = 1000.0
m = 1
mHz = 0.001
mm = 0.001
ms = 0.001
nHz = 1e-09
nm = 1e-09
ns = 1e-09
pHz = 1e-12
pm = 1e-12
ps = 1e-12
s = 1
uHz = 1e-06
um = 1e-06
us = 1e-06

svetlanna.wavefront module

class svetlanna.wavefront.Wavefront(data, *args, **kwargs)

Bases: Tensor

Class that represents wavefront

fwhm(simulation_parameters: SimulationParameters) tuple[float, float]

Calculates full width at half maximum of the wavefront

Returns

tuple[float, float]

full width at half maximum along x and y axes

classmethod gaussian_beam(simulation_parameters: SimulationParameters, waist_radius: float, distance: float = 0.0) Self

Generates the Gaussian beam.

Parameters

simulation_parametersSimulationParameters

simulation parameters

waist_radiusfloat

Waist radius of the beam

distancefloat, optional

free wave propagation distance, by default 0.

Returns

Wavefront

Beam field in the plane oXY propagated over the distance

property intensity: Tensor

Calculates intensity of the wavefront

Returns

torch.Tensor

intensity

property max_intensity: float

Calculates maximum intensity of the wavefront

Returns

float

maximum intensity

property phase: Tensor

Calculates phase of the wavefront

Returns

torch.Tensor

phase from $0$ to $2pi$

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

Generate wavefront of the plane wave

Parameters

simulation_parametersSimulationParameters

simulation parameters

distancefloat, optional

free wave propagation distance, by default 0.

wave_directionAny, 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_phasefloat, optional

additional phase to the resulting field, by default 0.

Returns

Wavefront

plane wave field.

classmethod spherical_wave(simulation_parameters: SimulationParameters, distance: float, initial_phase: float = 0.0) Self

Generate wavefront of the spherical wave

Parameters

simulation_parametersSimulationParameters

simulation parameters

distancefloat

distance between the source and the oXY plane.

initial_phasefloat, optional

additional phase to the resulting field, by default 0.

Returns

Wavefront

Beam field

svetlanna.wavefront.mul(wf: Wavefront, b: Any, b_axis: str | Iterable[str], sim_params: SimulationParameters | None = None) Wavefront

Multiplication of the wavefront and tensor.

Parameters

wfWavefront

wavefront

bAny

tensor

b_axisstr | Iterable[str]

tensor’s axis name

sim_paramsSimulationParameters | None, optional

simulation parameters, by default None

Returns

Wavefront

product result

Module contents

class svetlanna.Clerk(experiment_directory: str)

Bases: Generic[ConditionsType]

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

Configure the clerk for a new context.

Parameters

resumebool, 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_checkpointbool, 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_checkpointbool, optional

If True, a backup checkpoint will be saved in case the clerk context exits unexpectedly. By default, False.

Returns

Self

The clerk.

clean_backup_checkpoints()

Remove checkpoints that are matches backup checkpoints name pattern.

clean_checkpoints()

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.

load_checkpoint(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.

Parameters

indexstr | int

The checkpoint index.

targetsdict[str, StatefulTorchClass] | None, optional

Targets with unique keys, by default None. See the set_checkpoint_targets method.

weights_onlybool

See torch.load function docs, by default True.

Returns

object | None

The checkpoint metadata, if it exists.

load_conditions() ConditionsType

Read and return the experiment conditions.

Returns

Any

The experiment conditions.

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

Load logs from the file specified by the tag.

Parameters

tagstr

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(tag: str) pandas.DataFrame

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

Parameters

tagstr

The tag for the data. The name of the log file will be read is <tag>.jsonl.

Returns

pd.DataFrame

Log data with the specific tag.

save_conditions(conditions: ConditionsType)

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

conditionsAny

Any data that can be serialized into JSON. For example, a dict with string keys.

set_checkpoint_targets(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.

Parameters

targetsdict[str, StatefulTorchClass]

Targets with unique keys. The same keys should be used when loading the checkpoint.

write_checkpoint(metadata: object | None = None)

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

Parameters

metadataobject | None, optional

The metadata for the new checkpoint, by default None.

write_log(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.

Parameters

tagstr

The tag for the data. The name of the log file will be based on this tag: <tag>.jsonl.

datadict

The data to be logged. It should be serializable into JSON.

flush: bool

If flush is true, the underlying stream is forcibly flushed.

class svetlanna.ConstrainedParameter(*args, **kwargs)

Bases: Parameter

Constrained parameter

property value: Tensor

Parameter value

Returns

torch.Tensor

Constrained parameter value computed with bound_func

class svetlanna.LinearOpticalSetup(elements: Iterable[Element])

Bases: Module

A linear optical network composed of Element’s

forward(input_wavefront: Tensor) Tensor

A forward function for a network assembled from elements.

Parameters

input_wavefronttorch.Tensor

A wavefront that enters the optical network.

Returns

torch.Tensor

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

reverse(Ein: Tensor) Tensor
stepwise_forward(input_wavefront: Tensor)

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

Parameters

input_wavefronttorch.Tensor

A wavefront that enters the optical network.

Returns

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.

to_specs() Iterable[ParameterSpecs | SubelementSpecs]
class svetlanna.Parameter(*args, **kwargs)

Bases: Tensor

torch.Parameter replacement. Added for further feature enrichment.

class svetlanna.SimulationParameters(axes: dict[str, Tensor | float])

Bases: object

A class which describes characteristic parameters of the system

axes_size(axs: str | Iterable[str]) Size

Returns a size of axes in specified order.

Parameters

axsstr | Iterable[str]

An order of axis.

Returns

torch.Size()

Size of axes in a specified order.

property device: str | device | int
meshgrid(x_axis: str, y_axis: str)

Returns a meshgrid for a selected pair of axes. …

Parameters

x_axis, y_axisstr

Axis names to compose a meshgrid.

Returns

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).

to(device: str | device | int) SimulationParameters
class svetlanna.Wavefront(data, *args, **kwargs)

Bases: Tensor

Class that represents wavefront

fwhm(simulation_parameters: SimulationParameters) tuple[float, float]

Calculates full width at half maximum of the wavefront

Returns

tuple[float, float]

full width at half maximum along x and y axes

classmethod gaussian_beam(simulation_parameters: SimulationParameters, waist_radius: float, distance: float = 0.0) Self

Generates the Gaussian beam.

Parameters

simulation_parametersSimulationParameters

simulation parameters

waist_radiusfloat

Waist radius of the beam

distancefloat, optional

free wave propagation distance, by default 0.

Returns

Wavefront

Beam field in the plane oXY propagated over the distance

property intensity: Tensor

Calculates intensity of the wavefront

Returns

torch.Tensor

intensity

property max_intensity: float

Calculates maximum intensity of the wavefront

Returns

float

maximum intensity

property phase: Tensor

Calculates phase of the wavefront

Returns

torch.Tensor

phase from $0$ to $2pi$

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

Generate wavefront of the plane wave

Parameters

simulation_parametersSimulationParameters

simulation parameters

distancefloat, optional

free wave propagation distance, by default 0.

wave_directionAny, 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_phasefloat, optional

additional phase to the resulting field, by default 0.

Returns

Wavefront

plane wave field.

classmethod spherical_wave(simulation_parameters: SimulationParameters, distance: float, initial_phase: float = 0.0) Self

Generate wavefront of the spherical wave

Parameters

simulation_parametersSimulationParameters

simulation parameters

distancefloat

distance between the source and the oXY plane.

initial_phasefloat, optional

additional phase to the resulting field, by default 0.

Returns

Wavefront

Beam field

svetlanna.set_debug_logging(mode: bool, type: Literal['logging', 'print'] = 'print')

Enables and disables debug logging. If type is ‘print’, then messages are printed using print, if type is ‘logging’ the messages are written in the logger named svetlanna.logging.

Parameters

modebool

flag whether to enable debug logging

type: Literal[‘logging’, ‘print’]

type of logging messages output