Python class reference#

All dimensional arguments require quantities from MomentRT.ureg. Array shapes and physical conventions are described for each class. Objects are grouped by domain module; top-level convenience imports remain available.

Materials and sample geometry#

class PhaseFunction[source]#

Bases: ABC

Axisymmetric scalar phase function normalized over the unit sphere.

The normalized moment of degree l is the spherical integral of the phase function times the Legendre polynomial P_l. Polarization and azimuth-dependent scattering are outside this scalar model.

abstractmethod evaluate(*, cosine, anisotropy=None)[source]#

Evaluate probability density per unit solid angle.

Parameters:
  • cosine (array_like of float) – Plain cosines of scattering angles, in [-1, 1].

  • anisotropy (float or None, optional) – Material anisotropy when required by the phase function.

Returns:

Scalar phase density per steradian, normalized over 4 pi.

Return type:

numpy.ndarray

abstractmethod moments(*, anisotropy=None)[source]#

Return the normalized Legendre moments from degree zero to three.

Parameters:

anisotropy (float or None, optional) – Material anisotropy when required by the phase function.

Returns:

Four dimensionless values, with the first equal to one.

Return type:

numpy.ndarray

class HenyeyGreenstein[source]#

Bases: PhaseFunction

Henyey–Greenstein phase function parameterized by material anisotropy.

Supply anisotropy on the material, including a wavelength-dependent table for SpectralMaterial. This phase-function object contains no extra value.

evaluate(*, cosine, anisotropy=None)[source]#

Evaluate the Henyey–Greenstein density.

Parameters:
  • cosine (array_like of float) – Plain scattering-angle cosines in [-1, 1].

  • anisotropy (float or None, optional) – Required mean scattering cosine g in (-1, 1).

Returns:

Phase density per steradian, normalized over 4 pi.

Return type:

numpy.ndarray

moments(*, anisotropy=None)[source]#

Return the Henyey–Greenstein Legendre moments.

Parameters:

anisotropy (float or None, optional) – Required mean scattering cosine g in (-1, 1).

Returns:

Moments [1, g, g², g³].

Return type:

numpy.ndarray

class Isotropic[source]#

Bases: PhaseFunction

Equal scalar scattering probability per unit solid angle.

evaluate(*, cosine, anisotropy=None)[source]#

Evaluate the isotropic phase density.

Parameters:
  • cosine (array_like of float) – Plain scattering-angle cosines in [-1, 1].

  • anisotropy (float or None, optional) – Must be zero or None for isotropic scattering.

Returns:

Constant phase density 1/(4 pi) per steradian.

Return type:

numpy.ndarray

moments(*, anisotropy=None)[source]#

Return the isotropic Legendre moments.

Parameters:

anisotropy (float or None, optional) – Must be zero or None for isotropic scattering.

Returns:

Moments [1, 0, 0, 0].

Return type:

numpy.ndarray

class Rayleigh[source]#

Bases: PhaseFunction

Unpolarized scalar Rayleigh scattering; polarization is not modeled.

evaluate(*, cosine, anisotropy=None)[source]#

Evaluate the unpolarized Rayleigh phase density.

Parameters:
  • cosine (array_like of float) – Plain scattering-angle cosines in [-1, 1].

  • anisotropy (float or None, optional) – Must be zero or None for Rayleigh scattering.

Returns:

Phase density 3(1 + cosine²)/(16 pi) per steradian.

Return type:

numpy.ndarray

moments(*, anisotropy=None)[source]#

Return the unpolarized Rayleigh Legendre moments.

Parameters:

anisotropy (float or None, optional) – Must be zero or None for Rayleigh scattering.

Returns:

Moments [1, 0, 0.1, 0].

Return type:

numpy.ndarray

class Tabulated(*, cosine, values)[source]#

Bases: PhaseFunction

Piecewise-linear scalar phase function over scattering-angle cosines.

Parameters:
  • cosine (array_like of float) – Strictly increasing plain cosines covering exactly [-1, 1].

  • values (array_like of float) – Nonnegative relative phase densities on the same grid. The supplied shape is normalized over the sphere; an overall scale is immaterial.

Notes

Values are interpolated linearly in cosine, not in angle. The phase function is fixed across wavelengths. The first three moments are integrated exactly for each piecewise-linear interval.

evaluate(*, cosine, anisotropy=None)[source]#

Interpolate the normalized phase density in cosine.

Parameters:
  • cosine (array_like of float) – Plain scattering-angle cosines in [-1, 1].

  • anisotropy (float or None, optional) – If supplied, must match the table’s first moment.

Returns:

Interpolated phase density per steradian.

Return type:

numpy.ndarray

moments(*, anisotropy=None)[source]#

Integrate the tabulated phase function against Legendre polynomials.

Parameters:

anisotropy (float or None, optional) – If supplied, must match the table’s first moment.

Returns:

Normalized moments of degrees zero through three.

Return type:

numpy.ndarray

class Material(*, absorption, reduced_scattering, refractive_index, anisotropy=None, phase_function)[source]#

Bases: object

Wavelength-independent optical coefficients for moment models.

Parameters:
  • absorption (pint.Quantity) – Nonnegative absorption coefficient, with inverse-length units.

  • reduced_scattering (pint.Quantity) – Positive reduced scattering coefficient, with inverse-length units.

  • refractive_index (float) – Positive dimensionless refractive index, supplied without units.

  • anisotropy (float or None, optional) – Mean scattering cosine in (-1, 1), supplied without units. Required by Henyey–Greenstein SP3/P3 calculations. Phase functions with their own first moment can omit it; P1 does not use it.

  • phase_function (PhaseFunction) – Explicit scalar scattering phase function. SP3 and P3 use its moments; P1 only needs reduced scattering.

Notes

The diffusion length coefficient is D = 1 / (3 * (absorption + reduced_scattering)). No wavelength dependence is inferred.

Examples

>>> import MomentRT
>>> ureg = MomentRT.ureg
>>> tissue = MomentRT.Material(
...     absorption=0.1 / ureg.millimeter,
...     reduced_scattering=1.0 / ureg.millimeter,
...     refractive_index=1.4,
...     phase_function=MomentRT.phase_function.HenyeyGreenstein(),
... )
at(*, wavelength)[source]#

Return this wavelength-independent material at a positive wavelength.

Parameters:

wavelength (pint.Quantity) – Positive scalar vacuum wavelength, with length units.

Returns:

Monochromatic material at the requested wavelength.

Return type:

Material

class SpectralMaterial(*, wavelengths, absorption, reduced_scattering, refractive_index, anisotropy=None, phase_function)[source]#

Bases: object

Tabulated optical coefficients with linear interpolation and no extrapolation.

wavelengths must increase strictly. Coefficient arrays have the same shape. refractive_index is a positive plain scalar or an array on the same grid.

Parameters:
  • wavelengths (pint.Quantity) – Strictly increasing one-dimensional wavelength grid with at least two positive entries and length units.

  • absorption (pint.Quantity) – Nonnegative absorption values with inverse-length units, matching the wavelength grid shape.

  • reduced_scattering (pint.Quantity) – Positive reduced scattering values with inverse-length units, matching the wavelength grid shape.

  • refractive_index (float or array_like of float) – Positive plain scalar or vector matching the wavelength grid. Dimensionless quantities are not accepted.

  • anisotropy (float or array_like of float or None, optional) – Plain scalar or wavelength-grid vector of mean scattering cosines in (-1, 1). Interpolated linearly; required for Henyey–Greenstein SP3/P3 calculations, unused by P1.

  • phase_function (PhaseFunction) – Explicit scattering phase function, fixed across the wavelength table.

at(*, wavelength)[source]#

Evaluate a monochromatic Material without modifying the table.

Parameters:

wavelength (pint.Quantity) – Positive scalar vacuum wavelength, with length units.

Returns:

Monochromatic material at the requested wavelength.

Return type:

Material

Raises:

ValueError – If wavelength is nonpositive, nonscalar, or outside the tabulated range.

Premade materials#

class Epidermis(*, melanin_fraction, wavelength, refractive_index)[source]#

Bases: Material

Parameterized epidermal material with melanin-dependent absorption.

Parameters:
  • melanin_fraction (float) – Unitless epidermal melanin fraction from 0 to 1. This is a model fraction, not a direct clinical pigmentation measurement.

  • wavelength (pint.Quantity) – Vacuum wavelength from 400 to 1000 nm.

  • refractive_index (float) – Positive dimensionless refractive index.

Notes

Absorption combines the melanosome power law and a baseline epidermal absorber fit. Reduced scattering uses a two-component Rayleigh/Mie power law. Both are simplified literature parameterizations; this is not an individualized or validated patient model. A Henyey–Greenstein phase function with g=0.8 is supplied for moment solvers that require higher phase moments.

References

Jolivot, R. et al. (2013), International Journal of Biomedical Imaging, 2013, 978289. doi:10.1155/2013/978289. Jacques, S. L. (2013), Physics in Medicine & Biology, 58, R37–R61. doi:10.1088/0031-9155/58/11/R37.

class Dermis(*, hydration, wavelength, refractive_index)[source]#

Bases: Material

Parameterized dermal material with hydration-dependent absorption.

Parameters:
  • hydration (float) – Unitless water fraction from 0 to 1 in the non-blood dermal component.

  • wavelength (pint.Quantity) – Vacuum wavelength from 400 to 1000 nm.

  • refractive_index (float) – Positive dimensionless refractive index.

Notes

Absorption mixes pure-water absorption with a baseline dermal absorber using the hydration fraction. Reduced scattering uses a two-component Rayleigh/Mie power law. Melanin is modeled in the epidermis, rather than the dermis, in this simple layered model. A Henyey–Greenstein phase function with g=0.9 is supplied for higher moment calculations. These literature fits are approximate and omit blood-vessel structure, oxygenation, and patient-specific variation.

References

Jacques, S. L. (2013), Physics in Medicine & Biology, 58, R37–R61. doi:10.1088/0031-9155/58/11/R37. Hale, G. M. and Querry, M. R. (1973), Applied Optics, 12(3), 555–563. doi:10.1364/AO.12.000555.

class Intralipid(*, concentration, wavelength, refractive_index)[source]#

Bases: Material

Intralipid-20% phantom using a concentration-dependent scattering model.

Parameters:
  • concentration (float) – Lipid-particle volume fraction in percent, from 0.227 to 22.7. A value of 22.7 represents the undiluted Intralipid-20% stock; 1.0 represents a 1% particle volume fraction.

  • wavelength (pint.Quantity) – Vacuum wavelength from 400 to 1700 nm and above the model’s concentration-dependent validity limit.

  • refractive_index (float) – Positive dimensionless refractive index of the prepared solution.

Notes

The dependent-scattering equations estimate the scattering coefficient and anisotropy from wavelength and particle volume fraction. Absorption is approximated by the water fraction of the mixture using Hale–Querry data. The model’s empirical equations were validated only when wavelength_nm >= 560 + 2200 * particle_volume_fraction. This class uses a Henyey–Greenstein phase function matched to the modeled anisotropy; it does not reproduce the model’s full phase function, so SP3/P3 results are an approximation. Measure the actual mixture for high-accuracy work.

References

