Public Python API#

BornSim computes scattering from finite voxel samples. Choose physical units, spatial and angular configurations explicitly. Grid.from_extent derives an isotropic voxel spacing from explicit axis extents and shape. GaussianMedium, ExponentialMedium, and WhittleMaternMedium generate random fields; RandomSphereMedium places identical nonoverlapping spheres. StructuredMedium voxelizes backgrounds and shapes and can add a seeded fluctuation field over the full structure. Solver accepts either AngularSampling or Directions for fixed volumes, or an ensemble of generated volumes. Integrated coefficients describe finite-sample cross sections divided by volume. Infinite-medium analytical formulas are test references, not public solvers.

Incident direction and polarization#

Source accepts incident_direction, a real Cartesian unit vector, and polarization, a PolarizationState or an explicit complex Cartesian unit electric-field vector. Omitting polarization selects unpolarized light. The default incident direction is positive z.

The state constructors follow PyMieSim’s interface:

from bornsim import LeftCircular, PolarizationState, RightCircular, Source
from bornsim.units import ureg

linear_state = PolarizationState(angle=45 * ureg.degree)

elliptical_state = PolarizationState(jones_vector=[1, 0.5j])

left_circular_state = LeftCircular()

right_circular_state = RightCircular()

source = Source(
    wavelength=633 * ureg.nanometer,
    incident_direction=[0.6, 0, 0.8],
    polarization=linear_state,
)

Supply exactly one of angle (a finite angular quantity) or jones_vector (two finite complex components). Nonzero Jones vectors are normalized to unit incident intensity, preserving relative phase. The stored Jones array is immutable. For positive-z incidence its components are laboratory x and y. For oblique incidence, the first basis vector is the normalized projection of laboratory +x onto the transverse plane; the second is incident_direction cross first. For incidence parallel to laboratory x, +y is the reference instead. These conventions also define linear angle zero.

LeftCircular is [1, +1j] / sqrt(2) and RightCircular is [1, -1j] / sqrt(2), matching PyMieSim’s signs. The time convention is \(\exp(-i\omega t)\) and the transverse basis is right-handed.

Explicit three-component Cartesian vectors remain available for complete control over the electric field in laboratory coordinates. They must already have unit norm and be transverse to the incident direction. Source resolves Jones states to these immutable Cartesian vectors; archives retain the resolved physical illumination. No PyMieSim dependency is required.

A pure state has one incident-polarization amplitude channel. Unpolarized light has two orthogonal linear channels, whose intensities are averaged. Partially polarized mixtures are not currently configurable.

AngularSampling and Directions always describe laboratory coordinates: polar angle is measured from positive z, independently of the incident beam. For oblique incidence, a laboratory polar angle is not the scattering angle. g and mu_s_prime nevertheless use the physical scattering cosine, observation_direction @ incident_direction. Azimuth averages remain averages about laboratory z. The phase function is still normalized over the full sphere. See Oblique illumination and linear, circular, and elliptical polarization.

Numerical calculation#

from bornsim import AngularSampling, Directions, Grid, Solver, Source
from bornsim.medium.random_medium import GaussianMedium
from bornsim.units import ureg

grid = Grid(
    shape=(4, 4, 4),
    spacing=40 * ureg.nanometer,
)

medium = GaussianMedium(
    background_refractive_index=1.33,
    refractive_index_std=0.01,
    correlation_length=80 * ureg.nanometer,
)

volume = medium.to_volume(
    grid=grid,
    seed=42,
)

sampling = AngularSampling(
    start=0 * ureg.degree,
    end=180 * ureg.degree,
    n_points=19,
)

source = Source(wavelength=633 * ureg.nanometer)

solver = Solver(
    source=source,
    sampling=sampling,
    order=2,
)

result = solver.solve(target=volume)

print(f'mu_s = {result.mu_s}, g = {result.g}')

directions = Directions(
    vectors=[
        [0, 0, 1],
        [1, 0, 0],
    ],
)

directional_result = solver.solve(
    target=volume,
    sampling=directions,
)

cut = solver.solve_cut(
    target=volume,
    directions=directions,
)

np.testing.assert_allclose(
    directional_result.differential.magnitude,
    cut.differential.magnitude,
)

Field construction#

from bornsim import Grid, Layer, StructuredMedium, Volume
from bornsim.medium.random_medium import WhittleMaternMedium
from bornsim.units import ureg

grid = Grid.from_extent(
    shape=(16, 16, 16),
    extent=(400, 400, 400) * ureg.nanometer,
)

layer = Layer.from_center_and_thickness(
    centre=(0, 0, -100) * ureg.nanometer,
    thickness=200 * ureg.nanometer,
    refractive_index=1.335,
)

statistics = WhittleMaternMedium(
    background_refractive_index=1.33,
    refractive_index_std=0.002,
    correlation_length=50 * ureg.nanometer,
    smoothness=1.5,
)

medium = StructuredMedium()
medium.add_background(refractive_index=1.33)
medium.add_structures(layer)
medium.add_fluctuations(medium=statistics)

volume = medium.to_volume(
    grid=grid,
    seed=42,
)

absolute_refractive_index = volume.refractive_index

imported_volume = Volume.from_refractive_index(
    refractive_index=absolute_refractive_index,
    background_refractive_index=1.33,
    grid=grid,
)

Alternatively, independently generated volumes with matching grids and backgrounds can be combined with volume_a + volume_b. The result’s refractive_index property exposes its immutable absolute voxel field. Volume.from_refractive_index also constructs a volume from an absolute unitless index array, converting it to the linearized contrast representation.

Configuration#

Observable stability comparisons, distinct from physical validity claims.

class ConvergenceReport(*, results, labels, tolerance=0.01)[source]#

Bases: object

Compare final-order observables across an explicit refinement sequence.

Parameters:
  • results (tuple of Result) – At least two full angular results ordered from coarse to fine. Change one control at a time: grid, quadrature, sample extent, ensemble size, or solver order. The user controls physical equivalence of the cases.

  • labels (tuple of str) – One descriptive label per calculation.

  • tolerance (float, optional) – Relative tolerance for mu_s and mu_a, absolute tolerance for g. Default 0.01. Stability does not certify the Born model’s validity.

Notes

Each row uses the highest order in its result. Relative differences use max(abs(previous), abs(current)); two zeros have zero difference. Unknown observables are omitted, and unknown residuals remain None. Compare ensemble uncertainties separately from discretization errors.

labels: tuple[str, ...]#
results: tuple[Result, ...]#
property rows: tuple[dict, ...]#

Return fresh numeric rows for each refinement step.

Coefficients use inverse metres; anisotropy and residuals are dimensionless. Relative changes and phase-curve distances compare each row with its predecessor.

Returns:

Independent JSON-compatible row summaries. Mutating them does not affect the report.

Return type:

tuple of dict

summary()[source]#

Return a compact report without claiming physical convergence.

Returns:

Human-readable coefficients and stability indicators.

Return type:

str

tolerance: float = 0.01#

Incident illumination for BornSim scattering calculations.

class Source(*, wavelength, incident_direction=(0.0, 0.0, 1.0), polarization=None)[source]#

Bases: object

Define a plane wave with arbitrary propagation and polarization.

Parameters:
  • wavelength (Quantity) – Positive, finite vacuum wavelength with explicit length units.

  • incident_direction (array_like, optional) – Real Cartesian unit 3-vector in laboratory coordinates. Defaults to positive z. Values must be unitless; no automatic normalization occurs.

  • polarization (PolarizationState or array_like, optional) – A Jones state in the local transverse basis, or a complex Cartesian unit electric-field 3-vector perpendicular to incident_direction. Real vectors describe linear polarization; complex vectors allow circular and elliptical polarization. Omit for an equal incoherent mixture of two orthogonal transverse linear polarizations. Vectors are copied into immutable storage. Use exp(-i omega t).

Notes

Observation angles remain laboratory polar and azimuth angles. They are scattering angles relative to the beam only for positive-z incidence. A pure polarization has one amplitude channel; unpolarized light has two. Both configurations have the same total incident intensity normalization.

incident_direction: _Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | complex | bytes | str | _NestedSequence[complex | bytes | str] = (0.0, 0.0, 1.0)#
property metadata: dict#

Return fresh JSON-compatible illumination settings in SI units.

Returns:

Wavelength in metres and incident direction and polarization components as JSON lists.

Return type:

dict of str to object

polarization: PolarizationState | _Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | complex | bytes | str | _NestedSequence[complex | bytes | str] | None = None#
property polarization_vectors: ndarray#

Return unit electric-field modes for the incident source.

Returns:

Complex or real unit polarization vectors with shape (mode, 3). An unspecified polarization produces two equally weighted incoherent transverse modes.

Return type:

numpy.ndarray

wavelength: Quantity#

Pure polarization states in a source’s local transverse Jones basis.

class LeftCircular[source]#

Bases: PolarizationState

Unit Jones state (1, +i)/sqrt(2), matching PyMieSim’s convention.

class PolarizationState(*, angle=None, jones_vector=None)[source]#

Bases: object

Define linear polarization by angle or a general pure Jones state.

Parameters:
  • angle (Quantity, optional) – Linear polarization orientation with explicit angular units. Zero aligns with the source’s first transverse basis vector; positive angles turn toward its second. Cannot be combined with jones_vector.

  • jones_vector (array_like, optional) – Two finite, complex, unitless electric-field components. Nonzero vectors are normalized to unit incident intensity, retaining relative phase. Cannot be combined with angle. Supply exactly one argument.

Notes

Source projects laboratory +x onto the plane normal to its incident direction to obtain the first basis vector. For incidence parallel to x, laboratory +y is used instead. The second vector is direction cross first, so the basis and propagation direction form a right-handed frame. For positive-z incidence the Jones basis is exactly laboratory x, y. The time convention is exp(-i omega t). Jones vectors describe pure states; unpolarized illumination is selected by omitting Source.polarization.

angle: Quantity | None#
jones_vector: ndarray#
class RightCircular[source]#

