.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "gallery/validation/planar_slab_references.py" .. LINE NUMBERS ARE GIVEN BELOW. .. only:: html .. note:: :class: sphx-glr-download-link-note :ref:`Go to the end ` to download the full example code. .. rst-class:: sphx-glr-example-title .. _sphx_glr_gallery_validation_planar_slab_references.py: Compare P1 and SP3 with independent planar slab references ========================================================== Compare finite-element centerline fluence against two independent 1D solutions: a closed-form P1 diffusion slab and a matrix-exponential SP3 slab. These references check implementation and spatial discretization for this planar setup; they do not establish accuracy against radiative transfer or validate either model for a sensor geometry. .. GENERATED FROM PYTHON SOURCE LINES 10-20 .. code-block:: Python import os import matplotlib.pyplot as plt import numpy as np from scipy.linalg import expm import MomentRT ureg = MomentRT.ureg show_figures = os.environ.get("MOMENTRT_SPHINX_GALLERY") != "1" .. GENERATED FROM PYTHON SOURCE LINES 21-26 Configure a laterally uniform slab ---------------------------------- Reflecting side faces preserve a one-dimensional solution. Both models use the same homogeneous material, diffuse illumination, mesh, and matched-index top and bottom faces. .. GENERATED FROM PYTHON SOURCE LINES 26-80 .. code-block:: Python absorption = 20 / ureg.meter reduced_scattering = 1000 / ureg.meter anisotropy = 0.7 thickness = 4 * ureg.millimeter material = MomentRT.Material( absorption=absorption, reduced_scattering=reduced_scattering, refractive_index=1.4, anisotropy=anisotropy, phase_function=MomentRT.phase_function.HenyeyGreenstein(), ) sample = MomentRT.StructuredMedium( origin=np.zeros(3) * ureg.millimeter, size=np.array([2, 2, 4]) * ureg.millimeter, ) sample.add_background(material=material) mesh = MomentRT.CartesianMesh.from_sample(sample=sample, shape=(5, 5, 17)) source = MomentRT.UniformSurfaceSource( face="z_min", wavelength=970 * ureg.nanometer, optical_power=1 * ureg.milliwatt, ) open_face = MomentRT.RobinBoundary(effective_reflectance=0) boundaries = {face: MomentRT.ReflectingBoundary() for face in MomentRT.boundary.FACES} boundaries["z_min"] = open_face boundaries["z_max"] = open_face simulations = { "P1 diffusion": MomentRT.Simulation( medium=sample, source=source, mesh=mesh, solver=MomentRT.P1(boundaries=boundaries), ), "SP3": MomentRT.Simulation( medium=sample, source=source, mesh=mesh, solver=MomentRT.SP3(boundaries=boundaries), ), } depth = mesh.points[0, 0, :, 2].to("meter").magnitude length = thickness.to("meter").magnitude mu_a = absorption.to("1/meter").magnitude mu_s1 = reduced_scattering.to("1/meter").magnitude incident = source.optical_power.to("watt").magnitude / np.prod( sample.size[:2].to("meter").magnitude ) .. GENERATED FROM PYTHON SOURCE LINES 81-85 Calculate an independent closed-form P1 solution ------------------------------------------------------------ The homogeneous diffusion equation has hyperbolic solutions. Solve its two boundary equations directly, independently of the FEM matrix assembly. .. GENERATED FROM PYTHON SOURCE LINES 85-107 .. code-block:: Python diffusion_coefficient = 1 / (3 * (mu_a + mu_s1)) attenuation = np.sqrt(mu_a / diffusion_coefficient) beta = open_face.leakage_coefficient source_coefficient = 2 / (1 + open_face.effective_reflectance) top_row = np.array([beta, -diffusion_coefficient * attenuation]) bottom_row = np.array( [ diffusion_coefficient * attenuation * np.sinh(attenuation * length) + beta * np.cosh(attenuation * length), diffusion_coefficient * attenuation * np.cosh(attenuation * length) + beta * np.sinh(attenuation * length), ] ) constants = np.linalg.solve( np.vstack((top_row, bottom_row)), np.array([source_coefficient * incident, 0]), ) p1_reference = constants[0] * np.cosh(attenuation * depth) + constants[1] * np.sinh( attenuation * depth ) .. GENERATED FROM PYTHON SOURCE LINES 108-113 Calculate an independent SP3 matrix-exponential solution ------------------------------------------------------------ Integrate the first-order moment system through the slab and solve its Marshak conditions at both ends. This analytic 1D reference is independent of MomentRT's three-dimensional finite-element assembly. .. GENERATED FROM PYTHON SOURCE LINES 113-135 .. code-block:: Python mu_1 = mu_a + mu_s1 mu_2 = mu_a + mu_s1 * (1 + anisotropy) mu_3 = mu_a + mu_s1 * (1 + anisotropy + anisotropy**2) generator = np.array( [ [0, 0, -3 * mu_1, 0], [0, 0, 0, -7 * mu_3], [-mu_a, 2 * mu_a / 3, 0, 0], [2 * mu_a / 3, -(4 * mu_a + 5 * mu_2) / 9, 0, 0], ] ) transfer = expm(generator * length) top = np.array([[0.5, -0.125, 1, 0], [-0.125, 7 / 24, 0, 1]]) bottom = np.array([[-0.5, 0.125, 1, 0], [0.125, -7 / 24, 0, 1]]) initial = np.linalg.solve( np.vstack((top, bottom @ transfer)), np.array([2 * incident, -incident / 2, 0, 0]), ) states = np.array([expm(generator * position) @ initial for position in depth]) sp3_reference = states[:, 0] - 2 * states[:, 1] / 3 .. GENERATED FROM PYTHON SOURCE LINES 136-141 Compare FEM fields with the references -------------------------------------- The curves should approach their corresponding references as the mesh is refined. P1 and SP3 are different transport approximations, so their analytical references are distinct even when the numerical mesh is shared. .. GENERATED FROM PYTHON SOURCE LINES 141-161 .. code-block:: Python figure, axes = plt.subplots(figsize=(8, 5)) for label, simulation in simulations.items(): report = simulation.validate() print(f"{label} configuration:\n{report.summary()}") result = simulation.run() actual = result.fluence.values[2, 2, :].to("watt / meter**2").magnitude reference = p1_reference if label == "P1 diffusion" else sp3_reference relative_error = np.linalg.norm(actual - reference) / np.linalg.norm(reference) print(f"{label} relative L2 error against its slab reference: {relative_error:.3%}") axes.plot(depth * 1e3, actual, "o", label=f"{label} FEM") axes.plot(depth * 1e3, p1_reference, label="P1 analytical") axes.plot(depth * 1e3, sp3_reference, "--", label="SP3 matrix exponential") axes.set_xlabel("Depth into sample (mm)") axes.set_ylabel("Fluence rate (W m$^{-2}$)") axes.set_title("Finite-element fields and independent slab references") axes.grid(True, alpha=0.25) axes.legend() figure.tight_layout() plt.show() if show_figures else None .. image-sg:: /gallery/validation/images/sphx_glr_planar_slab_references_001.png :alt: Finite-element fields and independent slab references :srcset: /gallery/validation/images/sphx_glr_planar_slab_references_001.png :class: sphx-glr-single-img .. rst-class:: sphx-glr-script-out .. code-block:: none P1 diffusion configuration: Configuration valid Warning: Footprint sampling alone does not establish mesh convergence or transport accuracy. Model note: Diffusion is a steady-state P1 approximation on a finite sample, using linear tetrahedra and centroid-sampled material coefficients. Model note: Fluence is continuous across internal interfaces; refractive-index jumps are unsupported, while absorption and reduced scattering may vary. Model note: P1 diffusion is least reliable close to illumination and in weakly scattering regions; mesh refinement does not remove this model error. Model note: Robin effective_reflectance is supplied explicitly and is not inferred from refractive index. Source sampled area: 4×10⁻⁶ m² P1 diffusion relative L2 error against its slab reference: 0.004% SP3 configuration: Configuration valid Warning: Footprint sampling alone does not establish mesh convergence or transport accuracy. Model note: SP3 is a steady-state simplified P3 angular-moment approximation; it uses each material's normalized phase-function moments through degree 3. Model note: SP3 assumes isotropic incoming diffuse radiance, requires zero-reflectance Robin conditions on illuminated faces, permits reflecting unilluminated faces, and requires equal internal refractive indices. Model note: SP3 agreement with a slab reference verifies this implementation for that case, not accuracy for arbitrary geometries or sensors. Model note: Detector angular acceptance uses a separate Lambertian approximation. Source sampled area: 4×10⁻⁶ m² SP3 relative L2 error against its slab reference: 0.044% .. rst-class:: sphx-glr-timing **Total running time of the script:** (0 minutes 0.227 seconds) .. _sphx_glr_download_gallery_validation_planar_slab_references.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: planar_slab_references.ipynb ` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: planar_slab_references.py ` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: planar_slab_references.zip ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_