Attendu, X. et al. (2026), Journal of Biomedical Optics, 31(8), 085003. doi:10.1117/1.JBO.31.8.085003.

class Water(*, wavelength, refractive_index)[source]#

Bases: Material

Pure-water material at one visible wavelength.

Parameters:
  • wavelength (pint.Quantity) – Vacuum wavelength from 400 to 750 nm.

  • refractive_index (float) – Positive dimensionless refractive index at the configured wavelength and temperature.

Notes

Absorption is linearly interpolated from Hale and Querry’s tabulated data. Molecular scattering uses the Buiteveld fit over 340–750 nm and a Rayleigh phase function. Pure water is weakly scattering, so MomentRT’s diffusion approximation is generally unsuitable for this material.

References

Hale, G. M. and Querry, M. R. (1973), Applied Optics, 12(3), 555–563. doi:10.1364/AO.12.000555. Buiteveld, H. et al. (1994), Proc. SPIE 2258, 174–183. doi:10.1117/12.190060.

classmethod absorption_at(*, wavelength)[source]#

Interpolate Hale–Querry water absorption at a wavelength.

Parameters:

wavelength (pint.Quantity) – Vacuum wavelength from 400 to 1700 nm.

Returns:

Absorption coefficient in mm^-1.

Return type:

pint.Quantity

class HomogeneousMedium(*, material)[source]#

Bases: object

Uniform optical material in an unbounded physical medium.

Parameters:

material (Material or SpectralMaterial) – Optical coefficients assigned to this region.

at(*, wavelength)[source]#

Resolve optical coefficients at a positive vacuum wavelength.

Parameters:

wavelength (pint.Quantity) – Positive scalar vacuum wavelength, with length units.

Returns:

Geometry-preserving monochromatic medium; the original is unchanged.

Return type:

HomogeneousMedium

plot(*, mesh, length_unit='mm', show=True)[source]#

Create an interactive visualization of this object.

Parameters:
  • mesh (CartesianMesh) – Cartesian nodes used for sampling or finite-element discretization.

  • length_unit (str, optional) – Length unit used for displayed or exported coordinates. Default is ‘mm’.

  • show (bool, optional) – Whether to display the figure immediately. The figure is always returned. Default is True.

Returns:

Composable interactive figure, also displayed when show is True.

Return type:

plotly.graph_objects.Figure

class StructuredMedium(*, origin, size)[source]#

Bases: object

Finite sample with an explicit background and ordered material regions.

origin is the lower x/y/z corner; size is the full sample extent. Builders mutate in place and return None. Later structures replace earlier materials, including at shared interfaces. Shapes must fit inside the sample. This geometry is independent of the numerical discretization.

Parameters:
  • origin (pint.Quantity) – Lower Cartesian corner, shape (3,), with length units.

  • size (pint.Quantity) – Positive full Cartesian extents, shape (3,), with length units.

property structures: tuple[Box | Sphere | Layer, ...]#

Return the immutable ordered collection of material-bearing regions.

Returns:

Regions in insertion order; later regions replace earlier materials.

Return type:

tuple of Box, Sphere, or Layer

add_background(*, material)[source]#

Replace the background while retaining existing structures.

Parameters:

material (Material or SpectralMaterial) – Optical coefficients assigned to this region.

Return type:

None

at(*, wavelength)[source]#

Resolve all materials on a geometry-preserving monochromatic copy.

Parameters:

wavelength (pint.Quantity) – Positive scalar vacuum wavelength, with length units.

Returns:

Geometry-preserving monochromatic medium; the original is unchanged.

Return type:

StructuredMedium

add_structures(*structures)[source]#

Append named shapes in argument order; validate the whole batch first.

Parameters:

*structures (Box, Sphere, or Layer) – Named regions appended in argument order. Later regions replace earlier ones, including on shared interfaces; the batch is validated before any mutation.

Return type:

None

material_labels(*, points)[source]#

Return 0 for background and 1..N for ordered structures.

Points must lie inside the finite sample. The trailing axis is x/y/z.

Parameters:

points (pint.Quantity) – Query coordinates with length units and shape (…, 3).

Returns:

Labels with shape points.shape[:-1]: zero for background and 1..N for ordered structures. Later structures win at overlaps.

Return type:

ndarray of int

Raises:

ValueError – If no background is configured, points have invalid shape, or any query lies outside the finite sample.

optical_fields(*, mesh, wavelength=None)[source]#

Sample the material map onto mesh nodes, returning unit-bearing fields.

Parameters:
  • mesh (CartesianMesh or TetrahedralMesh) – Cartesian nodes used for sampling or finite-element discretization.

  • wavelength (pint.Quantity or None, optional) – Vacuum wavelength used to resolve spectral materials. Required when any material is spectral; None retains fixed coefficients. Default is None.

Returns:

Nodal absorption and reduced scattering in inverse meters, plus dimensionless refractive index. This is sampling, not interface fitting.

Return type:

dict of str to ScalarField

plot(*, mesh=None, wavelength=None, length_unit='mm', opacity=0.45, overlays=None, show=True)[source]#

Plot named region surfaces; mesh is optional and does not define geometry.

Transparent primitive surfaces show the construction geometry; overlap precedence follows insertion order, not optical mixing or CSG subtraction.

Parameters:
  • mesh (CartesianMesh, TetrahedralMesh or None, optional) – Optional compatibility argument; construction surfaces use the physical sample bounds and do not depend on a numerical mesh. Default is None.

  • wavelength (pint.Quantity or None, optional) – Vacuum wavelength used to resolve spectral materials. Required when any material is spectral; None retains fixed coefficients. Default is None.

  • length_unit (str, optional) – Length unit used for displayed or exported coordinates. Default is ‘mm’.

  • opacity (float, optional) – Construction-surface opacity in [0, 1]. Default is 0.45.

  • overlays (iterable of objects or None, optional) – Sources, detectors, and layers to draw on top of the sample geometry. Objects must implement the internal plotting hook used by the field visualizations. Default is None.

  • show (bool, optional) – Whether to display the figure immediately. The figure is always returned. Default is True.

Returns:

Composable interactive figure, also displayed when show is True.

Return type:

plotly.graph_objects.Figure

add_layer(*, name, thickness, material, clip_to_sample=False)[source]#

Append a layer below the deepest existing layer; return None.

The first layer starts at origin.z. Boxes and spheres do not change stacking depth. Explicit Layer objects added through add_structures also participate. New layers follow the usual insertion precedence. When clip_to_sample is True, truncate a layer at the sample’s maximum z boundary when its requested thickness extends beyond the sample. A layer with no overlap with the sample is omitted.

Parameters:
  • name (str) – Nonempty name identifying this object.

  • thickness (pint.Quantity) – Positive scalar layer thickness with length units.

  • material (Material or SpectralMaterial) – Optical coefficients assigned to this region.

  • clip_to_sample (bool, optional) – Whether to truncate the layer to the remaining depth up to the sample’s maximum z coordinate. A fully out-of-bounds layer is omitted when True. Default is False, which raises an error if the layer extends outside.

Return type:

None

section(*, normal, position, resolution=(200, 200), wavelength=None)[source]#

Sample a plane at an absolute coordinate, resolving region overlaps.

resolution gives (horizontal, vertical) cell counts. Cell-center samples represent a discrete map, not an exact geometric intersection.

Parameters:
  • normal ({'x', 'y', 'z'}) – Axis normal to the section plane.

  • position (pint.Quantity) – Absolute scalar coordinate along the plane normal, with length units.

  • resolution (tuple of int, optional) – Horizontal and vertical cell counts, each at least two. The stored section arrays have shape (vertical, horizontal). Default is (200, 200).

  • wavelength (pint.Quantity or None, optional) – Vacuum wavelength used to resolve spectral materials. Required when any material is spectral; None retains fixed coefficients. Default is None.

Returns:

Snapshot of cell-center labels and SI optical-property arrays.

Return type:

SampleSection

plot_section(*, normal, position, quantity='material', resolution=(200, 200), wavelength=None, length_unit='mm', value_unit=None, scale='linear', show=True)[source]#

Plot a resolved cross-section, with depth increasing downwards.

Parameters:
  • normal ({'x', 'y', 'z'}) – Axis normal to the section plane.

  • position (pint.Quantity) – Absolute scalar coordinate along the plane normal, with length units.

  • quantity ({'material', 'absorption', 'reduced_scattering', 'refractive_index'}, optional) – Material labels or optical property to display. Default is ‘material’.

  • resolution (tuple of int, optional) – Horizontal and vertical cell counts, each at least two. The stored section arrays have shape (vertical, horizontal). Default is (200, 200).

  • wavelength (pint.Quantity or None, optional) – Vacuum wavelength used to resolve spectral materials. Required when any material is spectral; None retains fixed coefficients. Default is None.

  • length_unit (str, optional) – Length unit used for displayed or exported coordinates. Default is ‘mm’.

  • value_unit (str or None, optional) – Unit for displayed optical-property values; None uses stored SI units. Default is None.

  • scale ({'linear', 'log'}, optional) – Display scaling. Logarithmic scaling requires strictly positive values. Default is ‘linear’.

  • show (bool, optional) – Whether to display the figure immediately. The figure is always returned. Default is True.

Returns:

Resolved cross-section figure with depth increasing downwards.

Return type:

plotly.graph_objects.Figure

class Box(*, origin, size, material, name)[source]#

Bases: object

Axis-aligned box, specified by its lower corner and full size.

Parameters:
  • origin (pint.Quantity) – Lower Cartesian corner, shape (3,), with length units.

  • size (pint.Quantity) – Positive full Cartesian extents, shape (3,), with length units.

  • material (Material or SpectralMaterial) – Optical coefficients assigned to this region.

  • name (str) – Nonempty name identifying this object.

contains(*, points)[source]#

Test point membership, including the region interfaces.

Parameters:

points (pint.Quantity) – Query coordinates with length units and shape (…, 3).

Returns:

Membership mask with shape points.shape[:-1]; interfaces are included.

Return type:

ndarray of bool

class Sphere(*, center, radius, material, name)[source]#

Bases: object

Sphere specified by center and radius.

Parameters:
  • center (pint.Quantity) – Absolute Cartesian center, shape (3,), with length units.

  • radius (pint.Quantity) – Positive scalar radius with length units.

  • material (Material or SpectralMaterial) – Optical coefficients assigned to this region.

  • name (str) – Nonempty name identifying this object.

contains(*, points)[source]#

Test point membership, including the region interfaces.

Parameters:

points (pint.Quantity) – Query coordinates with length units and shape (…, 3).

Returns:

Membership mask with shape points.shape[:-1]; interfaces are included.

Return type:

ndarray of bool

class Layer(*, depth, thickness, material, name)[source]#

Bases: object

Horizontal layer spanning the sample’s full x/y extent.

depth is the absolute z coordinate of the upper interface. The layer occupies depth <= z <= depth + thickness; later regions win at interfaces.

Parameters:
  • depth (pint.Quantity) – Absolute z coordinate of the upper interface, with length units.

  • thickness (pint.Quantity) – Positive scalar layer thickness with length units.

  • material (Material or SpectralMaterial) – Optical coefficients assigned to this region.

  • name (str) – Nonempty name identifying this object.

contains(*, points)[source]#