Bases: PolarizationState

Unit Jones state (1, -i)/sqrt(2), matching PyMieSim’s convention.

Reusable centred cubic voxel grids with unit-bearing coordinates.

class Grid(*, shape, spacing)[source]#

Bases: object

Define the spatial discretization once for generation and scattering.

Parameters:
  • shape (tuple of int) – Three explicitly chosen voxel counts, each from 2 to 32.

  • spacing (Quantity) – Positive, finite cubic voxel width, with its supplied length units. A spacing must be supplied.

Use from_extent() when the full physical voxel-box extent is known instead of the voxel spacing.

Notes

Voxel centres are (i - (N - 1)/2) * spacing on each axis. The box extends half a voxel beyond its outer centres. It describes the sampled domain, not an additional dielectric boundary. Background refractive index belongs to the medium or volume, rather than the spatial grid.

classmethod from_extent(*, shape, extent)[source]#

Create an isotropic voxel grid from its full physical extent.

Parameters:
  • shape (tuple of int) – Voxel counts along x, y, and z; each must be between 2 and 32.

  • extent (Quantity) – Full voxel-box lengths along x, y, and z, with explicit length units. All three lengths must imply the same voxel spacing.

Returns:

Grid with spacing derived from the first extent component.

Return type:

Grid

Raises:

ValueError – If shape, units, extent values, or implied spacings are invalid.

property metadata: dict[str, object]#

Return fresh JSON-compatible grid settings in SI units.

Returns:

Voxel shape and spacing in metres.

Return type:

dict of str to object

property positions: Quantity#

Return unit-bearing voxel-centre coordinates.

Returns:

Cartesian coordinates with shape (*shape, 3) and the spacing’s length units. The returned array is newly computed.

Return type:

Quantity

shape: tuple[int, int, int]#
spacing: Quantity#
property volume: Quantity#

Return the physical voxel-box volume.

Returns:

Box volume in cubic metres, including one full voxel per grid element.

Return type:

Quantity

Validated observation directions for numerical scattering.

class Directions(*, vectors)[source]#

Bases: object

Define an ordered collection of Cartesian unit observation vectors.

Parameters:

vectors (array_like or Quantity) – Explicit dimensionless vectors of shape (n, 3), with 1 to 16384 rows. Every vector must be finite and have unit length. Vectors are copied into an immutable array; they are never normalized automatically.

Notes

Coordinates use the global x, y, z axes, independently of the source incident direction. Vector order is preserved in scattered amplitudes. Use vectors to access the NumPy array and from_angles() to construct vectors from explicitly unit-bearing spherical coordinates.

classmethod from_angles(*, polar_angles, azimuth_angles)[source]#

Convert paired or broadcastable spherical angles into unit vectors.

Polar angles are measured from positive z and lie in [0, pi]. Azimuth angles are measured from positive x toward positive y and are periodic. Both inputs require explicit angular units. Broadcast coordinates are flattened in row-major order, preserving polar/azimuth grid ordering.

Parameters:
  • polar_angles (Quantity) – Polar angles in explicit angular units, in the inclusive range from zero to pi.

  • azimuth_angles (Quantity) – Finite azimuth angles in explicit angular units.

Returns:

Cartesian unit vectors in row-major broadcast order.

Return type:

Directions

Raises:

ValueError – If units or angle values are invalid.

vectors: ndarray[tuple[Any, ...], dtype[float64]]#

Full directional output sampling and independent solid-angle quadrature.

class AngularSampling(*, angles=None, start=None, end=None, n_points=None, polar_samples=32, azimuth_samples=8)[source]#

Bases: object

Configure directional plots and their solid-angle normalization.

Parameters:
  • angles (Quantity, optional) – One-dimensional output polar angles theta, from 0 to pi, with 1 to 181 entries. Angular values require explicit units. Cannot be combined with start, end or n_points. Omit to generate an evenly spaced range.

  • start (Quantity, optional) – Inclusive range endpoints between 0 and pi. Angular values require explicit units. Defaults are 0 and pi; descending ranges are supported.

  • end (Quantity, optional) – Inclusive range endpoints between 0 and pi. Angular values require explicit units. Defaults are 0 and pi; descending ranges are supported.

  • n_points (int, optional) – Number of evenly spaced output angles, from 1 to 181. Default is 121. A single point samples start.

  • polar_samples (int, optional) – Gauss-Legendre integration nodes in cos(theta), from 16 to 128. Default is 32. These are independent of the output angles.

  • azimuth_samples (int, optional) – Uniform azimuth directions in [0, 2*pi), from 4 to 32. Default is 8. Used for both directional output and solid-angle integration.

Notes

Intensities are retained at every output (theta, phi). One-dimensional curves select sampled meridians; azimuth averages require an explicit azimuth_average() call. 3D phase surfaces use directional data. Integration uses dOmega = dphi * d(cos(theta)). Each Born order’s phase density is its intensity divided by its integrated coefficient. Refine both quadratures independently of output plot resolution.

angles: Quantity#
azimuth_samples: int = 8#
property azimuths: Quantity#

Return uniform output and integration azimuths.

Returns:

Azimuth directions spanning one full turn, in radians.

Return type:

Quantity

check_work(*, grid, order, realizations=1)[source]#

Reject synchronous workloads above 100 million voxel-direction-orders.

Parameters:
  • grid (Grid) – Spatial grid used to estimate the number of voxel-direction pairs.

  • order (int) – Highest cumulative Born order in the requested calculation.

  • realizations (int, optional) – Number of independent volumes; defaults to 1.

Returns:

Returns normally when the estimated workload is within the limit.

Return type:

None

Raises:

ValueError – If the estimate exceeds 100 million voxel-direction-orders.

property directions: Directions#

Return unit directions for output and integration grids.

Returns:

Directions with output polar angles first, followed by the Gauss-Legendre integration nodes, for each azimuth.

Return type:

Directions

property metadata: dict[str, list[int | float] | int]#

Return fresh SI sampling settings for reproducible result archives.

Returns:

Output angles in radians and the polar and azimuthal sample counts.

Return type:

dict[str, list[int | float] | int]

polar_samples: int = 32#
summarize(*, result, incident_direction=(0.0, 0.0, 1.0))[source]#

Reduce numeric Born data while retaining all directional intensities.

Parameters:
  • incident_direction (array_like, optional) – Cartesian unit beam direction used for anisotropy and reduced scattering moments. Defaults to positive z; output angles stay in laboratory coordinates.

  • result (BornResult) – Numeric Born amplitudes, cumulative differential data, and isolated-term differential data for one volume.

Returns:

Numeric arrays with these keys: mean and terms have shape (order, output angle); directional_terms and directional_differential have shape (order, output angle, azimuth); directional_amplitudes adds incident polarization and vector-component axes of sizes one or two and three; integrals has shape (order, 3), for total, first-moment, and reduced coefficients.

Return type:

dict[str, numpy.ndarray]

Notes

Output amplitudes retain (order, theta, phi, incident polarization, vector component). Integrated coefficients are finite-sample cross sections divided by voxel-box volume, not intrinsic material values.

Reproducible independent-realization sampling configurations.

class EnsembleSampling(*, realizations=None, seed=None, seeds=None)[source]#

Bases: object

Choose consecutive seeds or an explicit ordered set of distinct seeds.

realizations defaults to four and seed to zero when seeds is omitted. Explicit seeds cannot be combined with realizations or seed. Seeds range from zero to 2**32-1; there are 1 to 32 independent realizations. Duplicate seeds are rejected because they do not provide independent uncertainty.

Parameters:
  • realizations (int)

  • seed (int)

  • seeds (tuple[int, ...])

property metadata#

Return exact ordered seeds for reproducibility.

realizations: int#
seed: int#
seeds: tuple[int, ...]#

Media and geometry#

Media are grouped by construction: bornsim.medium.random contains continuous random fields, bornsim.medium.structured contains composite and finite periodic structures, and bornsim.medium.particles contains particle media. Existing top-level and historical module imports remain supported.

CoreShellMedium represents a spherical core inside a spherical shell, with explicit radii, centre, and three absolute refractive indices. EllipsoidMedium represents an oriented particle with three semi-axis radii. CylinderMedium represents a finite dielectric rod with explicit radius, height, axis, centre, and orientation; it is suitable for antenna-like dielectric scatterers. Both sample interfaces at voxel centres and clip geometry to the grid. PeriodicMedium repeats existing geometry objects on a centred finite lattice; its three length-bearing lattice vectors are rows of a matrix. It uses finite-volume scattering, without periodic boundary conditions. These media retain the same linearized dielectric contrast and Born validity limitations as other BornSim media.

Finite lattice arrays of existing material shapes.

class PeriodicMedium(*, background_refractive_index, motif, lattice_vectors, repetitions, overlap='replace')[source]#

Bases: Medium

Repeat a motif on a centred finite lattice.

Parameters:
  • background_refractive_index (float) – Uniform exterior refractive index.

  • motif (tuple of geometry objects) – Shapes relative to each lattice site; ordering defines overlap precedence.

  • lattice_vectors (Quantity) – Three independent lattice vectors as rows of a (3, 3) length array.

  • repetitions (tuple of int) – Positive finite repetition counts along each lattice vector.

  • overlap (str) – StructuredMedium overlap policy. Geometry is clipped to the voxel box.

Notes

This generates finite samples, without periodic solver boundary conditions. All copies retain their motif orientations. Even repetition counts place the array centre halfway between lattice sites.

background_refractive_index: float#
lattice_vectors: Quantity#
property metadata: dict[str, object]#

Return motif and finite lattice settings in SI units.

Returns:

Motif geometry, lattice vectors in metres, and repetition counts.

Return type:

dict of str to object

motif: tuple#
overlap: str = 'replace'#
repetitions: tuple[int, int, int]#
to_volume(*, grid, seed=0)[source]#

Voxelize centred copies, clipping geometry to the supplied grid.

