"""
Absorbing random medium through fourth Born order
=================================================

Compare exactly the same seeded real-index fluctuations with and without
absorption. Both calculations retain four coherent scattering orders. The host
is lossless; absorption is confined to the finite voxel sample. These are
finite-sample coefficients, not converged infinite-medium transport properties.
"""

import matplotlib.pyplot as plt
import numpy as np

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

grid = Grid(
    shape=(8, 8, 8),
    spacing=30 * ureg.nanometer,
)

medium = GaussianMedium(
    background_refractive_index=1.33,
    refractive_index_std=0.002,
    correlation_length=60 * ureg.nanometer,
)

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

extinction_coefficient = 0.001

absorbing = volume.with_absorption(extinction_coefficient=extinction_coefficient)

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

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

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

reference = solver.solve(target=volume)

result = solver.solve(target=absorbing)

# %%
# Angular scattering through fourth order
# ----------------------------------------
# Sum complex amplitudes before evaluating intensity. The phase function is
# normalized by scattered power alone; absorbed power is not another direction.
# Azimuth averaging below is explicit because a finite realization need not be
# rotationally symmetric.
averaged = result.azimuth_average()

reference_averaged = reference.azimuth_average()

angles = result.angles.to("degree").magnitude

figure, axes = plt.subplots(1, 2, figsize=(11, 4), layout="constrained")

for index in range(4):
    label = f"Through order {index + 1}"

    axes[0].plot(angles, averaged.differential.to("1 / meter / steradian").magnitude[index], label=label)

    axes[1].plot(angles, averaged.phase_function.to("1 / steradian").magnitude[index], label=label)

axes[0].plot(
    angles,
    reference_averaged.differential.to("1 / meter / steradian").magnitude[-1],
    "k--",
    label="No absorption, order 4",
)

axes[1].plot(
    angles,
    reference_averaged.phase_function.to("1 / steradian").magnitude[-1],
    "k--",
    label="No absorption, order 4",
)

axes[0].set(xlabel="Scattering angle (degrees)", ylabel="Differential coefficient (m⁻¹ sr⁻¹)")

axes[1].set(xlabel="Scattering angle (degrees)", ylabel="Phase function (sr⁻¹)")

for axis in axes:
    axis.legend(fontsize="small")

plt.show()

# %%
# Absorbed power and the incident-field limit
# --------------------------------------------------
# At scattering order M, mu_a uses the cumulative internal field through M-1.
# First order therefore gives 4*pi*kappa/lambda_vacuum for uniform kappa.
# Subsequent orders include the change in local illumination from rescattering.
# This dissipation estimate and the truncated scattering calculation need not
# satisfy the optical theorem exactly at a finite Born order.
orders = np.arange(1, 5)

incident_limit = (4 * np.pi * extinction_coefficient / source.wavelength).to("1 / meter")

np.testing.assert_allclose(result.mu_a.magnitude[0], incident_limit.magnitude)

np.testing.assert_array_equal(reference.mu_a.magnitude, np.zeros(4))

absorption_figure, absorption_axis = plt.subplots(layout="constrained")

absorption_axis.plot(orders, result.mu_a.to("1 / meter").magnitude, "o-", label="Internal-field absorption")

absorption_axis.axhline(incident_limit.magnitude, color="black", linestyle="--", label="Incident-field limit")

absorption_axis.set(
    xlabel="Highest scattering order M",
    ylabel="Finite-sample absorption coefficient (m⁻¹)",
    xticks=orders,
)

absorption_axis.legend()

plt.show()

for index, coefficient in enumerate(result.mu_a.to("1 / meter").magnitude, start=1):
    print(f"Through scattering order {index}: mu_a = {coefficient:.6g} m⁻¹")

# %%
# Born-term diagnostics
# ---------------------
# Decreasing terms alone do not certify accuracy. Refine the grid, angular
# quadrature and sample size as well as comparing orders. Small differences
# between the curves are expected for this deliberately weak perturbation.
result.plot_field_norms()

plt.show()