Test point membership, including the region interfaces.

Parameters:

points (pint.Quantity) – Query coordinates with length units and shape (…, 3).

Returns:

Membership mask with shape points.shape[:-1]; interfaces are included.

Return type:

ndarray of bool

class SampleSection(*, sample, normal, position, resolution, wavelength=None)[source]#

Bases: object

Snapshot of cell-center samples on an axis-aligned plane.

Arrays use (vertical, horizontal) order. Physical inputs retain their units; optical-property arrays are stored in SI. No interpolation is applied.

Parameters:
  • sample (StructuredMedium) – Finite rectangular sample with an explicit background.

  • normal ({'x', 'y', 'z'}) – Axis normal to the section plane.

  • position (pint.Quantity) – Absolute scalar coordinate along the plane normal, with length units.

  • resolution (tuple of int) – Horizontal and vertical cell counts, each at least two. The stored section arrays have shape (vertical, horizontal).

  • wavelength (pint.Quantity or None, optional) – Vacuum wavelength used to resolve spectral materials. Required when any material is spectral; None retains fixed coefficients. Default is None.

Variables:
  • labels (numpy.ndarray of int) – Cell-center material labels, shape (vertical, horizontal). Zero denotes background; positive labels follow structure insertion order.

  • fields (dict of str to pint.Quantity) – Absorption and reduced scattering in inverse meters and dimensionless refractive index, with the same shape as labels.

  • names (tuple of str) – Background and structure names indexed by labels.

  • horizontal (pint.Quantity) – One-dimensional horizontal cell-center coordinates in meters.

  • vertical (pint.Quantity) – One-dimensional vertical cell-center coordinates in meters.

  • extent (pint.Quantity) – Horizontal and vertical lower/upper bounds, shape (2, 2), in meters.

  • axes (tuple of str) – Names of the horizontal and vertical Cartesian axes.

plot(*, quantity='material', length_unit='mm', value_unit=None, scale='linear', show=True)[source]#

Create an interactive visualization of this object.

Parameters:
  • quantity ({'material', 'absorption', 'reduced_scattering', 'refractive_index'}, optional) – Material labels or optical property to display. Default is ‘material’.

  • length_unit (str, optional) – Length unit used for displayed or exported coordinates. Default is ‘mm’.

  • value_unit (str or None, optional) – Unit for displayed optical-property values; None uses stored SI units. Default is None.

  • scale ({'linear', 'log'}, optional) – Display scaling. Logarithmic scaling requires strictly positive values. Default is ‘linear’.

  • show (bool, optional) – Whether to display the figure immediately. The figure is always returned. Default is True.

Returns:

Composable interactive figure, also displayed when show is True.

Return type:

plotly.graph_objects.Figure

Sources, detectors, and boundaries#

class SourceSpectrum(*, wavelengths, spectral_power)[source]#

Bases: object

Tabulated incoming spectral power density for a broadband source.

Parameters:
  • wavelengths (pint.Quantity) – Strictly increasing positive vacuum wavelengths, shape (n,), n >= 2. Their endpoints define the integration interval.

  • spectral_power (pint.Quantity) – Nonnegative spectral power density, shape (n,), such as W / nm. The trapezoidal integral must be positive. Surface-source power is diffuse power already coupled into the sample.

property optical_power: Quantity#

Return the trapezoidal spectral integral over the supplied interval.

Returns:

Total incoming optical power in watts.

Return type:

pint.Quantity

resample(*, wavelengths)[source]#

Interpolate density onto an explicit grid without extrapolation.

Parameters:

wavelengths (pint.Quantity) – Strictly increasing positive vacuum wavelengths, shape (n,), n >= 2, within the original table. Include existing knots when preserving the piecewise linear source and its total optical power.

Returns:

Independent interpolated table, retaining spectral density units.

Return type:

SourceSpectrum

Raises:

ValueError – If the grid is invalid, outside coverage, or loses all source power.

plot(*, wavelength_unit='nm', power_unit='uW/nm', show=True)[source]#

Plot the supplied spectral power-density samples.

Parameters:
  • wavelength_unit (str, optional) – Display length unit. Default is ‘nm’.

  • power_unit (str, optional) – Display spectral power-density unit. Default is ‘uW/nm’.

  • show (bool, optional) – Display the composable figure immediately. Default is True.

Returns:

Source density curve with physical wavelength and power labels.

Return type:

plotly.graph_objects.Figure

class DetectorResponsivity(*, wavelengths, responsivity)[source]#

Bases: object

Tabulated detector responsivity with linear interpolation and no extrapolation.

Parameters:
  • wavelengths (pint.Quantity) – Strictly increasing positive vacuum wavelengths, shape (n,), n >= 2.

  • responsivity (pint.Quantity) – Nonnegative electrical responsivity, shape (n,), with A / W units. It describes a linear detector without saturation or electronics gain.

at(*, wavelength)[source]#

Interpolate responsivity within the supplied wavelength interval.

Parameters:

wavelength (pint.Quantity) – Positive scalar or array of vacuum wavelengths with length units.

Returns:

Responsivity with A / W units, matching the input shape.

Return type:

pint.Quantity

Raises:

ValueError – If any wavelength lies outside the tabulated interval.

plot(*, wavelength_unit='nm', responsivity_unit='A/W', show=True)[source]#

Plot the tabulated linear electrical response.

Parameters:
  • wavelength_unit (str, optional) – Display length unit. Default is ‘nm’.

  • responsivity_unit (str, optional) – Display electrical response unit. Default is ‘A/W’.

  • show (bool, optional) – Display the composable figure immediately. Default is True.

Returns:

Response curve with physical wavelength and responsivity labels.

Return type:

plotly.graph_objects.Figure

class PointSource(*, position, wavelength=None, optical_power=None, spectrum=None, name='Point source', color='crimson')[source]#

Bases: _SourceEmission

Isotropic point illumination embedded in an infinite medium.

Parameters:
  • position (pint.Quantity) – Absolute Cartesian position, shape (3,), with length units.

  • wavelength (pint.Quantity or None, optional) – Positive scalar vacuum wavelength, with length units.

  • optical_power (pint.Quantity or None, optional) – Positive scalar optical power with power units.

  • spectrum (SourceSpectrum or None, optional) – Broadband spectral density. Supply this or both wavelength and optical_power. Default is None.

  • name (str, optional) – Legend label. Default is "Point source".

  • color (str, optional) – Plotly-compatible color. Default is "crimson".

Notes

Use with InfiniteDiffusion. The point-source singularity is not regularized, and the Cartesian mesh is an observation window.

class UniformSurfaceSource(*, face, wavelength=None, optical_power=None, spectrum=None, name='Full-face illumination', color='crimson')[source]#

Bases: _SourceEmission

Uniform incoming diffuse partial current across one complete sample face.

optical_power is power already transmitted into the sample, before diffuse internal reflection. This does not model collimated LED entry or specular Fresnel loss. The boundary condition’s source factor is applied by the solver.

Parameters:
  • face ({'x_min', 'x_max', 'y_min', 'y_max', 'z_min', 'z_max'}) – Axis-aligned sample face; min and max refer to outward boundaries.

  • wavelength (pint.Quantity or None, optional) – Positive scalar vacuum wavelength, with length units.

  • optical_power (pint.Quantity or None, optional) – Positive scalar optical power with power units.

  • spectrum (SourceSpectrum or None, optional) – Broadband spectral density. Supply this or both wavelength and optical_power. Default is None.

  • name (str, optional) – Legend label. Default is "Full-face illumination".

  • color (str, optional) – Plotly-compatible color. Default is "crimson".

Notes

Power is incoming diffuse power already coupled into the sample. Collimated propagation and specular Fresnel entry losses are not modeled. The solver applies the Robin source factor separately.

class SurfaceSource(*, face, position, radius, wavelength=None, optical_power=None, spectrum=None, name='Illumination spot', color='crimson')[source]#

Bases: UniformSurfaceSource

Circular top-hat incoming diffuse illumination on an axis-aligned face.

position is an absolute 3D surface coordinate; radius is the spot radius. The entire disk must fit on the selected face. Surface quadrature samples its footprint and is normalized to optical_power; refine the mesh to resolve the disk edge and check the reported quadrature spot area.

Parameters:
  • face ({'x_min', 'x_max', 'y_min', 'y_max', 'z_min', 'z_max'}) – Axis-aligned sample face; min and max refer to outward boundaries.

  • position (pint.Quantity) – Absolute Cartesian position, shape (3,), with length units.

  • radius (pint.Quantity) – Positive scalar radius with length units.

  • wavelength (pint.Quantity or None, optional) – Positive scalar vacuum wavelength, with length units.

  • optical_power (pint.Quantity or None, optional) – Positive scalar optical power with power units.

  • spectrum (SourceSpectrum or None, optional) – Broadband spectral density. Supply this or both wavelength and optical_power. Default is None.

  • name (str, optional) – Legend label. Default is "Illumination spot".

  • color (str, optional) – Plotly-compatible color. Default is "crimson".

Notes

The entire disk must fit on the selected Robin face. Boundary quadrature is normalized to the specified incoming power; energy conservation alone does not establish that the disk edge is spatially resolved.

classmethod on_face(*, sample, face, coordinates, radius, wavelength=None, optical_power=None, spectrum=None, name='Illumination spot', color='crimson')[source]#

Place a circular source using absolute coordinates in a sample face.

Parameters:
  • sample (StructuredMedium) – Physical sample used to determine the face coordinate.

  • face (str) – Cartesian face name, such as z_min.

  • coordinates (pint.Quantity) – Two absolute in-plane coordinates, ordered by Cartesian axis (y, z for x faces; x, z for y faces; x, y for z faces).

  • radius (pint.Quantity) – Positive illumination radius with length units.

  • wavelength (pint.Quantity or None, optional) – Positive vacuum wavelength with length units.

  • optical_power (pint.Quantity or None, optional) – Incoming diffuse power already coupled into the sample.

  • spectrum (SourceSpectrum or None, optional) – Broadband spectral density. Supply this or both wavelength and optical_power. Default is None.

  • name (str, optional) – Legend label. Default is "Illumination spot".

  • color (str, optional) – Plotly-compatible color. Default is "crimson".

Returns:

Source with its absolute three-dimensional position recorded.

Return type:

SurfaceSource

class SurfaceDetector(*, face, position, radius, collection_axis, acceptance_angle, responsivity=None, name='Surface detector', color='royalblue')[source]#

Bases: object

Circular aperture in a sample face with a cone of accepted outgoing rays.

collection_axis points along collected ray propagation, out of the sample. The aperture lies in the configured face even when the collection axis is tilted. acceptance_angle is the cone half-angle, with explicit angular units. This is a passive contact measurement with Lambertian escaping radiance; it does not alter the transport boundary or model refraction and lenses.