Parameters:
  • grid (Grid) – Explicit voxel grid.

  • seed (int, default=0) – Accepted for the common Medium interface; this deterministic geometry does not use it.

Returns:

Voxelized finite lattice and geometry provenance.

Return type:

Volume

Finite concentric core–shell spheres.

class CoreShellMedium(*, background_refractive_index, core_refractive_index, shell_refractive_index, core_radius, outer_radius, centre)[source]#

Bases: Medium

A concentric spherical core and shell in a uniform background.

Parameters:
  • background_refractive_index (float) – Absolute real refractive indices.

  • core_refractive_index (float) – Absolute real refractive indices.

  • shell_refractive_index (float) – Absolute real refractive indices.

  • core_radius (Quantity) – Positive length scalars with core_radius strictly below outer_radius.

  • outer_radius (Quantity) – Positive length scalars with core_radius strictly below outer_radius.

  • centre (Quantity) – Three-component particle position. Interfaces use voxel-centre sampling.

background_refractive_index: float#
centre: Quantity#
core_radius: Quantity#
core_refractive_index: float#
property metadata: dict[str, object]#

Return ordered shell and core geometry in SI units.

Returns:

Refractive indices, centre, and radii in metres.

Return type:

dict of str to object

outer_radius: Quantity#
shell_refractive_index: float#
to_volume(*, grid, seed=0)[source]#

Sample the shell first and replace its interior with the core.

Parameters:
  • grid (Grid) – Explicit voxel grid.

  • seed (int, default=0) – Accepted for the common Medium interface; this deterministic particle does not use it.

Returns:

Voxelized core-shell contrast and geometry provenance.

Return type:

Volume

Finite oriented ellipsoidal particles.

class EllipsoidMedium(*, background_refractive_index, particle_refractive_index, radii, centre, rotation=((1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0)))[source]#

Bases: Medium

A finite ellipsoidal particle with explicit semi-axes and orientation.

Parameters:
  • background_refractive_index (float) – Absolute real refractive indices.

  • particle_refractive_index (float) – Absolute real refractive indices.

  • radii (Quantity) – Three positive semi-axis lengths.

  • centre (Quantity) – Three-component particle position.

  • rotation (Rotation or array) – Rotation mapping local semi-axes into global coordinates.

background_refractive_index: float#
centre: Quantity#
property metadata: dict[str, object]#

Return particle geometry in SI units.

Returns:

Refractive indices, orientation, and dimensions in metres.

Return type:

dict of str to object

particle_refractive_index: float#
radii: Quantity#
rotation: object = ((1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0))#
to_volume(*, grid, seed=0)[source]#

Voxelize the oriented particle, clipping it to the supplied grid.

Parameters:
  • grid (Grid) – Explicit voxel grid.

  • seed (int, default=0) – Accepted for the common Medium interface; this deterministic particle does not use it.

Returns:

Voxelized particle contrast and geometry provenance.

Return type:

Volume

Finite cylindrical particles for rods and antenna-like scatterers.

class CylinderMedium(*, background_refractive_index, particle_refractive_index, radius, height, centre, axis=2, rotation=((1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0)))[source]#

Bases: Medium

A finite homogeneous cylinder in a uniform background.

Parameters:
  • background_refractive_index (float) – Absolute real refractive indices.

  • particle_refractive_index (float) – Absolute real refractive indices.

  • radius (Quantity) – Radius and full axial length of the cylinder.

  • height (Quantity) – Radius and full axial length of the cylinder.

  • centre (Quantity) – Three-component particle position.

  • axis (int) – Local cylinder axis: 0, 1, or 2 for x, y, or z.

  • rotation (Rotation or array) – Rotation mapping local cylinder coordinates into global coordinates.

Notes

This is a finite dielectric rod. It can approximate an antenna-like scatterer when the refractive-index model is appropriate. It does not include conducting boundary conditions, complex permittivity, or currents.

axis: int = 2#
background_refractive_index: float#
centre: Quantity#
height: Quantity#
property metadata: dict[str, object]#

Return cylinder geometry in SI units.

Returns:

Refractive indices, axis, centre, radius, and height in metres.

Return type:

dict of str to object

particle_refractive_index: float#
radius: Quantity#
rotation: object = ((1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0))#
to_volume(*, grid, seed=0)[source]#

Voxelize the finite cylinder on the supplied grid.

Parameters:
  • grid (Grid) – Explicit voxel grid.

  • seed (int, default=0) – Accepted for the common Medium interface; this deterministic particle does not use it.

Returns:

Voxelized cylinder contrast and geometry provenance.

Return type:

Volume

Numerical random-medium statistics, independent of analytical solutions.

class Medium[source]#

Bases: ABC

Abstract interface for media that can be sampled into a finite volume.

Instantiate bornsim.GaussianMedium or bornsim.StructuredMedium, not this base class. Concrete media specify a uniform background_refractive_index and implement to_volume() using cubic voxels, SI spacing, and centred coordinates. The resulting field stores delta_refractive_index = n(r) - n0; propagation retains epsilon_r = n0**2 + 2*n0*delta_refractive_index.

add_background(*, refractive_index=None, medium=None, material=None)[source]#

Configure a composable medium’s background in place.

StructuredMedium accepts exactly one of a positive uniform refractive_index or a RandomFieldMedium supplied as medium. Statistical media describe homogeneous distributions; use StructuredMedium to compose material.

Parameters:
  • refractive_index (float or None, optional) – Plain positive dimensionless background refractive index.

  • medium (RandomFieldMedium or None, optional) – Statistical medium that defines the random background.

  • material (Material or None, optional) – Material supplying refractive index and extinction coefficient.

Returns:

The abstract base does not configure state.

Return type:

None

Raises:

TypeError – This abstract interface cannot configure a background.

add_structures(*structures)[source]#

Append positional material shapes to a composable medium in place.

StructuredMedium supports Layer, Sphere, Ellipsoid, Box, and Cylinder. Later structures replace earlier material wherever their masks overlap.

Parameters:

*structures (Any) – Positional geometry objects to append.

Returns:

The abstract base does not append structures.

Return type:

None

Raises:

TypeError – This abstract interface cannot compose structures.

background_refractive_index: float | None#
property is_random: bool#

Whether independent generation seeds represent random realizations.

Returns:

False for deterministic media; random media override this property.

Return type:

bool

property metadata: dict[str, object]#

Return a fresh JSON-compatible description with numeric SI values.

Concrete media extend this dictionary with their own statistics or geometry. Generation seeds and grids belong to individual volumes.

Returns:

Fresh JSON-compatible metadata for this medium.

Return type:

dict of str to object

abstractmethod to_volume(*, grid, seed=0)[source]#

Voxelize or sample this medium on an explicit Grid.

Parameters:
  • grid (Grid) – Explicit spatial discretization.

  • seed (int, default=0) – Seed controlling random realization generation.

Returns:

Sampled refractive-index contrast and its metadata.

Return type:

Volume

Raises:

NotImplementedError – This abstract method must be implemented by concrete media.

Compatibility imports for existing callers.

class RandomSphereMedium(*, background_refractive_index, sphere_refractive_index, radius, sphere_count, max_placement_attempts=10000)[source]#

Bases: Medium

Place a fixed number of identical spheres by sequential rejection sampling.

Centres are proposed uniformly inside the grid box, inset by the radius so entire spheres remain inside. Proposals overlapping an accepted sphere are rejected. This defines a sequential placement distribution, rather than an equilibrium hard-sphere distribution. Dense configurations may fail to fit within max_placement_attempts; failure raises instead of returning fewer spheres. Voxelization samples material at voxel centres, so an unresolved sphere can occupy no voxels.

Both refractive indices are required plain numbers. Radius requires scalar length units. Each realization records its medium and generation seed.

Parameters:
  • background_refractive_index (float)

  • sphere_refractive_index (float)

  • radius (Quantity)

  • sphere_count (int)

  • max_placement_attempts (int)

background_refractive_index: float#
property is_random: bool#

Whether this medium generates seeded random placements.

Returns:

Always True for a random sphere collection.

Return type:

bool

max_placement_attempts: int = 10000#
property metadata: dict[str, object]#

Return the sphere placement settings for provenance.

Returns:

Refractive indices, radius in metres, count, and placement policy.

Return type:

dict of str to object

radius: Quantity#
sphere_centers(*, grid, seed=0)[source]#

Generate nonoverlapping sphere centres for one seed.

Parameters:
  • grid (Grid) – Finite voxel domain that must contain every sphere.

  • seed (int, default=0) – Nonnegative 32-bit generation seed.

Returns:

Sphere centres in the grid’s length units, shape (sphere_count, 3).

Return type:

Quantity

Raises:

ValueError – If spheres cannot fit or placement attempts are exhausted.

sphere_count: int#
sphere_refractive_index: float#
to_volume(*, grid, seed=0)[source]#

Sample the sphere material at voxel centres on an explicit grid.

Parameters:
  • grid (Grid) – Explicit voxel grid.

  • seed (int, default=0) – Seed determining the sphere centres.

Returns:

Sampled refractive-index contrast with placement provenance.

Return type:

Volume

Compatibility imports for existing callers.

class ExponentialMedium(*, background_refractive_index, refractive_index_std, correlation_length, extinction_coefficient=0.0)[source]#

Bases: RandomFieldMedium

Exponential spatial covariance: C(r) = refractive_index_std² exp(-r/ell).

Parameters:
  • background_refractive_index (float)

  • refractive_index_std (float)

  • correlation_length (Quantity)

  • extinction_coefficient (float)

correlation = 'exponential'#
class GaussianMedium(*, background_refractive_index, refractive_index_std, correlation_length, extinction_coefficient=0.0)[source]#

Bases: RandomFieldMedium

Gaussian spatial covariance: C(r) = refractive_index_std² exp(-r²/(2 ell²)).

Parameters:
  • background_refractive_index (float)

  • refractive_index_std (float)

  • correlation_length (Quantity)

  • extinction_coefficient (float)

correlation = 'gaussian'#
class RandomFieldMedium(*, background_refractive_index, refractive_index_std, correlation_length, extinction_coefficient=0.0)[source]#

Bases: Medium

Abstract spectral synthesis shared by covariance-specific random fields.

Fields have Gaussian one-point statistics. Synthesis preserves expected variance and the DC mode, using a doubled box followed by cropping. Individual realizations are never recentered or rescaled.

Parameters:
  • background_refractive_index (float)

  • refractive_index_std (float)

  • correlation_length (Quantity)

  • extinction_coefficient (float)

background_refractive_index: float#
abstract property correlation: str#

Return the spatial covariance family.

Returns:

Covariance-family identifier stored in provenance.

Return type:

str

correlation_length: Quantity#
extinction_coefficient: float = 0.0#
property is_random: bool#

Whether independent seeds generate distinct realizations.

Returns:

Always True for statistical random-field media.

Return type:

bool

property metadata: dict[str, object]#

Return independent SI statistics for result provenance.

Lengths use the _m suffix. This describes ensemble statistics rather than a particular seed or a sample’s measured mean and variance.

Returns:

Independent metadata with physical lengths represented in metres.

Return type:

dict of str to object

refractive_index_std: float#
spectral_weight(*, q_squared)[source]#

Return dimensionless spectrum shape at squared wavenumbers in m^-2.

The zero-wavenumber weight is one. This is not the normalized continuum power spectral density; the synthesis code supplies discrete variance normalization. Inputs must be finite and nonnegative.

Parameters:

q_squared (Quantity) – Nonnegative squared wavenumbers with explicit inverse-square-length units.

Returns:

Dimensionless spectral weights with the input shape.

Return type:

numpy.ndarray

Raises:

ValueError – If units or values are invalid.

to_volume(*, grid, seed=0)[source]#

Generate a seeded random refractive-index Volume on an explicit Grid.

The field has a Gaussian one-point probability distribution for every spatial covariance model. Spectral synthesis uses a doubled periodic box and crops its first half. Expected point variance is normalized; individual samples are never recentered or rescaled. Grid resolution and synthesis-box size can alter sampled covariance. The seed defaults to zero and remains explicit in the generated volume’s provenance.

Parameters:
  • grid (Grid) – Explicit cubic voxel grid.

  • seed (int, default=0) – Nonnegative 32-bit seed for the random realization.

Returns:

Sampled refractive-index contrast and generation metadata.

Return type:

Volume

Raises:

ValueError – If the seed or sampling configuration is invalid.

class WhittleMaternMedium(*, background_refractive_index, refractive_index_std, correlation_length, extinction_coefficient=0.0, smoothness)[source]#

Bases: RandomFieldMedium

Whittle–Matérn covariance with explicitly chosen positive smoothness.

The spectrum is proportional to (1 + (q ell)²/(2 smoothness))**(-smoothness-3/2). Smoothness 0.5 reproduces ExponentialMedium with the same correlation length.

Parameters:
  • background_refractive_index (float)

  • refractive_index_std (float)

  • correlation_length (Quantity)

  • extinction_coefficient (float)

  • smoothness (float)

correlation = 'matern'#
smoothness: float#

Voxel-centre geometry for finite structured dielectric samples.

Lengths use SI metres or compatible quantities. Shapes set absolute refractive index, not dielectric contrast; Volume retains the solver’s linearized constitutive law. Interfaces are sampled at cell centres without subvoxel averaging.

class Box(*, centre=<factory>, refractive_index=None, material=None, size, rotation=((1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0)))[source]#

Bases: _RotatableTransformable

Set absolute refractive index where abs(local) <= size/2 in every axis.

Size contains three positive full side lengths along the local axes. All lengths use SI or compatible quantities; the boundary is closed.

Parameters:
  • centre (Quantity)

  • refractive_index (float | None)

  • material (Material | None)

  • size (Quantity)

  • rotation (Rotation | tuple[tuple[float, float, float], tuple[float, float, float], tuple[float, float, float]] | ndarray[tuple[Any, ...], dtype[float64]] | Sequence[Sequence[float]] | Quantity)

centre: Quantity#
mask(*, positions)[source]#

Return voxel-centre membership in this shape.

Parameters:

positions (Quantity) – Cartesian positions with final axis length three and explicit length units.

Returns:

Membership mask matching the leading position dimensions.

Return type:

numpy.ndarray of bool

material: Material | None = None#
refractive_index: float | None = None#
rotation: Rotation | tuple[tuple[float, float, float], tuple[float, float, float], tuple[float, float, float]] | ndarray[tuple[Any, ...], dtype[float64]] | Sequence[Sequence[float]] | Quantity = ((1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0))#
size: Quantity#
class Cylinder(*, centre=<factory>, refractive_index=None, material=None, radius, height, axis=2, rotation=((1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0)))[source]#

Bases: _RotatableTransformable

A finite circular cylinder with absolute refractive index and closed boundary.

Membership requires abs(local[axis]) <= height/2 and squared transverse distance <= radius**2. Radius and full height are positive SI lengths or quantities; axis is 0, 1, or 2, default z. Centre has three lengths.

Parameters:
  • centre (Quantity)

  • refractive_index (float | None)

  • material (Material | None)

  • radius (Quantity)

  • height (Quantity)

  • axis (int)

  • rotation (Rotation | tuple[tuple[float, float, float], tuple[float, float, float], tuple[float, float, float]] | ndarray[tuple[Any, ...], dtype[float64]] | Sequence[Sequence[float]] | Quantity)

axis: int = 2#
centre: Quantity#
height: Quantity#
mask(*, positions)[source]#

Return voxel-centre membership in this shape.

Parameters:

positions (Quantity) – Cartesian positions with final axis length three and explicit length units.

Returns:

Membership mask matching the leading position dimensions.

Return type:

numpy.ndarray of bool

material: Material | None = None#
radius: Quantity#
refractive_index: float | None = None#
rotation: Rotation | tuple[tuple[float, float, float], tuple[float, float, float], tuple[float, float, float]] | ndarray[tuple[Any, ...], dtype[float64]] | Sequence[Sequence[float]] | Quantity = ((1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0))#
class Ellipsoid(*, centre=<factory>, refractive_index=None, material=None, radii, rotation=((1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0)))[source]#

Bases: _RotatableTransformable

Set absolute refractive index where sum((local/radii)**2) <= 1.

Three positive semi-axis radii align with local x, y, z. All lengths use SI or compatible quantities. rotation maps local semi-axes into global coordinates.

Parameters:
  • centre (Quantity)

  • refractive_index (float | None)

  • material (Material | None)

  • radii (Quantity)

  • rotation (Rotation | tuple[tuple[float, float, float], tuple[float, float, float], tuple[float, float, float]] | ndarray[tuple[Any, ...], dtype[float64]] | Sequence[Sequence[float]] | Quantity)

centre: Quantity#
mask(*, positions)[source]#

Return voxel-centre membership in this shape.

Parameters:

positions (Quantity) – Cartesian positions with final axis length three and explicit length units.

Returns:

Membership mask matching the leading position dimensions.

Return type:

numpy.ndarray of bool

material: Material | None = None#
radii: Quantity#
refractive_index: float | None = None#
rotation: Rotation | tuple[tuple[float, float, float], tuple[float, float, float], tuple[float, float, float]] | ndarray[tuple[Any, ...], dtype[float64]] | Sequence[Sequence[float]] | Quantity = ((1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0))#
class Layer(*, centre=<factory>, refractive_index=None, material=None, lower, upper, axis=2, rotation=((1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0)))[source]#

Bases: _RotatableTransformable

A slab with absolute refractive index inside lower <= local[axis] < upper.

Bounds are SI lengths in the slab local frame, offset by centre and oriented by rotation. The default axis is z (2); x and y are 0 and 1. The half-open interval gives adjacent slabs an unambiguous interface. The slab spans the voxel box in transverse axes; it represents a finite sample, not an infinite planar background.

Use from_center_and_thickness() to specify a slab by its centre and full thickness instead of its local lower and upper bounds.

Parameters:
  • centre (Quantity)

  • refractive_index (float | None)

  • material (Material | None)

  • lower (Quantity)

  • upper (Quantity)

  • axis (int)

  • rotation (Rotation | tuple[tuple[float, float, float], tuple[float, float, float], tuple[float, float, float]] | ndarray[tuple[Any, ...], dtype[float64]] | Sequence[Sequence[float]] | Quantity)

axis: int = 2#
centre: Quantity#
classmethod from_center_and_thickness(*, thickness, centre, refractive_index=None, material=None, axis=2, rotation=((1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0)))[source]#

Create a slab from its centre and full thickness along axis.

Parameters:
  • thickness (Quantity) – Positive full slab thickness with explicit length units.

  • centre (Quantity) – Global centre position with shape (3,) and length units.

  • refractive_index (float or None, default=None) – Plain positive refractive index, unless material is supplied.

  • material (Material or None, default=None) – Material assigned to the slab.

  • axis (int, default=2) – Local normal axis, where 0, 1, and 2 denote x, y, and z.

  • rotation (Rotation, array_like, or Quantity) – Optional proper orientation of the local axes.

Returns:

Slab with bounds at plus and minus half the requested thickness.

Return type:

Layer

Raises:

ValueError – If thickness, centre, axis, material, or rotation is invalid.

lower: Quantity#
mask(*, positions)[source]#

Return voxel-centre membership in this shape.

Parameters:

positions (Quantity) – Cartesian positions with final axis length three and explicit length units.

Returns:

Membership mask matching the leading position dimensions.

Return type:

numpy.ndarray of bool

material: Material | None = None#
refractive_index: float | None = None#
rotation: Rotation | tuple[tuple[float, float, float], tuple[float, float, float], tuple[float, float, float]] | ndarray[tuple[Any, ...], dtype[float64]] | Sequence[Sequence[float]] | Quantity = ((1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0))#
upper: Quantity#
class Sphere(*, centre=<factory>, refractive_index=None, material=None, radius)[source]#