Parameters:
  • face ({'x_min', 'x_max', 'y_min', 'y_max', 'z_min', 'z_max'}) – Axis-aligned sample face; min and max refer to outward boundaries.

  • position (pint.Quantity) – Absolute Cartesian position, shape (3,), with length units.

  • radius (pint.Quantity) – Positive scalar radius with length units.

  • collection_axis (array_like of float, shape (3,)) – Nonzero dimensionless direction along accepted outgoing rays. It is normalized internally and must point into the outward hemisphere.

  • acceptance_angle (pint.Quantity) – Acceptance-cone half-angle, from 0 to 90 degrees, with angular units.

  • responsivity (DetectorResponsivity or None, optional) – Linear spectral electrical response in A / W. None reports optical power without photocurrent. Default is None.

  • name (str, optional) – Legend label. Default is "Surface detector".

  • color (str, optional) – Plotly-compatible color. Default is "royalblue".

Notes

This is a passive contact measurement assuming Lambertian escaping radiance. It does not change the transport boundary or model lenses, refraction, or angle-resolved Fresnel transmission. For a cone wholly inside the outward hemisphere, the accepted fraction is cos(tilt) * sin(acceptance_angle)**2.

classmethod on_face(*, sample, face, coordinates, radius, acceptance_angle=None, orientation='outward_normal', acceptance=None, responsivity=None, name='Surface detector', color='royalblue')[source]#

Place an outward-facing detector using absolute in-plane coordinates.

Parameters:
  • sample (StructuredMedium) – Physical sample used to determine the face position.

  • face (str) – Cartesian face name, such as z_min.

  • coordinates (pint.Quantity) – Two absolute in-plane coordinates, ordered by Cartesian axis (y, z for x faces; x, z for y faces; x, y for z faces).

  • radius (pint.Quantity) – Positive aperture radius with length units.

  • acceptance_angle (pint.Quantity or None, optional) – Cone half-angle from zero to 90 degrees. Supply this or acceptance. Default is None.

  • orientation ({'outward_normal'}, optional) – Select the outward face normal as the collection axis by default. Use the main constructor for a tilted collection axis.

  • acceptance ({'full_hemisphere'} or None, optional) – Explicitly collect the complete outward hemisphere. Supply this or acceptance_angle. Default is None.

  • responsivity (DetectorResponsivity or None, optional) – Linear spectral electrical response in A / W. None reports optical power without photocurrent. Default is None.

  • name (str, optional) – Legend label. Default is "Surface detector".

  • color (str, optional) – Plotly-compatible color. Default is "royalblue".

Returns:

Detector with the derived 3D position and collection axis recorded.

Return type:

SurfaceDetector

classmethod full_hemisphere_on_face(*, sample, face, coordinates, radius, responsivity=None, name='Surface detector', color='royalblue')[source]#

Collect all escaping irradiance across a circular contact aperture.

Parameters:
  • sample (StructuredMedium) – Physical sample used to determine and validate the face position.

  • face ({'x_min', 'x_max', 'y_min', 'y_max', 'z_min', 'z_max'}) – Axis-aligned sample face.

  • coordinates (pint.Quantity) – Absolute in-plane coordinates, shape (2,), with length units, ordered by Cartesian axis.

  • radius (pint.Quantity) – Positive aperture radius with length units.

  • responsivity (DetectorResponsivity or None, optional) – Linear spectral electrical response in A / W. None reports optical power without photocurrent. Default is None.

  • name (str, optional) – Legend label. Default is "Surface detector".

  • color (str, optional) – Plotly-compatible color. Default is "royalblue".

Returns:

A detector with outward-normal axis and 90-degree acceptance half-angle.

Return type:

SurfaceDetector

Notes

This ideal contact measurement accepts the entire outward hemisphere. It does not model external optics or change the transport boundary.

property angular_fraction: float#

Fraction of Lambertian escaping irradiance inside the acceptance cone.

Returns:

Accepted fraction in [0, 1] under Lambertian escaping radiance.

Return type:

float

measure(*, result)[source]#

Integrate the solved escaping field over the sampled disk aperture.

Parameters:

result (SimulationResult) – Finite-sample solution with escaping-irradiance boundary fields.

Returns:

Collected power, sampled and exact areas, angular fraction, and minimum sampled irradiance. Quadrature area is not renormalized.

Return type:

DetectorResult

Raises:
  • ValueError – If boundary data are missing or the aperture does not fit on its face.

  • DetectorResolutionError – If no quadrature point samples the aperture; refine the mesh.

class RobinBoundary(*, effective_reflectance)[source]#

Bases: object

Diffuse internal reflection with an explicitly supplied effective reflectance.

This is a partial-current coefficient, not normal-incidence Fresnel R. No refractive-index-to-reflectance approximation is selected implicitly. With R=effective_reflectance, beta=(1-R)/(2(1+R)) and outward net current J.n = beta Phi - 2 I_in/(1+R). I_in is incoming diffuse partial current already coupled into the sample (W/m^2).

Parameters:

effective_reflectance (float) – Effective diffuse partial-current reflectance in [0, 1). This is not the normal-incidence Fresnel reflectance.

property leakage_coefficient: float#

Return the dimensionless Robin leakage coefficient.

Returns:

Dimensionless beta = (1 - R) / (2 * (1 + R)).

Return type:

float

property source_factor: float#

Return the dimensionless incoming-current multiplier.

Returns:

Dimensionless incoming-current factor 2 / (1 + R).

Return type:

float

class ReflectingBoundary[source]#

Bases: object

Zero normal current; illumination on this face is unsupported.

leakage_coefficient = 0.0#
class Boundaries(*, conditions)[source]#

Bases: Mapping[Literal[‘x_min’, ‘x_max’, ‘y_min’, ‘y_max’, ‘z_min’, ‘z_max’], RobinBoundary | ReflectingBoundary]

A complete set of explicitly chosen conditions on the six sample faces.

Parameters:

conditions (mapping of str to RobinBoundary or ReflectingBoundary) – Exactly one condition for each of the six Cartesian sample faces.

classmethod uniform(*, condition)[source]#

Apply the supplied explicit condition to every face.

Parameters:

condition (RobinBoundary or ReflectingBoundary) – Condition copied independently to each of the six faces.

Returns:

Complete set of face conditions.

Return type:

Boundaries

with_overrides(*, conditions)[source]#

Return a copy with explicitly selected face conditions replaced.

Parameters:

conditions (mapping of str to RobinBoundary or ReflectingBoundary) – Replacement conditions keyed by face name.

Returns:

New complete face mapping; this set is not modified.

Return type:

Boundaries

Meshes and transport#

class CartesianMesh(*, shape, spacing, origin)[source]#

Bases: object

Cartesian node grid for observations or finite-element discretization.

Parameters:
  • shape (tuple of int) – Node counts (nx, ny, nz), each at least two.

  • spacing (pint.Quantity) – Positive node separations (dx, dy, dz), with length units.

  • origin (pint.Quantity) – Lower Cartesian corner, shape (3,), with length units.

Examples

>>> import numpy as np
>>> import MomentRT
>>> mesh = MomentRT.CartesianMesh(
...     shape=(11, 11, 11),
...     spacing=np.ones(3) * MomentRT.ureg.millimeter,
...     origin=np.zeros(3) * MomentRT.ureg.millimeter,
... )
>>> mesh.points.shape
(11, 11, 11, 3)
property bounds: Quantity#

Return the lower and upper node coordinates.

Returns:

Cartesian bounds with shape (2, 3) and length units.

Return type:

pint.Quantity

property name: str#

Return the default overlay name for this mesh.

Returns:

Display name used in plot legends.

Return type:

str

property color: str#

Return the default color used when this mesh is an overlay.

Returns:

Slate color used for mesh edges.

Return type:

str

property resolution: Quantity | None#

Return the requested maximum spacing, when supplied to from_sample.

Returns:

Independent copy of the requested scalar or (3,) length quantity. None when the mesh was configured using explicit node counts. Actual node separations are available through spacing.

Return type:

pint.Quantity or None

copy()[source]#

Copy the mesh coordinates and requested resolution independently.

Returns:

Independent mesh snapshot with identical nodes and resolution.

Return type:

CartesianMesh

plot(*, length_unit='mm', max_edges=20000, show=True)[source]#

Plot the Cartesian grid and its translucent bounding surface.

Parameters:
  • length_unit (str, optional) – Coordinate unit. Default is ‘mm’.

  • max_edges (int, optional) – Maximum number of evenly selected grid edges. Default is 20000.

  • show (bool, optional) – Display immediately when True. Default is True.

Returns:

Composable grid plot with physical coordinates and depth direction.

Return type:

plotly.graph_objects.Figure

property points: Quantity#

Generate Cartesian node coordinates using ij array ordering.

Returns:

Cartesian coordinates in meters, shape (*shape, 3), using ij ordering.

Return type:

pint.Quantity

classmethod from_sample(*, sample, resolution=None, shape=None)[source]#

Create nodes spanning every face of the finite rectangular sample.

Parameters:
  • sample (StructuredMedium) – Finite rectangular sample with an explicit background.

  • resolution (pint.Quantity or None, optional) – Positive maximum node spacing with length units. A scalar applies to all axes; a quantity of shape (3,) specifies (rx, ry, rz). Actual uniform spacing on each axis is adjusted downward to fit the sample exactly, within floating-point precision. Default is None. Supply exactly one of resolution and shape.

  • shape (tuple of int or None, optional) – Node counts (nx, ny, nz), each at least two. Default is None. Supply exactly one of resolution and shape.

Returns:

Nodes spanning all sample faces, with spacing size / (shape - 1).

Return type:

CartesianMesh

class TetrahedralMesh(*, points, tetrahedra)[source]#

Bases: object

Conforming linear tetrahedra filling a finite rectangular sample.

Generation and local refinement use the required Gmsh dependency. Imported connectivity and numerical solves do not require Gmsh. Resolution is a target element size, not a guaranteed upper bound on every edge.

Parameters:
  • points (pint.Quantity) – Node positions with shape (N, 3) and length units.

  • tetrahedra (array_like of int) – Tetrahedral node indices with shape (T, 4). Cells must fill the bounding rectangle without cavities, duplicate cells, or nonmanifold faces.

property points: Quantity#

Return an independent copy of the unstructured node positions.

Returns:

Positions with shape (N, 3) and length units.

Return type:

pint.Quantity

property name: str#

Return the default overlay name for this mesh.

Returns:

Display name used in plot legends.

Return type:

str

property color: str#

Return the default color used when this mesh is an overlay.

Returns:

Slate color used for mesh edges.

Return type:

str

property tetrahedra: ndarray[tuple[Any, ...], dtype[int64]]#

Return an independent copy of element connectivity.

Returns:

Tetrahedral node indices with shape (T, 4).

Return type:

ndarray of int

property faces: dict[Literal['x_min', 'x_max', 'y_min', 'y_max', 'z_min', 'z_max'], ndarray[tuple[Any, ...], dtype[int64]]]#

Return exterior triangles grouped by the six physical sample faces.

Returns:

Independent triangle connectivity arrays with shape (F, 3).

Return type:

dict of str to ndarray of int

property shape: tuple[int]#

Return the storage shape of an unstructured nodal scalar field.

Returns:

(N,), where N is the number of nodes; these are not grid axes.

Return type:

tuple of int

property bounds: Quantity#

Return the physical lower and upper node coordinates.

Returns:

Bounds with shape (2, 3) and length units.

Return type:

pint.Quantity

property resolution: Quantity | None#

Return the requested global target element size, when generated.

Returns:

Scalar length quantity, or None for imported connectivity. Actual edges may exceed the target; local rules can request smaller sizes.

Return type:

pint.Quantity or None

copy()[source]#

Copy geometry and refinement rules without invoking the mesher.

Returns:

Independent snapshot unaffected by subsequent refinement.

Return type:

TetrahedralMesh

classmethod from_sample(*, sample, resolution)[source]#

Generate a mesh conforming to the sample and all region interfaces.

Box, layer, and sphere surfaces are fragmented together by Gmsh. Final material assignment retains the sample’s insertion precedence.

Parameters:
  • sample (StructuredMedium) – Finite rectangular geometry. A snapshot is retained for refinement.

  • resolution (pint.Quantity) – Positive scalar length setting the global target element size.

Returns:

Generated linear tetrahedra with shared nodes at region interfaces.

Return type:

TetrahedralMesh

refine_region(*, name, resolution)[source]#

Regenerate with a smaller target size in a named region; return None.

The rule covers the region’s geometric support, including parts later overridden by other regions. Generation succeeds before mutation.

Parameters:
  • name (str) – Name of a Box, Sphere, or Layer in the original sample snapshot.

  • resolution (pint.Quantity) – Positive scalar target length no larger than the global resolution.

Return type:

None

refine_near(*, objects, resolution, distance)[source]#

Regenerate with refinement near physical contact footprints.

The fine target applies within distance of each disk, including its interior and radius. It transitions to the global size over another distance. This changes the mesh, not source or detector quadrature.

Parameters:
  • objects (iterable of objects) – SurfaceSource, SurfaceSourceGroup, or SurfaceDetector objects. Geometry is snapshotted; contacts must fit on their sample face.

  • resolution (pint.Quantity) – Positive scalar target length no larger than the global resolution.

  • distance (pint.Quantity) – Positive scalar length of the fine neighborhood and transition band.

Return type:

None

plot(*, length_unit='mm', max_edges=20000, show=True)[source]#

Display tetrahedral edges to inspect local mesh resolution.

Parameters:
  • length_unit (str, optional) – Coordinate unit. Default is ‘mm’.

  • max_edges (int, optional) – Maximum number of evenly selected edges. Default is 20000. The title reports when only a subset is displayed.

  • show (bool, optional) – Display immediately when True. Default is True.

Returns:

Composable edge plot with physical coordinates and depth direction.

Return type:

plotly.graph_objects.Figure

class InfiniteP1[source]#

Bases: object

Evaluate Phi = P exp(-sqrt(mu_a/D) r) / (4 pi D r).

No boundary, Fresnel interface, or finite-source correction is applied. The observation window does not truncate the physical medium.

Notes

The Green function is Phi(r) = P exp(-sqrt(mu_a / D) r) / (4 pi D r). No physical outer boundary, Fresnel interface, or finite-source correction is applied. The observation window does not truncate the medium.

model_notes: tuple[str, ...] = ('InfiniteDiffusion is an analytical steady-state P1 Green function for an embedded isotropic point source in a homogeneous, unbounded medium.', 'The point-source singularity is excluded; boundaries, finite source footprints, and refractive interfaces are not modeled.', 'P1 diffusion is least reliable close to the source and where scattering does not dominate absorption.')#
solve(*, medium, source, mesh)[source]#

Solve the transport equation for the supplied physical configuration.

Parameters:
  • medium (HomogeneousMedium) – Infinite homogeneous material resolved at the source wavelength.

  • source (PointSource) – Embedded isotropic point source; no grid node may coincide with it.

  • mesh (CartesianMesh) – Cartesian nodes used for sampling or finite-element discretization.

Returns:

Analytical infinite-medium fluence rate in watts per square meter.

Return type:

ScalarField

Raises:
  • TypeError – If the medium or source is incompatible with the infinite model.

  • ValueError – If a grid node coincides with the singular point source.

class P1(*, boundaries)[source]#

Bases: object

Steady-state P1 diffusion with linear tetrahedral finite elements.

Geometry preparation is scoped to a solve or wavelength sweep. No persistent cache survives changes to a sample, source, mesh, or boundary configuration.

Parameters:

boundaries (mapping of str to RobinBoundary or ReflectingBoundary) – Conditions for exactly all six sample faces. Reflecting faces cannot carry illumination.

Notes

The steady-state P1 equation is -div(D grad(Phi)) + mu_a Phi = 0, with J = -D grad(Phi). Linear tetrahedra use centroid-sampled material coefficients. Fluence is continuous across interfaces; internal refractive-index jumps are unsupported. Footprint and unaligned interface errors require mesh refinement. Geometry preparation is scoped to a solve or sweep, with no persistent cache.

model_notes: tuple[str, ...] = ('Diffusion is a steady-state P1 approximation on a finite sample, using linear tetrahedra and centroid-sampled material coefficients.', 'Fluence is continuous across internal interfaces; refractive-index jumps are unsupported, while absorption and reduced scattering may vary.', 'P1 diffusion is least reliable close to illumination and in weakly scattering regions; mesh refinement does not remove this model error.', 'Robin effective_reflectance is supplied explicitly and is not inferred from refractive index.')#
solve(*, medium, source, mesh)[source]#

Solve the transport equation for the supplied physical configuration.

Parameters:
Returns:

Finite-element fluence, element flux, boundary fields, and power balance.

Return type:

SimulationResult

Raises:
  • TypeError – If the medium or source is incompatible with the finite model.

  • ValueError – If the mesh does not span the sample, interfaces have refractive-index jumps, or a source does not fit on an illuminated Robin face.

  • SourceResolutionError – If no boundary quadrature point resolves the illumination footprint.

class TransientP1(*, boundaries, times, power_profile, energy_speed)[source]#

Bases: object

Time-dependent P1 transport on a finite structured sample.

Parameters:
  • boundaries (mapping of str to RobinBoundary or ReflectingBoundary) – Explicit conditions on all six faces. The illuminated face must be Robin.

  • times (pint.Quantity) – Strictly increasing times in seconds or compatible units, shape (N,), N >= 2, beginning at zero.

  • power_profile (array_like of float) – Nonnegative dimensionless multipliers for source optical power, shape (N,), beginning at zero. Values are linearly interpolated between times.

  • energy_speed (pint.Quantity) – Positive uniform transport energy speed with length/time units. It is supplied explicitly rather than inferred from refractive index.

Notes

Initial fluence and current are zero. Linear tetrahedra represent nodal fluence; element-centered P1 currents obey their own relaxation equation. Absorption and reduced scattering are sampled at element centroids, so layered or heterogeneous media require interface and mesh convergence. Time integration uses implicit midpoint with piecewise-linear input. Matched internal refractive indices are required. P1 is not full radiative transfer, especially at early times or close to a source. Instantaneous boundary partial currents and Lambertian detector acceptance remain approximations.

model_notes = ('Transient P1 uses implicit midpoint and element-centered current relaxation; it is not time-dependent diffusion or full radiative transfer.', 'Initial fluence and current are zero; source samples define a nonnegative piecewise-linear coupled power profile.', 'The uniform energy speed is explicit and internal refractive-index jumps are unsupported.', 'P1 may be inaccurate at early times and near sources; check mesh and time convergence against an independent transport reference.')#
solve(*, medium, source, mesh)[source]#

Integrate coupled P1 fluence and current on a fixed finite mesh.

Parameters:
Returns:

Per-time nodal fluence, element current, boundary fields, and interval energy diagnostics. Detector signals are added by Simulation.

Return type:

TransientResult

class TransientResult(*, times, frames, stored_energy, absorbed_power, incoming_power, escaping_power, interval_energy_residual)[source]#

Bases: object

Time-resolved fields and power accounting for a finite P1 simulation.

Parameters:
  • times (pint.Quantity) – Simulation times with time units, shape (N,).

  • frames (tuple of SimulationResult) – Fields and per-face boundary snapshots at each time, length N.

  • stored_energy (pint.Quantity) – Integrated radiation energy, shape (N,), with energy units.

  • absorbed_power (pint.Quantity) – Integrated absorption, shape (N,), with power units.

  • incoming_power (pint.Quantity) – Incoming coupled power, shape (N,), with power units.

  • escaping_power (pint.Quantity) – Signed total escaping power, shape (N,), with power units.

  • interval_energy_residual (pint.Quantity) – Midpoint energy-balance residual for each interval, shape (N-1,), with power units. This is a numerical conservation diagnostic, not a measure of transport accuracy.

property detector_power: dict[str, Quantity]#

Return each detector’s time-resolved collected power.

Returns:

Detector names mapped to signed power arrays of shape (N,). Aperture integration uses the existing Lambertian angular model.

Return type:

dict of str to pint.Quantity

property net_outward_power: Quantity#

Return escaping minus incoming power over the complete boundary.

Returns:

Signed net outward power, shape (N,), with power units.

Return type:

pint.Quantity

class SP3(*, boundaries)[source]#

Bases: object

Solve two coupled simplified P3 moments using tetrahedral elements.

Parameters:

boundaries (mapping of str to RobinBoundary or ReflectingBoundary) – Conditions on all six faces. Robin boundaries must have zero effective reflectance, corresponding to a matched-index vacuum boundary.

Notes

Each material supplies its phase function. Henyey–Greenstein materials require anisotropy; isotropic, Rayleigh, and tabulated functions provide their own first three normalized Legendre moments. Illumination is isotropic over the incoming hemisphere. Fluence is the zeroth moment, not the first composite unknown. The implementation assumes continuous composite moments across internal interfaces and rejects index jumps. SP3 is an approximation, and agreement with SP3 slab references does not establish accuracy against radiative transfer for a particular sensor.

model_notes: tuple[str, ...] = ("SP3 is a steady-state simplified P3 angular-moment approximation; it uses each material's normalized phase-function moments through degree 3.", 'SP3 assumes isotropic incoming diffuse radiance, requires zero-reflectance Robin conditions on illuminated faces, permits reflecting unilluminated faces, and requires equal internal refractive indices.', 'SP3 agreement with a slab reference verifies this implementation for that case, not accuracy for arbitrary geometries or sensors.', 'Detector angular acceptance uses a separate Lambertian approximation.')#
solve(*, medium, source, mesh)[source]#

Solve the finite sample for one source wavelength.

Parameters:
Returns:

Zeroth-moment fluence, first-moment flux, boundary fields, energy balance, and composite fields in moments.

Return type:

SimulationResult

class P3(*, boundaries)[source]#

Bases: object

Full steady-state three-dimensional P3 transport on a finite sample.

Parameters:

boundaries (mapping of str to RobinBoundary) – Six matched-index faces with zero effective reflectance. Reflecting and index-mismatched boundaries are not implemented by this P3 solver.

Notes

Six even harmonics are solved with linear tetrahedral FEM; ten odd harmonics are reconstructed elementwise. Materials provide normalized scattering phase-function moments. Illumination is isotropic over the incoming hemisphere. P3 is an angular approximation and requires validation for the intended configuration.

model_notes: tuple[str, ...] = ('P3 is a steady-state full three-dimensional angular-moment approximation through degree 3, not a solution of the full radiative transfer equation.', 'P3 assumes isotropic incoming diffuse radiance and supports only zero-reflectance Robin faces with equal refractive index throughout; reflecting faces and index jumps are unsupported.', 'Detector angular acceptance uses a Lambertian approximation; validate the selected model against an independent reference for the intended use.')#
solve(*, medium, source, mesh)[source]#