Bases: _Transformable

Set absolute refractive index where sum((r-centre)**2) <= radius**2.

Radius is positive; centre is a three-component SI length or quantity. The closed surface is sampled at voxel centres, giving a staircase boundary.

Parameters:
centre: Quantity#
mask(*, positions)[source]#

Return voxel-centre membership in this shape.

Parameters:

positions (Quantity) – Cartesian positions with final axis length three and explicit length units.

Returns:

Membership mask matching the leading position dimensions.

Return type:

numpy.ndarray of bool

material: Material | None = None#
radius: Quantity#
refractive_index: float | None = None#

Immutable, reusable homogeneous optical materials.

class Material(*, refractive_index, extinction_coefficient=0.0)[source]#

Bases: object

A nondispersive real refractive index shared by any number of shapes.

refractive_index is an absolute positive dimensionless refractive index, not a contrast. Supply plain numbers; quantities are rejected. The nonnegative extinction_coefficient is kappa in n+i*kappa, using exp(-i omega t). Voxelization retains absorption within the finite sample; the exterior host remains lossless. Wavelength dispersion is not implemented.

Parameters:
  • refractive_index (float)

  • extinction_coefficient (float)

extinction_coefficient: float = 0.0#
property metadata: dict[str, float]#

Return a fresh JSON-compatible material description.

Returns:

Refractive index and, when nonzero, extinction coefficient.

Return type:

dict of str to float

refractive_index: float#

Rotation inputs accept a bornsim.rotation.Rotation, a nested matrix sequence, a NumPy array, or a dimensionless quantity. Shapes normalize accepted inputs to immutable bornsim.rotation.RotationMatrix tuples; bornsim.rotation.RotationInput describes the accepted forms.

Proper three-dimensional rotations for immutable material shapes.

class Rotation(*, axis, angle)[source]#

Bases: object

Define an active right-handed rotation about a dimensionless axis.

angle accepts angular quantities; angular values require explicit units. The axis is normalized. matrix maps local column coordinates into global coordinates. It follows the right-hand rule, and successive world rotations compose as R_new @ R_existing. Shape membership uses local row coordinates (positions - centre) @ R. Shapes accept this object, a proper orthonormal 3-by-3 matrix, or a dimensionless matrix quantity; they store the normalized matrix as an immutable tuple of tuples. No voxel resampling is performed.

Parameters:
  • axis (tuple[float, float, float])

  • angle (Quantity)

angle: Quantity#
axis: tuple[float, float, float]#
property matrix: ndarray[tuple[Any, ...], dtype[float64]]#

Return Rodrigues’ active rotation matrix.

Returns:

Dimensionless matrix of shape (3, 3) mapping local column coordinates to global coordinates.

Return type:

numpy.ndarray

Finite refractive-index fields on centred cubic voxel grids.

class Volume(*, delta_refractive_index, background_refractive_index, grid, medium=None, seed=None, extinction_coefficient=0.0)[source]#

Bases: object

Store a finite voxel field and its explicit spatial Grid.

The copied, read-only delta_refractive_index array has shape grid.shape. refractive_index returns the read-only absolute field background_refractive_index + delta_refractive_index. Addition combines contrasts from volumes only when their grids and backgrounds match. Background refractive index is a plain number; grid spacing and positions carry physical units. Relative permittivity is linearized as background_refractive_index**2 + 2*background_refractive_index*delta_refractive_index. The quadratic fluctuation term is omitted at every Born order. Medium.to_volume records generation statistics and seed. medium_metadata returns the metadata snapshot captured when the volume was created. Manually constructed volumes have only their explicitly supplied provenance.

Use from_refractive_index() when the input array contains absolute refractive indices rather than fluctuations from the background.

Parameters:
  • delta_refractive_index (ndarray)

  • background_refractive_index (float)

  • grid (Grid)

  • medium (Medium | None)

  • seed (int | None)

  • extinction_coefficient (ndarray | float)

background_refractive_index: float#
delta_refractive_index: ndarray#
extinction_coefficient: ndarray | float = 0.0#
classmethod from_refractive_index(*, refractive_index, background_refractive_index, grid, medium=None, seed=None)[source]#

Construct a volume from an absolute refractive-index field.

Parameters:
  • refractive_index (array_like) – Plain numerical absolute refractive indices, with shape grid.shape. Values must not carry units.

  • background_refractive_index (float) – Positive, unitless reference refractive index.

  • grid (Grid) – Explicit spatial grid matching the field shape.

  • medium (Medium, optional) – Medium metadata associated with generation. Must be supplied together with seed.

  • seed (int, optional) – Generation seed, supplied together with medium.

Returns:

Immutable volume storing the field as refractive_index - background_refractive_index.

Return type:

Volume

Raises:
  • ValueError – If the field, background, grid shape, or resulting linearized permittivity is invalid.

  • TypeError – If medium is not a Medium instance.

grid: Grid#
medium: Medium | None = None#
property medium_metadata: dict[str, object] | None#

Return a copy of the generation metadata captured at construction.

Returns:

A fresh copy of the source medium’s metadata, or None when the volume has no associated medium.

Return type:

dict[str, object] or None

plot_3d(*, backend='plotly', mode=None, field='delta_refractive_index', length_unit='nanometer', surface_count=8, opacity=None, opacity_scale='uniform')[source]#

Build a three-dimensional figure of the finite voxel medium.

Parameters:
  • backend ({'plotly'}, optional) – Plotly is the only supported 3D backend. Default is ‘plotly’.

  • mode (str, optional) – Choose ‘volume’ (default) or ‘isosurface’. Uniform fields are rendered as volume data; an isosurface cannot be generated from a uniform field.

  • field ({'delta_refractive_index', 'refractive_index', 'permittivity'}, optional) – Scalar field to display, default refractive index fluctuation. ‘refractive_index’ displays n0 + delta_refractive_index; ‘permittivity’ displays the solver’s linearized relative permittivity n0**2 + 2*n0*delta_refractive_index, not (n0+delta_refractive_index)**2.

  • length_unit (str, optional) – Spatial display unit, default ‘nanometer’. Stored SI data is unchanged.

  • surface_count (int, optional) – Number of contours, from 1 to 32; default 8. More surfaces increase browser rendering cost. Used only by Plotly volume and isosurface modes. An interactive density slider adjusts this display setting.

  • opacity (float, optional) – Initial surface opacity in (0, 1]. Default is 0.12 for volumes and 0.5 for isosurfaces. Plotly volumes include an opacity slider, with zero available to hide the field.

  • opacity_scale ({'uniform', 'increasing'}, optional) – Default ‘uniform’ gives all contours the same opacity. ‘increasing’ is available only for Plotly volume mode and scales opacity from zero at the lowest displayed contour to opacity at the highest. Use field=’refractive_index’ to emphasize high refractive index, rather than the magnitude of positive and negative fluctuations.

Returns:

figure – Call figure.show() to display or figure.write_html() to export. Constructing a figure opens no window or browser.

Return type:

plotly.graph_objects.Figure

Raises:

ValueError – If a mode, scalar field, display unit, or rendering setting is invalid.

Notes

Plotly contours interpolate between voxel centres and are visualization aids, not exact curved interfaces or a replacement for grid refinement. Aspect ratio follows physical dimensions. All voxels are retained, with at most 32**3 samples under Volume’s grid limit; browser performance also depends on surface count and graphics support. This plots the input material, not an electromagnetic field.

property positions: Quantity#

Return voxel-centre coordinates relative to the sample centre.

Returns:

positions – Unit-bearing coordinates, shape (nx, ny, nz, 3), with the final axis ordered as x, y, z.

Return type:

Quantity

property refractive_index: ndarray#

Return the read-only absolute refractive-index field.

Returns:

Absolute refractive indices, equal to the background plus delta_refractive_index.

Return type:

numpy.ndarray

seed: int | None = None#
spacing: Quantity#
property volume: Quantity#

Return the total physical volume of all voxels.

Returns:

volume – Unit-bearing sample volume, equal to delta_refractive_index.size*spacing**3.

Return type:

Quantity

with_absorption(*, extinction_coefficient)[source]#

Return a sample with passive absorption in a real, lossless host.

Parameters:

extinction_coefficient (float or array_like) – Unitless nonnegative kappa, scalar or matching the voxel grid. Uses exp(-i omega t) and linearized contrast 2*n0*(delta_n+i*kappa).

Returns:

Immutable sample retaining its real index field and generation metadata.

Return type:

Volume

Solver and results#

Solver configuration for finite-volume and ensemble Born calculations.

class Solver(*, source, sampling=<factory>, order=3)[source]#

Bases: object

Configure numerical Born scattering from explicit finite samples.

Source chooses wavelength, incident direction, and polarization. AngularSampling supplies output directions and integration quadrature; order sets the highest cumulative Born order. All orders retain the linearized dielectric contrast and the equal-volume Green self cell. Decreasing successive terms do not certify convergence.

Parameters:
ensemble(*, medium, grid, sampling=None, ensemble_sampling=None)[source]#

Average numerical scattering over independently generated finite samples.

Grid selects the voxel domain. AngularSampling selects output directions and integration quadrature; the solver’s sampling is used when omitted. EnsembleSampling selects ordered independent seeds and defaults to four consecutive seeds starting at zero. Deterministic structures use solve.

Intensities are averaged after coherent summation within each realization. Standard errors quantify realization uncertainty, not discretization or finite-size error. One realization has unknown (NaN) uncertainty. Integrated coefficients are finite-sample cross sections divided by voxel-box volume.

Parameters:
  • medium (Medium) – Medium sampled independently for each realization.

  • grid (Grid) – Explicit finite voxel domain.

  • sampling (AngularSampling or None, default=None) – Observation grid and integration quadrature; defaults to the solver’s configured sampling.

  • ensemble_sampling (EnsembleSampling or None, default=None) – Ordered random seeds and realization count; defaults to four seeds beginning at zero.

Returns:

Ensemble mean intensities, uncertainty estimates, and diagnostics.