Solve the P3 moment equations at the source wavelength.

Parameters:
Returns:

Fluence, element-centered flux, detector boundary fields, and six named nodal even-moment coefficients.

Return type:

SimulationResult

class TransportSolver(*args, **kwargs)[source]#

Bases: Protocol

Structural interface for solvers accepted by Simulation.

Implementations choose their supported medium and source types and validate those configurations at runtime. No inheritance from this protocol is needed.

solve(*, medium, source, mesh)[source]#

Solve the transport problem on a mesh supported by the implementation.

Parameters:
Returns:

Transport solution, or a fluence field wrapped by Simulation.run.

Return type:

SimulationResult, TransientResult, or ScalarField

class Simulation(*, medium, source, mesh, solver, detectors=None)[source]#

Bases: object

Compose physical geometry, illumination, a transport solver, and detectors.

Parameters:
  • medium (HomogeneousMedium or StructuredMedium) – Physical material configuration, compatible with the chosen solver.

  • source (PointSource, UniformSurfaceSource, or iterable of SurfaceSource) – Illumination configuration. An iterable of disk sources is converted automatically to a SurfaceSourceGroup for one simultaneous solve.

  • mesh (CartesianMesh or TetrahedralMesh) – Nodal coordinates for sampling or finite-element discretization.

  • solver (TransportSolver) – Transport model implementing the keyword-only solve protocol.

  • detectors (mapping of str to SurfaceDetector, or None, optional) – Nonempty names mapped to passive contact detectors. None disables detector measurements. Default is None.

validate(*, wavelengths=None)[source]#

Inspect configuration, material coverage, and mesh footprint sampling.

Parameters:

wavelengths (pint.Quantity or None, optional) – One-dimensional sweep wavelengths with length units. None checks the monochromatic source wavelength or the complete broadband source grid.

Returns:

Independent errors, cautions, solver assumptions and limits, and sampled source and detector areas. Validation does not solve transport or establish mesh convergence.

Return type:

ValidationReport

run()[source]#

Solve the configured transport problem and evaluate all named detectors.

Returns:

Monochromatic fields and measurements, or broadband detector spectra, trapezoidal optical and electrical integrals, and reference solves. Broadband integration uses exactly the source spectrum’s grid and endpoints; refine that grid to assess spectral quadrature error.

Return type:

SimulationResult, BroadbandSimulationResult, or TransientResult

sweep(*, wavelengths, optical_power=None)[source]#

Solve wavelengths in supplied order without mutating this configuration.

optical_power may be a scalar or a same-length vector of powers. When omitted, every solve uses the configured source’s optical_power. This is a set of monochromatic solves, not broadband spectral integration.

Parameters:
  • wavelengths (pint.Quantity) – Nonempty one-dimensional vector of positive vacuum wavelengths.

  • optical_power (pint.Quantity or None, optional) – Positive scalar power or vector matching wavelengths. None retains the configured source power for every monochromatic solve. Default is None.

Returns:

Ordered independent monochromatic solutions. Finite sweeps reuse geometry but rebuild the wavelength-dependent operator and factorization.

Return type:

SpectralSimulationResult

Notes

These are independent monochromatic powers, not a broadband spectral integral. Finite sweeps reuse geometry, material labels, source footprint, and boundary quadrature once per call. Each wavelength gets a new bulk operator and sparse factorization.

mesh_convergence(*, mesh_shapes=None, mesh_resolutions=None, contact_resolution=None, contact_distance=None, power_rtol=0.01, area_rtol=0.02, power_atol=None, required_consecutive=2)[source]#

Compare detector signals and footprint sampling across explicit meshes.

Parameters:
  • mesh_shapes (iterable of tuple of int or None, optional) – At least two coarse-to-fine Cartesian node shapes. Each shape must refine at least one axis and coarsen none. Supply this or mesh_resolutions, but not both. Default is None.

  • mesh_resolutions (iterable of pint.Quantity or None, optional) – At least two strictly decreasing global tetrahedral target sizes. Supply this or mesh_shapes, but not both. Default is None.

  • contact_resolution (pint.Quantity or None, optional) – Local target element size near disk sources and detectors. Required with contact_distance; applies only to tetrahedral studies. Default is None.

  • contact_distance (pint.Quantity or None, optional) – Positive distance defining each local contact refinement zone. Default is None.

  • power_rtol (float, optional) – Nonnegative relative power tolerance against adjacent and finest meshes. Default is 0.01.

  • area_rtol (float, optional) – Nonnegative relative tolerance of sampled source and detector areas against their geometric areas. Default is 0.02.

  • power_atol (pint.Quantity or None, optional) – Nonnegative absolute power tolerance. None means zero watts. Default is None.

  • required_consecutive (int, optional) – Positive number of consecutive passing refinements required at the fine end of the mesh sequence. Default is 2.

Returns:

Per-level fields, powers, areas, failures, and a mesh recommendation only when the final refinement sequence meets all requested criteria.

Return type:

DetectorConvergenceResult

convergence_study(*, mesh_shapes=None, mesh_resolutions=None, contact_resolution=None, contact_distance=None, power_rtol=0.01, area_rtol=0.02, power_atol=None, required_consecutive=2)#

Compare detector signals and footprint sampling across explicit meshes.

Parameters:
  • mesh_shapes (iterable of tuple of int or None, optional) – At least two coarse-to-fine Cartesian node shapes. Each shape must refine at least one axis and coarsen none. Supply this or mesh_resolutions, but not both. Default is None.

  • mesh_resolutions (iterable of pint.Quantity or None, optional) – At least two strictly decreasing global tetrahedral target sizes. Supply this or mesh_shapes, but not both. Default is None.

  • contact_resolution (pint.Quantity or None, optional) – Local target element size near disk sources and detectors. Required with contact_distance; applies only to tetrahedral studies. Default is None.

  • contact_distance (pint.Quantity or None, optional) – Positive distance defining each local contact refinement zone. Default is None.

  • power_rtol (float, optional) – Nonnegative relative power tolerance against adjacent and finest meshes. Default is 0.01.

  • area_rtol (float, optional) – Nonnegative relative tolerance of sampled source and detector areas against their geometric areas. Default is 0.02.

  • power_atol (pint.Quantity or None, optional) – Nonnegative absolute power tolerance. None means zero watts. Default is None.

  • required_consecutive (int, optional) – Positive number of consecutive passing refinements required at the fine end of the mesh sequence. Default is 2.

Returns:

Per-level fields, powers, areas, failures, and a mesh recommendation only when the final refinement sequence meets all requested criteria.

Return type:

DetectorConvergenceResult

spectral_convergence(*, wavelength_grids, include_table_knots=True, power_rtol=0.01, photocurrent_rtol=0.01, power_atol=None, photocurrent_atol=None, required_consecutive=2)[source]#

Check broadband power and current stability across wavelength grids.

Parameters:
  • wavelength_grids (iterable of pint.Quantity) – At least two nested coarse-to-fine wavelength vectors spanning the original source interval. Source knots are always retained.

  • include_table_knots (bool, optional) – Include material and responsivity knots inside the interval. The resulting inspectable grids must still add samples. Default is True.

  • power_rtol (float, optional) – Nonnegative relative optical-power tolerance. Default is 0.01.

  • photocurrent_rtol (float, optional) – Nonnegative relative current tolerance for detectors with response. Default is 0.01.

  • power_atol (pint.Quantity or None, optional) – Nonnegative absolute optical-power tolerance. None means zero watts. Default is None.

  • photocurrent_atol (pint.Quantity or None, optional) – Nonnegative absolute current tolerance. None means zero amperes. Default is None.

  • required_consecutive (int, optional) – Consecutive passing refinements required at the fine end. Default is 2.

Returns:

Per-level spectra, measurements, changes, and failures. A wavelength grid is recommended only after a stable final refinement sequence.

Return type:

SpectralConvergenceResult

Notes

Geometry, source data, and detector response remain fixed. This checks wavelength integration; assess spatial mesh and model accuracy separately.

plot_system(*, wavelength=None, length_unit='mm', show=True)[source]#

Display the physical sample, source, and detector geometry in 3D.

Parameters:
  • wavelength (pint.Quantity or None, optional) – Display wavelength for material properties. None uses the source wavelength for monochromatic sources. Broadband sources with spectral materials require an explicit display wavelength.

  • length_unit (str, optional) – Length unit used for displayed or exported coordinates. Default is ‘mm’.

  • show (bool, optional) – Whether to display the figure immediately. The figure is always returned. Default is True.

Returns:

Sample construction geometry with source and detector overlays.

Return type:

plotly.graph_objects.Figure

class ValidationReport(*, errors, warnings, source_sampled_area, detector_sampled_areas, model_notes=())[source]#

Bases: object

Configuration errors, numerical cautions, and sampled footprint areas.

Parameters:
  • errors (tuple of str) – Configuration errors that must be corrected before solving.

  • warnings (tuple of str) – Numerical cautions that do not prevent a solve.

  • source_sampled_area (pint.Quantity or None) – Boundary quadrature area sampled by the source, when available.

  • detector_sampled_areas (mapping of str to pint.Quantity) – Boundary quadrature area sampled by each valid detector.

  • model_notes (tuple of str) – Assumptions and known limits of the configured transport solver.

Notes

Passing validation does not establish mesh convergence or physical model accuracy. This report is a snapshot and never caches a prepared operator.

property valid: bool#

Report whether any configuration errors were found.

Returns:

True when no errors were found; warnings may still be present.

Return type:

bool

summary()[source]#

Format the validation findings for display.

Returns:

Human-readable findings and sampled areas with physical units.

Return type:

str

Fields and results#

class ScalarField(*, mesh, values, name, metadata=None)[source]#

Bases: object

Unit-bearing scalar samples at Cartesian or unstructured mesh nodes.

Parameters:
  • mesh (CartesianMesh or TetrahedralMesh) – Nodal coordinates for sampling or finite-element discretization.

  • values (pint.Quantity) – Finite nodal scalar values with shape equal to mesh.shape: Cartesian axis counts or (N,) for an unstructured mesh. The supplied physical units are retained.

  • name (str) – Nonempty name identifying this object.

  • metadata (mapping of str to object, or None, optional) – Field provenance and optional physical sample bounds. Default is None.

resample(*, resolution)[source]#

Interpolate a tetrahedral nodal field onto a Cartesian display grid.

Parameters:

resolution (pint.Quantity) – Positive scalar or (3,) length specifying maximum display spacing. This controls interpolation sampling, not FEM accuracy.

Returns:

Independent Cartesian field with interpolation provenance. Values use linear basis functions from the original tetrahedra; the source field and unsmoothed element flux are unchanged.

Return type:

ScalarField

plot(*, view='volume', scale='linear', length_unit='mm', opacity=None, isosurface_count=None, display_resolution=None, overlays=None, show=True)[source]#

Plot the scalar field with optional physical geometry overlays.

Meshes, sources, detectors, and layers can be overlaid. Each object’s name sets its legend label. Full-face sources and layers require physical sample bounds recorded by the finite solver.

Parameters:
  • view ({'volume', 'isosurfaces', 'slices'}, optional) – Three-dimensional scalar-field rendering mode. Default is ‘volume’.

  • scale ({'linear', 'log'}, optional) – Display scaling. Logarithmic scaling requires strictly positive values. Default is ‘linear’.

  • length_unit (str, optional) – Length unit used for displayed or exported coordinates. Default is ‘mm’.

  • opacity (float or None, optional) – Initial surface opacity in [0, 1]. None selects the rendering default. The volume view exposes an interactive opacity slider. Default is None.

  • isosurface_count (int or None, optional) – Initial positive number of iso levels for volume or isosurface rendering. Both views expose a density slider. None uses 8 for volume and 6 for isosurfaces; invalid for slices. Default is None.

  • display_resolution (pint.Quantity or None, optional) – Required maximum display spacing for tetrahedral fields, as a scalar or (3,) length. The interpolated grid is for visualization only. Default is None; Cartesian fields already have a grid.

  • overlays (iterable of objects or None, optional) – Meshes, sources, detectors, or layers implementing the plotting hook. Their name sets the legend label. Full-face sources and layers require finite-sample bounds. Default is None.

  • show (bool, optional) – Whether to display the figure immediately. The figure is always returned. Default is True.

Returns:

Composable interactive figure, also displayed when show is True.

Return type:

plotly.graph_objects.Figure

Notes

Logarithmic rendering rejects nonpositive data rather than clipping it. Full-face source and layer overlays require physical sample bounds saved by the finite solver; an infinite observation window is not a physical sample.

class VectorField(*, positions, values, name)[source]#

Bases: object

Element-centered vectors, without smoothing across material interfaces.

Parameters:
  • positions (pint.Quantity) – Element-center coordinates, shape (N, 3), with length units; N > 0.

  • values (pint.Quantity) – Finite vector values, shape (N, 3), with physical units. Values are not smoothed across material interfaces.

  • name (str) – Nonempty name identifying this object.

plot(*, max_vectors=500, length_unit='mm', show=True)[source]#

Create an interactive visualization of this object.

Parameters:
  • max_vectors (int, optional) – Positive maximum number of evenly selected element-centered arrows. Default is 500.

  • length_unit (str, optional) – Length unit used for displayed or exported coordinates. Default is ‘mm’.

  • show (bool, optional) – Whether to display the figure immediately. The figure is always returned. Default is True.

Returns:

Composable interactive figure, also displayed when show is True.

Return type:

plotly.graph_objects.Figure

class BoundaryField(*, face, positions, area_weights, escaping_irradiance, sample_origin, sample_size, wavelength)[source]#

Bases: object

Snapshot of escaping irradiance at boundary triangle quadrature points.

positions, area_weights, and escaping_irradiance share a leading shape. Escaping irradiance includes the incident-field correction on a source face. It is not an angle-resolved radiance.

Parameters:
  • face ({'x_min', 'x_max', 'y_min', 'y_max', 'z_min', 'z_max'}) – Axis-aligned sample face; min and max refer to outward boundaries.

  • positions (pint.Quantity) – Cartesian sampling coordinates with length units and trailing axis (3,).

  • area_weights (pint.Quantity) – Positive quadrature area weights with area units; shape matches the leading axes of positions.

  • escaping_irradiance (pint.Quantity) – Escaping diffuse irradiance with power-per-area units; shape matches area_weights. Values are not clipped to zero.

  • sample_origin (pint.Quantity) – Physical sample lower corner, shape (3,), with length units.

  • sample_size (pint.Quantity) – Positive physical sample extents, shape (3,), with length units.

  • wavelength (pint.Quantity) – Positive scalar vacuum wavelength, with length units.

property escaping_power: Quantity#

Integrate the escaping irradiance over the complete boundary face.

Returns:

Integral of escaping irradiance over this entire face, with power units.

Return type:

pint.Quantity

class SimulationResult(*, fluence, flux=None, moments=None, energy_balance=None, outgoing_power_by_face=None, diagnostics=None, boundary_fields=None, detectors=None)[source]#

Bases: object

Monochromatic transport fields, energy accounting, and measurements.

Parameters:
  • fluence (ScalarField) – Nodal fluence rate, with power-per-area units.

  • flux (VectorField or None, optional) – Element-centered diffuse current density, with power-per-area units. Default is None.

  • moments (mapping of str to ScalarField, or None, optional) – Additional solver-specific nodal moment fields.

  • energy_balance (mapping of str to pint.Quantity, or None, optional) – Incoming, absorbed, net outward, and residual power accounting. Default is None.

  • outgoing_power_by_face (mapping of str to pint.Quantity, or None, optional) – Escaping transmitted power per complete sample face; not a finite aperture measurement. Default is None.

  • diagnostics (mapping of str to object, or None, optional) – Numerical provenance, residuals, geometry statistics, or timing quantities. Default is None.

  • boundary_fields (mapping of str to BoundaryField, or None, optional) – Per-face snapshots of escaping-irradiance quadrature samples. Default is None.

  • detectors (mapping of str to DetectorResult, or None, optional) – Named finite-aperture measurements already evaluated on this solution. Default is None.

Variables:
  • fluence (ScalarField) – Nodal fluence rate with power-per-area units.

  • flux (VectorField or None) – Element-centered current density, absent for the infinite Green function.

  • boundary_fields (dict of str to BoundaryField) – Quadrature snapshots for finite-sample contact measurements.

  • detectors (dict of str to DetectorResult) – Evaluated measurements, keyed by detector name.

  • diagnostics (dict of str to object) – Solver provenance, residuals, and resolution statistics.

property source_sampled_area: Quantity | None#

Return the sampled source footprint area, when available.

Returns:

Sampled area with physical units, or None for an infinite solution.

Return type:

pint.Quantity or None

property source_geometric_area: Quantity | None#

Return the exact source footprint area, when available.

Returns:

Geometric area with physical units, or None for an infinite solution.

Return type:

pint.Quantity or None

property linear_relative_residual: float | None#

Return the relative linear-system residual, when available.

Returns:

Relative residual, or None for an analytical solution.

Return type:

float or None

property minimum_fluence: Quantity | None#

Return the minimum nodal fluence, when recorded by the solver.

Returns:

Minimum fluence rate; negative values are not clipped.

Return type:

pint.Quantity or None

summary(*, convergence=None)[source]#

Format detector powers, sampling, energy balance, and diagnostics.

Parameters:

convergence (DetectorConvergenceResult or None, optional) – Separately supplied convergence study to summarize. The caller must verify it applies to this result; None means none was supplied. Default is None.

Returns:

Human-readable result summary with the stored physical units.

Return type:

str

property detector_power: dict[str, Quantity]#

Return collected powers keyed by detector name.

Returns:

Collected optical powers keyed by detector name.

Return type:

dict of str to pint.Quantity

class DetectorResult(*, collected_power, sampled_area, geometric_area, angular_fraction, wavelength, minimum_escaping_irradiance, detector, photocurrent=None)[source]#

Bases: object

Finite-aperture diffuse collection and quadrature provenance.

Parameters:
  • collected_power (pint.Quantity) – Integrated accepted diffuse optical power, with power units.

  • sampled_area (pint.Quantity) – Aperture area represented by selected quadrature weights. It is not normalized to the geometric area.

  • geometric_area (pint.Quantity) – Exact circular aperture area, with area units.

  • angular_fraction (float) – Fraction of Lambertian escaping irradiance accepted by the cone.

  • wavelength (pint.Quantity) – Positive scalar vacuum wavelength, with length units.

  • minimum_escaping_irradiance (pint.Quantity) – Smallest sampled escaping irradiance inside the aperture. Negative values flag discretization artifacts and remain unchanged.

  • detector (SurfaceDetector) – Snapshot of the aperture and angular collection configuration.

  • photocurrent (pint.Quantity or None, optional) – Linear electrical current in amperes when responsivity is configured. Default is None.

class MeshConvergence(*, simulation, mesh_shapes=None, mesh_resolutions=None, contact_resolution=None, contact_distance=None, power_rtol=0.01, area_rtol=0.02, power_atol=None, required_consecutive=2, progress=True)[source]#

Bases: object

Configure a detector-power mesh-refinement study at one wavelength.

Parameters:
  • simulation (Simulation) – Finite simulation with a surface source and named detectors. Its source wavelength is used for every mesh.

  • mesh_shapes (iterable of tuple of int or None, optional) – Cartesian node shapes, ordered from coarse to fine. Supply exactly one of this and mesh_resolutions. Default is None.

  • mesh_resolutions (iterable of pint.Quantity or None, optional) – Strictly decreasing tetrahedral target sizes with length units. Default is None.

  • contact_resolution (pint.Quantity or None, optional) – Tetrahedral target size near source and detector disks. Supply with contact_distance. Default is None.

  • contact_distance (pint.Quantity or None, optional) – Distance from each contact defining local refinement. Default is None.

  • power_rtol (float, optional) – Relative detector-power tolerance. Default is 0.01.

  • area_rtol (float, optional) – Relative footprint-area tolerance. Default is 0.02.

  • power_atol (pint.Quantity or None, optional) – Absolute detector-power tolerance, with power units. None uses zero. Default is None.

  • required_consecutive (int, optional) – Number of passing refinements required at the fine end. Default is 2.

  • progress (bool, optional) – Print a live table as mesh levels finish. Default is True.

Notes

A passing mesh study does not establish the accuracy of the transport model. The simulation is sampled at run time and is not mutated by the study. Set the MomentRT.convergence logger to INFO for progress and values.

run()[source]#

Run the mesh study with the current simulation configuration.

Returns:

Per-mesh detector powers, footprint diagnostics, and convergence assessment. Unresolved levels and negative outputs are retained.

Return type:

DetectorConvergenceResult

class DetectorConvergenceResult(*, meshes, results, detectors, source_geometric_area, wavelength, level_errors, power_rtol, area_rtol, power_atol, required_consecutive)[source]#

Bases: object

Detector signals and footprint sampling on successively refined meshes.

Parameters:
  • meshes (sequence of CartesianMesh or TetrahedralMesh) – Coarse-to-fine meshes used in the study.

  • results (sequence of SimulationResult or None) – Per-level solutions; None records an unresolved source footprint.

  • detectors (mapping of str to SurfaceDetector) – Named passive contact detectors.

  • source_geometric_area (pint.Quantity) – Exact source footprint area, with area units.

  • wavelength (pint.Quantity) – Positive scalar vacuum wavelength, with length units.

  • level_errors (sequence of mapping of str to str) – Per-level resolution failures and negative-field diagnostics.

  • power_rtol (float) – Nonnegative relative power tolerance against adjacent and finest meshes.

  • area_rtol (float) – Nonnegative relative tolerance of sampled source and detector areas against their geometric areas.

  • power_atol (pint.Quantity) – Nonnegative absolute power tolerance, with power units.

  • required_consecutive (int) – Positive number of consecutive passing refinements required at the fine end of the mesh sequence.