Return type:

Result

Raises:
  • TypeError – If medium is not a Medium.

  • ValueError – If grid, sampling, or ensemble settings are invalid.

order: int = 3#
sampling: AngularSampling#
solve(*, target, sampling=None)[source]#

Compute scattering from a volume using angular or Cartesian sampling.

Pass AngularSampling for solid-angle integration, or Directions for an unnormalized set of observation directions. The target is an explicit voxelized Volume; random statistics use ensemble instead.

Parameters:
  • target (Volume) – Voxelized finite scattering sample.

  • sampling (AngularSampling, Directions, or None, default=None) – Angular integration grid or explicit Cartesian observation vectors. None uses the solver’s configured angular sampling.

Returns:

Numerical Born scattering data and available diagnostics.

Return type:

Result

Raises:

TypeError – If target is not a Volume.

solve_cut(*, target, angles=None, directions=None)[source]#

Compute an unnormalized angular cut through a fixed Volume.

Supply laboratory polar angles on the x-z meridian or a Directions configuration, but not both. This is a convenience wrapper for solve(target=..., sampling=Directions(...)). Explicit angular units are required. Default angles span 0 to pi with 121 samples. Cut amplitudes and intensities retain every requested direction. A cut alone cannot determine a solid-angle integral; integrated coefficients and normalized phase functions are unavailable.

Parameters:
  • target (Volume) – Voxelized finite scattering sample.

  • angles (Quantity or None, default=None) – Polar angles with explicit angular units; defaults to 121 samples spanning zero to pi.

  • directions (Directions or None, default=None) – Explicit Cartesian observations. Supply instead of angles.

Returns:

Unnormalized scattering data for the requested cut.

Return type:

Result

Raises:
  • TypeError – If target is not a Volume.

  • ValueError – If both angle and direction configurations are supplied.

source: Source#

Unitful scattering results, validated archives, and Matplotlib plots.

class BornResult(*, directions, amplitudes, differential, term_differential, field_norms, warnings, mu_a=None, residual_norms=None)[source]#

Bases: object

Store numeric SI results for one finite-volume Born calculation.

Parameters:
  • directions (numpy.ndarray) – Dimensionless observation vectors, shape (observation, 3).

  • amplitudes (numpy.ndarray) – Complex isolated amplitudes in metres, shape (order, observation, incident polarization, vector component).

  • differential (numpy.ndarray) – Cumulative scattering in m^-1 sr^-1, shape (order, observation).

  • term_differential (numpy.ndarray) – Isolated-term scattering in m^-1 sr^-1, same shape as differential.

  • field_norms (numpy.ndarray) – Dimensionless relative field norms, shape (order,).

  • warnings (tuple of str) – Numerical-resolution and Born-term diagnostics.

  • mu_a (ndarray | None)

  • residual_norms (ndarray | None)

Variables:

See also

bornsim.series.BornSeries.solve

Produce this numeric result.

bornsim.results.Result

Unitful result with plotting support.

Notes

Row zero denotes first order. Cumulative intensities include interference between amplitudes; isolated intensities must not be summed to reconstruct them. Integrated coefficients are not inferred from observation samples.

amplitudes: ndarray#
differential: ndarray#
directions: ndarray#
field_norms: ndarray#
mu_a: ndarray | None = None#
residual_norms: ndarray | None = None#
term_differential: ndarray#
warnings: tuple[str, ...]#
class Result(*, source, kind, angular=None, differential=None, sample_volume=None, azimuth_averaged=False, azimuth_stderr=None, angles=None, directions=None, azimuths=None, mu_s=None, g=None, mu_s_prime=None, mu_a=None, mu_a_stderr=None, residual_norms=None, coherent_differential=None, amplitudes=None, term_differential=None, stderr=None, field_norms=None, warnings=(), realizations=None, provenance=None)[source]#

Bases: object

Store unitful scattering, diagnostics and reproducible settings.

Full solves retain differential and term_differential with shape (order, polar angle, azimuth). Cuts and explicitly averaged results use (order, observation). amplitudes always adds polarization and Cartesian axes of sizes one or two and three to the differential shape. Ensembles retain intensities and standard errors, without coherent amplitudes.

angular groups read-only coordinates, intensities, amplitudes and phase densities. azimuth_average() explicitly averages intensities and retains the covariance-correct standard error of per-realization averaged curves. Plots of full results select one sampled meridian by default.

Angles use radians, amplitudes metres, differential data m^-1 sr^-1, integrated coefficients m^-1, and sample_volume m^3. Dimensional arrays require explicit units. Every full phase density uses its order’s solid-angle integral. Cuts have no inferred integrated coefficients or phase normalization.

Numerical coefficients are finite-sample cross sections divided by the entire voxel-box volume. differential_cross_section restores area per steradian using stored sample_volume.

mu_a is the finite-sample absorption coefficient, if available. At scattering order M it uses the cumulative internal field through M-1. absorption_cross_section restores absorbed-power cross sections.

Source and kind are required. Supply angular or individual differential data, never both. Results are immutable; provenance returns a fresh copy. Other fields describe sampling, isolated terms, integrated moments, uncertainty, diagnostics and provenance. NaN errors represent one realization; NaN anisotropy represents zero scattering. Arrays and JSON-compatible provenance are copied and validated. Use differential and amplitudes for both cuts and full solves.

Save and load use schema 3 archives (schema 2 remains readable); unsupported schemas are rejected. Numerical cumulative intensities retain coherent amplitude interference. Isolated intensities must not be summed to reconstruct cumulative results.

Parameters:
property absorption_cross_section: Quantity | None#

Return absorbed-power cross sections for the finite sample.

Returns:

Absorption cross section in square metres, or None if absorption coefficients or sample volume are unavailable.

Return type:

Quantity or None

property amplitudes: Quantity | None#

Return read-only complex scattering amplitudes.

Returns:

Amplitudes in metres, with polarization and Cartesian vector axes.

Return type:

Quantity or None

property angles: Quantity | None#

Return read-only polar-angle coordinates in radians.

Returns:

Polar angles for the observation axis, when available.

Return type:

Quantity or None

angular: AngularData#
azimuth_average()[source]#

Average intensities and their realization-level errors over azimuth.

Returns:

New result marked as azimuth-averaged. Coherent amplitudes are not averaged; covariance-correct ensemble errors are retained.

Return type:

Result

Raises:

ValueError – If the result has no full azimuth grid.

property azimuth_averaged: bool#

Whether intensities were explicitly averaged over azimuth.

Returns:

True for azimuth-averaged angular data.

Return type:

bool

property azimuth_stderr: Quantity | None#

Return standard errors for azimuth-averaged intensities.

Returns:

Errors in inverse metres per steradian, shaped by order and polar angle.

Return type:

Quantity or None

property azimuths: Quantity | None#

Return read-only sampled azimuth coordinates in radians.

Returns:

Azimuth coordinates for full angular data.

Return type:

Quantity or None

coherent_differential: Quantity | None#
property differential: Quantity#

Return read-only differential scattering data.

Returns:

Differential intensity in inverse metres per steradian, shaped (order, observation) or (order, polar, azimuth).

Return type:

Quantity

property differential_cross_section: Quantity#

Return finite-sample differential cross sections.

Returns:

dσ/dΩ in square metres per steradian, with the shape of differential.

Return type:

Quantity

Raises:

ValueError – If the result does not include a finite sample volume.

property diffuse_differential: Quantity | None#

Finite-ensemble mean intensity minus squared mean amplitude (m⁻¹ sr⁻¹).

The coherent estimate includes the ensemble-mean scattered field, not the direct incident beam. With N samples, this uncorrected diffuse estimate has factor (N-1)/N finite-sample bias; it is zero for N=1.

Returns:

Nonnegative diffuse differential intensity in inverse metres per steradian, or None when the coherent estimate is unavailable.

Return type:

Quantity or None

property directions: Quantity | None#

Return explicit Cartesian observation directions when stored.

Returns:

Unit vectors for cut data. Full-grid vectors are available through angular.directions.

Return type:

Quantity or None

field_norms: Quantity | None#
g: Quantity | None#
kind: str#
classmethod load(*, path)[source]#

Load and validate a BornSim result archive without using pickle.

Parameters:

path (str or pathlib.Path) – Archive created by Result.save.

Returns:

result – Restored quantities, complex amplitudes, diagnostics, and original provenance. Loading does not change the recorded package version.

Return type:

Result

Raises:
  • ValueError – If the schema is unsupported, metadata or arrays are missing or inconsistent, or result validation fails.

  • OSError – If the archive cannot be read.

meridian(*, azimuth, method='exact')[source]#

Select one sampled azimuth from full data without interpolation.

Parameters:
  • azimuth (Quantity) – Requested scalar azimuth with explicit angular units.

  • method ({'exact', 'nearest'}, default='exact') – Require a matching sample or select the closest sample.

Returns:

Selected meridian data, available independently of the Result wrapper.

Return type:

AngularData

Raises:

ValueError – If angular sampling is incomplete or the requested sample is absent.

mu_a: Quantity | None#
mu_a_stderr: Quantity | None#
property mu_s: Quantity | None#

Return integrated scattering coefficients.

Returns:

Finite-sample coefficients in inverse metres, one per Born order.

Return type:

Quantity or None

mu_s_prime: Quantity | None#
property phase_function: Quantity#

Return directional phase density per steradian.

Full solves retain (order, polar angle, azimuth). Explicitly averaged results retain (order, polar angle). Cuts have no normalization. Every order uses its own full solid-angle scattering coefficient.

Returns:

Phase density in inverse steradians. Shape matches differential.

Return type:

Quantity

Raises:

ValueError – If normalization is unavailable, as for a directional cut.

plot(*, terms=False, log_y=False, title=None, azimuth=0)[source]#

Build a Matplotlib figure of differential scattering curves.

Parameters:
  • terms (bool, optional) – Plot isolated numerical terms instead of cumulative curves. Default is False. Isolated terms omit interference and ensemble error bars.

  • log_y (bool, optional) – Use a logarithmic scattering axis. Default is False.

  • azimuth (int, optional) – Index of the sampled meridian; default zero. Use azimuth_average() explicitly to plot averaged intensities.

  • title (str, optional) – Override the default title.

Returns:

figure – Figure with angles in degrees and scattering in m^-1 sr^-1. Explicit direction samples use input indices and markers. Ensemble cumulative curves show one-standard-error bars where sampling error is known.

Return type:

matplotlib.figure.Figure

Raises:

ValueError – If terms=True and isolated-term curves are unavailable.

Notes

The figure is registered with pyplot and returned without displaying it. Call matplotlib.pyplot.show() to display open figures or figure.savefig(path) to export a PNG, SVG, or PDF. Zero values cannot be displayed on a log axis. A one-realization ensemble has unknown sampling error, so no error bars are shown. This method plots differential scattering, not a normalized phase function.

plot_cross_section(*, volume=None, area_unit='nanometer**2', terms=False, log_y=False, title=None, azimuth=0)[source]#

Build differential cross-section curves for a finite sample.

Parameters:
  • volume (Volume, optional) – Optional sample. Normally the recorded sample_volume supplies the conversion without retaining the input voxel field.

  • area_unit (str, optional) – Display area unit; default ‘nanometer**2’.

  • terms (bool, optional) – Show isolated terms, which omit interference and sampling error bars, instead of cumulative coherent curves. Default False.

  • log_y (bool, optional) – Use a logarithmic scattering axis. Default False.

  • azimuth (int, optional) – Index of the sampled meridian; default zero. Use azimuth_average() explicitly to plot averaged intensities.

  • title (str, optional) – Override the default title.

Returns:

figure – Angle or direction curves, with ensemble standard errors scaled by the same sample volume. Returned without displaying it.

Return type:

matplotlib.figure.Figure

Raises:
  • TypeError – If volume is not a Volume.

  • ValueError – If recorded grid dimensions differ, area_unit is invalid, or isolated curves are unavailable.

Notes

Uses dσ/dΩ = V * differential. These are finite-sample cross sections, not intrinsic infinite-medium transport coefficients. An optional supplied volume must agree with the recorded physical volume and grid. Stored scattering data and its SI units remain unchanged.

plot_field_norms(*, log_y=True)[source]#

Plot relative Born field-term norms for each available realization.

Parameters:

log_y (bool, optional) – Use a logarithmic vertical axis. Default is True. Zero norms cannot be displayed on a logarithmic axis.

Returns:

figure – One trace per realization versus one-based field-term order. Norms are dimensionless relative to the incident field.

Return type:

matplotlib.figure.Figure

Raises:

ValueError – If no numerical field norms are available.

Notes

The figure preserves per-realization diagnostics. Decreasing field terms do not certify Born convergence or remove discretization error.

plot_phase_function(*, view='3d', order=None, log_y=False, azimuth=0, backend=None)[source]#

Plot normalized phase functions as angular curves, polar cuts, or a surface.

Parameters:
  • view ({'angular', 'polar', '3d'}, default='3d') – Angular curves select a sampled meridian by default. Polar cuts use its opposite azimuth for the other half of the plane. The 3D surface uses p(theta, phi), with radius and color in sr^-1, retaining directional asymmetry. Analytical distributions are independent of phi.

  • order (int, optional) – One-based cumulative order. Angular and polar views show all orders by default; the 3D view shows only the highest order.

  • log_y (bool, optional) – Logarithmic vertical scale for angular curves. Default is False; only supported with view='angular'.

  • backend ({'plotly', 'matplotlib'}, optional) – 3D views use Plotly exclusively; angular and polar views use Matplotlib. Omit backend to select the renderer for the view.

  • azimuth (int)

Returns:

figure – Returned without displaying it. Call figure.show() for Plotly, or matplotlib.pyplot.show() for Matplotlib. The 3D coordinates are probability-density radii, not spatial positions.

Return type:

matplotlib.figure.Figure or plotly.graph_objects.Figure

Raises:

ValueError – If phase normalization is unavailable, the view or order is invalid, directional data are unavailable for a numerical 3D view, log scaling is requested for another view, or polar/3D data do not span the full [0, pi] range with at least three angles.

Notes

Numerical 3D surfaces retain every sampled azimuth; no azimuth averaging is applied. For one realization this displays the fixed sample’s directional distribution; multiple realizations display the ensemble intensity average. Older archives lacking directional data must be recomputed for a directional 3D view. Angular and polar views select sampled meridians; averaging requires azimuth_average(). A flat phase function produces a spherical surface in laboratory coordinates; forward scattering follows the source direction. Samples are sorted by angle for rendering. Error bars for normalized ratios are omitted because the required covariance is not stored.

property provenance: dict[str, Any]#

Return a fresh copy of provenance metadata.

Returns:

JSON-compatible provenance. Mutating the returned object does not change this result.

Return type:

dict of str to object

realizations: int | None#
residual_norms: Quantity | None#
property sample_volume: Quantity | None#

Return the finite-sample voxel-box volume.

Returns:

Sample volume in cubic metres.

Return type:

Quantity or None

save(*, path)[source]#

Save data, units, warnings, and provenance in a versioned NPZ archive.

Parameters:

path (str or pathlib.Path) – Destination file, typically ending in .npz. The exact path is used without appending an extension. An existing file is replaced.

Returns:

path – Destination of the compressed NumPy archive.

Return type:

pathlib.Path

Raises:
  • ValueError – If result fields were modified into an invalid state.

  • OSError – If the destination cannot be written.

Notes

Arrays are stored in SI units, including complex Born amplitudes. Metadata is JSON, and loading never enables pickle. The archive stores result data rather than the original voxel field; retain that field separately for manual volumes. A field SHA-256 identifies the input. Generated volumes also record their medium and seed. Exact seeded reproduction depends on the recorded implementation versions.

source: Source#
property stderr: Quantity | None#

Return pointwise ensemble standard errors.

Returns:

Standard errors in inverse metres per steradian.

Return type:

Quantity or None

property term_differential: Quantity | None#

Return read-only isolated Born-term intensities.

Returns:

Isolated term intensities in inverse metres per steradian.

Return type:

Quantity or None

warnings: tuple#

Consistent unitful directional scattering data for solves and cuts.

class AngularData(*, differential, directions=None, amplitudes=None, angles=None, azimuths=None, term_differential=None, stderr=None, azimuth_stderr=None, mu_s=None, sample_volume=None, kind='volume', azimuth_averaged=False, meridian_azimuth=None)[source]#

Bases: object

Group coordinates, amplitudes, intensities and normalization.

Full angular data have shape (order, polar angle, azimuth). Cuts and explicitly averaged curves have shape (order, observation). Directions have the same observation axes and a final Cartesian axis of size three. Amplitudes add incident-polarization and vector axes of sizes one or two and three. Ensemble amplitudes are absent: intensities, not amplitudes, are averaged across realizations. Arrays are copied, unitful and read-only.

Parameters:
amplitudes: Quantity | None = None#
angles: Quantity | None = None#
azimuth_average()[source]#

Average intensities over the sampled azimuth axis.

Coherent amplitudes and directions are omitted because averaging them would not represent the intensity average.

Returns:

New data with shape (order, polar angle) and azimuth_averaged=True.

Return type:

AngularData

Raises:

ValueError – If this object does not contain a full azimuth grid.

azimuth_averaged: bool = False#
azimuth_stderr: Quantity | None = None#
azimuths: Quantity | None = None#
differential: Quantity#
property differential_cross_section: Quantity#

Return the finite-sample differential cross section.

Returns:

Differential cross section in square metres per steradian, with the same shape as differential.

Return type:

Quantity

Raises:

ValueError – If sample_volume is unavailable.

directions: Quantity | None = None#
kind: Literal['volume', 'ensemble'] = 'volume'#
meridian(*, azimuth, method='exact')[source]#

Select one sampled meridian while preserving normalization.

Azimuth is periodic modulo \(2\pi\). exact requires a sample within 1e-10 radians; nearest selects the closest sample. No interpolation or averaging is performed. The selected angle is stored in meridian_azimuth.

Parameters:
  • azimuth (Quantity) – Requested azimuth with explicit angular units; must be scalar and finite.

  • method ({'exact', 'nearest'}, default='exact') – Whether to require a sampled angle or select its nearest sample.

Returns:

Data for the selected meridian, with shape (order, polar angle).

Return type:

AngularData

Raises:

ValueError – If the data do not have an azimuth grid, the request is invalid, or method='exact' has no matching sample.

meridian_azimuth: Quantity | None = None#
mu_s: Quantity | None = None#
property phase_function: Quantity#

Return the differential density normalized over solid angle.

Returns:

Phase function in inverse steradians, with the same shape as differential.

Return type:

Quantity

Raises:

ValueError – If positive finite integrated mu_s values are unavailable.

plot(*, terms=False, log_y=False, title=None, azimuth=0)[source]#

Plot differential scattering on a meridian or averaged curve.

Parameters:
  • terms (bool, default=False) – Plot isolated Born terms instead of cumulative intensities.

  • log_y (bool, default=False) – Use a logarithmic vertical axis.

  • title (str or None, default=None) – Optional custom figure title.

  • azimuth (int, default=0) – Sample index used when selecting a meridian from full angular data.

Returns:

Figure containing the requested differential-scattering curves.

Return type:

matplotlib.figure.Figure

Raises:

ValueError – If the requested meridian cannot be selected.

plot_phase_function(*, view='3d', order=None, log_y=False, azimuth=0, backend=None)[source]#

Plot normalized directional densities.