Variables:
  • node_counts (numpy.ndarray of int) – Number of nodes at each refinement level.

  • tetrahedron_counts (numpy.ndarray of int) – Number of tetrahedra at each refinement level.

  • source_sampled_area (pint.Quantity) – Sampled illumination areas in square meters, one per level.

  • source_area_relative_error (numpy.ndarray of float) – Absolute relative errors against the exact source footprint area.

  • detector_power (dict of str to pint.Quantity) – Per-detector collected power vectors in watts. Unavailable powers are NaN.

  • detector_sampled_area (dict of str to pint.Quantity) – Per-detector sampled aperture areas in square meters. Unsampled apertures have zero sampled area; unresolved sources produce NaN.

  • detector_geometric_area (dict of str to pint.Quantity) – Exact aperture area for each detector.

  • detector_area_relative_error (dict of str to numpy.ndarray) – Absolute relative aperture-area errors at each mesh level.

  • power_relative_change (dict of str to numpy.ndarray) – Relative power differences against the preceding level. The first difference and unavailable values are NaN.

  • power_relative_to_finest (dict of str to numpy.ndarray) – Relative power differences against the finest level; unavailable values are NaN.

  • meets_tolerances (numpy.ndarray of bool) – Per-level power, area, and resolution checks.

  • stable_refinements (numpy.ndarray of int) – Number of consecutive passing refinements ending at each level.

  • recommended_index (int or None) – Index of the recommended mesh; None if the final sequence fails.

Notes

Only a stable final sequence can support a recommendation. Sampled source and detector areas must approximate their exact geometric areas, and powers must meet adjacent-level and finest-level tolerances. Unresolved levels and negative fields remain visible; passing these checks is not proof of accuracy of the P1 approximation.

property converged: bool#

Report whether the final refinement sequence supports a mesh recommendation.

Returns:

Whether the final stable refinement sequence supports a recommendation.

Return type:

bool

property recommended_mesh: CartesianMesh | TetrahedralMesh | None#

Return the recommended mesh when the convergence criteria are met.

Returns:

Recommended existing mesh, or None when criteria are not met.

Return type:

CartesianMesh, TetrahedralMesh, or None

property recommended_shape: tuple[int, int, int] | None#

Return the node shape of the recommended mesh, if any.

Returns:

Recommended node counts, or None when no mesh is recommended.

Return type:

tuple of int or None

property recommended_resolution: Quantity | None#

Return the target size of the recommended generated tetrahedral mesh.

Returns:

Scalar target element size, or None for Cartesian or imported meshes.

Return type:

pint.Quantity or None

property records: list[dict[str, object]]#

Return per-level records with quantities intact and explicit failure flags.

Returns:

Per-level quantities, detector diagnostics, and explicit failure flags.

Return type:

list of dict

assessment()[source]#

Explain the final convergence decision and any blocking checks.

Returns:

Final passing-refinement count, requested tolerances, recommendation, and reasons the relevant refinement failed, when applicable.

Return type:

str

summary()[source]#

Describe mesh levels, detector powers, failures, and the assessment.

Returns:

Labeled per-level quantities, footprint errors, relative power changes, and the final mesh recommendation, if available.

Return type:

str

plot(*, power_unit='mW', area_unit='mm^2', show=True)[source]#

Compare powers, aperture areas, and source area against mesh node count.

Shaded bands mark power tolerance around each finest-mesh detector value and area tolerance around each exact footprint area. Power bands include the absolute tolerance and are omitted for unresolved finest values. Passing these bands alone does not establish convergence: the study also checks adjacent refinements and diagnostic failures.

Parameters:
  • power_unit (str, optional) – Power unit used for plotted detector signals. Default is ‘mW’.

  • area_unit (str, optional) – Area unit used for plotted sampled and geometric areas. Default is ‘mm^2’.

  • show (bool, optional) – Whether to display the figure immediately. The figure is always returned. Default is True.

Returns:

Composable interactive figure, also displayed when show is True.

Return type:

plotly.graph_objects.Figure

class SpectralSimulationResult(*, wavelengths, results, diagnostics=None)[source]#

Bases: object

Ordered independent monochromatic solves on one instrument geometry.

Parameters:
  • wavelengths (pint.Quantity) – Nonempty one-dimensional vector of positive vacuum wavelengths.

  • results (sequence of SimulationResult) – One solution for each wavelength, in the same order. All solutions must contain the same detector names.

  • diagnostics (mapping of str to object, or None, optional) – Numerical provenance, residuals, geometry statistics, or timing quantities. Default is None.

Variables:
  • wavelengths (pint.Quantity) – Supplied vacuum wavelengths in their original units and order.

  • results (tuple of SimulationResult) – One independent solution at each wavelength.

  • diagnostics (dict of str to object) – Sweep preparation count and unit-bearing preparation, solve, and total timings when created by Simulation.sweep.

property detectors: dict[str, tuple[DetectorResult, ...]]#

Return each detector’s measurements in supplied wavelength order.

Returns:

Detector names mapped to monochromatic measurements, including collected power and sampled and geometric aperture areas. These are independent solves, not a broadband integral.

Return type:

dict of str to tuple of DetectorResult

property detector_power: dict[str, Quantity]#

Return collected powers keyed by detector name.

Returns:

Collected optical powers keyed by detector name.

Return type:

dict of str to pint.Quantity

plot(*, wavelength_unit='nm', power_unit='mW', show=True)[source]#

Plot collected power for each detector; no spectral integration is applied.

Parameters:
  • wavelength_unit (str, optional) – Length unit used for plotted vacuum wavelengths. Default is ‘nm’.

  • power_unit (str, optional) – Power unit used for plotted detector signals. Default is ‘mW’.

  • show (bool, optional) – Whether to display the figure immediately. The figure is always returned. Default is True.

Returns:

Composable interactive figure, also displayed when show is True.

Return type:

plotly.graph_objects.Figure

class BroadbandSimulationResult(*, spectrum, reference_results, reference_optical_power)[source]#

Bases: object

Broadband detector predictions and the underlying unit-power solves.

Parameters:
  • spectrum (SourceSpectrum) – Source spectral density and the integration wavelength grid.

  • reference_results (SpectralSimulationResult) – Independent monochromatic solves on the source grid, each excited by reference_optical_power. Their fields retain those reference units.

  • reference_optical_power (pint.Quantity) – Positive scalar optical power used for every reference solve.

property detector_power: dict[str, Quantity]#

Return the wavelength-integrated optical powers for named detectors.

Returns:

Accepted broadband optical powers in watts.

Return type:

dict of str to pint.Quantity

class BroadbandDetectorResult(*, wavelengths, spectral_power, responsivity=None, reference_measurements=None)[source]#

Bases: object

Collected spectral density and its explicit wavelength integrals.

Parameters:
  • wavelengths (pint.Quantity) – Strictly increasing positive vacuum wavelengths, shape (n,), n >= 2.

  • spectral_power (pint.Quantity) – Collected power density, shape (n,), with W / length units. Negative numerical outputs are retained. Integration uses the supplied endpoints.

  • responsivity (DetectorResponsivity or None, optional) – Linear electrical response. None leaves photocurrent unavailable. Default is None.

  • reference_measurements (sequence of DetectorResult or None, optional) – Measurements on the same aperture and mesh, one per wavelength. Supplies the sampled and geometric areas. Default is None.

Variables:
  • spectral_power (pint.Quantity) – Signed collected power density in its supplied W / length units.

  • collected_power (pint.Quantity) – Trapezoidal optical integral in watts.

  • photocurrent (pint.Quantity or None) – Trapezoidal electrical integral in amperes when responsivity is supplied.

  • responsivity (DetectorResponsivity or None) – Snapshot of the linear response used for electrical conversion.

  • sampled_area (pint.Quantity or None) – Shared sampled aperture area. None when no geometry was supplied.

  • geometric_area (pint.Quantity or None) – Shared exact aperture area. None when no geometry was supplied.

class SpectralConvergenceResult(*, wavelength_grids, results, detectors, level_errors, power_rtol, photocurrent_rtol, power_atol, photocurrent_atol, required_consecutive)[source]#

Bases: object

Detector power and photocurrent stability on nested wavelength grids.

Parameters:
  • wavelength_grids (sequence of pint.Quantity) – Increasing-resolution wavelength vectors over one fixed source interval.

  • results (sequence of BroadbandSimulationResult or None) – Per-level predictions. None retains a failed refinement.

  • detectors (mapping of str to SurfaceDetector) – Fixed detector geometry and optional electrical response.

  • level_errors (sequence of mapping of str to str) – Per-level solve failures and negative-field diagnostics.

  • power_rtol (float) – Nonnegative relative optical-power tolerance.

  • photocurrent_rtol (float) – Nonnegative relative electrical-current tolerance.

  • power_atol (pint.Quantity) – Nonnegative absolute optical-power tolerance.

  • photocurrent_atol (pint.Quantity) – Nonnegative absolute electrical-current tolerance.

  • required_consecutive (int) – Consecutive passing refinements required at the fine end.

Variables:
  • wavelength_grids (tuple of pint.Quantity) – Actual nested integration grids after required table knots are merged.

  • sample_counts (numpy.ndarray of int) – Number of wavelengths at each level.

  • detector_power (dict of str to pint.Quantity) – Integrated optical-power vectors in watts, with NaN for failed levels.

  • detector_photocurrent (dict of str to pint.Quantity) – Integrated current vectors in amperes for detectors with responsivity.

  • power_relative_change (dict of str to numpy.ndarray) – Adjacent power changes divided by the larger absolute adjacent value.

  • photocurrent_relative_change (dict of str to numpy.ndarray) – Adjacent current changes using the same normalization as power changes.

  • power_relative_to_finest (dict of str to numpy.ndarray) – Absolute power differences divided by the finest absolute power.

  • photocurrent_relative_to_finest (dict of str to numpy.ndarray) – Current differences relative to the finest absolute current.

  • meets_tolerances (numpy.ndarray of bool) – Per-level stability checks including failures and negative outputs.

  • recommended_index (int or None) – Recommended grid index, or None after an unresolved final sequence.

Notes

A recommendation requires adjacent-level stability and agreement with the finest result for every measured quantity. Failed or negative outputs are retained and prevent a recommendation from a failed final sequence. These criteria concern wavelength integration, not spatial or model accuracy.

property converged: bool#

Report whether the final sequence supports a wavelength recommendation.

Returns:

True when all detector quantities meet the final stability criteria.

Return type:

bool

property recommended_wavelengths: Quantity | None#

Return a copy of the recommended grid when tolerances are met.

Returns:

Increasing vacuum wavelengths, or None after an unresolved sequence.

Return type:

pint.Quantity or None

property records: list[dict[str, object]]#

Return per-level powers, currents, changes, and explicit failures.

Returns:

Records preserving physical units and all failed refinement levels.

Return type:

list of dict

summary()[source]#

Describe wavelength refinement outcomes and the final recommendation.

Returns:

Labeled sample counts, passing levels, failures, and recommendation.

Return type:

str

plot(*, power_unit='uW', current_unit='uA', show=True)[source]#

Plot integrated measurements against wavelength sample count.

Parameters:
  • power_unit (str, optional) – Optical-power display unit. Default is ‘uW’.

  • current_unit (str, optional) – Electrical-current display unit. Default is ‘uA’.

  • show (bool, optional) – Display immediately when True. Default is True.

Returns:

Composable power and optional photocurrent curves with failed gaps.

Return type:

plotly.graph_objects.Figure