Parameters:
  • view ({'angular', 'polar', '3d'}, default='3d') – Angular curve, polar curve, or directional 3D surface. The 3D view uses Plotly; 2D views use Matplotlib.

  • order (int or None, default=None) – One-based cumulative Born order. None plots all angular curves or the final available surface.

  • log_y (bool, default=False) – Use a logarithmic vertical axis; supported for the angular view.

  • azimuth (int, default=0) – Sample index used for angular and polar meridian views.

  • backend ({'matplotlib', 'plotly'} or None, default=None) – Rendering backend. Plotly is used for 3D; Matplotlib is used for 2D.

Returns:

Figure containing the selected phase-function view.

Return type:

matplotlib.figure.Figure or plotly.graph_objects.Figure

Raises:
  • ValueError – If normalization is unavailable or the view, order, backend, or angular sampling is incompatible.

  • ImportError – If Plotly is unavailable for the 3D view.

sample_volume: Quantity | None = None#
stderr: Quantity | None = None#
term_differential: Quantity | None = None#

Numerical engine#

Reusable finite-volume vector Born-series engine.

Time convention exp(-i omega t). Relative dielectric contrast is linearized as 2 n0 (delta_n + i kappa) at every order. Amplitudes interfere coherently before the incident-mode intensity average is evaluated.

class BornSeries(*, grid, background_refractive_index, wavelength, directions, order=3, incident_direction=(0.0, 0.0, 1.0), polarization=None)[source]#

Bases: object

Own the fixed geometry and propagation operator for numerical Born orders.

Parameters:
  • grid (Grid) – Shared spatial configuration, also used by the input Volume. Required for generation and scattering.

  • background_refractive_index (float) – Positive uniform background refractive index, dimensionless.

  • wavelength (Quantity) – Positive vacuum wavelength; explicit length units are required.

  • directions (Directions) – Validated, immutable Cartesian unit observation vectors.

  • order (int, optional) – Highest cumulative Born order, from 1 to 12; default 3.

  • incident_direction (array_like, optional) – Cartesian unit propagation vector; defaults to positive z.

  • polarization (array_like, optional) – Complex transverse unit electric-field vector; omit for unpolarized light.

Variables:

operator (bornsim.green.GreenOperator) – One open-boundary FFT Green operator reused for every compatible volume.

Notes

The cached incident plane wave follows incident_direction. A supplied complex polarization defines one pure mode; otherwise two orthogonal transverse modes are averaged incoherently. For each call, E[0] = E_inc and E[m] = K(chi*E[m-1]), where chi = 2*n0*delta_refractive_index and K integrates the background dyadic Green tensor multiplied by k0**2. Order-m far-field amplitude is computed from chi*E[m-1]. Cumulative intensity is |sum_m f[m]|**2, averaged over the incident polarization modes and divided by the entire voxel-box volume.

Geometry, incident field, and the Green tensor are reused; contrast, propagated fields, amplitudes, and diagnostics are local to each solve. Compatible volumes must have exactly the configured grid and background. Configuration is frozen to prevent stale propagation settings. Decreasing field terms do not establish universal convergence; the dielectric linearization is unchanged at higher orders.

background_refractive_index: float#
directions: Directions#
grid: Grid#
incident_direction: _Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | complex | bytes | str | _NestedSequence[complex | bytes | str] = (0.0, 0.0, 1.0)#
operator: GreenOperator#
order: int = 3#
polarization: PolarizationState | _Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | complex | bytes | str | _NestedSequence[complex | bytes | str] | None = None#
shape: tuple#
solve(*, volume)[source]#

Compute coherent scattering from one compatible finite refractive index volume.

Parameters:

volume (Volume) – Fixed fluctuation field with positive linearized permittivity, matching this engine’s grid spacing, dimensions and background.

Returns:

result – Fresh numeric SI amplitudes, cumulative and isolated intensities, relative field norms, and diagnostic messages.

Return type:

bornsim.results.BornResult

Raises:
  • TypeError – If volume is not a Volume.

  • ValueError – If grid or background differs from the engine configuration, or iteration produces nonfinite fields.

Notes

Each solve starts with the incident field. Amplitudes are summed before squaring, preserving interference. Intensities are finite-sample cross sections divided by the entire voxel-box volume, not intrinsic infinite-medium transport coefficients. The dielectric contrast is 2*n0*delta_refractive_index at every order. Growing field terms generate a diagnostic; decreasing terms do not certify convergence.

Examples

>>> from bornsim.units import ureg
>>> from bornsim import Directions, Grid, GaussianMedium
>>> from bornsim.series import BornSeries
...
...
>>> medium = GaussianMedium(
...     background_refractive_index=1.33,
...     refractive_index_std=0.01,
...     correlation_length=100e-9 * ureg.meter,
... )

… >>> grid = Grid( … shape=(2, 2, 2), … spacing=50 * ureg.nanometer, … ) >>> volume = medium.to_volume( … grid=grid, … seed=42, … ) >>> directions = Directions(vectors=[[0.0, 0.0, 1.0]]) >>> engine = BornSeries( … grid=grid, … background_refractive_index=volume.background_refractive_index, … wavelength=633 * ureg.nanometer, … directions=directions, … order=2, … ) >>> result = engine.solve(volume=volume) >>> result.amplitudes.shape (2, 1, 2, 3)

spacing: Quantity#
wavelength: Quantity#

Numerical ensemble quadrature and realization sampling uncertainty.

ensemble_scattering(*, medium, wavelength, grid, sampling=None, order=3, incident_direction=(0.0, 0.0, 1.0), polarization=None, ensemble_sampling=None)[source]#

Run numerical Born ensembles on an explicit Grid.

A random Medium generates one Volume per ordered seed in EnsembleSampling. AngularSampling defines output observations and independent integration quadrature. Complex amplitudes interfere within each realization; intensities are averaged across realizations. The returned dictionary contains numeric SI directional intensities, isolated-term intensities, integrated moments, standard errors, per-realization field norms, and diagnostic warnings. Angles and azimuths retain quantities from the sampling configuration.

Coefficients are finite-sample cross sections divided by voxel-box volume. Standard errors describe realization sampling; one realization produces NaN. Check spatial, angular, finite-size, and ensemble convergence separately.

Parameters:
  • medium (Medium)

  • wavelength (Quantity)

  • grid (Grid)

  • sampling (AngularSampling | None)

  • order (int)

  • incident_direction (_Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | complex | bytes | str | _NestedSequence[complex | bytes | str])

  • polarization (PolarizationState | _Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | complex | bytes | str | _NestedSequence[complex | bytes | str] | None)

  • ensemble_sampling (EnsembleSampling | None)

Return type:

dict[str, Any]

Units#

Shared TypedUnit registry and validation API.

class Angle[source]#

Bases: BaseUnit

Quantity specifically for angle units.

class Dimensionless[source]#

Bases: BaseUnit

Quantity specifically for dimensionless units.

class Length[source]#

Bases: BaseUnit

Quantity specifically for length units.

class NoUnit[source]#

Bases: object

Marker requiring bare numeric values without Pint units.

Use NoUnit[Scalar, Float] to require a bare floating-point scalar.

class Quantity(value: MagnitudeT, units: UnitLike | None = None)[source]#
class Quantity(value: str, units: UnitLike | None = None)
class Quantity(value: Sequence[ScalarT], units: UnitLike | None = None)
class Quantity(value: PlainQuantity[Any], units: UnitLike | None = None)

Bases: Generic[MagnitudeT], SystemQuantity[MagnitudeT], ContextQuantity[MagnitudeT], DaskQuantity[MagnitudeT], NumpyQuantity[MagnitudeT], MeasurementQuantity[MagnitudeT], NonMultiplicativeQuantity[MagnitudeT], PlainQuantity[MagnitudeT]

class RefractiveIndex[source]#

Bases: BaseUnit

Quantity specifically for refractive index units.

class Scalar[source]#

Bases: object

Marker requiring a scalar quantity with a zero-dimensional magnitude.

validate_annotation(value, *, annotation, name)[source]#

Validate one value directly against a TypedUnit annotation.

Parameters:
  • value (Any) – Value to validate.

  • annotation (Any) – Unit, no-unit, optional, collection, shape, or value-constraint annotation supported by unit_validator().

  • name (str) – Name used in validation errors.

Returns:

The value is validated without being modified.

Return type:

None

Raises:
  • TypeError – If annotation is not supported by TypedUnit.

  • ValueError – If value does not satisfy the annotation.

validate_quantity(value, *, unit, name, registry=None, shape=None, scalar=None, positive=False, nonnegative=False, finite=True)[source]#

Validate a quantity’s registry, dimensions, shape, and magnitudes.

Parameters:
  • value (pint.Quantity) – Quantity to validate; it is not changed or replaced.

  • unit (str) – Unit compatible with the required dimensionality. Magnitudes are checked after conversion to this unit.

  • name (str) – Parameter name included in error messages.

  • registry (pint.UnitRegistry or None, optional) – If supplied, require a quantity created by this exact registry. None accepts quantities from any Pint registry. Default is None.

  • shape (tuple of int or None, optional) – Required magnitude shape. An empty tuple requires a scalar; None leaves the shape unrestricted. Default is None.

  • scalar (bool or None, optional) – Compatibility shorthand for shape=() when true. False leaves the shape unrestricted. Do not combine with a non-None shape.

  • positive (bool, optional) – Require every magnitude to be strictly positive. Default is False.

  • nonnegative (bool, optional) – Require every magnitude to be nonnegative. Default is False.

  • finite (bool, optional) – Require finite magnitudes. Default is True. Set False only when the calling API deliberately permits non-finite sentinel values and checks them separately.

Returns:

The supplied quantity is preserved and no converted value is returned.

Return type:

None

Raises:

ValueError – If value is not a Pint quantity, belongs to a disallowed registry, has incompatible units, or violates shape or sign requirements. If magnitudes are nonfinite or violate shape or sign requirements.

Archives#

Results save schema-3 NPZ archives with explicit SI units, illumination settings, and no pickle. Schema-2 archives remain readable as unpolarized positive-z illumination. Unsupported schemas are rejected. Arrays and provenance are copied when results are constructed. Result.angular holds immutable directional data; .vectors on Directions exposes the observation configuration’s immutable Cartesian array.