From 8ddb75a15e782cfa2efa52c4269c8274e3f403bc Mon Sep 17 00:00:00 2001 From: cfranken Date: Fri, 13 Nov 2026 10:32:03 -0800 Subject: [PATCH 1/2] Absorbed light per constituent, pigment partitions, chloroplast emission, ocean floor Development state of 0.2.0 before the code overhaul: - OceanLayerOptics carries absorbers (one component per absorber or absorption part), scatterers and inelastic components. - Pigment partitions of phytoplankton absorption (ProspectPigments, Bidigare1990Pigments) and absorption parts. - Absorbed power, photons and PAR per component from the solver's scalar irradiance; inelastic emission per layer. - Chlorophyll fluorescence driven by excitation pathways, with the chloroplast-level emission spectra used by Fluspect. - TabulatedLambertianBottom. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01TRfrLS11vLye7ZcoRFSe5B --- CHANGELOG.md | 53 +++- Project.toml | 2 +- README.md | 44 ++- data/bidigare_1990_pigments.csv | 192 ++++++++++++ data/fluspect_chloroplast_emission.csv | 237 ++++++++++++++ data/prospect_d_pigment_absorption.csv | 414 +++++++++++++++++++++++++ docs/make.jl | 2 +- docs/src/consumer_api.md | 118 ++++++- docs/src/example.md | 66 ++-- docs/src/gallery.md | 72 ++++- docs/src/index.md | 35 ++- docs/src/reference/inelastic.md | 18 +- docs/src/reference/materials.md | 14 + docs/src/reference/types.md | 3 + docs/src/vsmartmom_integration.md | 31 +- src/OceanOptics.jl | 42 ++- src/diagnostics/absorbed_light.jl | 165 ++++++++++ src/inelastic/fluorescence.jl | 370 +++++++++++++++------- src/inelastic/redistribution.jl | 99 +++++- src/materials/phytoplankton.jl | 47 ++- src/materials/pigments.jl | 235 ++++++++++++++ src/mixing/layer_assembly.jl | 118 +++++-- src/types/abstract_types.jl | 41 +++ src/types/layer_optics.jl | 225 ++++++++++++-- src/types/ocean_column.jl | 28 +- src/types/ocean_layer.jl | 20 +- test/runtests.jl | 2 + test/test_absorbed_light.jl | 138 +++++++++ test/test_column.jl | 10 +- test/test_fluorescence.jl | 187 ++++++----- test/test_layer_optics.jl | 53 ++-- test/test_pigments.jl | 91 ++++++ test/test_redistribution.jl | 21 ++ test/test_tabulated.jl | 2 +- 34 files changed, 2802 insertions(+), 393 deletions(-) create mode 100644 data/bidigare_1990_pigments.csv create mode 100644 data/fluspect_chloroplast_emission.csv create mode 100644 data/prospect_d_pigment_absorption.csv create mode 100644 src/diagnostics/absorbed_light.jl create mode 100644 src/materials/pigments.jl create mode 100644 test/test_absorbed_light.jl create mode 100644 test/test_pigments.jl diff --git a/CHANGELOG.md b/CHANGELOG.md index 2006ae1..db8c5b0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,58 @@ All notable changes to OceanOptics.jl are recorded here. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). -## [Unreleased] +## [Unreleased] — 0.2.0 + +Light absorbed per constituent, chlorophyll fluorescence with +land-analogous chloroplast emission, and the ocean floor, for the +fluorescence and absorbed-PAR requirements of the coupled solver. + +### Changed (breaking) + +- `OceanLayerOptics` carries `absorbers` (one `AbsorptionComponent` per + absorber or absorption part: `label`, `part`, `τ`), `scatterers` (the + former `components`) and `inelastic` (one `InelasticComponent` per + process, with the indices of the absorption components that excite it + and their energy-transfer efficiencies). The `τ_abs` field is gone; + `absorption_optical_depth(o)` sums the absorption components. +- `OceanLayer` and the column helpers take `inelastic` (formerly + `fluorophores`), since water Raman is not a fluorophore. +- `IsotropicFluorescence(excitation; emission, quantum_yield, + excitation_range)` is driven by `ExcitationPathway`s (absorber, part, + efficiency η): `a^I = φ Σ_k η_k a_k`. Quantum yields have no default + (`chlorophyll_fluorescence`, `CDOMFluorescence`, `IsotropicFluorescence`); + previously 0.003 and 0.01 were implied. +- `chlorophyll_fluorescence` defaults to the chloroplast-level emission of + Fluspect instead of a 685-nm Gaussian (still available through + `emission = GaussianEmission(...)`). +- `layer_optics` throws if a fluorescence process is excited by an + absorber that is not a constituent of the layer. + +### Added + +- Absorption parts: `absorption_parts`, `absorption_by_part`, + `absorption_part`; `Phytoplankton(...; pigments)` with the pigment + partitions `ProspectPigments` (chlorophyll and carotenoids with the + PROSPECT-D leaf spectra used by Fluspect; land analogy) and + `Bidigare1990Pigments` (chlorophylls a, b, c, photosynthetic and + photoprotective carotenoids, phycoerythrins; Bidigare et al. 1990). The + total absorption is unchanged; unattributable absorption is + `:unassigned`. +- `chlorophyll_fluorescence(phyto; quantum_yield, carotenoid_transfer, + phycobilin_transfer, transfer)`: chlorophyll-only excitation + (`carotenoid_transfer = 0`), carotenoids as lossless antenna (`1`), or + any share in between, per pigment group if needed. +- `TabulatedEmission` and `chloroplast_emission([FT]; psi_share)`: + Fluspect's combined chloroplast emission, or a PSI/PSII mixture. +- `absorbed_power`, `absorbed_photons`, `absorbed_par` and + `inelastic_emission`: light absorbed per layer and component, and the + emission it drives, from the solver's layer-mean scalar irradiance; + `excitation_optical_depth(o, j)` and `absorber_index(o, label, part)`. +- `TabulatedLambertianBottom(λ, albedo; source)`: a floor albedo spectrum + on its own grid, interpolated onto the column grid by `column_optics`. +- Data: `fluspect_chloroplast_emission.csv`, `prospect_d_pigment_absorption.csv` + (both from SCOPE's Optipar2017_ProspectD) and `bidigare_1990_pigments.csv` + (Ocean Optics Web Book, CC BY). ## [0.1.0] — 2026-10-16 diff --git a/Project.toml b/Project.toml index 060eb3f..8d5349e 100644 --- a/Project.toml +++ b/Project.toml @@ -1,7 +1,7 @@ name = "OceanOptics" uuid = "81d78f2c-09e7-43ab-88c2-b5d9ea2c354a" authors = ["RemoteSensingTools"] -version = "0.1.0" +version = "0.2.0-DEV" [deps] DocStringExtensions = "ffbed154-4ef7-542d-bbb7-c09d3a79fcae" diff --git a/README.md b/README.md index fbf25e1..1f3a5a9 100644 --- a/README.md +++ b/README.md @@ -14,9 +14,11 @@ no dependency on it. It is the ocean counterpart of - **Constituents:** `PureWater` (absorption `IOCCG2018` (default), `PopeFry1997`, `Kou1993`, `SmithBaker1981`; scattering `ZhangHu2009` - (default) or `Morel1974`), `CDOM`, `Phytoplankton{Bricaud1998}`, - `NonAlgalParticles`, and exact published values (`TabulatedAbsorber`, - with a `total` flag for bulk absorption; `TabulatedScatterer`). + (default) or `Morel1974`), `CDOM`, `Phytoplankton{Bricaud1998}` + (optionally split into pigment groups: `ProspectPigments`, + `Bidigare1990Pigments`), `NonAlgalParticles`, and exact published + values (`TabulatedAbsorber`, with a `total` flag for bulk absorption; + `TabulatedScatterer`). - **Phase functions and matrices**, expanded as `GreekCoefficients` in vSmartMOM's convention: `RayleighWaterPhase` (phase matrix), `FournierForandPhase` (Mobley et al. 2002 B → (n, μ) family), @@ -25,13 +27,19 @@ no dependency on it. It is the ocean counterpart of hydrosols) and `WavelengthDependentPhase`. Expansions are integrated in scattering angle until converged; nothing is renormalized silently. - **Solver output:** `layer_optics` → `OceanLayerOptics` (absorption - optical depth plus one scattering component per constituent, each with - its phase-matrix expansion and a polarization label) and + components per constituent or pigment group; scattering components, + each with its phase-matrix expansion and a polarization label; inelastic + processes linked to the absorption that excites them) and `column_optics` → `OceanColumnOptics` (layers, interface refractive - index, bottom). + index, black or Lambertian floor). - **Seawater refractive index:** `FixedRefractiveIndex`, `QuanFry1995`. -- **Inelastic kernels** for fluorescence and water Raman, with an - explicit photon/energy contract (`radiance_source_kernel`). +- **Fluorescence and Raman:** chlorophyll fluorescence with the + chloroplast-level emission of the leaf model Fluspect, excited by + chlorophyll and a chosen share of carotenoid absorption; water Raman; + an explicit photon/energy contract (`radiance_source_kernel`). +- **Absorbed light:** absorbed power, photons and PAR per layer and + component (e.g. by chlorophyll), and the fluorescence emission it + drives, from the solver's scalar irradiance. Every table throws outside its data range, scalar-only phase functions are never given an invented phase matrix, and published bulk absorption cannot @@ -61,8 +69,21 @@ col = column_optics(column, collect(400.0:5.0:700.0); layer = col[1] optical_depth(layer), single_scattering_albedo(layer) -[(c.label, c.polarization) for c in layer.components] # PureWater :full, Phytoplankton :depolarizing -greek_expansion(layer.components[2], 1) # GreekCoefficients of the particles +[(c.label, c.polarization) for c in layer.scatterers] # PureWater :full, Phytoplankton :depolarizing +greek_expansion(layer.scatterers[2], 1) # GreekCoefficients of the particles +``` + +Chlorophyll fluorescence, excited by chlorophyll and half of the +carotenoid absorption, and the PAR each pigment group absorbs: + +```julia +phyto = Phytoplankton(Chl = 0.5, pigments = ProspectPigments(carotenoid_ratio = 0.3)) +sif = chlorophyll_fluorescence(phyto; quantum_yield = 0.02, carotenoid_transfer = 0.5) +layer = OceanLayer(0.0, 5.0, AbstractOceanConstituent{Float64}[water, phyto]; + inelastic = AbstractOceanInelasticProcess{Float64}[sif]) +o = layer_optics(layer, collect(400.0:5.0:750.0)) +E₀ = ones(n_wavelengths(o)) # stand-in for the solver's layer-mean scalar irradiance [W m⁻² nm⁻¹] +absorbed_par(o, E₀) # µmol photons m⁻² s⁻¹ per absorption component ``` ## Documentation @@ -99,6 +120,9 @@ DOI, URL, retrieval date, unit changes): | `rottgers_2014_temperature.csv` | Röttgers et al. 2014, figshare (CC BY 4.0) | Temperature coefficient Ψ_T, 550–2500 nm | | `bricaud_1998_A.csv`, `bricaud_1998_E.csv` | Ocean Optics Web Book (CC-BY) | Phytoplankton `A(λ)`, `E(λ)`, 300–1000 nm | | `petzold_sdh.csv` | Ocean Optics Web Book (CC-BY) | Petzold San Diego Harbor VSF, 0.1°–180° | +| `bidigare_1990_pigments.csv` | Ocean Optics Web Book (CC-BY) | In vivo specific absorption of algal pigment groups, 400–750 nm (Bidigare et al. 1990) | +| `fluspect_chloroplast_emission.csv` | SCOPE `Optipar2017_ProspectD` (GPL-3.0; also in CliMA Land, Apache-2.0) | Chloroplast-level fluorescence emission (combined, PSI, PSII), 640–851 nm | +| `prospect_d_pigment_absorption.csv` | as above | PROSPECT-D in vivo chlorophyll and carotenoid absorption, 400–800 nm | | `reference/loisel2023_hydrolight_iops.csv` | Loisel et al. 2023 (CC0) | HydroLight input IOPs: pure seawater and three scenarios | Cite the original papers in derived work. diff --git a/data/bidigare_1990_pigments.csv b/data/bidigare_1990_pigments.csv new file mode 100644 index 0000000..6fe54ce --- /dev/null +++ b/data/bidigare_1990_pigments.csv @@ -0,0 +1,192 @@ +# Dataset: In vivo weight-specific absorption spectra of algal pigment groups +# Source: R. R. Bidigare, M. E. Ondrusek, J. H. Morrow and D. A. Kiefer (1990), "In vivo absorption +# properties of algal pigments," Ocean Optics X, Proc. SPIE 1302, 290-302, +# doi:10.1117/12.21451. Solvent spectra shifted to their in vivo positions. +# Retrieved: https://www.oceanopticsbook.info/packages/iws_l2h/conversion/files/Bidigare_et_al_1990.xls +# (Ocean Optics Web Book, file by E. Boss, 2010; retrieved 2026-10-17), +# SHA-256 a55e51031f51215e0a03fe017960a0e14a80a1c7d651af326c625327cadea4e3 +# License: Creative Commons Attribution (Ocean Optics Web Book site-wide) +# Columns: chl_a, chl_b, chl_c: chlorophylls a, b, c; psc: photosynthetic carotenoids; +# ppc: photoprotective carotenoids; pe_peb, pe_pub: phycourobilin-poor (PEB-rich, +# Synechococcus WH7803) and phycourobilin-rich (PUB-rich, WH8103) phycoerythrin +# (source columns WH78O3PE and WH81O3PE). Values transcribed unchanged. +# Range: 400-750 nm, 2 nm +# Units: lambda_nm [nm]; all others [m^2/mg] (absorption per pigment mass) +# Columns: lambda_nm, chl_a, chl_b, chl_c, psc, ppc, pe_peb, pe_pub +lambda_nm,chl_a,chl_b,chl_c,psc,ppc,pe_peb,pe_pub +400,0.0128,0.0042,0.0203,0.0059,0.0131,0.00066,0.00013 +402,0.0129,0.0038,0.0206,0.0061,0.0145,0.00064,0.00012 +404,0.0132,0.0035,0.0209,0.0065,0.0157,0.00061,0.00011 +406,0.0139,0.0032,0.0211,0.0067,0.0171,0.00057,0.0001 +408,0.0148,0.0031,0.0211,0.007,0.0185,0.00054,0.00009 +410,0.0159,0.0031,0.0212,0.0074,0.0196,0.00052,0.00008 +412,0.017,0.0032,0.0213,0.0078,0.0209,0.00049,0.00008 +414,0.018,0.0033,0.0212,0.0082,0.0221,0.00046,0.00008 +416,0.0188,0.0034,0.0212,0.0087,0.0233,0.00045,0.00008 +418,0.0193,0.0036,0.0216,0.0092,0.0247,0.00043,0.00008 +420,0.0195,0.0038,0.022,0.0097,0.0261,0.00042,0.00008 +422,0.0193,0.004,0.0225,0.0102,0.028,0.00041,0.00008 +424,0.0191,0.0043,0.0234,0.0108,0.0299,0.0004,0.00009 +426,0.0189,0.0047,0.0245,0.0113,0.0321,0.00039,0.00009 +428,0.0191,0.0053,0.0258,0.012,0.0343,0.00039,0.00011 +430,0.0199,0.0061,0.0271,0.0127,0.0365,0.00038,0.00013 +432,0.0212,0.0071,0.0289,0.0135,0.0384,0.00038,0.00014 +434,0.0229,0.0082,0.0306,0.0143,0.0399,0.00038,0.00015 +436,0.0247,0.0094,0.0326,0.0151,0.0412,0.00038,0.00016 +438,0.0261,0.0106,0.0348,0.016,0.0422,0.00038,0.00018 +440,0.0265,0.0118,0.0372,0.0168,0.043,0.00039,0.00021 +442,0.0255,0.0127,0.04,0.0177,0.0437,0.00039,0.00023 +444,0.0229,0.0132,0.0434,0.0185,0.0446,0.0004,0.00026 +446,0.0193,0.0137,0.0476,0.0194,0.0458,0.00042,0.00029 +448,0.0151,0.0139,0.0521,0.0203,0.0474,0.00044,0.00034 +450,0.0111,0.0142,0.0572,0.0212,0.0494,0.00047,0.00039 +452,0.0077,0.0147,0.0618,0.0223,0.0517,0.00051,0.00045 +454,0.0052,0.0155,0.0656,0.0233,0.0542,0.00053,0.00049 +456,0.0034,0.017,0.0686,0.0243,0.0564,0.00057,0.00057 +458,0.0022,0.0192,0.0702,0.0253,0.0583,0.00062,0.00065 +460,0.0015,0.022,0.0708,0.0263,0.0596,0.00063,0.00069 +462,0.001,0.0252,0.0703,0.0272,0.0603,0.00069,0.00073 +464,0.0007,0.0286,0.0689,0.028,0.0602,0.00074,0.00082 +466,0.0006,0.0316,0.0665,0.0288,0.0593,0.00079,0.00091 +468,0.0005,0.0337,0.0629,0.0296,0.0579,0.00088,0.001 +470,0.0004,0.0347,0.0584,0.0304,0.056,0.00092,0.00109 +472,0.0004,0.0343,0.0527,0.031,0.0541,0.00099,0.00117 +474,0.0003,0.0327,0.0461,0.0319,0.0524,0.00108,0.00127 +476,0.0003,0.03,0.0395,0.0327,0.051,0.00117,0.00139 +478,0.0003,0.0269,0.0326,0.0336,0.0503,0.00124,0.00152 +480,0.0003,0.0233,0.0258,0.0345,0.0503,0.00137,0.00171 +482,0.0003,0.0198,0.0204,0.0353,0.0506,0.00149,0.00194 +484,0.0003,0.0163,0.0156,0.036,0.0515,0.00162,0.00229 +486,0.0003,0.0133,0.0119,0.0364,0.0524,0.00169,0.00245 +488,0.0003,0.0107,0.0088,0.0367,0.0529,0.00189,0.00258 +490,0.0003,0.0084,0.0068,0.0368,0.0532,0.00219,0.00265 +492,0.0003,0.0066,0.0053,0.0367,0.0526,0.0024,0.00266 +494,0.0004,0.0052,0.0042,0.0365,0.051,0.00257,0.00241 +496,0.0004,0.004,0.0035,0.0361,0.0488,0.00264,0.00215 +498,0.0004,0.0031,0.0031,0.0358,0.0457,0.00275,0.00191 +500,0.0004,0.0025,0.0027,0.0354,0.042,0.00278,0.00155 +502,0.0005,0.002,0.0022,0.0351,0.0378,0.00278,0.00121 +504,0.0005,0.0017,0.0023,0.0349,0.0334,0.00278,0.00095 +506,0.0005,0.0014,0.0021,0.0348,0.0288,0.00277,0.00085 +508,0.0005,0.0012,0.0021,0.0346,0.0245,0.00277,0.00075 +510,0.0005,0.0011,0.0019,0.0344,0.0205,0.00278,0.00067 +512,0.0005,0.001,0.0018,0.0342,0.0168,0.00282,0.00064 +514,0.0005,0.0009,0.0018,0.0337,0.0138,0.00291,0.00064 +516,0.0005,0.0009,0.0018,0.033,0.011,0.00301,0.00064 +518,0.0005,0.0009,0.0017,0.0321,0.0087,0.00307,0.00067 +520,0.0005,0.0009,0.0016,0.031,0.0069,0.00319,0.0007 +522,0.0005,0.0008,0.0015,0.0297,0.0054,0.00335,0.00074 +524,0.0006,0.0008,0.0015,0.0283,0.0043,0.0035,0.0008 +526,0.0006,0.0008,0.0015,0.0268,0.0033,0.00374,0.00083 +528,0.0007,0.0008,0.0016,0.0253,0.0027,0.00389,0.00086 +530,0.0007,0.0009,0.0016,0.0237,0.0022,0.00406,0.00094 +532,0.0008,0.0009,0.0017,0.0222,0.0016,0.00436,0.00099 +534,0.0008,0.0009,0.0017,0.0206,0.0013,0.00455,0.00105 +536,0.0009,0.001,0.0018,0.0191,0.001,0.00487,0.00108 +538,0.0009,0.001,0.0017,0.0177,0.0007,0.00511,0.00111 +540,0.0009,0.0011,0.0019,0.0163,0.0007,0.00533,0.00113 +542,0.0009,0.0011,0.0021,0.015,0.0006,0.00562,0.00112 +544,0.0009,0.0012,0.0021,0.0137,0.0003,0.00581,0.00112 +546,0.0009,0.0013,0.0024,0.0125,0.0003,0.00587,0.00106 +548,0.0009,0.0013,0.0024,0.0114,0.0002,0.00591,0.00102 +550,0.0009,0.0014,0.0025,0.0104,0.0001,0.00575,0.00094 +552,0.0009,0.0014,0.0027,0.0094,0.0001,0.00559,0.00084 +554,0.0009,0.0015,0.0027,0.0084,0,0.00522,0.00069 +556,0.0009,0.0016,0.0028,0.0076,0,0.00474,0.00053 +558,0.0009,0.0016,0.0029,0.0069,0,0.00406,0.00043 +560,0.0009,0.0016,0.0031,0.0061,0,0.00311,0.00036 +562,0.0009,0.0016,0.0033,0.0055,0,0.00253,0.00028 +564,0.0009,0.0017,0.0035,0.0048,0,0.00151,0.00021 +566,0.0009,0.0017,0.0037,0.0043,0,0.00108,0.00019 +568,0.001,0.0017,0.0039,0.0039,0,0.00078,0.00017 +570,0.0011,0.0018,0.0041,0.0034,0,0.00061,0.00012 +572,0.0012,0.0018,0.0043,0.0031,0,0.00045,0.00008 +574,0.0013,0.0019,0.0045,0.0027,0,0.00038,0.00006 +576,0.0014,0.0019,0.0048,0.0024,0,0.00031,0.00004 +578,0.0016,0.0019,0.0052,0.0022,0,0.00026,0.00003 +580,0.0017,0.0019,0.0057,0.0019,0,0.00021,0.00001 +582,0.0018,0.002,0.006,0.0017,0,0.00019,0.00001 +584,0.002,0.002,0.0063,0.0015,0,0.00015,0 +586,0.0021,0.0021,0.0064,0.0013,0,0.00014,0 +588,0.0022,0.0022,0.0063,0.0012,0,0.00012,0 +590,0.0022,0.0023,0.0059,0.001,0,0.00011,0 +592,0.0023,0.0024,0.0056,0.0009,0,0.0001,0 +594,0.0023,0.0026,0.0051,0.0008,0,0.00009,0 +596,0.0023,0.0027,0.0046,0.0007,0,0.00008,0 +598,0.0022,0.0028,0.004,0.0006,0,0.00007,0 +600,0.0022,0.0029,0.0037,0.0006,0,0.00005,0 +602,0.0021,0.0029,0.0034,0.0004,0,0.00005,0 +604,0.0021,0.0029,0.0031,0.0004,0,0.00004,0 +606,0.0021,0.0028,0.003,0.0004,0,0.00003,0 +608,0.0022,0.0027,0.003,0.0003,0,0.00003,0 +610,0.0024,0.0026,0.0032,0.0002,0,0.00002,0 +612,0.0026,0.0025,0.0033,0.0001,0,0.00001,0 +614,0.0029,0.0024,0.0035,0.0001,0,0,0 +616,0.0031,0.0024,0.0037,0.0001,0,0,0 +618,0.0034,0.0023,0.0038,0,0,0,0 +620,0.0036,0.0023,0.0041,0,0,0,0 +622,0.0038,0.0023,0.0046,0,0,0,0 +624,0.004,0.0023,0.0052,0,0,0,0 +626,0.0041,0.0023,0.0058,0,0,0,0 +628,0.0041,0.0024,0.0068,0,0,0,0 +630,0.0041,0.0025,0.0079,0,0,0,0 +632,0.004,0.0027,0.009,0,0,0,0 +634,0.0039,0.0031,0.0097,0,0,0,0 +636,0.0038,0.0036,0.0098,0,0,0,0 +638,0.0036,0.0044,0.0094,0,0,0,0 +640,0.0034,0.0054,0.0086,0,0,0,0 +642,0.0032,0.0066,0.0072,0,0,0,0 +644,0.003,0.008,0.0061,0,0,0,0 +646,0.0029,0.0094,0.0047,0,0,0,0 +648,0.0029,0.0106,0.0036,0,0,0,0 +650,0.003,0.0115,0.0032,0,0,0,0 +652,0.0032,0.0118,0.0027,0,0,0,0 +654,0.0036,0.0115,0.0024,0,0,0,0 +656,0.0042,0.0106,0.0021,0,0,0,0 +658,0.0052,0.0091,0.0018,0,0,0,0 +660,0.0066,0.0077,0.0015,0,0,0,0 +662,0.0082,0.0063,0.0013,0,0,0,0 +664,0.0106,0.0046,0.0011,0,0,0,0 +666,0.0137,0.0036,0.0008,0,0,0,0 +668,0.0155,0.0028,0.0006,0,0,0,0 +670,0.0182,0.0021,0.0004,0,0,0,0 +672,0.0196,0.0016,0.0003,0,0,0,0 +674,0.0203,0.0012,0.0002,0,0,0,0 +676,0.0199,0.0009,0.0002,0,0,0,0 +678,0.0182,0.0007,0.0001,0,0,0,0 +680,0.0154,0.0005,0.0001,0,0,0,0 +682,0.0127,0.0004,0.0001,0,0,0,0 +684,0.0104,0.0001,0,0,0,0,0 +686,0.0076,0.0003,0,0,0,0,0 +688,0.0058,0.0002,0,0,0,0,0 +690,0.0045,0.0001,0,0,0,0,0 +692,0.0033,0.0001,0,0,0,0,0 +694,0.002,0.0001,0,0,0,0,0 +696,0.0013,0.0001,0,0,0,0,0 +698,0.001,0.0001,0,0,0,0,0 +700,0.0008,0.0001,0,0,0,0,0 +702,0.0006,0,0,0,0,0,0 +704,0.0005,0,0,0,0,0,0 +706,0.0004,0,0,0,0,0,0 +708,0.0004,0,0,0,0,0,0 +710,0.0003,0,0,0,0,0,0 +712,0.0003,0,0,0,0,0,0 +714,0.0002,0,0,0,0,0,0 +716,0.0002,0,0,0,0,0,0 +718,0.0002,0,0,0,0,0,0 +720,0.0002,0,0,0,0,0,0 +722,0.0001,0,0,0,0,0,0 +724,0.0001,0,0,0,0,0,0 +726,0.0001,0,0,0,0,0,0 +728,0.0001,0,0,0,0,0,0 +730,0.0001,0,0,0,0,0,0 +732,0.0001,0,0,0,0,0,0 +734,0,0,0,0,0,0,0 +736,0,0,0,0,0,0,0 +738,0,0,0,0,0,0,0 +740,0,0,0,0,0,0,0 +742,0,0,0,0,0,0,0 +744,0,0,0,0,0,0,0 +746,0,0,0,0,0,0,0 +748,0,0,0,0,0,0,0 +750,0,0,0,0,0,0,0 diff --git a/data/fluspect_chloroplast_emission.csv b/data/fluspect_chloroplast_emission.csv new file mode 100644 index 0000000..f90a759 --- /dev/null +++ b/data/fluspect_chloroplast_emission.csv @@ -0,0 +1,237 @@ +# Dataset: Chlorophyll fluorescence emission spectra at the photosystem (chloroplast) level, as +# used by the leaf model Fluspect: combined spectrum phi (Fluspect-B/CX in SCOPE 2) and +# the separate photosystem I and II spectra phiI and phiII +# Source: Fluspect parameter file Optipar2017_ProspectD.mat (fields wl, phi, phiI, phiII), +# C. van der Tol et al., distributed with SCOPE. Fluspect: N. Vilfan, C. van der Tol, +# O. Muller, U. Rascher and W. Verhoef (2016), "Fluspect-B: A model for leaf fluorescence, +# reflectance and transmittance spectra," Remote Sens. Environ. 186, 596-615, +# doi:10.1016/j.rse.2016.09.017; N. Vilfan, C. van der Tol, P. Yang, R. Wyber, +# Z. Malenovsky, S. A. Robinson and W. Verhoef (2018), "Extending Fluspect to simulate +# xanthophyll driven leaf reflectance dynamics," Remote Sens. Environ. 211, 345-356, +# doi:10.1016/j.rse.2018.04.012 +# Retrieved: https://raw.githubusercontent.com/Christiaanvandertol/SCOPE/master/input/fluspect_parameters/Optipar2017_ProspectD.mat +# (2026-10-17), SHA-256 03bd2dfc37e11fa085f00013ce99d6c8ed5a0b427e4c65211f4d32e36f8cc596; identical values in the copy redistributed with CliMA Land +# License: SCOPE is distributed under the GNU GPL v3; CliMA Land redistributes the same file under +# Apache-2.0. See README (Data) before reusing. +# Convention: Photon-number densities per nm of emission wavelength: SCOPE (src/RTMs/RTMf.m) converts +# excitation irradiance to photons, applies fqe * phi * kChl, and converts the emitted +# photons back to energy. Each column sums to 1 on the 1 nm grid (unit area). +# Range: 640-851 nm, 1 nm (the source spans 400-2400 nm; all three spectra are zero outside +# 641-850 nm). Zero rows at both ends. Values transcribed unchanged; phi has one +# negative value (-4.5e-6 at 641 nm, a numerical artefact) that chloroplast_emission +# sets to zero. +# Units: lambda_nm [nm]; phi, phiI, phiII [1/nm] +# Columns: lambda_nm, phi, phiI, phiII +lambda_nm,phi,phiI,phiII +640,0,0,0 +641,-4.536889502e-06,0,1e-06 +642,1.048775972e-06,0,6e-06 +643,1.744430534e-05,0,1.8e-05 +644,4.53370075e-05,0,5.9e-05 +645,8.541419139e-05,0,0.000122 +646,0.0001383631659,0,0.000209 +647,0.00020487124,0,0.000318 +648,0.0002856257225,0,0.000451 +649,0.0003813139224,0,0.000607 +650,0.0004926231486,0,0.000785 +651,0.00062024071,4.2e-05,0.000986 +652,0.0007648539155,8.5e-05,0.001211 +653,0.000927150074,8.9e-05,0.001458 +654,0.001107816478,8.2e-05,0.001729 +655,0.001307540354,8e-05,0.002022 +656,0.001527008987,8.1e-05,0.002339 +657,0.001766909967,9.9e-05,0.002652 +658,0.002027930673,0.000124,0.002963 +659,0.002310757333,0.000153,0.003307 +660,0.002616076961,0.00018,0.003762 +661,0.00294458087,0.000214,0.004252 +662,0.003296957436,0.00026,0.004654 +663,0.003673878996,0.000322,0.005237 +664,0.004076028842,0.000409,0.005953 +665,0.004504150129,0.000508,0.006644 +666,0.004958945125,0.000615,0.007548 +667,0.005440892689,0.000727,0.008352 +668,0.005950624272,0.000847,0.009271 +669,0.006489605093,0.000975,0.010381 +670,0.007058730897,0.001105,0.011662 +671,0.00765578576,0.00122,0.012885 +672,0.008280679067,0.001348,0.014275 +673,0.008944933108,0.001526,0.016192 +674,0.009652138414,0.001749,0.017591 +675,0.01036254556,0.001988,0.019361 +676,0.01106600685,0.002193,0.021075 +677,0.01191412152,0.00246,0.022523 +678,0.01301975037,0.002822,0.025446 +679,0.01417905347,0.00318,0.026517 +680,0.01516617163,0.003537,0.028035 +681,0.01598386915,0.003868,0.028705 +682,0.01667306833,0.004211,0.029088 +683,0.01719870004,0.004568,0.029036 +684,0.01752013353,0.004923,0.028632 +685,0.01765048321,0.005278,0.027784 +686,0.01760567512,0.005602,0.026463 +687,0.01735913677,0.005846,0.024735 +688,0.01689057079,0.00606,0.022467 +689,0.01624727864,0.006282,0.020802 +690,0.01548589716,0.006521,0.019141 +691,0.01463280572,0.006683,0.0175 +692,0.01372229642,0.006811,0.015861 +693,0.01285056989,0.006922,0.014488 +694,0.01209942083,0.006986,0.013264 +695,0.0114311117,0.007037,0.012099 +696,0.01079561343,0.007116,0.011258 +697,0.01021326313,0.007243,0.010642 +698,0.009709982465,0.007379,0.009969 +699,0.009263665011,0.007491,0.009408 +700,0.008849073334,0.007628,0.008961 +701,0.008476473987,0.007825,0.008418 +702,0.008160940383,0.008045,0.007913 +703,0.007901269397,0.008258,0.007522 +704,0.007689750773,0.008437,0.00729 +705,0.007508922273,0.008618,0.007062 +706,0.007344436237,0.008832,0.006717 +707,0.007204155291,0.009051,0.006451 +708,0.007098303632,0.009341,0.006239 +709,0.007024341473,0.009691,0.006056 +710,0.006977816295,0.009965,0.005921 +711,0.006959388643,0.010214,0.005815 +712,0.006966570846,0.010574,0.005699 +713,0.006979169298,0.010904,0.005584 +714,0.006983174104,0.011111,0.005487 +715,0.007007016121,0.011327,0.005419 +716,0.007073980232,0.011637,0.00536 +717,0.007144326652,0.01192,0.0053 +718,0.007180349311,0.012062,0.005238 +719,0.007215501658,0.012183,0.005173 +720,0.007287341201,0.012359,0.005098 +721,0.007378682163,0.012607,0.005028 +722,0.00746385114,0.012737,0.004973 +723,0.00753796751,0.012797,0.00494 +724,0.007602444304,0.012874,0.004915 +725,0.007663076395,0.01294,0.004882 +726,0.007726885085,0.013023,0.00484 +727,0.007801415563,0.013095,0.004797 +728,0.007890528208,0.013117,0.004756 +729,0.007982820279,0.01308,0.00472 +730,0.008067234439,0.013,0.00469 +731,0.008149358078,0.012879,0.004667 +732,0.008234617963,0.012735,0.004658 +733,0.008311153639,0.01257,0.004659 +734,0.008367481054,0.012412,0.004661 +735,0.008410908992,0.012302,0.004658 +736,0.008451318875,0.012212,0.004649 +737,0.008490089836,0.012129,0.004631 +738,0.008523238293,0.012042,0.004597 +739,0.0085338321,0.01194,0.00455 +740,0.008508102488,0.01181,0.004495 +741,0.008457882752,0.011639,0.004454 +742,0.008396015286,0.01143,0.004384 +743,0.008313776819,0.011196,0.004263 +744,0.008201125859,0.010955,0.004132 +745,0.008064313691,0.010736,0.004046 +746,0.007910931496,0.010504,0.003976 +747,0.007737637237,0.010258,0.00386 +748,0.0075408075,0.010015,0.003731 +749,0.007326626564,0.009813,0.003595 +750,0.007102726646,0.009491,0.00346 +751,0.006872724006,0.009211,0.003324 +752,0.006639057735,0.009011,0.003187 +753,0.006403474215,0.00876,0.003044 +754,0.006168840205,0.008403,0.002903 +755,0.005943196699,0.00818,0.002781 +756,0.005730765839,0.007955,0.002695 +757,0.005515320132,0.007709,0.002619 +758,0.005280475655,0.007468,0.002523 +759,0.005029672409,0.007246,0.002412 +760,0.004774300637,0.007028,0.002298 +761,0.004537727634,0.006819,0.00219 +762,0.004337878157,0.006639,0.002094 +763,0.004158929756,0.006446,0.002004 +764,0.003981681748,0.006224,0.001917 +765,0.003807167731,0.005977,0.001835 +766,0.003638277797,0.005785,0.001756 +767,0.003465093746,0.005628,0.001676 +768,0.003280251606,0.005418,0.001592 +769,0.003099412633,0.00521,0.0015 +770,0.002937572418,0.005029,0.001413 +771,0.002784038674,0.004859,0.001341 +772,0.002626477155,0.004699,0.001275 +773,0.002471673637,0.004557,0.001202 +774,0.002329651265,0.004429,0.001113 +775,0.002204262632,0.004308,0.001015 +776,0.002094929447,0.004192,0.000922 +777,0.001989520461,0.004081,0.000833 +778,0.001878862691,0.003972,0.000749 +779,0.001777169184,0.003863,0.000669 +780,0.001698109845,0.00375,0.000594 +781,0.001629795963,0.003632,0.000523 +782,0.001558255905,0.00352,0.000457 +783,0.00148674495,0.00342,0.000395 +784,0.001421365457,0.003325,0.000338 +785,0.001362381178,0.003237,0.000285 +786,0.001308616726,0.003153,0.000236 +787,0.001258978754,0.003072,0.000193 +788,0.001211258495,0.002992,0.000153 +789,0.001158703469,0.002911,0.000118 +790,0.001098174883,0.002823,8.8e-05 +791,0.001045532424,0.002732,6.2e-05 +792,0.001014948786,0.002643,4.1e-05 +793,0.0009948502351,0.002563,2.4e-05 +794,0.0009710344955,0.002489,1.1e-05 +795,0.0009445315633,0.002411,0 +796,0.0009191591332,0.002337,0 +797,0.0008946534253,0.002276,0 +798,0.0008700036981,0.002233,0 +799,0.0008452928377,0.002171,0 +800,0.0008208038783,0.00211,0 +801,0.0007965268172,0.00205,0 +802,0.0007723980222,0.00199,0 +803,0.0007484323802,0.001932,0 +804,0.000724659148,0.001874,0 +805,0.0007010865433,0.001818,0 +806,0.0006777189335,0.001762,0 +807,0.0006545663232,0.001707,0 +808,0.0006316397489,0.001653,0 +809,0.0006089487364,0.0016,0 +810,0.0005865025353,0.001548,0 +811,0.0005643107996,0.001496,0 +812,0.0005423832576,0.001446,0 +813,0.0005207295292,0.001396,0 +814,0.0004993592143,0.001347,0 +815,0.0004782819419,0.001299,0 +816,0.0004575073464,0.001252,0 +817,0.0004370450543,0.001206,0 +818,0.0004169046909,0.00116,0 +819,0.0003970958829,0.001116,0 +820,0.0003776282575,0.001072,0 +821,0.0003585114417,0.00103,0 +822,0.0003397550628,0.000988,0 +823,0.0003213687479,0.000947,0 +824,0.0003033621241,0.000907,0 +825,0.0002857448185,0.000867,0 +826,0.0002685264584,0.000829,0 +827,0.0002517166707,0.000791,0 +828,0.0002353250828,0.000755,0 +829,0.0002193613217,0.000719,0 +830,0.0002038350145,0.000684,0 +831,0.0001887557884,0.00065,0 +832,0.0001741332706,0.000617,0 +833,0.0001599770882,0.000585,0 +834,0.0001462968683,0.000553,0 +835,0.000133102238,0.000523,0 +836,0.0001204028246,0.000493,0 +837,0.0001082082551,0.000464,0 +838,9.652815667e-05,0.000436,0 +839,8.53721565e-05,0.000409,0 +840,7.474988169e-05,0.000383,0 +841,6.46709594e-05,0.000357,0 +842,5.514501675e-05,0.000333,0 +843,4.61816809e-05,0.000309,0 +844,3.779057899e-05,0.000286,0 +845,2.998133815e-05,0.000265,0 +846,2.276358552e-05,0.000244,0 +847,1.614694825e-05,0.000223,0 +848,1.014105348e-05,0.000204,0 +849,4.755528352e-06,0.000186,0 +850,0,0.000168,0 +851,0,0,0 diff --git a/data/prospect_d_pigment_absorption.csv b/data/prospect_d_pigment_absorption.csv new file mode 100644 index 0000000..e5c437c --- /dev/null +++ b/data/prospect_d_pigment_absorption.csv @@ -0,0 +1,414 @@ +# Dataset: In vivo specific absorption coefficients of leaf chlorophylls (a+b) and carotenoids +# from the leaf model PROSPECT-D, as used by Fluspect +# Source: J.-B. Feret, A. A. Gitelson, S. D. Noble and S. Jacquemoud (2017), "PROSPECT-D: Towards +# modeling leaf optical properties through a complete lifecycle," Remote Sens. Environ. +# 193, 204-215, doi:10.1016/j.rse.2017.03.004; values from the Fluspect parameter file +# Optipar2017_ProspectD.mat (fields wl, Kab, Kca) distributed with SCOPE +# Retrieved: https://raw.githubusercontent.com/Christiaanvandertol/SCOPE/master/input/fluspect_parameters/Optipar2017_ProspectD.mat +# (2026-10-17), SHA-256 03bd2dfc37e11fa085f00013ce99d6c8ed5a0b427e4c65211f4d32e36f8cc596 +# License: as for fluspect_chloroplast_emission.csv (SCOPE: GNU GPL v3; CliMA Land: Apache-2.0) +# Range: 400-800 nm, 1 nm (Kab is zero above 780 nm, Kca above 557 nm) +# Units: lambda_nm [nm]; Kab, Kca [cm^2/ug] (absorption per areal pigment content) +# Columns: lambda_nm, Kab, Kca +lambda_nm,Kab,Kca +400,0.0648815,0.16734 +401,0.0667318,0.167607 +402,0.0685513,0.167184 +403,0.0699821,0.167207 +404,0.0709,0.167613 +405,0.0713334,0.167596 +406,0.0713202,0.167513 +407,0.0712604,0.167426 +408,0.0712231,0.167239 +409,0.071228,0.166682 +410,0.0714914,0.165882 +411,0.0718877,0.165517 +412,0.0720185,0.165446 +413,0.0718268,0.165689 +414,0.0714934,0.166088 +415,0.0711319,0.166189 +416,0.0707629,0.166288 +417,0.0704367,0.166456 +418,0.070094,0.166622 +419,0.0698404,0.166873 +420,0.0698193,0.167164 +421,0.0700539,0.167544 +422,0.0702815,0.16798 +423,0.070503,0.168439 +424,0.0704727,0.168599 +425,0.0705277,0.168474 +426,0.0708095,0.168142 +427,0.0713124,0.168 +428,0.0716223,0.167725 +429,0.0719053,0.167413 +430,0.0724491,0.167551 +431,0.0730907,0.167744 +432,0.0736521,0.167905 +433,0.074047,0.167971 +434,0.0743349,0.167937 +435,0.0745425,0.167973 +436,0.0746911,0.168177 +437,0.0746534,0.168322 +438,0.0745703,0.168695 +439,0.0742853,0.169163 +440,0.0737942,0.169569 +441,0.072818,0.169678 +442,0.0716223,0.169631 +443,0.0704587,0.1699 +444,0.0691047,0.169905 +445,0.0675675,0.169815 +446,0.0660264,0.16977 +447,0.0644919,0.16973 +448,0.0626681,0.169345 +449,0.0607546,0.168568 +450,0.0587747,0.167441 +451,0.0567782,0.166023 +452,0.0547324,0.164464 +453,0.0528441,0.162899 +454,0.0511254,0.161362 +455,0.0495729,0.15978 +456,0.048139,0.158224 +457,0.0468009,0.156555 +458,0.0456455,0.154969 +459,0.0446906,0.153299 +460,0.0438733,0.151672 +461,0.0431621,0.149969 +462,0.0426533,0.148319 +463,0.0422062,0.146765 +464,0.0417743,0.145076 +465,0.0412972,0.143493 +466,0.0409113,0.142004 +467,0.0405705,0.14055 +468,0.0403017,0.139191 +469,0.0400089,0.138023 +470,0.0397273,0.137008 +471,0.0395205,0.136145 +472,0.039292,0.13548 +473,0.0390352,0.134998 +474,0.0387726,0.134639 +475,0.0385228,0.134366 +476,0.0382599,0.134169 +477,0.0378812,0.133937 +478,0.03751,0.133745 +479,0.0371492,0.133557 +480,0.0367757,0.133271 +481,0.0363,0.132787 +482,0.0357606,0.132173 +483,0.03521,0.131409 +484,0.0345829,0.130422 +485,0.0339091,0.129222 +486,0.0331842,0.127818 +487,0.0323774,0.126314 +488,0.0315189,0.124566 +489,0.0305842,0.122692 +490,0.0296622,0.120655 +491,0.0286992,0.118603 +492,0.0276921,0.11652 +493,0.0266404,0.11441 +494,0.0255901,0.112274 +495,0.0245165,0.110113 +496,0.0234283,0.10793 +497,0.0223279,0.105726 +498,0.0212239,0.103502 +499,0.0201366,0.101261 +500,0.0190485,0.0990044 +501,0.0179798,0.0967335 +502,0.0169429,0.0944502 +503,0.0159234,0.0921564 +504,0.0149343,0.08985123333 +505,0.0139785,0.0875295881 +506,0.0130497,0.08521264683 +507,0.0121542,0.08274830421 +508,0.0112959,0.08015067215 +509,0.01048,0.07769336211 +510,0.00970081,0.07523605207 +511,0.00895396,0.07287121465 +512,0.0082461,0.07050637723 +513,0.00758,0.06791942566 +514,0.00695743,0.0653324741 +515,0.00638669,0.06291166385 +516,0.00586805,0.06049085361 +517,0.00540153,0.0580361056 +518,0.00499129,0.0555813576 +519,0.00463493,0.0531177983 +520,0.00433379,0.050654239 +521,0.00408503,0.04831886836 +522,0.00388739,0.04598349772 +523,0.00374206,0.04374373162 +524,0.00365252,0.04150396551 +525,0.00361178,0.03935828011 +526,0.00361934,0.0372125947 +527,0.00367282,0.03517747979 +528,0.00376967,0.03314236488 +529,0.00390324,0.03123215359 +530,0.00406899,0.02932194229 +531,0.00426366,0.02755354422 +532,0.00448428,0.02578514614 +533,0.00472995,0.02409843585 +534,0.00499348,0.02241172556 +535,0.00527276,0.02082402421 +536,0.00556455,0.01923632287 +537,0.00586623,0.01777735563 +538,0.00617059,0.01631838839 +539,0.00647922,0.01495928703 +540,0.0067864,0.01362655134 +541,0.00709,0.01236080219 +542,0.007388,0.0111735325 +543,0.00767415,0.009984617847 +544,0.00794833,0.008856109936 +545,0.00820829,0.007776709186 +546,0.00845364,0.006763866919 +547,0.00868499,0.005787595665 +548,0.00890368,0.00487548897 +549,0.0091119,0.004021459036 +550,0.00930939,0.003234092488 +551,0.00950012,0.002520957811 +552,0.00968213,0.0018917622 +553,0.00986391,0.001248354621 +554,0.01004,0.0007313376661 +555,0.0102144,0.0003600068044 +556,0.0103855,0.0001827981737 +557,0.0105557,6.487059245e-05 +558,0.0107242,0 +559,0.0108889,0 +560,0.011048,0 +561,0.0112169,0 +562,0.0114015,0 +563,0.0116055,0 +564,0.0118272,0 +565,0.0120748,0 +566,0.0123402,0 +567,0.012628,0 +568,0.012933,0 +569,0.0132595,0 +570,0.0135979,0 +571,0.0139469,0 +572,0.0143014,0 +573,0.0146577,0 +574,0.0150102,0 +575,0.0153567,0 +576,0.0156935,0 +577,0.0160234,0 +578,0.0163397,0 +579,0.0166478,0 +580,0.0169452,0 +581,0.0172407,0 +582,0.0175269,0 +583,0.0178005,0 +584,0.0180658,0 +585,0.0183248,0 +586,0.0185679,0 +587,0.0188,0 +588,0.0190186,0 +589,0.0192278,0 +590,0.0194191,0 +591,0.0195991,0 +592,0.0197663,0 +593,0.0199222,0 +594,0.0200656,0 +595,0.0201988,0 +596,0.0203266,0 +597,0.0204577,0 +598,0.0205849,0 +599,0.0207154,0 +600,0.020854,0 +601,0.0210068,0 +602,0.0211716,0 +603,0.0213477,0 +604,0.0215458,0 +605,0.0217636,0 +606,0.0220033,0 +607,0.022268,0 +608,0.0225525,0 +609,0.0228594,0 +610,0.0231769,0 +611,0.0235022,0 +612,0.0238419,0 +613,0.0241985,0 +614,0.024561,0 +615,0.024917,0 +616,0.0252691,0 +617,0.0256167,0 +618,0.0259503,0 +619,0.0262545,0 +620,0.0265303,0 +621,0.0267861,0 +622,0.0270098,0 +623,0.0272066,0 +624,0.0273792,0 +625,0.0275228,0 +626,0.0276449,0 +627,0.0277392,0 +628,0.0278211,0 +629,0.0278951,0 +630,0.0279776,0 +631,0.0280723,0 +632,0.0281944,0 +633,0.0283603,0 +634,0.0285729,0 +635,0.028846,0 +636,0.0291814,0 +637,0.0295993,0 +638,0.0300771,0 +639,0.0306343,0 +640,0.0312475,0 +641,0.0319268,0 +642,0.0326585,0 +643,0.0334412,0 +644,0.0342546,0 +645,0.0351007,0 +646,0.0359489,0 +647,0.0367793,0 +648,0.037588,0 +649,0.0383232,0 +650,0.0390136,0 +651,0.0396312,0 +652,0.0402217,0 +653,0.0408042,0 +654,0.0414183,0 +655,0.0421067,0 +656,0.04288,0 +657,0.0438083,0 +658,0.0448612,0 +659,0.0461069,0 +660,0.0474949,0 +661,0.0491126,0 +662,0.0508487,0 +663,0.0527301,0 +664,0.0546996,0 +665,0.0567611,0 +666,0.0588679,0 +667,0.0608295,0 +668,0.06275,0 +669,0.0644721,0 +670,0.0661121,0 +671,0.0674706,0 +672,0.0686749,0 +673,0.0696352,0 +674,0.0704652,0 +675,0.0709948,0 +676,0.0714015,0 +677,0.0713582,0 +678,0.0711272,0 +679,0.0701854,0 +680,0.0689206,0 +681,0.0665762,0 +682,0.0639476,0 +683,0.0604821,0 +684,0.0568583,0 +685,0.0527473,0 +686,0.0487258,0 +687,0.044707,0 +688,0.0408585,0 +689,0.0371411,0 +690,0.033671,0 +691,0.0304587,0 +692,0.0275021,0 +693,0.0247868,0 +694,0.0223303,0 +695,0.0201436,0 +696,0.0181733,0 +697,0.0164205,0 +698,0.0148521,0 +699,0.0134714,0 +700,0.0122406,0 +701,0.0111549,0 +702,0.0101925,0 +703,0.00934301,0 +704,0.00858695,0 +705,0.00791505,0 +706,0.00731259,0 +707,0.00677109,0 +708,0.0062803,0 +709,0.00583221,0 +710,0.00542144,0 +711,0.0050449,0 +712,0.00469652,0 +713,0.00437346,0 +714,0.00407204,0 +715,0.00379222,0 +716,0.0035302,0 +717,0.00328562,0 +718,0.00305749,0 +719,0.00284347,0 +720,0.0026434,0 +721,0.00245633,0 +722,0.00228092,0 +723,0.0021168,0 +724,0.00196361,0 +725,0.00182056,0 +726,0.00168688,0 +727,0.00156284,0 +728,0.00144677,0 +729,0.00133883,0 +730,0.0012386,0 +731,0.0011459,0 +732,0.00105907,0 +733,0.000978276,0 +734,0.000904086,0 +735,0.00083609,0 +736,0.000772889,0 +737,0.000715026,0 +738,0.000661618,0 +739,0.000612349,0 +740,0.000567642,0 +741,0.00052722,0 +742,0.00048994,0 +743,0.000456364,0 +744,0.000425665,0 +745,0.000398123,0 +746,0.000373159,0 +747,0.000351044,0 +748,0.000331411,0 +749,0.000313711,0 +750,0.000298414,0 +751,0.000283146,0 +752,0.00026796,0 +753,0.000252885,0 +754,0.000237952,0 +755,0.000223193,0 +756,0.000208636,0 +757,0.000194314,0 +758,0.000180256,0 +759,0.000166494,0 +760,0.000153058,0 +761,0.000139979,0 +762,0.000127287,0 +763,0.000115013,0 +764,0.000103187,0 +765,9.18411e-05,0 +766,8.10049e-05,0 +767,7.07092e-05,0 +768,6.09847e-05,0 +769,5.18621e-05,0 +770,4.3372e-05,0 +771,3.5545e-05,0 +772,2.84118e-05,0 +773,2.20031e-05,0 +774,1.63494e-05,0 +775,1.14814e-05,0 +776,7.42983e-06,0 +777,4.22525e-06,0 +778,1.89832e-06,0 +779,4.79687e-07,0 +780,1.05249e-13,0 +781,0,0 +782,0,0 +783,0,0 +784,0,0 +785,0,0 +786,0,0 +787,0,0 +788,0,0 +789,0,0 +790,0,0 +791,0,0 +792,0,0 +793,0,0 +794,0,0 +795,0,0 +796,0,0 +797,0,0 +798,0,0 +799,0,0 +800,0,0 diff --git a/docs/make.jl b/docs/make.jl index 7dcfe5c..16a9087 100644 --- a/docs/make.jl +++ b/docs/make.jl @@ -18,7 +18,7 @@ makedocs( # Chart pages embed their data (JSON + table) and have no image # fallback, so allow larger pages and example outputs. size_threshold = 400 * 2^10, - size_threshold_warn = 250 * 2^10, + size_threshold_warn = 320 * 2^10, example_size_threshold = 96 * 2^10, ), pages = [ diff --git a/docs/src/consumer_api.md b/docs/src/consumer_api.md index 4e8dca2..17af6fe 100644 --- a/docs/src/consumer_api.md +++ b/docs/src/consumer_api.md @@ -24,12 +24,20 @@ per wavelength, and the bottom ([`BlackBottom`](@ref) or |---|---| | `λ` | wavelengths `[nm]`, strictly increasing or decreasing | | `depth_top`, `depth_bottom`, [`thickness`](@ref) | depths below the surface `[m]` | -| `τ_abs`, [`absorption_optical_depth`](@ref) | absorption optical depth of all absorbers | -| `components` | one [`ScatteringComponent`](@ref) per scattering constituent | -| [`optical_depth`](@ref), [`scattering_optical_depth`](@ref), [`single_scattering_albedo`](@ref) | derived totals | +| `absorbers` | one [`AbsorptionComponent`](@ref) per absorber, or per absorption part (pigment group) | +| `scatterers` | one [`ScatteringComponent`](@ref) per scattering constituent | +| `inelastic` | one [`InelasticComponent`](@ref) per inelastic process, linked to the absorption that excites it | +| [`absorption_optical_depth`](@ref), [`optical_depth`](@ref), [`scattering_optical_depth`](@ref), [`single_scattering_albedo`](@ref) | derived totals | | [`greek_expansion`](@ref)`(o, iλ)` | mixed expansion at a wavelength (scattering-weighted) | | [`backscatter_fraction`](@ref)`(o)` | scattering-weighted backscatter fraction of the phase functions | +An [`AbsorptionComponent`](@ref) carries a `label` (as for scattering +components), a `part` (`:total`, or a pigment group such as +`:chlorophyll`; see [Pigments and fluorescence excitation](@ref)) and its +absorption optical depth `τ = a Δz` per wavelength. The elastic solve +needs only their sum; the split lets the solver report the light absorbed +by each constituent and pigment group. + A [`ScatteringComponent`](@ref) carries a `label` (constituent type, or the `source` of tabulated data), its scattering optical depth `τ` per wavelength, its distinct expansions `greek` ([`GreekCoefficients`](@ref); @@ -53,7 +61,7 @@ operators can be reused. Layers are ordered from the surface down; [`interface_depths`](@ref)`(col)` gives the layer boundaries. **Derivatives.** Every optical depth is linear in its constituent's -concentration (`τ_c = b_c Δz`, `τ_abs = Σ a_c Δz`) and the layer mixture is +concentration (`τ = b_c Δz`, `τ = a_c Δz`) and the layer mixture is linear in the component optical depths, so derivatives with respect to component amounts follow directly from the component split; the assembly itself is evaluated in floating point (`FT`). @@ -69,7 +77,9 @@ represented by a bottom layer thick enough for the bottom not to matter | Wavelength `λ` | nm | As tabulated by the source data; no air/vacuum conversion is applied | | `a`, `b`, `b_b` | m⁻¹ | Volumetric coefficients, not spectral densities | | Depth, thickness | m | Positive downward from the surface | -| `τ_abs`, component `τ` | — | `a Δz`, `b Δz` | +| Component `τ` | — | `a Δz` (absorption), `b Δz` (scattering) | +| Scalar irradiance `E₀` | W m⁻² nm⁻¹ | Supplied by the solver; total intensity over all directions | +| Absorbed photons, absorbed PAR | µmol photons m⁻² s⁻¹ (nm⁻¹) | Photon energy `hc/λ` | | Refractive index | — | Real, seawater relative to air | | Redistribution `emission(p, λ′, λ)` | nm⁻¹ | Photon density per nm of emission wavelength | @@ -179,9 +189,17 @@ paper's stated asymmetry parameters (0.95, 0.97) and backscatter ratios `QuanFry1995(; temperature, salinity)` — Quan & Fry (1995), relative to air, fitted to 400–700 nm, 0–30 °C, 0–35 PSU; outside that domain it throws unless `extrapolate = true`. -* `bottom = BlackBottom()` or `LambertianBottom(albedo)` (one value or one - per wavelength). The solver applies the bottom; OceanOptics only - describes it. +* `bottom = BlackBottom()` (deep water), `LambertianBottom(albedo)` (one + value or one per wavelength) or + [`TabulatedLambertianBottom`](@ref)`(λ, albedo; source)` — an albedo + spectrum on its own grid (e.g. measured sand or seagrass reflectance), + interpolated onto `λ`. The column always carries a `BlackBottom` or a + `LambertianBottom` with [`bottom_albedo`](@ref)`(col)` per wavelength. + +The solver applies the floor at [`bottom_depth`](@ref)`(col)`, below the +last layer: a Lambertian floor reflects intensity isotropically and +depolarizes (only the azimuthal mode `m = 0`, only `I`). OceanOptics only +describes it. ## Validity and provenance @@ -192,10 +210,72 @@ provenance headers. The default water absorption, [`IOCCG2018`](@ref), covers 350–2500 nm; [`SmithBaker1981`](@ref) reaches down to 200 nm but is several times too high below ~420 nm. +## Pigments and fluorescence excitation + +Phytoplankton can attribute its absorption to pigment groups with a +partition ([`ProspectPigments`](@ref): chlorophyll and carotenoids with +the PROSPECT-D leaf spectra, by analogy with land; or +[`Bidigare1990Pigments`](@ref): chlorophylls a, b, c, photosynthetic and +photoprotective carotenoids and phycoerythrins). The total stays that of +the phytoplankton model; each group becomes an absorption component, and +absorption that the spectra cannot attribute (e.g. in the UV) goes to +`:unassigned`. + +A fluorescence process is excited through [`ExcitationPathway`](@ref)s, +each an absorber (or absorption part) with an energy-transfer efficiency +`η ∈ [0, 1]`: + +`excitation_absorption(p, λ′) = φ · Σ_k η_k · a_k(λ′)`. + +Chlorophyll has `η = 1`; carotenoids acting as antenna pass on `η ≤ 1`; +photoprotective absorption and quenching have `η = 0`. +[`chlorophyll_fluorescence`](@ref) builds the pathways from the +partition: `carotenoid_transfer = 0` is chlorophyll-only excitation (as +in Fluspect), `1` a lossless carotenoid antenna, values between the +share passed on; `transfer` sets groups individually. Its default +emission is the chloroplast-level spectrum of Fluspect +([`chloroplast_emission`](@ref)); the quantum yield is always explicit. + +In [`layer_optics`](@ref), each process becomes an +[`InelasticComponent`](@ref) whose `excitation` indexes the layer's +`absorbers` and whose `efficiency` holds the `η`s, so that +`quantum_yield · Σ_k efficiency[k] · absorbers[excitation[k]].τ / Δz` +equals `excitation_absorption(process, λ)` on the layer grid. An absorber +that excites fluorescence must be a constituent of the layer: its light +absorption has to attenuate the field it is excited by. + +## Light absorbed per layer + +Given the solver's layer-mean spectral scalar irradiance +`Ē₀(λ) = (1/Δz) ∫ E₀(z, λ) dz` `[W m⁻² nm⁻¹]` for a layer (total intensity +over all directions, direct and diffuse, integrated through the layer — +not interface values), every component absorbs `A_c(λ) = τ_c(λ) Ē₀(λ)`: + +* [`absorbed_power`](@ref)`(o, Ē₀)` — `A_c(λ)` `[W m⁻² nm⁻¹]` per + absorption component; +* [`absorbed_photons`](@ref)`(o, Ē₀)` — the same in µmol photons + m⁻² s⁻¹ nm⁻¹; +* [`absorbed_par`](@ref)`(o, Ē₀; range = (400, 700))` — absorbed PAR per + component `[µmol photons m⁻² s⁻¹]`, e.g. by chlorophyll, per layer; +* [`excitation_optical_depth`](@ref)`(o, j)` — `τᴵ = aᴵ Δz` of the + layer's `j`-th inelastic process on the layer grid, from the stored + components; +* [`absorber_index`](@ref)`(o, label, part)` — the row of a component, + e.g. `absorber_index(o, "Phytoplankton", :chlorophyll)`; +* [`inelastic_emission`](@ref)`(o, j, Ē₀, λ_em)` — spectral power + `[W m⁻² nm⁻¹]` emitted in all directions through the layer's `j`-th + inelastic process. For fluorescence, emitted photons equal the quantum + yield times the photons delivered by the excitation pathways. + +Over a column, in the elastic case, `E_d(0⁻) − E_u(0⁻) = Σ_layers Σ_c A_c +` +the floor's absorption `(1 − albedo) E_d(floor)`: a closure test for the +solver. + ## Inelastic source kernels -Inelastic sources are not part of `layer_optics`; they are kernels the -solver evaluates against its own internal radiation field: +Each inelastic process is carried by its layer's +[`InelasticComponent`](@ref); its kernels are evaluated by the solver +against its own internal radiation field: * [`excitation_absorption`](@ref)`(p, λ′)` — photon conversion rate `[1/m]`; includes the quantum yield for fluorescence, is the Raman @@ -219,20 +299,26 @@ solver's convention and must match the reference it is compared with. * **Solver output:** [`column_optics`](@ref), [`OceanColumnOptics`](@ref), [`layer_optics`](@ref), [`OceanLayerOptics`](@ref), - [`ScatteringComponent`](@ref), [`GreekCoefficients`](@ref) and the + [`AbsorptionComponent`](@ref), [`ScatteringComponent`](@ref), + [`InelasticComponent`](@ref), [`GreekCoefficients`](@ref) and the accessors above; [`BlackBottom`](@ref), [`LambertianBottom`](@ref), - [`bottom_albedo`](@ref). + [`TabulatedLambertianBottom`](@ref), [`bottom_albedo`](@ref). +* **Absorbed light:** [`absorbed_power`](@ref), [`absorbed_photons`](@ref), + [`absorbed_par`](@ref), [`inelastic_emission`](@ref), + [`excitation_optical_depth`](@ref), [`absorber_index`](@ref). * **Constituents:** [`AbstractOceanConstituent`](@ref) and its role - types; [`absorption`](@ref), [`scattering`](@ref), + types; [`absorption`](@ref), [`absorption_parts`](@ref), + [`absorption_by_part`](@ref), [`scattering`](@ref), [`backscattering`](@ref), [`scattering_phase`](@ref), - [`is_total_absorption`](@ref). + [`is_total_absorption`](@ref); pigment partitions + ([`AbstractPigmentPartition`](@ref)). * **Phase functions:** [`AbstractOceanPhaseFunction`](@ref), [`greek_expansion`](@ref), [`phase_function_moments`](@ref), [`is_polarizable`](@ref), [`is_wavelength_dependent`](@ref). * **Refractive index:** [`AbstractRefractiveIndexModel`](@ref), [`refractive_index`](@ref). -* **Inelastic processes:** [`AbstractOceanInelasticProcess`](@ref) and the - kernels above. +* **Inelastic processes:** [`AbstractOceanInelasticProcess`](@ref), + [`excitation_pathways`](@ref) and the kernels above. Exported names do not collide with vSmartMOM's exports, so both packages can be loaded together. diff --git a/docs/src/example.md b/docs/src/example.md index 1fca123..0cc360d 100644 --- a/docs/src/example.md +++ b/docs/src/example.md @@ -45,15 +45,16 @@ b_phyto = scattering(phyto, λ) Stack the three constituents in a 5-m surface layer and compute its optical properties at 10-nm resolution across the visible. The result -holds the absorption optical depth and one scattering component per -scattering constituent (here water and phytoplankton; CDOM only absorbs): +holds one absorption component per absorber and one scattering component +per scattering constituent (here water and phytoplankton; CDOM only +absorbs): ```@example ex layer = OceanLayer(0.0, 5.0, AbstractOceanConstituent{Float64}[water, cdom, phyto]) λ_grid = collect(400.0:10.0:700.0) opt = layer_optics(layer, λ_grid; ℓ_max = 32) -[(c.label, c.polarization) for c in opt.components] +[(c.label, c.part) for c in opt.absorbers], [(c.label, c.polarization) for c in opt.scatterers] ``` Mixed quantities are derived from the components: @@ -101,37 +102,66 @@ col = column_optics(column, [450.0, 550.0, 650.0]; (n_layers(col), col.refractive_index) ``` -## Inelastic kernels +## Chlorophyll absorption and fluorescence -Chlorophyll-a fluorescence is built from the phytoplankton absorber -plus a Gaussian emission band at 685 nm. The package returns kernels -a downstream two-pass RT solver convolves against the pass-1 -irradiance; we do not solve RT here. +To follow the light absorbed by chlorophyll, give the phytoplankton a +pigment partition. [`ProspectPigments`](@ref) splits its absorption into +chlorophyll and carotenoids with the leaf spectra of PROSPECT-D (the land +analogy); [`Bidigare1990Pigments`](@ref) uses ocean pigment groups. The +total absorption is unchanged: ```@example ex -sif = chlorophyll_fluorescence(phyto) -sif +pig = Phytoplankton(Chl = 0.5, pigments = ProspectPigments(carotenoid_ratio = 0.3)) +a = absorption_by_part(pig, 490.0) +(absorption_parts(pig), a, sum(a) ≈ absorption(pig, 490.0)) ``` +Fluorescence is excited by chlorophyll absorption and by the share `η` +of carotenoid absorption passed to chlorophyll (`0`: chlorophyll only; +`1`: lossless antenna). The default emission is the chloroplast-level +spectrum of the leaf model Fluspect; the quantum yield is always given: + +```@example ex +chl_only = chlorophyll_fluorescence(pig; quantum_yield = 0.02, carotenoid_transfer = 0.0) +antenna = chlorophyll_fluorescence(pig; quantum_yield = 0.02, carotenoid_transfer = 0.5) +excitation_absorption(chl_only, 490.0), excitation_absorption(antenna, 490.0) +``` + +The emission density (photons per nm) has its maxima at 685 and 739 nm: + ```@example ex -excitation_absorption(sif, 440.0) # φ · a_φ(440): photons, yield included +using Printf +println(" λ [nm] f(λ) [1/nm]") +for λ in (660.0, 685.0, 700.0, 720.0, 739.0, 760.0, 800.0) + @printf("%6.1f %.5f\n", λ, emission(antenna, 440.0, λ)) +end ``` [`radiance_source_kernel`](@ref) adds the photon-energy ratio `λ'/λ` needed for an energy (radiance) source: ```@example ex -radiance_source_kernel(sif, 440.0, 685.0) / inelastic_coefficient(sif, 440.0, 685.0) +radiance_source_kernel(antenna, 440.0, 685.0) / inelastic_coefficient(antenna, 440.0, 685.0) ``` -The emission density peaks at 685 nm with FWHM ≈ 25 nm: +In a layer, the process is linked to the absorption components that +excite it, and the light each component absorbs follows from the +solver's layer-mean scalar irradiance. Here a uniform 1 W m⁻² nm⁻¹ stands +in for the solver's field: ```@example ex -using Printf -println(" λ [nm] f(440, λ) [1/nm]") -for λ in (640.0, 670.0, 680.0, 685.0, 690.0, 700.0, 730.0) - @printf("%6.1f %.5f\n", λ, emission(sif, 440.0, λ)) -end +lay = layer_optics(OceanLayer(0.0, 5.0, AbstractOceanConstituent{Float64}[water, pig]; + inelastic = AbstractOceanInelasticProcess{Float64}[antenna]), + collect(400.0:5.0:750.0)) +E₀ = ones(n_wavelengths(lay)) +par = absorbed_par(lay, E₀) # µmol photons m⁻² s⁻¹ per absorption component +[(c.label, c.part, round(p; sigdigits = 4)) for (c, p) in zip(lay.absorbers, par)] +``` + +```@example ex +λ_em = collect(640.0:1.0:850.0) +P = inelastic_emission(lay, 1, E₀, λ_em) # W m⁻² nm⁻¹ emitted by the layer +λ_em[argmax(P)], maximum(P) ``` Water Raman at 440-nm excitation peaks around 517 nm (the `3400 cm⁻¹` diff --git a/docs/src/gallery.md b/docs/src/gallery.md index 0558d83..57a9667 100644 --- a/docs/src/gallery.md +++ b/docs/src/gallery.md @@ -178,28 +178,66 @@ linechart([Series("Petzold (1972), San Diego Harbor", rad2deg.(petzold.θ), petz ## 6. Chlorophyll fluorescence emission spectrum -Comparison target: Fell (1997) Fig. 5.5 and Gordon (1979) — Gaussian -emission band centred at 685 nm with σ = 10.6 nm (FWHM ≈ 25 nm). The -band is excitation-independent in the 400–700 nm PAR window, so the -shape does not shift with `λ'`. +Comparison target: the chloroplast-level emission of the leaf model +Fluspect (Vilfan et al. 2016, 2018), as used in SCOPE: the combined +spectrum `phi` with maxima at 685 and 739 nm, and the photosystem I +(728 nm) and II (682 nm) spectra. All are photon densities per nm, +without reabsorption, and do not depend on the excitation wavelength. +For reference, the single 685-nm Gaussian (σ = 10.6 nm) of Fell (1997) +and Gordon (1979). ```@example gallery -phyto = Phytoplankton{Float64, Bricaud1998}(Chl = 0.5) -sif = chlorophyll_fluorescence(phyto) - -λ_emit = collect(640.0:1.0:740.0) -f(λ′) = [emission(sif, λ′, λ) for λ in λ_emit] -# The band does not depend on the excitation wavelength in 400–700 nm: -println("max |f(400, λ) − f(600, λ)| = ", maximum(abs, f(400.0) .- f(600.0))) -linechart([Series("emission density f(λ', λ), any λ' in 400–700 nm", λ_emit, f(440.0)), - Series("peak = 685 nm", [685.0, 685.0], [0.0, maximum(f(440.0))]; - reference = true, dot = true)]; - title = "Chlorophyll fluorescence emission (Fell 1997, Fig. 5.5)", - xlabel = "emission wavelength λ [nm]", ylabel = "f(λ', λ) [nm⁻¹]", +λ_emit = collect(640.0:1.0:851.0) +dens(r) = [redistribution(r, 440.0, λ) for λ in λ_emit] +linechart([Series("Fluspect combined (default)", λ_emit, dens(chloroplast_emission())), + Series("photosystem I", λ_emit, dens(chloroplast_emission(psi_share = 1)); dash = true), + Series("photosystem II", λ_emit, dens(chloroplast_emission(psi_share = 0)); dot = true), + Series("Gaussian 685 nm, σ = 10.6 nm (Fell 1997)", λ_emit, + dens(GaussianEmission(center_nm = 685.0, σ_nm = 10.6)); reference = true, dot = true)]; + title = "Chlorophyll fluorescence emission at the chloroplast level", + xlabel = "emission wavelength λ [nm]", ylabel = "f(λ) [photons nm⁻¹, unit area]", xname = "λ [nm]") ``` -## 7. Water Raman emission vs excitation wavelength +## 7. Pigment partition of phytoplankton absorption + +Chlorophyll and carotenoid shares of `a_φ(λ)` at Chl = 0.5 mg m⁻³. The +parts sum to the Bricaud (1998) total (grey); fluorescence counts the +carotenoid parts with their energy-transfer efficiency. First the land +analogy, with the PROSPECT-D leaf spectra and a carotenoid:chlorophyll +ratio of 0.3: + +```@example gallery +λp = collect(400.0:2.0:720.0) +part(p, name) = [absorption_part(p, name, λ) for λ in λp] +pl = Phytoplankton(Chl = 0.5, pigments = ProspectPigments(carotenoid_ratio = 0.3)) +linechart([Series("total a_φ (Bricaud 1998)", λp, absorption(pl, λp); reference = true), + Series("chlorophyll", λp, part(pl, :chlorophyll); slot = 0), + Series("carotenoids", λp, part(pl, :carotenoids); slot = 1)]; + title = "Land analogy (PROSPECT-D), Chl = 0.5 mg m⁻³", + xlabel = "wavelength λ [nm]", ylabel = "absorption [m⁻¹]", xname = "λ [nm]", + digits = 4) +``` + +Then the ocean pigment groups of Bidigare et al. (1990), for an +illustrative diatom-like composition (chl a 0.5, chl c 0.1, photosynthetic +carotenoids 0.3, photoprotective carotenoids 0.1 mg m⁻³): + +```@example gallery +po = Phytoplankton(Chl = 0.5, pigments = Bidigare1990Pigments(chl_a = 0.5, chl_c = 0.1, + psc = 0.3, ppc = 0.1)) +linechart([Series("total a_φ (Bricaud 1998)", λp, absorption(po, λp); reference = true), + Series("chlorophyll a", λp, part(po, :chlorophyll_a); slot = 0), + Series("photosynthetic carotenoids", λp, part(po, :photosynthetic_carotenoids); slot = 1), + Series("photoprotective carotenoids", λp, part(po, :photoprotective_carotenoids); + slot = 2, dash = true), + Series("chlorophyll c", λp, part(po, :chlorophyll_c); slot = 3, dot = true)]; + title = "Ocean pigment groups (Bidigare et al. 1990), Chl = 0.5 mg m⁻³", + xlabel = "wavelength λ [nm]", ylabel = "absorption [m⁻¹]", xname = "λ [nm]", + digits = 4) +``` + +## 8. Water Raman emission vs excitation wavelength Comparison target: Haltrin & Kattawar (1991) and Bartlett et al. (1998) — a Stokes-shifted Gaussian emission in wavenumber (fixed diff --git a/docs/src/index.md b/docs/src/index.md index 5669634..11f975f 100644 --- a/docs/src/index.md +++ b/docs/src/index.md @@ -57,18 +57,20 @@ phyto = Phytoplankton{Float64, Bricaud1998}(Chl = 0.5) layer = OceanLayer(0.0, 5.0, AbstractOceanConstituent{Float64}[water, cdom, phyto]) -# 2. Optical properties on a wavelength grid: absorption plus one -# scattering component per constituent +# 2. Optical properties on a wavelength grid: absorption and scattering +# components per constituent opt = layer_optics(layer, collect(400.0:5.0:700.0); ℓ_max = 32) optical_depth(opt) # τ per λ single_scattering_albedo(opt) # ϖ per λ -opt.components[2].greek # phytoplankton expansion (GreekCoefficients) +opt.scatterers[2].greek # phytoplankton expansion (GreekCoefficients) greek_expansion(opt, 1) # mixed expansion at 400 nm -# 3. Inelastic kernels for a downstream two-pass RT solver -sif = chlorophyll_fluorescence(phyto) -excitation_absorption(sif, 440.0) # φ · a_φ(440) -emission(sif, 440.0, 685.0) # Gaussian at 685 nm, σ = 10.6 nm +# 3. Chlorophyll fluorescence: chloroplast-level emission (Fluspect), +# excitation by chlorophyll plus half of the carotenoid absorption +pig = Phytoplankton(Chl = 0.5, pigments = ProspectPigments(carotenoid_ratio = 0.3)) +sif = chlorophyll_fluorescence(pig; quantum_yield = 0.02, carotenoid_transfer = 0.5) +excitation_absorption(sif, 440.0) # φ · (a_chl + 0.5 a_car) at 440 nm +emission(sif, 440.0, 685.0) # photons per nm at 685 nm ``` For a longer walk-through with numerical output, see @@ -77,18 +79,25 @@ For a longer walk-through with numerical output, see ## What's covered * **Materials**: [`PureWater`](@ref), [`CDOM`](@ref), - [`Phytoplankton`](@ref), [`NonAlgalParticles`](@ref). See - [Materials](@ref). + [`Phytoplankton`](@ref) (optionally with a pigment partition, + [`ProspectPigments`](@ref) or [`Bidigare1990Pigments`](@ref)), + [`NonAlgalParticles`](@ref). See [Materials](@ref). * **Phase functions and matrices**: [`RayleighWaterPhase`](@ref), [`FournierForandPhase`](@ref), [`HenyeyGreensteinPhase`](@ref), [`PetzoldPhase`](@ref), [`TabulatedGreekPhase`](@ref), [`TabulatedMuellerPhase`](@ref), [`WavelengthDependentPhase`](@ref), expanded as [`GreekCoefficients`](@ref). See [Phase functions](@ref). -* **Solver output**: [`layer_optics`](@ref) → [`OceanLayerOptics`](@ref), +* **Solver output**: [`layer_optics`](@ref) → [`OceanLayerOptics`](@ref) + (absorption, scattering and inelastic components), [`column_optics`](@ref) → [`OceanColumnOptics`](@ref) with the - interface [`refractive_index`](@ref) and bottom. See - [Consumer API](@ref) and [vSmartMOM integration](@ref). -* **Inelastic processes**: [`IsotropicFluorescence`](@ref), + interface [`refractive_index`](@ref) and the floor (black or + Lambertian). See [Consumer API](@ref) and [vSmartMOM integration](@ref). +* **Absorbed light**: [`absorbed_power`](@ref), [`absorbed_par`](@ref) + and [`inelastic_emission`](@ref) per layer and component, from the + solver's scalar irradiance. +* **Inelastic processes**: [`IsotropicFluorescence`](@ref) with + [`ExcitationPathway`](@ref)s, [`chlorophyll_fluorescence`](@ref) with + the chloroplast-level emission of Fluspect ([`chloroplast_emission`](@ref)), [`CDOMFluorescence`](@ref), [`WaterRaman`](@ref). See [Inelastic processes](@ref). * **Layer + column**: [`OceanLayer`](@ref), [`OceanColumn`](@ref), diff --git a/docs/src/reference/inelastic.md b/docs/src/reference/inelastic.md index 92832ec..0d52a91 100644 --- a/docs/src/reference/inelastic.md +++ b/docs/src/reference/inelastic.md @@ -1,12 +1,15 @@ # Inelastic processes Fluorescence, water Raman, and CDOM fluorescence packaged as kernels -consumed by a two-pass RT solver (Fell 1997 §2.2.9). +consumed by a two-pass RT solver (Fell 1997 §2.2.9), and the light +absorbed per layer and component that drives them. ## Spectral redistribution ```@docs AbstractSpectralRedistribution +TabulatedEmission +chloroplast_emission GaussianEmission WavenumberShiftEmission redistribution @@ -16,6 +19,7 @@ fwhm_to_sigma ## Concrete processes ```@docs +ExcitationPathway IsotropicFluorescence CDOMFluorescence WaterRaman @@ -30,7 +34,19 @@ AbstractOceanInelasticProcess excitation_absorption emission excitation_range +excitation_pathways is_isotropic inelastic_coefficient radiance_source_kernel ``` + +## Light absorbed per layer + +```@docs +absorbed_power +absorbed_photons +absorbed_par +inelastic_emission +excitation_optical_depth +absorber_index +``` diff --git a/docs/src/reference/materials.md b/docs/src/reference/materials.md index 5f005df..ff08f78 100644 --- a/docs/src/reference/materials.md +++ b/docs/src/reference/materials.md @@ -40,6 +40,20 @@ Bricaud1998 Gordon1992 ``` +## Pigment partitions + +```@docs +AbstractPigmentPartition +ProspectPigments +Bidigare1990Pigments +pigment_parts +pigment_class +pigment_fractions +absorption_parts +absorption_by_part +absorption_part +``` + ## Non-algal particles ```@docs diff --git a/docs/src/reference/types.md b/docs/src/reference/types.md index c39ac39..1cfb00c 100644 --- a/docs/src/reference/types.md +++ b/docs/src/reference/types.md @@ -47,11 +47,14 @@ fell_column layer_optics column_optics OceanLayerOptics +AbsorptionComponent ScatteringComponent +InelasticComponent OceanColumnOptics AbstractOceanBottom BlackBottom LambertianBottom +TabulatedLambertianBottom bottom_albedo interface_depths wavelengths diff --git a/docs/src/vsmartmom_integration.md b/docs/src/vsmartmom_integration.md index 7c96e93..c4fbf7c 100644 --- a/docs/src/vsmartmom_integration.md +++ b/docs/src/vsmartmom_integration.md @@ -15,8 +15,10 @@ documentation, not part of either package. `phase_function` and `scattering_matrix` refer to its analytic phase functions; OceanOptics uses [`greek_expansion`](@ref), [`scattering_phase`](@ref) and [`evaluate_scattering_matrix`](@ref).) -* OceanOptics is not registered yet: register and tag it before a - vSmartMOM release declares it in `[weakdeps]`/`[compat]`. +* OceanOptics v0.1.0 is in the General registry's queue; v0.2.0 (this + documentation) adds absorption and inelastic components and breaks the + v0.1 layer layout. Declare the version the adapter is written against in + vSmartMOM's `[weakdeps]`/`[compat]`. ## Mapping @@ -24,11 +26,13 @@ documentation, not part of either package. |---|---| | [`GreekCoefficients`](@ref) `(α, β, γ, δ, ϵ, ζ)` | `Scattering.GreekCoefs(α, β, γ, δ, ϵ, ζ)` — same fields, order and signs | | [`ScatteringComponent`](@ref) | one `CoreScatteringOpticalProperties` per component, `ϖ = 1`, truncated like an aerosol type | -| `absorption_optical_depth(layer)` | `CoreAbsorptionOpticalProperties(τ)` | -| components within a layer | combined with vSmartMOM's `+` (weights `τ·ϖ`, identical to OceanOptics' scattering weights) | +| `absorption_optical_depth(layer)` (sum of `layer.absorbers`) | `CoreAbsorptionOpticalProperties(τ)` | +| scattering components within a layer | combined with vSmartMOM's `+` (weights `τ·ϖ`, identical to OceanOptics' scattering weights) | | layers of an [`OceanColumnOptics`](@ref) | vertical composition by adding on the water quadrature grid, below the refracting interface — never `*`, which concatenates spectral points | | `col.refractive_index` | interface index per spectral point (relative to air) | -| `bottom_albedo(col)` | lower boundary of the water grid | +| `bottom_albedo(col)` at `bottom_depth(col)` | Lambertian reflection operator (`m = 0`, intensity only) below the last layer; zero for `BlackBottom` | +| `layer.absorbers` (individual `τ`) | absorbed power per component from the layer-mean scalar irradiance ([`absorbed_power`](@ref), [`absorbed_par`](@ref)) | +| `layer.inelastic` | distributed sources (V3/V4): kernels of each `process`, excitation from the linked absorption components | | `λ` `[nm]` | evaluate at `λ = 10⁷ ./ ν`; decreasing grids are accepted | Rayleigh Greek values agree with `get_greek_rayleigh` exactly, and the @@ -51,7 +55,7 @@ function layer_core_optics(layer, μ, m, pol, l_trunc) nλ = n_wavelengths(layer) core = RT.CoreAbsorptionOpticalProperties(absorption_optical_depth(layer)) scat = nothing - for c in layer.components + for c in layer.scatterers is_wavelength_dependent(c) && # per-band expansion assumed here error("$(c.label): one expansion per band expected") g = greek_expansion(c, 1) @@ -99,5 +103,18 @@ implementation defines. matrices) are not converged at practical `ℓ_max` — e.g. the Chowdhary AOS-IV hydrosols still have `β₁₀₀₀/2001 ≈ 3×10⁻³` — so truncation is required, with its own convergence study. +* **Absorbed light per layer.** Chlorophyll light-absorption profiles and + fluorescence need, per layer and spectral point, the layer-mean scalar + irradiance `(1/Δz) ∫ E₀ dz` (direct and diffuse, all directions), + integrated within each layer — sublayers or an analytic layer integral, + not interface values alone. With it, [`absorbed_power`](@ref), + [`absorbed_par`](@ref) and [`inelastic_emission`](@ref) give the + diagnostics and the reference fluorescence budget; energy closure + (net irradiance below the surface = absorbed in the layers + absorbed by + the floor) is the test. * **Inelastic sources** follow the photon contract on the - [Consumer API](@ref) page ([`radiance_source_kernel`](@ref)). + [Consumer API](@ref) page ([`radiance_source_kernel`](@ref)). For + fluorescence, [`excitation_optical_depth`](@ref)`(layer, j)` gives the + excitation optical depth on the layer grid from the linked absorption + components; [`excitation_absorption`](@ref) gives the same coefficient + at any wavelength. diff --git a/src/OceanOptics.jl b/src/OceanOptics.jl index ac3de1a..dd5cc88 100644 --- a/src/OceanOptics.jl +++ b/src/OceanOptics.jl @@ -11,10 +11,16 @@ coupled atmosphere–ocean solver in vSmartMOM.jl, without depending on it. `HenyeyGreensteinPhase`, `PetzoldPhase`, `TabulatedGreekPhase`, `TabulatedMuellerPhase`, `WavelengthDependentPhase`, all expanded as `GreekCoefficients` in vSmartMOM's convention. -- `layer_optics` → `OceanLayerOptics`: absorption optical depth plus one - scattering component per constituent; `column_optics` → - `OceanColumnOptics` with the interface refractive index and the bottom. -- Inelastic process kernels (fluorescence, water Raman) for the solver. +- Pigment partitions of phytoplankton absorption (`ProspectPigments`, + `Bidigare1990Pigments`) for chlorophyll and accessory-pigment shares. +- `layer_optics` → `OceanLayerOptics`: absorption components (per + constituent or pigment group), scattering components with their + expansions, and inelastic processes linked to the absorption that + excites them; `column_optics` → `OceanColumnOptics` with the interface + refractive index and the bottom. +- Inelastic process kernels (fluorescence with chloroplast-level emission, + water Raman), and the light absorbed per component and the emission it + drives, given the solver's scalar irradiance. Units, conventions and validation rules are on the *Consumer API* docs page. """ @@ -58,6 +64,7 @@ include("phase/wavelength_phase.jl") include("materials/refractive_index.jl") include("materials/pure_water.jl") include("materials/cdom.jl") +include("materials/pigments.jl") include("materials/phytoplankton.jl") include("materials/nap.jl") include("materials/tabulated.jl") @@ -75,6 +82,11 @@ include("inelastic/raman.jl") # ----------------------------------------------------------------------------- include("mixing/layer_assembly.jl") +# ----------------------------------------------------------------------------- +# Light absorbed per component (given the solver's scalar irradiance) +# ----------------------------------------------------------------------------- +include("diagnostics/absorbed_light.jl") + # ============================================================================= # Public API # ============================================================================= @@ -82,7 +94,7 @@ include("mixing/layer_assembly.jl") # Abstract hierarchy export AbstractOceanConstituent, AbstractAbsorber, AbstractScatterer, AbstractAbsorbingScatterer export AbstractOceanPhaseFunction, AbstractRefractiveIndexModel, AbstractOceanBottom -export AbstractOceanInelasticProcess, AbstractSpectralRedistribution +export AbstractOceanInelasticProcess, AbstractSpectralRedistribution, AbstractPigmentPartition # Constituents export PureWater @@ -93,6 +105,10 @@ export Phytoplankton, AbstractPhytoplanktonModel, Bricaud1998, Gordon1992 export NonAlgalParticles, AbstractNAPModel, BabinBricaud2003, FellMineral export TabulatedAbsorber, TabulatedScatterer export absorption, scattering, backscattering, attenuation, scattering_phase, is_total_absorption +export absorption_parts, absorption_by_part, absorption_part + +# Pigment partitions of phytoplankton absorption +export ProspectPigments, Bidigare1990Pigments, pigment_parts, pigment_class, pigment_fractions # Refractive index of seawater export FixedRefractiveIndex, QuanFry1995, refractive_index @@ -109,7 +125,9 @@ export backscatter_fraction, asymmetry_parameter, is_polarizable, is_wavelength_ export IOP, OceanLayer, OceanColumn export thickness, midpoint_depth, n_layers, bottom_depth, midpoint_depths, layer_thicknesses export uniform_column, fell_column -export ScatteringComponent, OceanLayerOptics, OceanColumnOptics, BlackBottom, LambertianBottom +export AbsorptionComponent, ScatteringComponent, InelasticComponent +export OceanLayerOptics, OceanColumnOptics +export BlackBottom, LambertianBottom, TabulatedLambertianBottom export layer_optics, column_optics export n_moments, n_wavelengths, wavelengths, is_polarized export optical_depth, absorption_optical_depth, scattering_optical_depth @@ -119,11 +137,15 @@ export single_scattering_albedo, bottom_albedo, interface_depths export SpectralTable, linterp, data_path, load_spectral_csv # Inelastic processes -export GaussianEmission, WavenumberShiftEmission, fwhm_to_sigma -export IsotropicFluorescence, CDOMFluorescence, WaterRaman -export chlorophyll_fluorescence -export excitation_absorption, excitation_range, emission, is_isotropic +export GaussianEmission, WavenumberShiftEmission, TabulatedEmission, fwhm_to_sigma +export ExcitationPathway, IsotropicFluorescence, CDOMFluorescence, WaterRaman +export chlorophyll_fluorescence, chloroplast_emission +export excitation_absorption, excitation_range, excitation_pathways, emission, is_isotropic export quantum_yield, inelastic_coefficient, radiance_source_kernel, redistribution export raman_peak_wavelength +# Light absorbed per component +export absorbed_power, absorbed_photons, absorbed_par, inelastic_emission +export excitation_optical_depth, absorber_index + end # module diff --git a/src/diagnostics/absorbed_light.jl b/src/diagnostics/absorbed_light.jl new file mode 100644 index 0000000..fd81c73 --- /dev/null +++ b/src/diagnostics/absorbed_light.jl @@ -0,0 +1,165 @@ +# ============================================================================= +# Light absorbed per component, and the emission it drives +# ============================================================================= +# +# A radiative-transfer solver supplies, for each layer and wavelength, the +# layer-mean spectral scalar irradiance +# +# Ē₀(λ) = (1/Δz) ∫_layer E₀(z, λ) dz [W m⁻² nm⁻¹] +# +# (E₀: total intensity integrated over all directions, direct and diffuse). +# In a homogeneous layer every component absorbs +# +# A_c(λ) = a_c(λ) ∫ E₀ dz = τ_c(λ) Ē₀(λ) [W m⁻² nm⁻¹], +# +# so the absorption components of `OceanLayerOptics` give the light absorbed +# by each constituent or pigment group. These helpers turn that into photon +# units, absorbed PAR, and the spectral power emitted by an inelastic +# process. Spectral integrals over a window [lo, hi] integrate the linear +# interpolant of the integrand on the layer's wavelength grid exactly (the +# trapezoidal rule, with the end intervals clipped at lo and hi); a solver +# with its own bin weights may integrate itself. +# ============================================================================= + +# h c N_A in J m mol⁻¹ (SI 2019 exact constants) +const _PLANCK_SI = 6.62607015e-34 # J s +const _LIGHT_SI = 299_792_458.0 # m s⁻¹ +const _AVOGADRO_SI = 6.02214076e23 # mol⁻¹ + +"Photon flux per unit power at wavelength `λ` `[nm]`: µmol photons J⁻¹." +_µmol_per_joule(λ) = λ * 1e-9 / (_PLANCK_SI * _LIGHT_SI * _AVOGADRO_SI) * 1e6 + +function _check_irradiance(o::OceanLayerOptics, E₀::AbstractVector, who) + length(E₀) == n_wavelengths(o) || + throw(DimensionMismatch("$who: $(length(E₀)) irradiance values for " * + "$(n_wavelengths(o)) wavelengths")) + all(x -> isfinite(x) && x ≥ 0, E₀) || + throw(ArgumentError("$who: scalar irradiance must be finite and non-negative")) + return nothing +end + +""" + absorbed_power(o::OceanLayerOptics, E₀) -> Matrix + +Spectral power absorbed by each absorption component of layer `o`, +`A[c, k] = τ_c(λ_k) · E₀[k]`, given the layer-mean spectral scalar +irradiance `E₀[k]` at `o.λ[k]` (`(1/Δz) ∫ E₀ dz` over the layer, total +intensity over all directions, direct and diffuse). Rows follow +`o.absorbers`; units are those of `E₀` (`W m⁻² nm⁻¹` ⇒ absorbed +`W m⁻² nm⁻¹` per layer). +""" +function absorbed_power(o::OceanLayerOptics, E₀::AbstractVector{<:Real}) + _check_irradiance(o, E₀, "absorbed_power") + return [c.τ[k] * E₀[k] for c in o.absorbers, k in eachindex(o.λ)] +end + +""" + absorbed_photons(o::OceanLayerOptics, E₀) -> Matrix + +[`absorbed_power`](@ref) in photon units: µmol photons m⁻² s⁻¹ nm⁻¹ per +absorption component, for `E₀` in `W m⁻² nm⁻¹` (photon energy `hc/λ`). +""" +function absorbed_photons(o::OceanLayerOptics, E₀::AbstractVector{<:Real}) + A = absorbed_power(o, E₀) + return A .* _µmol_per_joule.(permutedims(o.λ)) +end + +""" + absorbed_par(o::OceanLayerOptics, E₀; range = (400, 700)) -> Vector + +Photosynthetically available radiation absorbed by each absorption +component of layer `o`: [`absorbed_photons`](@ref) integrated over +`range` `[nm]`, in µmol photons m⁻² s⁻¹. The integral is that of the +linear interpolant on the layer grid (trapezoidal rule, end intervals +clipped at the range limits), so the grid must span `range` but need not +contain its limits. Entries follow `o.absorbers`; see +[`absorber_index`](@ref). + +For phytoplankton with a pigment partition this gives the PAR absorbed by +each pigment group, e.g. by chlorophyll. +""" +function absorbed_par(o::OceanLayerOptics, E₀::AbstractVector{<:Real}; + range::Tuple{<:Real, <:Real} = (400, 700)) + w = _window_weights(o.λ, range, "absorbed_par") + N = absorbed_photons(o, E₀) + return N * w +end + +# Weights w (on the points of λ, in either order) such that Σ w_k y_k is the +# integral over [lo, hi] of the linear interpolant of y: the trapezoidal +# rule, with the intervals that straddle lo or hi clipped there. +function _window_weights(λ::AbstractVector{FT}, range, who) where {FT} + lo, hi = range + lo < hi || throw(ArgumentError("$who: range must be (lo, hi) with lo < hi, got $range")) + λmin, λmax = extrema(λ) + λmin ≤ lo && λmax ≥ hi || + throw(ArgumentError("$who: the wavelength grid ($(λmin)–$(λmax) nm) does not span " * + "the integration range $(lo)–$(hi) nm")) + order = sortperm(λ) + w = zeros(FT, length(λ)) + for (a, b) in zip(@view(order[1:end-1]), @view(order[2:end])) + xa, xb = λ[a], λ[b] + u, v = max(xa, lo), min(xb, hi) + v > u || continue + h = xb - xa + tu, tv = (u - xa) / h, (v - xa) / h + wb = h * (tv^2 - tu^2) / 2 # ∫ t dx over the clipped interval + w[a] += h * (tv - tu) - wb # ∫ (1 − t) dx + w[b] += wb + end + return w +end + +""" + excitation_optical_depth(o::OceanLayerOptics, j) -> Vector + +Excitation optical depth `τᴵ(λ) = aᴵ(λ) Δz` of the layer's `j`-th +inelastic component on the layer grid. For a process with excitation +pathways (fluorescence) it is formed from the stored absorption +components, `quantum_yield(p) · Σ_k efficiency[k] · absorbers[excitation[k]].τ`, +which equals `Δz · excitation_absorption(p, λ)`; otherwise (water Raman) +it is `Δz · excitation_absorption(p, λ)`. +""" +function excitation_optical_depth(o::OceanLayerOptics{FT}, j::Integer) where {FT} + c = o.inelastic[j] + isempty(c.excitation) && + return [FT(thickness(o) * excitation_absorption(c.process, λ)) for λ in o.λ] + τ = zeros(FT, n_wavelengths(o)) + for (i, η) in zip(c.excitation, c.efficiency) + τ .+= η .* o.absorbers[i].τ + end + return FT(quantum_yield(c.process)) .* τ +end + +""" + inelastic_emission(o::OceanLayerOptics, j, E₀, λ_em; range = excitation_range(p)) -> Vector + +Spectral power `[W m⁻² nm⁻¹]` emitted in all directions by layer `o` +through its `j`-th inelastic component (process `p`), at emission +wavelengths `λ_em` `[nm]`: + +`P(λ) = ∫ τᴵ(λ′) Ē₀(λ′) f(λ′, λ) λ′/λ dλ′ = Δz ∫ radiance_source_kernel(p, λ′, λ) Ē₀(λ′) dλ′`, + +with `τᴵ` from [`excitation_optical_depth`](@ref) (the layer's stored +absorption components) and `E₀` the layer-mean scalar irradiance on the +layer grid (as in [`absorbed_power`](@ref)), integrated over `range` as +in [`absorbed_par`](@ref). For an isotropic process the volume source of +radiance is `P / (4π Δz)` per unit emission wavelength. + +For fluorescence, the photons emitted equal the quantum yield times the +photons the excitation components deliver, +`∫ P λ/(hc) dλ = φ Σ_k η_k ∫ A_k λ′/(hc) dλ′` (to the extent `λ_em` +covers the emission band); reabsorption of the emission is left to the +radiative transfer. +""" +function inelastic_emission(o::OceanLayerOptics{FT}, j::Integer, E₀::AbstractVector{<:Real}, + λ_em::AbstractVector{<:Real}; + range::Tuple{<:Real, <:Real} = excitation_range(o.inelastic[j].process)) where {FT} + _check_irradiance(o, E₀, "inelastic_emission") + p = o.inelastic[j].process + w = _window_weights(o.λ, range, "inelastic_emission") + x = w .* excitation_optical_depth(o, j) .* E₀ # excitation per grid point + ks = [k for k in eachindex(o.λ) if x[k] != 0] + return [sum(x[k] * emission(p, o.λ[k], λ) * o.λ[k] / λ for k in ks; init = zero(FT) * zero(float(λ))) + for λ in λ_em] +end diff --git a/src/inelastic/fluorescence.jl b/src/inelastic/fluorescence.jl index 7c40ee6..6de7fce 100644 --- a/src/inelastic/fluorescence.jl +++ b/src/inelastic/fluorescence.jl @@ -2,131 +2,292 @@ # Fluorescence processes # ============================================================================= # -# Ocean fluorescence sources covered here: +# A fluorescence process turns absorbed photons into emitted photons. With +# quantum yield φ and excitation pathways k, # -# IsotropicFluorescence — generic isotropic fluorescence parameterized by -# an `AbstractAbsorber` (phytoplankton, NAP, …), -# a spectral-redistribution profile, and a -# quantum yield. Chlorophyll-a fluorescence is -# the primary use case. -# CDOMFluorescence — convenience wrapper specialized on a `CDOM` -# absorber; same physics, narrower type. +# a^I(λ') = φ · Σ_k η_k · a_k(λ') [1/m] +# f(λ', λ) = f(λ) [1/nm], ∫ f dλ = 1 # -# The chlorophyll-fluorescence parameterization matches Fell (1997) §2.2.9 -# and Gordon (1979): Gaussian emission centered at 685 nm with σ = 10.6 nm -# (FWHM ≈ 25 nm), quantum yield φ_C ≈ 0.003 over the 400–700 nm -# photosynthetically-active excitation range. +# where a_k is the absorption of one absorber, or one pigment group of it +# (see `absorption_parts`), and η_k ∈ [0, 1] is the fraction of the photons +# it absorbs that reach the fluorescing chlorophyll. Chlorophyll has η = 1; +# accessory pigments acting as antenna pass on a fraction η ≤ 1; light +# absorbed for photoprotection, or otherwise quenched, has η = 0. +# +# IsotropicFluorescence — generic isotropic fluorescence from any set of +# excitation pathways and emission spectrum. +# chlorophyll_fluorescence — chlorophyll fluorescence of `Phytoplankton`, +# with the chloroplast-level emission of the land +# leaf model Fluspect by default and pathways +# from the phytoplankton's pigment partition. +# CDOMFluorescence — CDOM fluorescence, a separate type so solvers +# can dispatch on it. +# +# Quantum yields have no defensible universal value and are always given +# explicitly. # ============================================================================= """ $(TYPEDEF) -Isotropic fluorescence from an `AbstractAbsorber` with a configurable -spectral redistribution and quantum yield. +One excitation pathway of a fluorescence process: the photons absorbed by +part `part` of `absorber` (see [`absorption_parts`](@ref)), of which the +fraction `efficiency` is passed on to the fluorescing pigment. # Fields $(TYPEDFIELDS) -# Examples +# Construction + + ExcitationPathway(absorber, part = :total, efficiency = 1) + +`efficiency` (η) lies in `[0, 1]`: 1 for chlorophyll itself, the energy +transfer efficiency for an antenna pigment, 0 for absorption that is +dissipated (photoprotective pigments, quenching). +""" +struct ExcitationPathway{FT<:AbstractFloat, A<:AbstractAbsorber{FT}} + "Absorbing constituent; must also be a constituent of every layer the process is in" + absorber::A + "Absorption part of `absorber`" + part::Symbol + "Fraction of absorbed photons passed to the fluorescing pigment (η)" + efficiency::FT + + function ExcitationPathway{FT, A}(absorber::A, part::Symbol, + efficiency) where {FT<:AbstractFloat, A<:AbstractAbsorber{FT}} + part in absorption_parts(absorber) || + throw(ArgumentError("ExcitationPathway: $(nameof(A)) has no absorption part :$part; " * + "its parts are $(absorption_parts(absorber))")) + isfinite(efficiency) && 0 ≤ efficiency ≤ 1 || + throw(ArgumentError("ExcitationPathway: efficiency must lie in [0, 1], got $efficiency")) + new{FT, A}(absorber, part, efficiency) + end +end + +ExcitationPathway(absorber::AbstractAbsorber{FT}, part::Symbol = :total, + efficiency::Real = 1) where {FT} = + ExcitationPathway{FT, typeof(absorber)}(absorber, part, FT(efficiency)) + +function Base.show(io::IO, x::ExcitationPathway) + print(io, "ExcitationPathway(", nameof(typeof(x.absorber)), ", :", x.part, ", η = ", + x.efficiency, ")") +end + +""" + excitation_pathways(p::AbstractOceanInelasticProcess) -> Tuple + +The [`ExcitationPathway`](@ref)s whose absorbed photons drive `p`; empty +for processes not driven by absorption (water Raman). +""" +excitation_pathways(::AbstractOceanInelasticProcess) = () + +_pathways(x::ExcitationPathway) = (x,) +_pathways(x::AbstractAbsorber) = (ExcitationPathway(x),) +_pathways(x::Union{Tuple, AbstractVector}) = Tuple(Iterators.flatten(map(_pathways, x))) +""" +$(TYPEDEF) + +Isotropic fluorescence: photons absorbed through the excitation pathways +are re-emitted with quantum yield `quantum_yield` and spectral +distribution `emission`. + +# Fields +$(TYPEDFIELDS) + +# Construction + + IsotropicFluorescence(excitation; emission, quantum_yield, excitation_range) + +`excitation` is an absorber (all of its absorption, η = 1), an +[`ExcitationPathway`](@ref), or a collection of them. The excitation +coefficient is + +`excitation_absorption(p, λ′) = φ · Σ_k η_k · absorption_part(absorber_k, part_k, λ′)`. + +# Example ```julia -phyto = Phytoplankton{Float64, Bricaud1998}(Chl = 0.5) -sif = chlorophyll_fluorescence(phyto) # default config -sif = IsotropicFluorescence{Float64}(phyto; - emission = GaussianEmission{Float64}(center_nm = 685.0, - σ_nm = 10.6), - quantum_yield = 0.003, - excitation_range = (400.0, 700.0)) +phyto = Phytoplankton(Chl = 0.5, pigments = ProspectPigments(carotenoid_ratio = 0.3)) +f = IsotropicFluorescence([ExcitationPathway(phyto, :chlorophyll, 1.0), + ExcitationPathway(phyto, :carotenoids, 0.5)]; + emission = chloroplast_emission(), quantum_yield = 0.02, + excitation_range = (400.0, 700.0)) ``` +See [`chlorophyll_fluorescence`](@ref) for the same with defaults per +pigment group. """ -struct IsotropicFluorescence{FT, A<:AbstractAbsorber{FT}, - E<:AbstractSpectralRedistribution{FT}} <: AbstractOceanInelasticProcess{FT} - "Absorbing constituent whose absorbed photons drive emission" - absorber::A - "Spectral redistribution `f(λ', λ)` `[1/nm]`" +struct IsotropicFluorescence{FT, X<:Tuple{Vararg{ExcitationPathway{FT}}}, + E<:AbstractSpectralRedistribution{FT}} <: AbstractOceanInelasticProcess{FT} + "Excitation pathways" + excitation::X + "Spectral redistribution `f(λ', λ)` `[1/nm]` of the emitted photons" emission::E - "Quantum yield `φ` (dimensionless, typically 0.001–0.01 for Chl-a)" + "Fluorescence quantum yield φ: photons emitted per photon delivered to the fluorescing pigment" quantum_yield::FT "Excitation-wavelength integration window `[nm]`" excitation_range::Tuple{FT, FT} - function IsotropicFluorescence{FT, A, E}(absorber::A, emission::E, - quantum_yield::FT, - excitation_range::Tuple{FT, FT}) where { - FT<:AbstractFloat, A<:AbstractAbsorber{FT}, - E<:AbstractSpectralRedistribution{FT}} - zero(FT) ≤ quantum_yield ≤ one(FT) || - throw(ArgumentError("IsotropicFluorescence: quantum_yield must be in [0, 1], got $quantum_yield")) - excitation_range[1] < excitation_range[2] || - throw(ArgumentError("IsotropicFluorescence: excitation_range must be (lo < hi), got $excitation_range")) - new{FT, A, E}(absorber, emission, quantum_yield, excitation_range) + function IsotropicFluorescence{FT, X, E}(excitation::X, emission::E, quantum_yield, + excitation_range) where {FT, X, E} + isempty(excitation) && + throw(ArgumentError("IsotropicFluorescence: no excitation pathway")) + _check_yield_and_range(quantum_yield, excitation_range, "IsotropicFluorescence") + new{FT, X, E}(excitation, emission, quantum_yield, excitation_range) end end -""" - IsotropicFluorescence{FT}(absorber; emission, quantum_yield, excitation_range) - -Construct an `IsotropicFluorescence` process from an `AbstractAbsorber`. -`absorber` must be typed `<:AbstractAbsorber{FT}`, which — after the -hierarchy refactor in §4.1 — includes all `AbstractAbsorbingScatterer` -subtypes (`PureWater`, `Phytoplankton`, `NonAlgalParticles`). -""" -function IsotropicFluorescence{FT}(absorber::AbstractAbsorber{FT}; - emission::AbstractSpectralRedistribution{FT}, - quantum_yield = FT(0.003), - excitation_range::Tuple{<:Real, <:Real} = (FT(400), FT(700)), -) where {FT<:AbstractFloat} - return IsotropicFluorescence{FT, typeof(absorber), typeof(emission)}( - absorber, emission, FT(quantum_yield), - (FT(excitation_range[1]), FT(excitation_range[2]))) +function IsotropicFluorescence(excitation; emission::AbstractSpectralRedistribution{FT}, + quantum_yield::Real, + excitation_range::Tuple{<:Real, <:Real}) where {FT} + x = _pathways(excitation) + all(p -> p isa ExcitationPathway{FT}, x) || + throw(ArgumentError("IsotropicFluorescence: absorbers and emission must share the " * + "floating-point type $FT")) + return IsotropicFluorescence{FT, typeof(x), typeof(emission)}( + x, emission, FT(quantum_yield), (FT(excitation_range[1]), FT(excitation_range[2]))) end -# ----------------------------------------------------------------------------- -# Trait implementations -# ----------------------------------------------------------------------------- +function _check_yield_and_range(φ, range, who) + isfinite(φ) && 0 ≤ φ ≤ 1 || + throw(ArgumentError("$who: quantum_yield must be in [0, 1], got $φ")) + 0 < range[1] < range[2] || + throw(ArgumentError("$who: excitation_range must be (lo, hi) with 0 < lo < hi, got $range")) + return nothing +end -# a^I(λ') = φ · a_absorber(λ'): quantum-yield-weighted excitation absorption -excitation_absorption(p::IsotropicFluorescence, λ_prime::Real) = - p.quantum_yield * absorption(p.absorber, λ_prime) +# a^I(λ') = φ · Σ_k η_k a_k(λ') +function excitation_absorption(p::IsotropicFluorescence, λ_prime::Real) + return p.quantum_yield * sum(x.efficiency * absorption_part(x.absorber, x.part, λ_prime) + for x in p.excitation) +end emission(p::IsotropicFluorescence, λ_prime::Real, λ::Real) = redistribution(p.emission, λ_prime, λ) -excitation_range(p::IsotropicFluorescence) = p.excitation_range -is_isotropic(::IsotropicFluorescence) = true -quantum_yield(p::IsotropicFluorescence) = p.quantum_yield +excitation_range(p::IsotropicFluorescence) = p.excitation_range +excitation_pathways(p::IsotropicFluorescence) = p.excitation +is_isotropic(::IsotropicFluorescence) = true +quantum_yield(p::IsotropicFluorescence) = p.quantum_yield function Base.show(io::IO, p::IsotropicFluorescence{FT}) where {FT} - print(io, "IsotropicFluorescence{$FT}(", typeof(p.absorber).name.name, - ", φ=", p.quantum_yield, ", ", p.emission, ")") + print(io, "IsotropicFluorescence{$FT}(φ = ", p.quantum_yield, ", ", + join(("$(nameof(typeof(x.absorber))):$(x.part) η=$(x.efficiency)" for x in p.excitation), ", "), + ", ", p.emission, ")") end # ----------------------------------------------------------------------------- -# Convenience constructor: chlorophyll fluorescence per Fell (1997) +# Chloroplast-level emission (land analogy, Fluspect) # ----------------------------------------------------------------------------- +const _FLUSPECT_EMISSION = _read_csv_columns(data_path("fluspect_chloroplast_emission.csv")) +const _FLUSPECT_SOURCE = "Fluspect Optipar2017_ProspectD (SCOPE; Vilfan et al. 2016, 2018)" + """ - chlorophyll_fluorescence(phyto::Phytoplankton; peak_nm=685.0, σ_nm=10.6, - quantum_yield=0.003, - excitation_range=(400.0, 700.0)) - -Construct the standard oceanic chlorophyll-a fluorescence process: a -Gaussian emission band at 685 nm with σ ≈ 10.6 nm (FWHM ≈ 25 nm) and -quantum yield φ_C = 0.003 — the parameterization used in Fell (1997) -§2.2.9 (North Sea average; cites Fischer & Kronfeld 1990, Deep-Sea Res. -37, 865) and Gordon (1979, Appl. Opt. 18, 1161). + chloroplast_emission([FT = Float64]; psi_share = nothing) -> TabulatedEmission + +Chlorophyll fluorescence emission at the photosystem (chloroplast) level, +before any reabsorption, as used for leaves by Fluspect +(`data/fluspect_chloroplast_emission.csv`, 640–851 nm): + +- `psi_share = nothing`: Fluspect's combined spectrum `phi` (the default + of SCOPE 2), with maxima at 685 and 739 nm; +- `psi_share = w ∈ [0, 1]`: the photosystem mixture + `w · phiI + (1 − w) · phiII` of the separate PSI (maximum at 728 nm) and + PSII (682 nm) spectra, with `w` the share of emitted photons from PSI. + +The spectra are photon densities per nm. Reabsorption by water and by the +pigments themselves is left to the radiative transfer: the emission +shape contains none. +""" +function chloroplast_emission(::Type{FT} = Float64; + psi_share::Union{Nothing, Real} = nothing) where {FT<:AbstractFloat} + λ = _FLUSPECT_EMISSION["lambda_nm"] + if psi_share === nothing + # phi carries one numerical artefact, -4.5e-6 at 641 nm (see the data file) + shape = max.(_FLUSPECT_EMISSION["phi"], 0) + source = _FLUSPECT_SOURCE * ", combined phi" + else + 0 ≤ psi_share ≤ 1 || + throw(ArgumentError("chloroplast_emission: psi_share must lie in [0, 1], got $psi_share")) + shape = psi_share .* _FLUSPECT_EMISSION["phiI"] .+ + (1 - psi_share) .* _FLUSPECT_EMISSION["phiII"] + source = _FLUSPECT_SOURCE * ", PSI share $psi_share" + end + return TabulatedEmission(FT.(λ), FT.(shape); source) +end + +""" + chlorophyll_fluorescence(phyto::Phytoplankton; quantum_yield, + carotenoid_transfer = nothing, phycobilin_transfer = 1, + transfer = (;), emission = chloroplast_emission(FT), + excitation_range = (400, 700)) -> IsotropicFluorescence + +Chlorophyll-a fluorescence of `phyto`, with one excitation pathway per +absorption part of `phyto`: + +| part | default η | +|:-----|:----------| +| `:total` (no pigment partition) | 1: all phytoplankton absorption | +| chlorophylls | 1 | +| carotenoids | `carotenoid_transfer`: required when the partition has carotenoids | +| phycobilins | `phycobilin_transfer` (phycobilisomes are a photosystem II antenna; the default 1 is a modelling choice) | +| `:unassigned` | 0 | + +`transfer` overrides η for named parts, e.g. +`(photosynthetic_carotenoids = 0.8, photoprotective_carotenoids = 0.0)` +for [`Bidigare1990Pigments`](@ref). `carotenoid_transfer = 0` is +chlorophyll-only excitation (as in Fluspect, whose excitation is the +chlorophyll share of leaf absorption); `1` makes carotenoids a lossless +antenna; values between give the share that is passed on rather than +quenched. + +`quantum_yield` (φ) has no default: in situ values range over roughly +0.01–0.05 (Loisel et al. 2023, who use HydroLight's 0.02). The default emission is Fluspect's chloroplast-level spectrum +([`chloroplast_emission`](@ref)), the default excitation window PAR. +`phyto` must also be a constituent of every layer the process is in; see +[`layer_optics`](@ref). + +# Example +```julia +phyto = Phytoplankton(Chl = 0.5, pigments = ProspectPigments(carotenoid_ratio = 0.3)) +chl_only = chlorophyll_fluorescence(phyto; quantum_yield = 0.02, carotenoid_transfer = 0.0) +antenna = chlorophyll_fluorescence(phyto; quantum_yield = 0.02, carotenoid_transfer = 0.6) +``` """ function chlorophyll_fluorescence(phyto::Phytoplankton{FT}; - peak_nm = FT(685.0), - σ_nm = FT(10.6), - quantum_yield = FT(0.003), + quantum_yield::Real, + carotenoid_transfer::Union{Nothing, Real} = nothing, + phycobilin_transfer::Real = 1, + transfer::NamedTuple = NamedTuple(), + emission::AbstractSpectralRedistribution{FT} = chloroplast_emission(FT), excitation_range::Tuple{<:Real, <:Real} = (FT(400), FT(700)), ) where {FT<:AbstractFloat} - em = GaussianEmission{FT}(center_nm = FT(peak_nm), σ_nm = FT(σ_nm)) - return IsotropicFluorescence{FT}(phyto; - emission = em, - quantum_yield = quantum_yield, - excitation_range = excitation_range) + parts = absorption_parts(phyto) + for k in keys(transfer) + k in parts || throw(ArgumentError("chlorophyll_fluorescence: `transfer` names :$k, " * + "which is not an absorption part of the phytoplankton $parts")) + end + if phyto.pigments === nothing && carotenoid_transfer !== nothing + throw(ArgumentError("chlorophyll_fluorescence: carotenoid_transfer needs a pigment " * + "partition; construct the Phytoplankton with `pigments = " * + "ProspectPigments(...)` or `Bidigare1990Pigments(...)`")) + end + function efficiency(part) + haskey(transfer, part) && return transfer[part] + part === :total && return 1 + class = pigment_class(phyto.pigments, part) + class === :chlorophyll && return 1 + class === :phycobilin && return phycobilin_transfer + class === :unassigned && return 0 + carotenoid_transfer === nothing && + throw(ArgumentError("chlorophyll_fluorescence: choose the carotenoid energy " * + "transfer: `carotenoid_transfer = 0` excites by chlorophyll " * + "absorption only, `1` uses carotenoids as a lossless antenna, " * + "values between pass on that share (or set :$part in `transfer`)")) + return carotenoid_transfer + end + pathways = Tuple(ExcitationPathway(phyto, part, efficiency(part)) for part in parts) + return IsotropicFluorescence(pathways; emission, quantum_yield, excitation_range) end # ============================================================================= @@ -137,7 +298,7 @@ end $(TYPEDEF) CDOM fluorescence as an isotropic inelastic process. Structurally equivalent -to [`IsotropicFluorescence`](@ref) specialized on a [`CDOM`](@ref) absorber, +to [`IsotropicFluorescence`](@ref) with a single [`CDOM`](@ref) pathway, but carried as a distinct type so solvers can dispatch separately and users can read model intent directly from the type. @@ -148,33 +309,33 @@ over the band. Fell (1997) uses a simple Gaussian model. # Fields $(TYPEDFIELDS) + +# Construction + + CDOMFluorescence(cdom; emission, quantum_yield, excitation_range = (300, 400)) """ -struct CDOMFluorescence{FT, E<:AbstractSpectralRedistribution{FT}} <: AbstractOceanInelasticProcess{FT} +struct CDOMFluorescence{FT, C<:CDOM{FT}, E<:AbstractSpectralRedistribution{FT}} <: AbstractOceanInelasticProcess{FT} "CDOM absorber driving the fluorescence" - cdom::CDOM{FT} + cdom::C "Spectral redistribution `f(λ', λ)` `[1/nm]`" emission::E "Quantum yield `φ_g` (dimensionless, band-integrated)" quantum_yield::FT "Excitation-wavelength integration window `[nm]`" excitation_range::Tuple{FT, FT} + + function CDOMFluorescence{FT, C, E}(cdom::C, emission::E, quantum_yield, + excitation_range) where {FT, C, E} + _check_yield_and_range(quantum_yield, excitation_range, "CDOMFluorescence") + new{FT, C, E}(cdom, emission, quantum_yield, excitation_range) + end end -""" - CDOMFluorescence{FT}(cdom; emission, quantum_yield=0.01, excitation_range=(300,400)) -""" -function CDOMFluorescence{FT}(cdom::CDOM{FT}; - emission::AbstractSpectralRedistribution{FT}, - quantum_yield = FT(0.01), - excitation_range::Tuple{<:Real, <:Real} = (FT(300), FT(400)), -) where {FT<:AbstractFloat} - zero(FT) ≤ FT(quantum_yield) ≤ one(FT) || - throw(ArgumentError("CDOMFluorescence: quantum_yield must be in [0, 1], got $quantum_yield")) - excitation_range[1] < excitation_range[2] || - throw(ArgumentError("CDOMFluorescence: excitation_range must be (lo < hi)")) - return CDOMFluorescence{FT, typeof(emission)}( - cdom, emission, FT(quantum_yield), - (FT(excitation_range[1]), FT(excitation_range[2]))) +function CDOMFluorescence(cdom::CDOM{FT}; emission::AbstractSpectralRedistribution{FT}, + quantum_yield::Real, + excitation_range::Tuple{<:Real, <:Real} = (FT(300), FT(400))) where {FT} + return CDOMFluorescence{FT, typeof(cdom), typeof(emission)}( + cdom, emission, FT(quantum_yield), (FT(excitation_range[1]), FT(excitation_range[2]))) end # Trait implementations @@ -184,9 +345,10 @@ excitation_absorption(p::CDOMFluorescence, λ_prime::Real) = emission(p::CDOMFluorescence, λ_prime::Real, λ::Real) = redistribution(p.emission, λ_prime, λ) -excitation_range(p::CDOMFluorescence) = p.excitation_range -is_isotropic(::CDOMFluorescence) = true -quantum_yield(p::CDOMFluorescence) = p.quantum_yield +excitation_range(p::CDOMFluorescence) = p.excitation_range +excitation_pathways(p::CDOMFluorescence) = (ExcitationPathway(p.cdom),) +is_isotropic(::CDOMFluorescence) = true +quantum_yield(p::CDOMFluorescence) = p.quantum_yield function Base.show(io::IO, p::CDOMFluorescence{FT}) where {FT} print(io, "CDOMFluorescence{$FT}(φ=", p.quantum_yield, ", ", p.emission, ")") diff --git a/src/inelastic/redistribution.jl b/src/inelastic/redistribution.jl index 0c0a737..f62accf 100644 --- a/src/inelastic/redistribution.jl +++ b/src/inelastic/redistribution.jl @@ -11,15 +11,20 @@ # is redistributed over emission wavelength `λ`. It is dimensioned # `[1/nm]` and normalized `∫ f(λ', λ) dλ = 1` for every excitation `λ'`. # -# Two shapes cover the ocean cases of interest: +# Three shapes cover the ocean cases of interest: # +# * `TabulatedEmission(λ, shape)` — tabulated emission spectrum, +# independent of `λ'`; e.g. the +# chloroplast-level chlorophyll +# emission of Fluspect +# (`chloroplast_emission`). # * `GaussianEmission(center, σ)` — Gaussian in *wavelength* space, # centered at a fixed `center` -# regardless of `λ'`. This is the -# chlorophyll-a fluorescence profile -# (685 nm, σ = 10.6 nm per Fell 1997 -# §2.2.9) and the standard CDOM -# fluorescence model. +# regardless of `λ'`: the single-band +# chlorophyll-a profile (685 nm, +# σ = 10.6 nm per Fell 1997 §2.2.9) +# and the standard CDOM fluorescence +# model. # * `WavenumberShiftEmission(Δν, σ_ν)` — Gaussian in *wavenumber* space, # centered at `ν' - Δν` where # `ν = 10⁷/λ` [1/cm]. Water Raman @@ -99,6 +104,88 @@ function redistribution(r::GaussianEmission, λ_prime::Real, λ::Real) return inv(σ * sqrt(2π)) * exp(-((λ - μ) / σ)^2 / 2) end +# ----------------------------------------------------------------------------- +# Tabulated emission spectrum +# ----------------------------------------------------------------------------- + +""" +$(TYPEDEF) + +Emission spectrum tabulated in wavelength, independent of excitation: +photon density `f(λ)` `[1/nm]`, interpolated linearly between the +tabulated points and zero outside them. + +# Fields +$(TYPEDFIELDS) + +# Construction + + TabulatedEmission(λ, shape; units = :photons, source = "") + +`λ` `[nm]` strictly increasing; `shape` finite, non-negative and not all +zero, in any scale. `shape` is a spectral *shape*: it is divided by its +trapezoidal integral, which makes the interpolated density integrate to +exactly one. With `units = :energy`, `shape` is an energy spectrum (as +most measured emission spectra are) and is first converted to photon +numbers, `∝ shape · λ`. Tabulate down to zero at both ends: the density +drops to zero outside the table. +""" +struct TabulatedEmission{FT<:AbstractFloat} <: AbstractSpectralRedistribution{FT} + "Emission wavelengths `[nm]`, strictly increasing" + λ::Vector{FT} + "Photon density `[1/nm]` at each `λ`, with unit trapezoidal integral" + density::Vector{FT} + "Provenance: citation, table and any transformation applied" + source::String + + function TabulatedEmission{FT}(λ::Vector{FT}, density::Vector{FT}, + source::String) where {FT<:AbstractFloat} + who = "TabulatedEmission" + length(λ) ≥ 2 || throw(ArgumentError("$who: need at least two wavelengths")) + _check_exact_λ_grid(λ, who) + length(density) == length(λ) || + throw(DimensionMismatch("$who: $(length(density)) values for $(length(λ)) wavelengths")) + all(x -> isfinite(x) && x ≥ 0, density) || + throw(ArgumentError("$who: the emission shape must be finite and non-negative")) + area = _trapezoid(λ, density) + abs(area - 1) ≤ sqrt(eps(FT)) || + throw(ArgumentError("$who: the density integrates to $area, not 1")) + new{FT}(λ, density, source) + end +end + +function TabulatedEmission(λ::AbstractVector{<:Real}, shape::AbstractVector{<:Real}; + units::Symbol = :photons, source::AbstractString = "") + units in (:photons, :energy) || + throw(ArgumentError("TabulatedEmission: units must be :photons or :energy, got :$units")) + FT = float(promote_type(eltype(λ), eltype(shape))) + x = collect(FT, λ) + y = collect(FT, shape) + length(x) == length(y) || + throw(DimensionMismatch("TabulatedEmission: $(length(y)) values for $(length(x)) wavelengths")) + all(v -> isfinite(v) && v ≥ 0, y) || + throw(ArgumentError("TabulatedEmission: the emission shape must be finite and non-negative")) + units === :energy && (y .*= x) + area = _trapezoid(x, y) + area > 0 || throw(ArgumentError("TabulatedEmission: the emission shape is zero everywhere")) + return TabulatedEmission{FT}(x, y ./ area, String(source)) +end + +_trapezoid(x, y) = sum((x[i+1] - x[i]) * (y[i] + y[i+1]) / 2 for i in 1:length(x)-1) + +function redistribution(r::TabulatedEmission, λ_prime::Real, λ::Real) + x, y = r.λ, r.density + first(x) ≤ λ ≤ last(x) || return zero(promote_type(eltype(y), typeof(float(λ)))) + i = clamp(searchsortedlast(x, λ), 1, length(x) - 1) + t = (λ - x[i]) / (x[i+1] - x[i]) + return (1 - t) * y[i] + t * y[i+1] +end + +function Base.show(io::IO, r::TabulatedEmission{FT}) where {FT} + print(io, "TabulatedEmission{$FT}(", first(r.λ), "–", last(r.λ), " nm", + isempty(r.source) ? "" : ", \"$(r.source)\"", ")") +end + # ----------------------------------------------------------------------------- # Wavenumber-shifted Gaussian (water Raman) # ----------------------------------------------------------------------------- diff --git a/src/materials/phytoplankton.jl b/src/materials/phytoplankton.jl index d30e6ae..2460609 100644 --- a/src/materials/phytoplankton.jl +++ b/src/materials/phytoplankton.jl @@ -56,6 +56,13 @@ currently uses Morel & Maritorena (2001) irrespective of `M`, and the phase function defaults to `FournierForandPhase` with backscatter fraction 0.01 (typical open-ocean living phytoplankton). +An optional pigment partition ([`ProspectPigments`](@ref), +[`Bidigare1990Pigments`](@ref)) attributes the absorption to pigment +groups: [`absorption_parts`](@ref) then names the groups, +[`layer_optics`](@ref) reports one absorption component per group, and +[`chlorophyll_fluorescence`](@ref) can weight each group by its energy +transfer to chlorophyll. The total absorption is unchanged. + # Fields $(TYPEDFIELDS) @@ -67,31 +74,49 @@ phyto = Phytoplankton{Float64, Bricaud1998}(Chl = 0.5) # Custom backscatter fraction (coastal, larger cells) phyto = Phytoplankton{Float64, Bricaud1998}(Chl = 2.0, B = 0.015) + +# Absorption attributed to chlorophyll and carotenoids +phyto = Phytoplankton(Chl = 0.5, pigments = ProspectPigments(carotenoid_ratio = 0.3)) +absorption_parts(phyto) # (:chlorophyll, :carotenoids, :unassigned) ``` """ -struct Phytoplankton{FT, M<:AbstractPhytoplanktonModel, - P<:AbstractOceanPhaseFunction{FT}} <: AbstractAbsorbingScatterer{FT} +struct Phytoplankton{FT, M<:AbstractPhytoplanktonModel, P<:AbstractOceanPhaseFunction{FT}, + G<:Union{Nothing, AbstractPigmentPartition}} <: AbstractAbsorbingScatterer{FT} "Parameterization-model tag (e.g. `Bricaud1998()`)" model::M "Chlorophyll-a concentration `[mg/m³]`" Chl::FT "Particulate-scattering phase function" phase::P + "Pigment partition of the absorption, or `nothing` (a single part, `:total`)" + pigments::G end """ - Phytoplankton{FT, M}(; Chl, B=0.01) + Phytoplankton{FT, M}(; Chl, B = 0.01, pigments = nothing) Construct a `Phytoplankton` instance with Fournier-Forand phase function -parameterized by backscatter fraction `B`. +parameterized by backscatter fraction `B`, and optionally a pigment +partition of its absorption. """ -function Phytoplankton{FT, M}(; Chl, B = FT(0.01)) where {FT<:AbstractFloat, M<:AbstractPhytoplanktonModel} +function Phytoplankton{FT, M}(; Chl, B = FT(0.01), + pigments::Union{Nothing, AbstractPigmentPartition} = nothing + ) where {FT<:AbstractFloat, M<:AbstractPhytoplanktonModel} Chl ≥ zero(Chl) || throw(ArgumentError("Phytoplankton: Chl must be non-negative, got $Chl")) phase = FournierForandPhase{FT}(backscatter_fraction = FT(B)) - return Phytoplankton{FT, M, typeof(phase)}(M(), FT(Chl), phase) + pg = _partition_precision(FT, pigments) + return Phytoplankton{FT, M, typeof(phase), typeof(pg)}(M(), FT(Chl), phase, pg) end +# Floating-point partitions take the phytoplankton's precision, so that the +# absorption parts have the type of the total; dual numbers (AD) pass through. +_partition_precision(::Type{FT}, p) where {FT} = p +_partition_precision(::Type{FT}, p::ProspectPigments{<:AbstractFloat}) where {FT} = + ProspectPigments{FT}(p.carotenoid_ratio) +_partition_precision(::Type{FT}, p::Bidigare1990Pigments{<:AbstractFloat}) where {FT} = + Bidigare1990Pigments{FT}(_concentrations(p)...) + Phytoplankton{FT}(; kwargs...) where {FT<:AbstractFloat} = Phytoplankton{FT, Bricaud1998}(; kwargs...) Phytoplankton(; kwargs...) = Phytoplankton{Float64}(; kwargs...) @@ -123,6 +148,13 @@ end absorption(p::Phytoplankton, λ::AbstractVector) = [absorption(p, λi) for λi in λ] +absorption_parts(p::Phytoplankton) = p.pigments === nothing ? (:total,) : pigment_parts(p.pigments) + +function absorption_by_part(p::Phytoplankton, λ::Real) + a = absorption(p, λ) + return p.pigments === nothing ? (a,) : map(f -> f * a, pigment_fractions(p.pigments, λ)) +end + # ----------------------------------------------------------------------------- # Scattering — Morel & Maritorena (2001) Case-1 particulate form # ----------------------------------------------------------------------------- @@ -156,5 +188,6 @@ backscattering(p::Phytoplankton, λ::AbstractVector) = [backscattering(p, λi) f function Base.show(io::IO, p::Phytoplankton{FT, M}) where {FT, M} print(io, "Phytoplankton{$FT}(", nameof(M), ", Chl=$(p.Chl) mg/m³, ", - "B=", backscatter_fraction(p.phase), ")") + "B=", backscatter_fraction(p.phase), + p.pigments === nothing ? "" : ", $(p.pigments)", ")") end diff --git a/src/materials/pigments.jl b/src/materials/pigments.jl new file mode 100644 index 0000000..01ddd87 --- /dev/null +++ b/src/materials/pigments.jl @@ -0,0 +1,235 @@ +# ============================================================================= +# Pigment partitions of phytoplankton absorption +# ============================================================================= +# +# Chlorophyll fluorescence is excited by the light that chlorophyll absorbs +# and by the share of light absorbed by accessory pigments that they pass on +# to chlorophyll (antenna); the rest is dissipated (photoprotection, +# quenching). To account for this, a pigment partition attributes a +# phytoplankton absorption coefficient a_ph(λ) to pigment groups, +# +# a_k(λ) = f_k(λ) · a_ph(λ), f_k(λ) = c_k a*_k(λ) / Σ_j c_j a*_j(λ), +# +# from in vivo specific absorption spectra a*_k of the groups and their +# relative contents c_k. The total a_ph — packaging included — still comes +# from the phytoplankton model; only its attribution is added. The shares +# come from unpackaged spectra, so packaging is assumed to flatten all +# groups alike at each wavelength. +# +# Where every group spectrum is zero, or outside the tabulated range, the +# absorption goes to the part `:unassigned` instead of being guessed (the +# shares jump there). Fluorescence counts `:unassigned` with η = 0 unless +# told otherwise. +# +# Two partitions are bundled: +# ProspectPigments — land analogy: chlorophyll a+b and carotenoids with +# the PROSPECT-D in vivo spectra used by Fluspect. +# Bidigare1990Pigments — ocean pigment groups (chlorophylls a, b, c, +# photosynthetic and photoprotective carotenoids, +# phycoerythrins) after Bidigare et al. (1990). +# A partition only needs `pigment_parts`, `pigment_class` and +# `pigment_fractions`. +# ============================================================================= + +""" +$(TYPEDEF) + +Attribution of phytoplankton absorption to pigment groups. Subtypes +implement [`pigment_parts`](@ref), [`pigment_class`](@ref) and +[`pigment_fractions`](@ref). +""" +abstract type AbstractPigmentPartition end + +""" + pigment_parts(p::AbstractPigmentPartition) -> Tuple{Vararg{Symbol}} + +Names of the pigment groups of `p`; the last is `:unassigned`. +""" +function pigment_parts end + +""" + pigment_class(p::AbstractPigmentPartition, part::Symbol) -> Symbol + +`:chlorophyll`, `:carotenoid`, `:phycobilin` or `:unassigned`: the role +that sets the default energy-transfer efficiency of the part in +[`chlorophyll_fluorescence`](@ref). +""" +function pigment_class end + +""" + pigment_fractions(p::AbstractPigmentPartition, λ) -> Tuple + +Share of phytoplankton absorption attributed to each part of +[`pigment_parts`](@ref)`(p)` at `λ` `[nm]`; the shares sum to one. +""" +function pigment_fractions end + +# Shares c_k a*_k / Σ c_j a*_j, or everything unassigned where the sum is zero. +function _pigment_shares(s::NTuple{N, T}) where {N, T} + S = sum(s) + S > 0 || return (ntuple(_ -> zero(T), Val(N))..., one(T)) + return (map(x -> x / S, s)..., zero(T)) +end + +_unassigned_shares(::Val{N}, ::Type{T}) where {N, T} = (ntuple(_ -> zero(T), Val(N))..., one(T)) + +# ----------------------------------------------------------------------------- +# Land analogy: PROSPECT-D chlorophyll and carotenoid spectra +# ----------------------------------------------------------------------------- + +const _PROSPECT_D_TABLE = _read_csv_columns(data_path("prospect_d_pigment_absorption.csv")) +const _PROSPECT_KAB = SpectralTable(_PROSPECT_D_TABLE["lambda_nm"], _PROSPECT_D_TABLE["Kab"]) +const _PROSPECT_KCA = SpectralTable(_PROSPECT_D_TABLE["lambda_nm"], _PROSPECT_D_TABLE["Kca"]) + +""" +$(TYPEDEF) + +Land-analogous partition into chlorophyll (a + b) and carotenoids, with +the in vivo specific absorption spectra `Kab` and `Kca` of the leaf model +PROSPECT-D (Féret et al. 2017) that Fluspect uses +(`data/prospect_d_pigment_absorption.csv`, 400–800 nm). Parts: +`(:chlorophyll, :carotenoids, :unassigned)`; outside 400–800 nm all +absorption is `:unassigned`. + +# Fields +$(TYPEDFIELDS) + +# Example +```julia +phyto = Phytoplankton(Chl = 0.5, pigments = ProspectPigments(carotenoid_ratio = 0.25)) +absorption_by_part(phyto, 450.0) # (a_chl, a_car, 0.0) +``` +SCOPE's default leaf has 40 µg cm⁻² chlorophyll and 10 µg cm⁻² +carotenoids, a ratio of 0.25; phytoplankton ratios differ between groups +and with light history. +""" +struct ProspectPigments{FT<:Real} <: AbstractPigmentPartition + "Carotenoid-to-chlorophyll mass ratio" + carotenoid_ratio::FT + + function ProspectPigments{FT}(carotenoid_ratio) where {FT<:Real} + isfinite(carotenoid_ratio) && carotenoid_ratio ≥ 0 || + throw(ArgumentError("ProspectPigments: carotenoid_ratio must be finite and " * + "non-negative, got $carotenoid_ratio")) + new{FT}(carotenoid_ratio) + end +end + +ProspectPigments(; carotenoid_ratio::Real) = + ProspectPigments{float(typeof(carotenoid_ratio))}(carotenoid_ratio) + +pigment_parts(::ProspectPigments) = (:chlorophyll, :carotenoids, :unassigned) + +pigment_class(p::ProspectPigments, part::Symbol) = + part === :chlorophyll ? :chlorophyll : + part === :carotenoids ? :carotenoid : + part === :unassigned ? :unassigned : _unknown_pigment(p, part) + +function pigment_fractions(p::ProspectPigments, λ::Real) + T = promote_type(typeof(p.carotenoid_ratio), typeof(float(λ))) + first(_PROSPECT_KAB.λ) ≤ λ ≤ last(_PROSPECT_KAB.λ) || return _unassigned_shares(Val(2), T) + return _pigment_shares((T(linterp(_PROSPECT_KAB, λ)), + T(p.carotenoid_ratio * linterp(_PROSPECT_KCA, λ)))) +end + +function Base.show(io::IO, p::ProspectPigments) + print(io, "ProspectPigments(carotenoid_ratio = ", p.carotenoid_ratio, ")") +end + +# ----------------------------------------------------------------------------- +# Ocean pigment groups: Bidigare et al. (1990) +# ----------------------------------------------------------------------------- + +const _BIDIGARE_TABLE = _read_csv_columns(data_path("bidigare_1990_pigments.csv")) +const _BIDIGARE_COLUMNS = ("chl_a", "chl_b", "chl_c", "psc", "ppc", "pe_peb", "pe_pub") +const _BIDIGARE_SPECTRA = Tuple(SpectralTable(_BIDIGARE_TABLE["lambda_nm"], _BIDIGARE_TABLE[c]) + for c in _BIDIGARE_COLUMNS) + +""" +$(TYPEDEF) + +Partition into the algal pigment groups of Bidigare et al. (1990), with +their in vivo weight-specific absorption spectra +(`data/bidigare_1990_pigments.csv`, 400–750 nm, from the Ocean Optics Web +Book). Fields are pigment concentrations `[mg m⁻³]`, e.g. from HPLC; only +their ratios matter, since the total comes from the phytoplankton model. + +Parts: `(:chlorophyll_a, :chlorophyll_b, :chlorophyll_c, +:photosynthetic_carotenoids, :photoprotective_carotenoids, +:phycoerythrin_peb, :phycoerythrin_pub, :unassigned)`. Outside +400–750 nm, and where all group spectra vanish (above the chlorophyll a +red band, ≈ 732 nm), all absorption is `:unassigned`. + +# Fields +$(TYPEDFIELDS) + +# Example +```julia +pig = Bidigare1990Pigments(chl_a = 0.5, chl_c = 0.1, psc = 0.3, ppc = 0.15) +phyto = Phytoplankton(Chl = 0.5, pigments = pig) +absorption_part(phyto, :photoprotective_carotenoids, 470.0) +``` +""" +struct Bidigare1990Pigments{FT<:Real} <: AbstractPigmentPartition + "Chlorophyll a `[mg m⁻³]`" + chl_a::FT + "Chlorophyll b `[mg m⁻³]`" + chl_b::FT + "Chlorophyll c `[mg m⁻³]`" + chl_c::FT + "Photosynthetic carotenoids (e.g. fucoxanthin, peridinin) `[mg m⁻³]`" + psc::FT + "Photoprotective carotenoids (e.g. zeaxanthin, diadinoxanthin, β-carotene) `[mg m⁻³]`" + ppc::FT + "Phycoerythrin rich in phycoerythrobilin (Synechococcus WH7803 type) `[mg m⁻³]`" + pe_peb::FT + "Phycoerythrin rich in phycourobilin (Synechococcus WH8103 type) `[mg m⁻³]`" + pe_pub::FT + + function Bidigare1990Pigments{FT}(c...) where {FT<:Real} + all(x -> isfinite(x) && x ≥ 0, c) || + throw(ArgumentError("Bidigare1990Pigments: concentrations must be finite and " * + "non-negative, got $c")) + any(>(0), c) || + throw(ArgumentError("Bidigare1990Pigments: at least one concentration must be positive")) + new{FT}(c...) + end +end + +function Bidigare1990Pigments(; chl_a::Real, chl_b::Real = 0, chl_c::Real = 0, psc::Real = 0, + ppc::Real = 0, pe_peb::Real = 0, pe_pub::Real = 0) + c = (chl_a, chl_b, chl_c, psc, ppc, pe_peb, pe_pub) + FT = float(promote_type(map(typeof, c)...)) + return Bidigare1990Pigments{FT}(map(FT, c)...) +end + +pigment_parts(::Bidigare1990Pigments) = + (:chlorophyll_a, :chlorophyll_b, :chlorophyll_c, :photosynthetic_carotenoids, + :photoprotective_carotenoids, :phycoerythrin_peb, :phycoerythrin_pub, :unassigned) + +function pigment_class(p::Bidigare1990Pigments, part::Symbol) + part in (:chlorophyll_a, :chlorophyll_b, :chlorophyll_c) && return :chlorophyll + part in (:photosynthetic_carotenoids, :photoprotective_carotenoids) && return :carotenoid + part in (:phycoerythrin_peb, :phycoerythrin_pub) && return :phycobilin + part === :unassigned && return :unassigned + return _unknown_pigment(p, part) +end + +_concentrations(p::Bidigare1990Pigments) = (p.chl_a, p.chl_b, p.chl_c, p.psc, p.ppc, p.pe_peb, p.pe_pub) + +function pigment_fractions(p::Bidigare1990Pigments{FT}, λ::Real) where {FT} + T = promote_type(FT, typeof(float(λ))) + tbl = first(_BIDIGARE_SPECTRA) + first(tbl.λ) ≤ λ ≤ last(tbl.λ) || return _unassigned_shares(Val(7), T) + return _pigment_shares(map((c, t) -> T(c * linterp(t, λ)), _concentrations(p), _BIDIGARE_SPECTRA)) +end + +function Base.show(io::IO, p::Bidigare1990Pigments) + names = ("chl_a", "chl_b", "chl_c", "psc", "ppc", "pe_peb", "pe_pub") + set = [string(n, " = ", c) for (n, c) in zip(names, _concentrations(p)) if c > 0] + print(io, "Bidigare1990Pigments(", join(set, ", "), ")") +end + +_unknown_pigment(p, part) = + throw(ArgumentError("$(nameof(typeof(p))) has no pigment part :$part; its parts are " * + "$(pigment_parts(p))")) diff --git a/src/mixing/layer_assembly.jl b/src/mixing/layer_assembly.jl index 4a76399..f77cfa5 100644 --- a/src/mixing/layer_assembly.jl +++ b/src/mixing/layer_assembly.jl @@ -3,11 +3,13 @@ # ============================================================================= # # For one layer and wavelength grid: -# 1. absorption optical depth τ_abs = Σ_c a_c Δz over all constituents -# (with the total-absorption exclusivity rule); +# 1. one AbsorptionComponent per absorber and absorption part: +# τ = a_part Δz (with the total-absorption exclusivity rule); # 2. one ScatteringComponent per scattering constituent: τ_c = b_c Δz, the # phase function's expansion (once, or per wavelength if it depends on -# wavelength), its backscatter fraction and a polarization label. +# wavelength), its backscatter fraction and a polarization label; +# 3. one InelasticComponent per inelastic process, linked to the +# absorption components of its excitation pathways. # ============================================================================= """ @@ -32,18 +34,24 @@ Optical properties of one [`OceanLayer`](@ref) at wavelengths `λ` `[nm]` - `FT` — floating-point type of the result. # Result -An [`OceanLayerOptics`](@ref) with the absorption optical depth and one -[`ScatteringComponent`](@ref) per scattering constituent, in constituent -order. Mixed quantities follow from [`optical_depth`](@ref), -[`single_scattering_albedo`](@ref) and +An [`OceanLayerOptics`](@ref) with, in constituent order, +- one [`AbsorptionComponent`](@ref) per absorbing constituent and + absorption part (see [`absorption_parts`](@ref): one part, `:total`, + unless e.g. phytoplankton carries a pigment partition); +- one [`ScatteringComponent`](@ref) per scattering constituent; +- one [`InelasticComponent`](@ref) per process in `layer.inelastic`, with + the indices of the absorption components that excite it. +Mixed quantities follow from [`absorption_optical_depth`](@ref), +[`optical_depth`](@ref), [`single_scattering_albedo`](@ref) and [`greek_expansion`](@ref)`(o, iλ)`. If a constituent declares [`is_total_absorption`](@ref) (a `TabulatedAbsorber` with `total = true`), it must be the only one, and every other constituent must have zero absorption at every wavelength. -Inelastic processes in `layer.fluorophores` are not included; they are -source terms for the solver (see the *Consumer API* docs page). +Every absorber that excites a fluorescence process must itself be a +constituent of the layer (the same object, or an equal one): otherwise its +absorption would drive emission without attenuating the light. # Example ```julia @@ -52,7 +60,7 @@ phyto = Phytoplankton{Float64, Bricaud1998}(Chl = 0.5) layer = OceanLayer(0.0, 5.0, AbstractOceanConstituent{Float64}[water, phyto]) opt = layer_optics(layer, collect(400.0:5.0:700.0); ℓ_max = 64) optical_depth(opt), single_scattering_albedo(opt) -opt.components[2].label # "Phytoplankton" +opt.scatterers[2].label # "Phytoplankton" ``` """ function layer_optics(layer::OceanLayer, λ_grid::AbstractVector{<:Real}; @@ -81,22 +89,45 @@ function _layer_optics(layer::OceanLayer, λ_grid, ℓ_max, polarized, Δz = FT(thickness(layer)) constituents = layer.constituents - # --- absorption --------------------------------------------------------- - i_total = findall(is_total_absorption, constituents) + # --- absorption components ----------------------------------------------- + absorbing = [c for c in constituents if c isa AbstractAbsorber] + i_total = findall(is_total_absorption, absorbing) length(i_total) ≤ 1 || throw(ArgumentError("layer_optics: $(length(i_total)) constituents declare total " * "(bulk) absorption; at most one can")) - i_bulk = isempty(i_total) ? 0 : only(i_total) - τ_abs = zeros(FT, length(λ)) - for (i, c) in enumerate(constituents), (k, λk) in enumerate(λ) - a = FT(absorption(c, λk)) - if i_bulk != 0 && i != i_bulk && a != 0 - throw(ArgumentError("layer_optics: $(constituents[i_bulk]) is the total " * - "absorption of the layer, but $(nameof(typeof(c))) also " * - "absorbs (a = $a 1/m at λ = $λk nm); this would count " * - "its absorbers twice")) + i_bulk = isempty(i_total) ? 0 : only(i_total) + absorbers = AbsorptionComponent{FT}[] + first_part = Int[] # index of each absorber's first component + for (i, c) in enumerate(absorbing) + parts = absorption_parts(c) + τ = zeros(FT, length(parts), length(λ)) + for (k, λk) in enumerate(λ) + a = absorption_by_part(c, λk) + if i_bulk != 0 && i != i_bulk && any(!iszero, a) + throw(ArgumentError("layer_optics: $(absorbing[i_bulk]) is the total " * + "absorption of the layer, but $(nameof(typeof(c))) also " * + "absorbs (a = $(sum(a)) 1/m at λ = $λk nm); this would " * + "count its absorbers twice")) + end + for j in eachindex(parts) + τ[j, k] = FT(a[j]) * Δz + end end - τ_abs[k] += a * Δz + push!(first_part, length(absorbers) + 1) + for (j, part) in enumerate(parts) + push!(absorbers, AbsorptionComponent{FT}(_component_label(c), part, τ[j, :])) + end + end + + # --- inelastic components --------------------------------------------- + inelastic = map(layer.inelastic) do p + pathways = excitation_pathways(p) + index = map(pathways) do x + i = _matching_absorber(absorbing, x.absorber, p, layer) + first_part[i] + findfirst(==(x.part), absorption_parts(absorbing[i])) - 1 + end + InelasticComponent{FT}(string(nameof(typeof(p))), p, collect(Int, index), + FT[x.efficiency for x in pathways]) end # --- scattering components ------------------------------------------- @@ -114,8 +145,9 @@ function _layer_optics(layer::OceanLayer, λ_grid, ℓ_max, polarized, end components = [_scattering_component(c, λ, Δz, ℓ_max, polarized, FT, cache) for c in scatterers] - return OceanLayerOptics{FT}(λ, FT(layer.depth_top), FT(layer.depth_bottom), τ_abs, - components, ℓ_max + 1, polarized) + return OceanLayerOptics{FT}(λ, FT(layer.depth_top), FT(layer.depth_bottom), absorbers, + components, collect(InelasticComponent{FT}, inelastic), + ℓ_max + 1, polarized) end function _scattering_component(c, λ::Vector{FT}, Δz::FT, ℓ_max, polarized, ::Type{FT}, @@ -150,6 +182,24 @@ end _component_label(c::AbstractOceanConstituent) = string(nameof(typeof(c))) +# The constituent of the layer that is the exciting absorber: the same object, +# or else an equal one; it must be unique, so that excitation is attributed +# to one absorption component. +function _matching_absorber(absorbing, absorber, p, layer) + where_ = "$(nameof(typeof(p))) in the layer at $(layer.depth_top)–$(layer.depth_bottom) m" + i = findall(c -> c === absorber, absorbing) + isempty(i) && (i = findall(c -> isequal(c, absorber), absorbing)) + isempty(i) && + throw(ArgumentError("layer_optics: $where_ is excited by $absorber, which is not a " * + "constituent of that layer. Add it to the constituents, so that " * + "the light it absorbs is also removed from the radiation field.")) + length(i) == 1 || + throw(ArgumentError("layer_optics: $where_ is excited by $absorber, which appears " * + "$(length(i)) times among the constituents; merge the equal " * + "constituents into one")) + return only(i) +end + _convert_greek(::Type{FT}, g::GreekCoefficients{FT}) where {FT} = g _convert_greek(::Type{FT}, g::GreekCoefficients) where {FT} = GreekCoefficients{FT}((FT.(getfield(g, f)) for f in fieldnames(GreekCoefficients))...) @@ -167,8 +217,10 @@ one `phase_id` and the same expansion objects across layers. `refractive_index` (an [`AbstractRefractiveIndexModel`](@ref), e.g. `FixedRefractiveIndex(1.34)` or `QuanFry1995(; temperature, salinity)`) -and `bottom` (`BlackBottom()` or `LambertianBottom(albedo)`) are required: -neither has a defensible default. +and `bottom` are required: neither has a defensible default. The bottom +is `BlackBottom()` (deep water), `LambertianBottom(albedo)` (one albedo, +or one per wavelength of `λ`) or a [`TabulatedLambertianBottom`](@ref), +which is interpolated onto `λ`. # Example ```julia @@ -190,5 +242,17 @@ function column_optics(column::OceanColumn, λ_grid::AbstractVector{<:Real}; for l in column] λ = first(layers).λ n = FT.(OceanOptics.refractive_index(refractive_index, λ)) - return OceanColumnOptics(layers, n, bottom) + return OceanColumnOptics(layers, n, _resolve_bottom(bottom, λ, FT)) +end + +_resolve_bottom(b::AbstractOceanBottom, λ, FT) = b +_resolve_bottom(b::LambertianBottom, λ, FT) = LambertianBottom(FT.(b.albedo)) +function _resolve_bottom(b::TabulatedLambertianBottom, λ, FT) + lo, hi = first(b.λ), last(b.λ) + all(x -> lo ≤ x ≤ hi, λ) || + throw(DomainError(extrema(λ), "TabulatedLambertianBottom" * + (isempty(b.source) ? "" : " ($(b.source))") * " covers $(lo)–$(hi) nm, " * + "the column grid $(minimum(λ))–$(maximum(λ)) nm")) + tbl = SpectralTable(FT.(b.λ), FT.(b.albedo)) + return LambertianBottom(FT[linterp(tbl, x) for x in λ]) end diff --git a/src/types/abstract_types.jl b/src/types/abstract_types.jl index 6d97b4b..0866326 100644 --- a/src/types/abstract_types.jl +++ b/src/types/abstract_types.jl @@ -175,6 +175,47 @@ says which one to use. """ function scattering_phase end +# ----------------------------------------------------------------------------- +# Absorption parts +# ----------------------------------------------------------------------------- +# +# An absorber may attribute its absorption to parts — phytoplankton with a +# pigment partition splits a_ph into chlorophyll, carotenoid, … parts — so +# that a solver can report the light absorbed by each and a fluorescence +# process can name the parts that excite it. `layer_optics` makes one +# absorption component per part. + +""" + absorption_parts(c::AbstractAbsorber) -> Tuple{Vararg{Symbol}} + +Names of the parts into which `c` attributes its absorption, in the order +of [`absorption_by_part`](@ref). `(:total,)` unless `c` splits its +absorption, as [`Phytoplankton`](@ref) does with a pigment partition. +""" +absorption_parts(::AbstractAbsorber) = (:total,) + +""" + absorption_by_part(c::AbstractAbsorber, λ) -> Tuple + +Absorption coefficient `[1/m]` of each part in +[`absorption_parts`](@ref)`(c)` at `λ` `[nm]`; the parts sum to +[`absorption`](@ref)`(c, λ)`. +""" +absorption_by_part(c::AbstractAbsorber, λ::Real) = (absorption(c, λ),) + +""" + absorption_part(c::AbstractAbsorber, part::Symbol, λ) -> FT + +Absorption coefficient `[1/m]` of one part of `c` at `λ` `[nm]`. +""" +function absorption_part(c::AbstractAbsorber, part::Symbol, λ::Real) + i = findfirst(==(part), absorption_parts(c)) + i === nothing && + throw(ArgumentError("$(nameof(typeof(c))) has no absorption part :$part; its parts " * + "are $(absorption_parts(c))")) + return absorption_by_part(c, λ)[i] +end + # ============================================================================= # Inelastic processes (fluorescence, Raman) — abstract root # ============================================================================= diff --git a/src/types/layer_optics.jl b/src/types/layer_optics.jl index 23c5f34..3f5c5a8 100644 --- a/src/types/layer_optics.jl +++ b/src/types/layer_optics.jl @@ -3,13 +3,16 @@ # ============================================================================= # # A layer is described the way plane-parallel solvers combine optical -# properties: one absorption optical depth plus one scattering component -# per scattering constituent, each with its own scattering optical depth -# and phase-matrix expansion. Mixed quantities (total τ, ϖ, the mixed -# expansion) are derived on demand. Keeping components separate lets a -# solver build each component's phase operators once per band and truncate -# them individually, as it does for aerosol types, and it keeps the -# provenance of every phase matrix visible. +# properties: absorption components (one per absorber, or per absorption +# part such as a pigment group), scattering components (one per scatterer, +# with its phase-matrix expansion) and the inelastic processes active in +# the layer, each linked to the absorption components that excite it. +# Mixed quantities (total τ, ϖ, the mixed expansion) are derived on demand. +# Keeping components separate lets a solver build each component's phase +# operators once per band and truncate them individually, as it does for +# aerosol types; lets it report the light absorbed by each constituent +# (absorbed PAR, fluorescence excitation); and keeps the provenance of +# every phase matrix visible. # ============================================================================= _is_strictly_increasing(x::AbstractVector) = all(i -> x[i] < x[i+1], firstindex(x):lastindex(x)-1) @@ -125,6 +128,74 @@ backscatter_fraction(c::ScatteringComponent, iλ::Integer) = is_wavelength_dependent(c) ? c.backscatter_fraction[c.phase_index[iλ]] : first(c.backscatter_fraction) +# ============================================================================= +# Absorption and inelastic components +# ============================================================================= + +""" +$(TYPEDEF) + +Absorption by one constituent of a layer, or by one part of it (see +[`absorption_parts`](@ref)): `τ = a·Δz` per wavelength. + +# Fields +$(TYPEDFIELDS) +""" +struct AbsorptionComponent{FT} + "Constituent the component came from (type name, or the source of tabulated data)" + label::String + "Absorption part of the constituent (`:total` unless it splits its absorption)" + part::Symbol + "Absorption optical depth `a·Δz` per wavelength" + τ::Vector{FT} + + function AbsorptionComponent{FT}(label, part, τ) where {FT} + all(x -> isfinite(x) && x ≥ 0, τ) || + throw(ArgumentError("AbsorptionComponent \"$label\" (:$part): absorption optical " * + "depths must be finite and non-negative")) + new{FT}(label, part, τ) + end +end + +AbsorptionComponent(label::AbstractString, part::Symbol, τ::AbstractVector{FT}) where {FT} = + AbsorptionComponent{FT}(String(label), part, collect(τ)) + +""" +$(TYPEDEF) + +An inelastic process (fluorescence, water Raman) active in a layer, with +the absorption components of the layer that excite it. + +# Fields +$(TYPEDFIELDS) + +For fluorescence, `excitation[k]` indexes the layer's `absorbers` and +`efficiency[k]` is the energy-transfer efficiency η of that pathway, so +that the excitation coefficient on the layer grid is +`quantum_yield(process) · Σ_k efficiency[k] · absorbers[excitation[k]].τ / Δz` +— the same as [`excitation_absorption`](@ref)`(process, λ)`. Water Raman +has no excitation components. +""" +struct InelasticComponent{FT} + "Process type name" + label::String + "The process, with its kernels (excitation, emission, quantum yield)" + process::AbstractOceanInelasticProcess + "Indices of the layer's absorption components that excite the process" + excitation::Vector{Int} + "Energy-transfer efficiency η of each excitation component" + efficiency::Vector{FT} + + function InelasticComponent{FT}(label, process, excitation, efficiency) where {FT} + length(excitation) == length(efficiency) || + throw(DimensionMismatch("InelasticComponent \"$label\": $(length(efficiency)) " * + "efficiencies for $(length(excitation)) excitation components")) + all(η -> isfinite(η) && 0 ≤ η ≤ 1, efficiency) || + throw(ArgumentError("InelasticComponent \"$label\": efficiencies must lie in [0, 1]")) + new{FT}(label, process, excitation, efficiency) + end +end + # ============================================================================= # Layer # ============================================================================= @@ -140,18 +211,22 @@ $(TYPEDFIELDS) # Derived quantities +[`absorption_optical_depth`](@ref) (all absorbers), [`optical_depth`](@ref), [`scattering_optical_depth`](@ref), [`single_scattering_albedo`](@ref), [`backscatter_fraction`](@ref) and the mixed expansion [`greek_expansion`](@ref)`(o, iλ)` — the -scattering-weighted mixture of the components. +scattering-weighted mixture of the scattering components. Light absorbed +per component, given the scalar irradiance: [`absorbed_power`](@ref), +[`absorbed_photons`](@ref), [`absorbed_par`](@ref). # Validation `λ` finite, positive and strictly monotone (increasing or decreasing); `0 ≤ depth_top < depth_bottom`; optical depths finite and non-negative; -every component on the same wavelength grid, with `n_moments` terms and -the layer's polarization. Arrays are checked at construction; mutating -them afterwards is not re-checked. +every component on the same wavelength grid; scattering components with +`n_moments` terms and the layer's polarization; inelastic components +referring to existing absorption components. Arrays are checked at +construction; mutating them afterwards is not re-checked. """ struct OceanLayerOptics{FT} "Wavelengths `[nm]`, strictly monotone" @@ -160,18 +235,21 @@ struct OceanLayerOptics{FT} depth_top::FT "Depth of the layer bottom below the surface `[m]`" depth_bottom::FT - "Absorption optical depth `a·Δz` per wavelength (all absorbers)" - τ_abs::Vector{FT} + "Absorption components, one per absorber or absorption part" + absorbers::Vector{AbsorptionComponent{FT}} "Scattering components, one per scattering constituent" - components::Vector{ScatteringComponent{FT}} + scatterers::Vector{ScatteringComponent{FT}} + "Inelastic processes, with the absorption components that excite them" + inelastic::Vector{InelasticComponent{FT}} "Number of expansion terms, `ℓ_max + 1`" n_moments::Int - "Whether every component carries phase-matrix coefficients" + "Whether every scattering component carries phase-matrix coefficients" polarized::Bool - function OceanLayerOptics{FT}(λ, depth_top, depth_bottom, τ_abs, components, + function OceanLayerOptics{FT}(λ, depth_top, depth_bottom, absorbers, scatterers, inelastic, n_moments, polarized) where {FT} - o = new{FT}(λ, depth_top, depth_bottom, τ_abs, components, n_moments, polarized) + o = new{FT}(λ, depth_top, depth_bottom, absorbers, scatterers, inelastic, n_moments, + polarized) _validate_layer(o) return o end @@ -188,12 +266,18 @@ function _validate_layer(o::OceanLayerOptics) isfinite(o.depth_top) && isfinite(o.depth_bottom) && 0 ≤ o.depth_top < o.depth_bottom || throw(ArgumentError("$who: need 0 ≤ depth_top < depth_bottom, got " * "$(o.depth_top)–$(o.depth_bottom) m")) - length(o.τ_abs) == nλ || - throw(DimensionMismatch("$who: $(length(o.τ_abs)) absorption optical depths for $nλ wavelengths")) - all(x -> isfinite(x) && x ≥ 0, o.τ_abs) || - throw(ArgumentError("$who: absorption optical depths must be finite and non-negative")) + for c in o.absorbers + length(c.τ) == nλ || + throw(DimensionMismatch("$who: absorption component \"$(c.label)\" (:$(c.part)) has " * + "$(length(c.τ)) optical depths for $nλ wavelengths")) + end + for c in o.inelastic + all(i -> 1 ≤ i ≤ length(o.absorbers), c.excitation) || + throw(ArgumentError("$who: inelastic component \"$(c.label)\" refers to a missing " * + "absorption component")) + end o.n_moments ≥ 1 || throw(ArgumentError("$who: n_moments must be positive")) - for c in o.components + for c in o.scatterers length(c.τ) == nλ || throw(DimensionMismatch("$who: component \"$(c.label)\" has $(length(c.τ)) " * "optical depths for $nλ wavelengths")) @@ -222,20 +306,44 @@ carries all six phase-matrix coefficients. """ is_polarized(o::OceanLayerOptics) = o.polarized -"Absorption optical depth per wavelength." -absorption_optical_depth(o::OceanLayerOptics) = o.τ_abs +""" + absorber_index(o::OceanLayerOptics, label, part = :total) -> Int + +Index in `o.absorbers` (and in the rows of [`absorbed_power`](@ref) and +the entries of [`absorbed_par`](@ref)) of the absorption component with +`label` and `part`, e.g. `absorber_index(o, "Phytoplankton", :chlorophyll)`. +Throws if there is no such component or more than one. +""" +function absorber_index(o::OceanLayerOptics, label::AbstractString, part::Symbol = :total) + i = findall(c -> c.label == label && c.part === part, o.absorbers) + length(i) == 1 && return only(i) + throw(ArgumentError(isempty(i) ? + "absorber_index: no absorption component \"$label\" (:$part); the layer has " * + join(("\"$(c.label)\" (:$(c.part))" for c in o.absorbers), ", ") : + "absorber_index: $(length(i)) absorption components \"$label\" (:$part); " * + "give equal constituents distinct sources or index o.absorbers directly")) +end -"Scattering optical depth per wavelength, summed over components." +"Absorption optical depth per wavelength, summed over absorption components." +function absorption_optical_depth(o::OceanLayerOptics{FT}) where {FT} + τ = zeros(FT, n_wavelengths(o)) + for c in o.absorbers + τ .+= c.τ + end + return τ +end + +"Scattering optical depth per wavelength, summed over scattering components." function scattering_optical_depth(o::OceanLayerOptics{FT}) where {FT} τ = zeros(FT, n_wavelengths(o)) - for c in o.components + for c in o.scatterers τ .+= c.τ end return τ end "Total (extinction) optical depth `τ_abs + τ_scat` per wavelength." -optical_depth(o::OceanLayerOptics) = o.τ_abs .+ scattering_optical_depth(o) +optical_depth(o::OceanLayerOptics) = absorption_optical_depth(o) .+ scattering_optical_depth(o) """ single_scattering_albedo(o::OceanLayerOptics) -> Vector @@ -244,7 +352,7 @@ optical_depth(o::OceanLayerOptics) = o.τ_abs .+ scattering_optical_depth(o) """ function single_scattering_albedo(o::OceanLayerOptics{FT}) where {FT} τs = scattering_optical_depth(o) - τ = o.τ_abs .+ τs + τ = absorption_optical_depth(o) .+ τs return [τ[i] > 0 ? τs[i] / τ[i] : zero(FT) for i in eachindex(τ)] end @@ -257,7 +365,7 @@ functions per wavelength; zero where the layer does not scatter. function backscatter_fraction(o::OceanLayerOptics{FT}) where {FT} τs = scattering_optical_depth(o) B = zeros(FT, n_wavelengths(o)) - for c in o.components, i in eachindex(B) + for c in o.scatterers, i in eachindex(B) B[i] += c.τ[i] * backscatter_fraction(c, i) end return [τs[i] > 0 ? B[i] / τs[i] : zero(FT) for i in eachindex(B)] @@ -272,18 +380,20 @@ does not scatter, the isotropic expansion `β = [1, 0, …]` (zero polarization terms). """ function greek_expansion(o::OceanLayerOptics{FT}, iλ::Integer) where {FT} - w = [c.τ[iλ] for c in o.components] + w = [c.τ[iλ] for c in o.scatterers] if isempty(w) || sum(w) == 0 β = zeros(FT, o.n_moments); β[1] = one(FT) g = GreekCoefficients(β) return o.polarized ? depolarized(g) : g end - return mix_greek(w, [greek_expansion(c, iλ) for c in o.components]) + return mix_greek(w, [greek_expansion(c, iλ) for c in o.scatterers]) end function Base.show(io::IO, o::OceanLayerOptics{FT}) where {FT} print(io, "OceanLayerOptics{$FT}($(o.depth_top)–$(o.depth_bottom) m, ", - n_wavelengths(o), " λ, ", length(o.components), " scattering components, ", + n_wavelengths(o), " λ, ", length(o.absorbers), " absorption, ", + length(o.scatterers), " scattering", + isempty(o.inelastic) ? "" : ", $(length(o.inelastic)) inelastic", " components, ", "ℓ ≤ $(o.n_moments - 1), ", o.polarized ? "polarized" : "scalar", ")") end @@ -322,6 +432,49 @@ LambertianBottom(albedo::Real) = LambertianBottom{float(typeof(albedo))}([float( LambertianBottom(albedo::AbstractVector{<:Real}) = LambertianBottom{float(eltype(albedo))}(collect(float(eltype(albedo)), albedo)) +""" +$(TYPEDEF) + +Lambertian bottom whose albedo spectrum is tabulated on its own wavelength +grid, e.g. a measured sediment, seagrass or coral reflectance. +[`column_optics`](@ref) interpolates it linearly onto the column's +wavelengths (which must lie within the table) and stores the result as a +[`LambertianBottom`](@ref). + +# Fields +$(TYPEDFIELDS) + +# Construction + + TabulatedLambertianBottom(λ, albedo; source = "") +""" +struct TabulatedLambertianBottom{FT} <: AbstractOceanBottom + "Wavelengths `[nm]`, strictly increasing" + λ::Vector{FT} + "Albedo at each `λ`, in `[0, 1]`" + albedo::Vector{FT} + "Provenance" + source::String + + function TabulatedLambertianBottom{FT}(λ, albedo, source) where {FT} + who = "TabulatedLambertianBottom" + length(λ) ≥ 2 || throw(ArgumentError("$who: need at least two wavelengths")) + all(x -> isfinite(x) && x > 0, λ) && _is_strictly_increasing(λ) || + throw(ArgumentError("$who: wavelengths must be finite, positive and strictly increasing")) + length(albedo) == length(λ) || + throw(DimensionMismatch("$who: $(length(albedo)) albedos for $(length(λ)) wavelengths")) + all(a -> isfinite(a) && 0 ≤ a ≤ 1, albedo) || + throw(ArgumentError("$who: albedo must lie in [0, 1]")) + new{FT}(λ, albedo, source) + end +end + +function TabulatedLambertianBottom(λ::AbstractVector{<:Real}, albedo::AbstractVector{<:Real}; + source::AbstractString = "") + FT = float(promote_type(eltype(λ), eltype(albedo))) + return TabulatedLambertianBottom{FT}(collect(FT, λ), collect(FT, albedo), String(source)) +end + # ============================================================================= # Column # ============================================================================= @@ -332,7 +485,10 @@ $(TYPEDEF) Optical description of a whole water column, produced by [`column_optics`](@ref): contiguous layers from the surface down on one wavelength grid, the refractive index of the water at the surface relative -to air, and the bottom. +to air, and the bottom: `BlackBottom`, or `LambertianBottom` with one +albedo per wavelength or one for all (a [`TabulatedLambertianBottom`](@ref) +given to [`column_optics`](@ref) is resolved into the latter). Other +`AbstractOceanBottom` subtypes pass through for solvers that know them. # Fields $(TYPEDFIELDS) @@ -383,6 +539,9 @@ function _validate_column(col::OceanColumnOptics) length(col.bottom.albedo) in (1, nλ) || throw(DimensionMismatch("$who: bottom albedo needs 1 or $nλ values")) end + col.bottom isa TabulatedLambertianBottom && + throw(ArgumentError("$who: a TabulatedLambertianBottom must be interpolated onto the " * + "column grid; pass it to column_optics")) return nothing end diff --git a/src/types/ocean_column.jl b/src/types/ocean_column.jl index 505e8ac..8eb1ab4 100644 --- a/src/types/ocean_column.jl +++ b/src/types/ocean_column.jl @@ -20,7 +20,7 @@ # 5 m below. Mirrors the grid used in Fell's North-Sea coupled # atmosphere-ocean tests. # -# Both helpers take a `fluorophores` keyword that is broadcast to every +# Both helpers take an `inelastic` keyword that is broadcast to every # layer (typical pattern when chlorophyll fluorescence or Raman is # active throughout the water column). # ============================================================================= @@ -99,22 +99,22 @@ end # ============================================================================= """ - uniform_column(constituents; n_layers=10, depth=50.0, fluorophores=[]) + uniform_column(constituents; n_layers=10, depth=50.0, inelastic=[]) Build an `OceanColumn` with `n_layers` equal-thickness layers spanning 0 → `depth` metres. Each layer carries the same `constituents` and -`fluorophores` lists. +`inelastic` lists. """ function uniform_column(constituents::AbstractVector; n_layers::Integer = 10, depth = 50.0, - fluorophores::AbstractVector = AbstractOceanInelasticProcess{Float64}[]) + inelastic::AbstractVector = AbstractOceanInelasticProcess{Float64}[]) n_layers > 0 || throw(ArgumentError("uniform_column: n_layers must be positive")) depth > 0 || throw(ArgumentError("uniform_column: depth must be positive")) - FT = _column_float_type(constituents, fluorophores) + FT = _column_float_type(constituents, inelastic) dz = FT(depth) / n_layers layers = Vector{OceanLayer{FT}}(undef, n_layers) @@ -122,13 +122,13 @@ function uniform_column(constituents::AbstractVector; z_top = (i - 1) * dz z_bot = i * dz layers[i] = OceanLayer(z_top, z_bot, constituents; - fluorophores = fluorophores) + inelastic = inelastic) end return OceanColumn{FT}(layers) end """ - fell_column(constituents; depth=60.0, fluorophores=[]) + fell_column(constituents; depth=60.0, inelastic=[]) Build an `OceanColumn` following Fell (1997) §5.2.1: 1 m layers in 0–10 m, 2 m layers in 10–20 m, 5 m layers below. Truncates gracefully @@ -137,11 +137,11 @@ depth` exactly. """ function fell_column(constituents::AbstractVector; depth::Real = 60.0, - fluorophores::AbstractVector = AbstractOceanInelasticProcess{Float64}[]) + inelastic::AbstractVector = AbstractOceanInelasticProcess{Float64}[]) depth > 0 || throw(ArgumentError("fell_column: depth must be positive")) - FT = _column_float_type(constituents, fluorophores) + FT = _column_float_type(constituents, inelastic) D = FT(depth) # Boundary list: 0 → 10 at Δ=1, 10 → 20 at Δ=2, 20 → D at Δ=5 @@ -154,7 +154,7 @@ function fell_column(constituents::AbstractVector; last(boundaries) == D || push!(boundaries, D) layers = [OceanLayer(boundaries[i], boundaries[i+1], constituents; - fluorophores = fluorophores) + inelastic = inelastic) for i in 1:length(boundaries)-1] return OceanColumn{FT}(layers) end @@ -174,13 +174,13 @@ function _append_staircase!(boundaries::Vector{FT}, D::FT, Δ::FT, upper::FT) wh return boundaries end -# Infer FT from the constituents or fluorophores (first non-empty one wins). +# Infer FT from the constituents or inelastic processes (first non-empty one wins). function _column_float_type(constituents::AbstractVector, - fluorophores::AbstractVector) + inelastic::AbstractVector) if !isempty(constituents) return _constituent_float_type(first(constituents)) - elseif !isempty(fluorophores) - return _fluorophore_float_type(first(fluorophores)) + elseif !isempty(inelastic) + return _inelastic_float_type(first(inelastic)) else return Float64 end diff --git a/src/types/ocean_layer.jl b/src/types/ocean_layer.jl index 83ad008..07e2f46 100644 --- a/src/types/ocean_layer.jl +++ b/src/types/ocean_layer.jl @@ -22,35 +22,35 @@ struct OceanLayer{FT} "Elastic optical constituents active in this layer" constituents::Vector{<:AbstractOceanConstituent{FT}} "Inelastic processes (fluorescence, Raman) active in this layer" - fluorophores::Vector{<:AbstractOceanInelasticProcess{FT}} + inelastic::Vector{<:AbstractOceanInelasticProcess{FT}} function OceanLayer{FT}(depth_top, depth_bottom, constituents, - fluorophores) where {FT} + inelastic) where {FT} dt, db = FT(depth_top), FT(depth_bottom) db > dt || throw(ArgumentError("depth_bottom ($db) must be > depth_top ($dt)")) dt ≥ zero(FT) || throw(ArgumentError("depth_top must be non-negative")) - new{FT}(dt, db, constituents, fluorophores) + new{FT}(dt, db, constituents, inelastic) end end # User-friendly constructor — pick FT from the first constituent (or first # fluorophore, if there are no elastic constituents). function OceanLayer(depth_top, depth_bottom, constituents::AbstractVector; - fluorophores::AbstractVector = AbstractOceanInelasticProcess{Float64}[]) + inelastic::AbstractVector = AbstractOceanInelasticProcess{Float64}[]) FT = if !isempty(constituents) _constituent_float_type(first(constituents)) - elseif !isempty(fluorophores) - _fluorophore_float_type(first(fluorophores)) + elseif !isempty(inelastic) + _inelastic_float_type(first(inelastic)) else Float64 end cvec = convert(Vector{AbstractOceanConstituent{FT}}, constituents) - fvec = convert(Vector{AbstractOceanInelasticProcess{FT}}, fluorophores) + fvec = convert(Vector{AbstractOceanInelasticProcess{FT}}, inelastic) return OceanLayer{FT}(FT(depth_top), FT(depth_bottom), cvec, fvec) end _constituent_float_type(::AbstractOceanConstituent{FT}) where {FT} = FT -_fluorophore_float_type(::AbstractOceanInelasticProcess{FT}) where {FT} = FT +_inelastic_float_type(::AbstractOceanInelasticProcess{FT}) where {FT} = FT "Geometric thickness [m]" thickness(layer::OceanLayer) = layer.depth_bottom - layer.depth_top @@ -59,9 +59,9 @@ thickness(layer::OceanLayer) = layer.depth_bottom - layer.depth_top midpoint_depth(layer::OceanLayer) = (layer.depth_top + layer.depth_bottom) / 2 function Base.show(io::IO, layer::OceanLayer{FT}) where {FT} - nf = length(layer.fluorophores) + nf = length(layer.inelastic) print(io, "OceanLayer{$FT}($(layer.depth_top)-$(layer.depth_bottom) m, ", "$(length(layer.constituents)) constituents", - nf > 0 ? ", $nf fluorophores" : "", + nf > 0 ? ", $nf inelastic processes" : "", ")") end diff --git a/test/runtests.jl b/test/runtests.jl index 0068ae7..10163f7 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -10,6 +10,7 @@ using ForwardDiff include("test_greek.jl") include("test_phase.jl") include("test_phytoplankton.jl") + include("test_pigments.jl") include("test_nap.jl") include("test_redistribution.jl") include("test_fluorescence.jl") @@ -17,6 +18,7 @@ using ForwardDiff include("test_tabulated.jl") include("test_hydrolight_reference.jl") include("test_layer_optics.jl") + include("test_absorbed_light.jl") include("test_column.jl") include("test_ad.jl") end diff --git a/test/test_absorbed_light.jl b/test/test_absorbed_light.jl new file mode 100644 index 0000000..793fc34 --- /dev/null +++ b/test/test_absorbed_light.jl @@ -0,0 +1,138 @@ +@testset "Absorbed light and emission" begin + water = PureWater{Float64}() + phyto = Phytoplankton(Chl = 1.0, pigments = ProspectPigments(carotenoid_ratio = 0.3)) + f = chlorophyll_fluorescence(phyto; quantum_yield = 0.02, carotenoid_transfer = 0.5) + layer = OceanLayer(5.0, 7.0, AbstractOceanConstituent{Float64}[water, phyto]; + inelastic = AbstractOceanInelasticProcess{Float64}[f, WaterRaman{Float64}()]) + λ = collect(400.0:2.0:750.0) + o = layer_optics(layer, λ; ℓ_max = 8) + E₀ = [1.2 + 0.3sin(x / 40) for x in λ] # W m⁻² nm⁻¹, layer mean + + @testset "Components and links" begin + @test [(c.label, c.part) for c in o.absorbers] == + [("PureWater", :total), ("Phytoplankton", :chlorophyll), + ("Phytoplankton", :carotenoids), ("Phytoplankton", :unassigned)] + @test absorption_optical_depth(o) ≈ 2 .* (absorption(water, λ) .+ absorption(phyto, λ)) rtol = 1e-12 + c = o.inelastic[1] + @test c.process === f && c.excitation == [2, 3, 4] && c.efficiency == [1.0, 0.5, 0.0] + # The linked components reproduce the process's excitation coefficient. + for k in (1, 40, 140) + τI = quantum_yield(f) * sum(c.efficiency[i] * o.absorbers[c.excitation[i]].τ[k] + for i in eachindex(c.excitation)) + @test τI / thickness(o) ≈ excitation_absorption(f, λ[k]) rtol = 1e-12 + end + @test isempty(o.inelastic[2].excitation) + end + + @testset "Absorbed power, photons and PAR" begin + A = absorbed_power(o, E₀) + @test size(A) == (4, length(λ)) + @test A[2, 10] ≈ o.absorbers[2].τ[10] * E₀[10] + @test vec(sum(A; dims = 1)) ≈ absorption_optical_depth(o) .* E₀ rtol = 1e-12 + # 1 W at 550 nm is 4.598 µmol photons s⁻¹ (hc N_A = 0.119627 J m mol⁻¹). + N = absorbed_photons(o, ones(length(λ))) + k = findfirst(==(550.0), λ) + @test N[1, k] / o.absorbers[1].τ[k] ≈ 550e-9 / 0.119626566 * 1e6 rtol = 1e-7 + par = absorbed_par(o, E₀) + inpar = 400 .≤ λ .≤ 700 + Np = absorbed_photons(o, E₀) + @test par[2] ≈ sum((Np[2, i] + Np[2, i+1]) / 2 * 2.0 for i in findall(inpar)[1:end-1]) rtol = 1e-12 + @test par[4] == 0 # all absorption in 400–700 nm is attributed + @test all(≥(0), par) + # Decreasing grids give the same integrals. + orev = layer_optics(layer, reverse(λ); ℓ_max = 8) + @test absorbed_par(orev, reverse(E₀)) ≈ par rtol = 1e-12 + @test absorber_index(o, "Phytoplankton", :carotenoids) == 3 + @test absorber_index(o, "PureWater") == 1 + @test_throws ArgumentError absorber_index(o, "Phytoplankton") + @test_throws DimensionMismatch absorbed_power(o, E₀[1:5]) + @test_throws ArgumentError absorbed_power(o, -E₀) + @test_throws ArgumentError absorbed_par(o, E₀; range = (380.0, 700.0)) + end + + @testset "Integration windows" begin + w(x, r) = OceanOptics._window_weights(x, r, "") + # Linear integrands are integrated exactly over [lo, hi], also when the + # grid has no points at the limits, and in either order. + x = collect(398.0:5.0:703.0) + @test sum(w(x, (400, 700))) ≈ 300 rtol = 1e-12 + @test sum(w(x, (400, 700)) .* x) ≈ (700^2 - 400^2) / 2 rtol = 1e-12 + @test w(reverse(x), (400, 700)) ≈ reverse(w(x, (400, 700))) + @test sum(w(x, (401.5, 402.5))) ≈ 1 rtol = 1e-12 # inside a single interval + @test w(collect(400.0:10.0:700.0), (400, 700))[[1, 2, end]] ≈ [5, 10, 5] + @test_throws ArgumentError w(x, (390, 700)) + @test_throws ArgumentError w(x, (700, 400)) + end + + @testset "Excitation optical depth" begin + c = o.inelastic[1] + τI = excitation_optical_depth(o, 1) + @test τI ≈ [thickness(o) * excitation_absorption(f, x) for x in λ] rtol = 1e-12 + τR = excitation_optical_depth(o, 2) # Raman: from the process + @test τR ≈ [thickness(o) * excitation_absorption(o.inelastic[2].process, x) for x in λ] + end + + @testset "Fluorescence photon budget" begin + λ_em = collect(630.0:0.5:860.0) + P = inelastic_emission(o, 1, E₀, λ_em) + @test all(≥(0), P) + hc = 6.62607015e-34 * 299_792_458.0 + emitted = sum(P[i] * λ_em[i] * 1e-9 / hc for i in eachindex(λ_em)) * 0.5 + # Photons delivered to chlorophyll in 400–700 nm (trapezoidal on the layer grid). + Nd = absorbed_photons(o, E₀) + c = o.inelastic[1] + w = OceanOptics._window_weights(λ, (400.0, 700.0), "") + delivered = sum(w[k] * sum(c.efficiency[i] * Nd[c.excitation[i], k] + for i in eachindex(c.excitation)) for k in eachindex(λ)) + # µmol → photons: × N_A × 1e-6 + @test emitted ≈ quantum_yield(f) * delivered * 6.02214076e23 * 1e-6 rtol = 1e-6 + # Linear in the yield; zero yield emits nothing. + f2 = chlorophyll_fluorescence(phyto; quantum_yield = 0.04, carotenoid_transfer = 0.5) + o2 = layer_optics(OceanLayer(5.0, 7.0, AbstractOceanConstituent{Float64}[water, phyto]; + inelastic = AbstractOceanInelasticProcess{Float64}[f2]), λ; ℓ_max = 8) + @test inelastic_emission(o2, 1, E₀, λ_em) ≈ 2P rtol = 1e-12 + f0 = chlorophyll_fluorescence(phyto; quantum_yield = 0.0, carotenoid_transfer = 0.5) + o0 = layer_optics(OceanLayer(5.0, 7.0, AbstractOceanConstituent{Float64}[water, phyto]; + inelastic = AbstractOceanInelasticProcess{Float64}[f0]), λ; ℓ_max = 8) + @test all(iszero, inelastic_emission(o0, 1, E₀, λ_em)) + end + + @testset "Excitation must attenuate" begin + other = Phytoplankton(Chl = 2.0, pigments = ProspectPigments(carotenoid_ratio = 0.3)) + g = chlorophyll_fluorescence(other; quantum_yield = 0.02, carotenoid_transfer = 0.0) + bad = OceanLayer(0.0, 1.0, AbstractOceanConstituent{Float64}[water, phyto]; + inelastic = AbstractOceanInelasticProcess{Float64}[g]) + @test_throws ArgumentError layer_optics(bad, λ) + # An equal (not identical) constituent is accepted. + same = Phytoplankton(Chl = 1.0, pigments = ProspectPigments(carotenoid_ratio = 0.3)) + ok = OceanLayer(0.0, 1.0, AbstractOceanConstituent{Float64}[water, same]; + inelastic = AbstractOceanInelasticProcess{Float64}[f]) + @test layer_optics(ok, λ; ℓ_max = 4).inelastic[1].excitation == [2, 3, 4] + # Two equal constituents would make the excitation ambiguous. + twice = OceanLayer(0.0, 1.0, AbstractOceanConstituent{Float64}[water, phyto, same]; + inelastic = AbstractOceanInelasticProcess{Float64}[f]) + @test_throws ArgumentError layer_optics(twice, λ; ℓ_max = 4) + end + + @testset "Column with a tabulated Lambertian floor" begin + column = uniform_column(AbstractOceanConstituent{Float64}[water, phyto]; n_layers = 3, + depth = 15.0, inelastic = AbstractOceanInelasticProcess{Float64}[f]) + floor = TabulatedLambertianBottom([350.0, 550.0, 800.0], [0.1, 0.3, 0.2]; source = "test") + col = column_optics(column, λ; refractive_index = FixedRefractiveIndex(1.34), + bottom = floor, ℓ_max = 8) + @test col.bottom isa LambertianBottom + @test bottom_albedo(col)[findfirst(==(450.0), λ)] ≈ 0.2 + @test bottom_albedo(col)[findfirst(==(550.0), λ)] ≈ 0.3 + @test all(l -> length(l.inelastic) == 1, col) + @test_throws DomainError column_optics(column, [340.0, 400.0]; + refractive_index = FixedRefractiveIndex(1.34), + bottom = floor) + @test_throws ArgumentError OceanColumnOptics(col.layers, col.refractive_index, floor) + # Other bottom types pass through to the solver. + struct TestBottom <: AbstractOceanBottom end + @test column_optics(column, λ; refractive_index = FixedRefractiveIndex(1.34), + bottom = TestBottom(), ℓ_max = 4).bottom isa TestBottom + @test_throws ArgumentError TabulatedLambertianBottom([400.0, 500.0], [0.1, 1.1]) + @test_throws ArgumentError TabulatedLambertianBottom([500.0, 400.0], [0.1, 0.1]) + end +end diff --git a/test/test_column.jl b/test/test_column.jl index d59b1a2..7a34420 100644 --- a/test/test_column.jl +++ b/test/test_column.jl @@ -98,13 +98,13 @@ @test col25[end].depth_bottom == 25.0 end - @testset "Column carries fluorophores through layers" begin + @testset "Column carries inelastic processes through layers" begin phyto = Phytoplankton{Float64, Bricaud1998}(Chl = 0.5) - sif = chlorophyll_fluorescence(phyto) + sif = chlorophyll_fluorescence(phyto; quantum_yield = 0.02) col = uniform_column(AbstractOceanConstituent{Float64}[phyto]; n_layers = 5, depth = 25.0, - fluorophores = AbstractOceanInelasticProcess{Float64}[sif]) - @test all(length(layer.fluorophores) == 1 for layer in col) - @test all(layer.fluorophores[1] === sif for layer in col) + inelastic = AbstractOceanInelasticProcess{Float64}[sif]) + @test all(length(layer.inelastic) == 1 for layer in col) + @test all(layer.inelastic[1] === sif for layer in col) end end diff --git a/test/test_fluorescence.jl b/test/test_fluorescence.jl index 8c2d18f..c17fd5f 100644 --- a/test/test_fluorescence.jl +++ b/test/test_fluorescence.jl @@ -1,108 +1,151 @@ @testset "Fluorescence processes" begin @testset "IsotropicFluorescence with a CDOM absorber" begin - # Use CDOM as the driving absorber so we get a concrete absorption - # without relying on Bricaud data. Physics is still meaningful - # (conceptual CDOM → visible fluorescence, Coble-style). + # CDOM as a concrete driving absorber; the physics (UV-excited + # visible fluorescence) is still meaningful. cdom = CDOM{Float64}(a_ref = 0.1, λ_ref = 440.0, slope = 0.014) em = GaussianEmission{Float64}(center_nm = 520.0, σ_nm = 20.0) - sif = IsotropicFluorescence{Float64}(cdom; - emission = em, - quantum_yield = 0.005, - excitation_range = (350.0, 500.0)) - + sif = IsotropicFluorescence(cdom; emission = em, quantum_yield = 0.005, + excitation_range = (350.0, 500.0)) # excitation_absorption = φ · a_absorber(λ') - @test excitation_absorption(sif, 440.0) ≈ 0.005 * 0.1 rtol=1e-12 + @test excitation_absorption(sif, 440.0) ≈ 0.005 * 0.1 rtol = 1e-12 @test excitation_absorption(sif, 500.0) ≈ 0.005 * absorption(cdom, 500.0) - - # emission delegates to the redistribution @test emission(sif, 440.0, 520.0) ≈ redistribution(em, 440.0, 520.0) - - # Integration window @test excitation_range(sif) == (350.0, 500.0) - @test is_isotropic(sif) - @test quantum_yield(sif) == 0.005 - - # inelastic_coefficient = a^I · f + @test is_isotropic(sif) && quantum_yield(sif) == 0.005 + @test only(excitation_pathways(sif)) == ExcitationPathway(cdom) @test inelastic_coefficient(sif, 440.0, 520.0) ≈ excitation_absorption(sif, 440.0) * emission(sif, 440.0, 520.0) + # Constructor validation; the yield and range are always explicit. + kw = (emission = em, excitation_range = (350.0, 500.0)) + @test_throws ArgumentError IsotropicFluorescence(cdom; kw..., quantum_yield = -0.1) + @test_throws ArgumentError IsotropicFluorescence(cdom; kw..., quantum_yield = 1.5) + @test_throws ArgumentError IsotropicFluorescence(cdom; emission = em, quantum_yield = 0.01, + excitation_range = (500.0, 400.0)) + @test_throws UndefKeywordError IsotropicFluorescence(cdom; kw...) + @test_throws ArgumentError IsotropicFluorescence(ExcitationPathway[]; kw..., quantum_yield = 0.01) + end - # Constructor validation - @test_throws ArgumentError IsotropicFluorescence{Float64}(cdom; - emission = em, quantum_yield = -0.1) - @test_throws ArgumentError IsotropicFluorescence{Float64}(cdom; - emission = em, quantum_yield = 1.5) - @test_throws ArgumentError IsotropicFluorescence{Float64}(cdom; - emission = em, excitation_range = (500.0, 400.0)) + @testset "Excitation pathways" begin + phyto = Phytoplankton(Chl = 0.5, pigments = ProspectPigments(carotenoid_ratio = 0.3)) + @test ExcitationPathway(phyto, :carotenoids, 0.4).efficiency == 0.4 + @test_throws ArgumentError ExcitationPathway(phyto, :total) # not a part of it + @test_throws ArgumentError ExcitationPathway(phyto, :chlorophyll, 1.2) + f = IsotropicFluorescence([ExcitationPathway(phyto, :chlorophyll, 1.0), + ExcitationPathway(phyto, :carotenoids, 0.4)]; + emission = chloroplast_emission(), quantum_yield = 0.02, + excitation_range = (400.0, 700.0)) + for λ in (440.0, 490.0, 650.0) + achl, acar, _ = absorption_by_part(phyto, λ) + @test excitation_absorption(f, λ) ≈ 0.02 * (achl + 0.4acar) rtol = 1e-12 + end end - @testset "chlorophyll_fluorescence: Fell (1997) parameterization" begin - phyto = Phytoplankton{Float64, Bricaud1998}(Chl = 0.5) - sif = chlorophyll_fluorescence(phyto) + @testset "chloroplast_emission (Fluspect)" begin + em = chloroplast_emission() + @test em isa TabulatedEmission{Float64} && em.λ[[1, end]] == [640.0, 851.0] + x = 630.0:0.25:860.0 + area(r) = sum(redistribution(r, 0.0, xi) for xi in x) * step(x) + @test area(em) ≈ 1 rtol = 1e-10 + # Combined spectrum: maxima at 685 and 739 nm, as in Fluspect's phi. + f = [redistribution(em, 0.0, λ) for λ in 640.0:851.0] + @test 640 + argmax(f) - 1 == 685 + @test 720 + argmax(f[81:end]) - 1 == 739 # second maximum, beyond the 685 nm band + # Photosystem mixture: PSI peaks at 728 nm, PSII at 682 nm. + psi, psii = chloroplast_emission(psi_share = 1), chloroplast_emission(psi_share = 0) + @test 640 + argmax([redistribution(psi, 0.0, λ) for λ in 640.0:851.0]) - 1 == 728 + @test 640 + argmax([redistribution(psii, 0.0, λ) for λ in 640.0:851.0]) - 1 == 682 + mix = chloroplast_emission(psi_share = 0.3) + @test redistribution(mix, 0.0, 700.0) ≈ + 0.3redistribution(psi, 0.0, 700.0) + 0.7redistribution(psii, 0.0, 700.0) rtol = 1e-6 + @test area(mix) ≈ 1 rtol = 1e-10 + @test chloroplast_emission(Float32) isa TabulatedEmission{Float32} + @test_throws ArgumentError chloroplast_emission(psi_share = 1.5) + end - # Type-parameter plumbing + @testset "chlorophyll_fluorescence" begin + # Without a pigment partition: all phytoplankton absorption excites. + phyto = Phytoplankton(Chl = 0.5) + sif = chlorophyll_fluorescence(phyto; quantum_yield = 0.02) @test sif isa IsotropicFluorescence{Float64} - @test sif.quantum_yield == 0.003 - @test excitation_range(sif) == (400.0, 700.0) - @test is_isotropic(sif) - - # Emission peaks at 685 nm with σ = 10.6 nm, independent of λ' - @test sif.emission isa GaussianEmission{Float64} - @test sif.emission.center_nm == 685.0 - @test sif.emission.σ_nm == 10.6 - - # Emission density at the peak and at the half-max - f_peak = emission(sif, 500.0, 685.0) - f_half = emission(sif, 500.0, 685.0 + sqrt(2 * log(2)) * 10.6) - @test f_peak > 0 - @test f_half ≈ f_peak / 2 rtol=1e-10 - - # excitation_absorption now works with the Bricaud 1998 data bundled. - # a^I(λ') = φ · a_absorber(λ'), so positive and much smaller than a_φ. - a_phyto = absorption(phyto, 440.0) - @test excitation_absorption(sif, 440.0) ≈ 0.003 * a_phyto rtol=1e-12 - - # Custom parameterization - sif_ens = chlorophyll_fluorescence(phyto; - peak_nm = 683.0, σ_nm = 12.0, quantum_yield = 0.005) - @test sif_ens.emission.center_nm == 683.0 - @test sif_ens.emission.σ_nm == 12.0 - @test sif_ens.quantum_yield == 0.005 + @test sif.emission isa TabulatedEmission && excitation_range(sif) == (400.0, 700.0) + @test excitation_absorption(sif, 440.0) ≈ 0.02 * absorption(phyto, 440.0) rtol = 1e-12 + @test_throws UndefKeywordError chlorophyll_fluorescence(phyto) + @test_throws ArgumentError chlorophyll_fluorescence(phyto; quantum_yield = 0.02, + carotenoid_transfer = 0.5) + # The single-band Gaussian of Fell (1997) remains available. + fell = chlorophyll_fluorescence(phyto; quantum_yield = 0.003, + emission = GaussianEmission(center_nm = 685.0, σ_nm = 10.6)) + @test emission(fell, 500.0, 685.0) ≈ 1 / (10.6 * sqrt(2π)) + + # Land analogy: chlorophyll only vs. carotenoids as (partial) antenna. + p = Phytoplankton(Chl = 0.5, pigments = ProspectPigments(carotenoid_ratio = 0.3)) + @test_throws ArgumentError chlorophyll_fluorescence(p; quantum_yield = 0.02) # choose η + only_chl = chlorophyll_fluorescence(p; quantum_yield = 0.02, carotenoid_transfer = 0.0) + antenna = chlorophyll_fluorescence(p; quantum_yield = 0.02, carotenoid_transfer = 1.0) + half = chlorophyll_fluorescence(p; quantum_yield = 0.02, carotenoid_transfer = 0.5) + @test [x.efficiency for x in excitation_pathways(half)] == [1.0, 0.5, 0.0] + for λ in (450.0, 490.0, 520.0) + achl, acar, aun = absorption_by_part(p, λ) + @test excitation_absorption(only_chl, λ) ≈ 0.02achl rtol = 1e-12 + @test excitation_absorption(antenna, λ) ≈ 0.02(achl + acar) rtol = 1e-12 + @test excitation_absorption(half, λ) ≈ 0.02(achl + 0.5acar) rtol = 1e-12 + end + @test excitation_absorption(only_chl, 490.0) < excitation_absorption(antenna, 490.0) + # Beyond the carotenoid band the choice does not matter. + @test excitation_absorption(only_chl, 650.0) ≈ excitation_absorption(antenna, 650.0) + + # Ocean pigment groups: separate efficiencies for photosynthetic and + # photoprotective carotenoids; phycobilins default to 1. + pig = Bidigare1990Pigments(chl_a = 0.5, chl_c = 0.1, psc = 0.3, ppc = 0.15, pe_peb = 0.05) + pb = Phytoplankton(Chl = 0.5, pigments = pig) + f = chlorophyll_fluorescence(pb; quantum_yield = 0.02, + transfer = (photosynthetic_carotenoids = 0.8, + photoprotective_carotenoids = 0.0)) + η = Dict(x.part => x.efficiency for x in excitation_pathways(f)) + @test η[:chlorophyll_a] == η[:chlorophyll_c] == 1 + @test η[:photosynthetic_carotenoids] == 0.8 && η[:photoprotective_carotenoids] == 0 + @test η[:phycoerythrin_peb] == 1 && η[:unassigned] == 0 + a = absorption_by_part(pb, 470.0) + @test excitation_absorption(f, 470.0) ≈ 0.02(a[1] + a[2] + a[3] + 0.8a[4] + a[6] + a[7]) rtol = 1e-12 + @test_throws ArgumentError chlorophyll_fluorescence(pb; quantum_yield = 0.02, + transfer = (photosynthetic_carotenoids = 0.8,)) + @test_throws ArgumentError chlorophyll_fluorescence(pb; quantum_yield = 0.02, + carotenoid_transfer = 0.5, + transfer = (fucoxanthin = 1.0,)) + g = chlorophyll_fluorescence(pb; quantum_yield = 0.02, carotenoid_transfer = 0.5, + phycobilin_transfer = 0.9) + @test Dict(x.part => x.efficiency for x in excitation_pathways(g))[:phycoerythrin_pub] == 0.9 end @testset "CDOMFluorescence" begin cdom = CDOM{Float64}(a_ref = 0.5, λ_ref = 440.0, slope = 0.017) em = GaussianEmission{Float64}(center_nm = 440.0, σ_nm = 40.0) - fluo = CDOMFluorescence{Float64}(cdom; - emission = em, - quantum_yield = 0.01, - excitation_range = (300.0, 400.0)) - + fluo = CDOMFluorescence(cdom; emission = em, quantum_yield = 0.01) @test excitation_absorption(fluo, 350.0) ≈ 0.01 * absorption(cdom, 350.0) - @test emission(fluo, 350.0, 440.0) == redistribution(em, 350.0, 440.0) - @test excitation_range(fluo) == (300.0, 400.0) - @test is_isotropic(fluo) - @test quantum_yield(fluo) == 0.01 - - # Validation - @test_throws ArgumentError CDOMFluorescence{Float64}(cdom; - emission = em, quantum_yield = -0.01) + @test emission(fluo, 350.0, 440.0) == redistribution(em, 350.0, 440.0) + @test excitation_range(fluo) == (300.0, 400.0) + @test is_isotropic(fluo) && quantum_yield(fluo) == 0.01 + @test only(excitation_pathways(fluo)).absorber === cdom + @test_throws ArgumentError CDOMFluorescence(cdom; emission = em, quantum_yield = -0.01) + @test_throws UndefKeywordError CDOMFluorescence(cdom; emission = em) end @testset "Photon and energy kernels" begin - phyto = Phytoplankton{Float64, Bricaud1998}(Chl = 1.0) - sif = chlorophyll_fluorescence(phyto) + phyto = Phytoplankton(Chl = 1.0) + sif = chlorophyll_fluorescence(phyto; quantum_yield = 0.02) λ′, λ = 440.0, 685.0 # Quantum yield is part of the excitation coefficient, applied once. @test excitation_absorption(sif, λ′) ≈ quantum_yield(sif) * absorption(phyto, λ′) # Energy kernel = photon kernel × λ'/λ (ratio of photon energies). @test radiance_source_kernel(sif, λ′, λ) ≈ inelastic_coefficient(sif, λ′, λ) * λ′ / λ # Photon budget: emission integrates to the excitation coefficient. - em = 600.0:0.25:800.0 + em = 600.0:0.25:900.0 @test sum(inelastic_coefficient(sif, λ′, x) for x in em) * step(em) ≈ - excitation_absorption(sif, λ′) rtol = 1e-6 + excitation_absorption(sif, λ′) rtol = 1e-9 # Zero yield, zero source. - dark = IsotropicFluorescence{Float64}(phyto; emission = sif.emission, quantum_yield = 0.0) + dark = chlorophyll_fluorescence(phyto; quantum_yield = 0.0) @test radiance_source_kernel(dark, λ′, λ) == 0 + @test isempty(excitation_pathways(WaterRaman{Float64}())) end end diff --git a/test/test_layer_optics.jl b/test/test_layer_optics.jl index 51ba85c..10ba52d 100644 --- a/test/test_layer_optics.jl +++ b/test/test_layer_optics.jl @@ -10,13 +10,17 @@ o = layer_optics(layer, λ; ℓ_max = 32) @test o isa OceanLayerOptics{Float64} && !is_polarized(o) @test thickness(o) == 5 && o.depth_top == 2 && n_moments(o) == 33 - @test [c.label for c in o.components] == ["PureWater", "Phytoplankton"] + @test [c.label for c in o.scatterers] == ["PureWater", "Phytoplankton"] + @test [(c.label, c.part) for c in o.absorbers] == + [("PureWater", :total), ("CDOM", :total), ("Phytoplankton", :total)] + @test isempty(o.inelastic) for (i, λi) in enumerate(λ) a = absorption(water, λi) + absorption(cdom, λi) + absorption(phyto, λi) bw, bp = scattering(water, λi), scattering(phyto, λi) @test absorption_optical_depth(o)[i] ≈ 5a rtol = 1e-12 - @test o.components[1].τ[i] ≈ 5bw rtol = 1e-12 - @test o.components[2].τ[i] ≈ 5bp rtol = 1e-12 + @test o.absorbers[2].τ[i] ≈ 5absorption(cdom, λi) rtol = 1e-12 + @test o.scatterers[1].τ[i] ≈ 5bw rtol = 1e-12 + @test o.scatterers[2].τ[i] ≈ 5bp rtol = 1e-12 @test optical_depth(o)[i] ≈ 5(a + bw + bp) rtol = 1e-12 @test single_scattering_albedo(o)[i] ≈ (bw + bp) / (a + bw + bp) rtol = 1e-12 # Mixed expansion: scattering-weighted, so β₁ comes from the particles only. @@ -28,8 +32,8 @@ (bw + bp) rtol = 1e-12 end # Wavelength-independent phase functions are expanded once. - @test all(!is_wavelength_dependent(c) for c in o.components) - @test all(c.polarization == :scalar for c in o.components) + @test all(!is_wavelength_dependent(c) for c in o.scatterers) + @test all(c.polarization == :scalar for c in o.scatterers) end @testset "Polarization policy and labels" begin @@ -40,10 +44,10 @@ o = layer_optics(layer, λ; ℓ_max = 8, polarized = true, scalar_phase_approximation = :depolarizing) @test is_polarized(o) - @test [c.polarization for c in o.components] == [:full, :depolarizing] + @test [c.polarization for c in o.scatterers] == [:full, :depolarizing] # Particles contribute only to β: the mixed α₂ is the water share of 3. for i in eachindex(λ) - w = o.components[1].τ[i] / scattering_optical_depth(o)[i] + w = o.scatterers[1].τ[i] / scattering_optical_depth(o)[i] g = greek_expansion(o, i) @test g.α[3] ≈ 3w rtol = 1e-12 @test g.γ[3] ≈ sqrt(1.5) * w rtol = 1e-12 @@ -54,7 +58,7 @@ # A pure-water layer needs no approximation. ow = layer_optics(OceanLayer(0.0, 1.0, AbstractOceanConstituent{Float64}[water]), λ; ℓ_max = 4, polarized = true) - @test only(ow.components).polarization == :full + @test only(ow.scatterers).polarization == :full end @testset "Zero scattering and empty layers" begin @@ -67,7 +71,7 @@ @test g.β == [1.0, 0, 0, 0, 0] && all(iszero, (g.α, g.γ, g.δ, g.ϵ, g.ζ)) @test greek_expansion(o, 2).α[3] ≈ 3 e = layer_optics(OceanLayer(0.0, 1.0, AbstractOceanConstituent{Float64}[]), [500.0]; ℓ_max = 2) - @test isempty(e.components) && optical_depth(e) == [0.0] + @test isempty(e.scatterers) && isempty(e.absorbers) && optical_depth(e) == [0.0] @test greek_expansion(e, 1).β == [1.0, 0.0, 0.0] end @@ -95,7 +99,7 @@ s = TabulatedScatterer(λ2, [0.1, 0.1], pf) o = layer_optics(OceanLayer(0.0, 1.0, AbstractOceanConstituent{Float64}[s]), λ2; ℓ_max = 4, polarized = true) - c = only(o.components) + c = only(o.scatterers) @test is_wavelength_dependent(c) && length(c.greek) == 2 && c.phase_index == [1, 2] @test greek_expansion(c, 1).γ[3] ≈ sqrt(1.5) @test greek_expansion(c, 2).γ[3] < sqrt(1.5) @@ -108,7 +112,7 @@ sf = TabulatedScatterer(λf, fill(0.1, 2000), pn) t = @elapsed of = layer_optics(OceanLayer(0.0, 1.0, AbstractOceanConstituent{Float64}[sf]), λf; ℓ_max = 64, polarized = true) - cf = only(of.components) + cf = only(of.scatterers) @test length(cf.greek) == 2 && length(cf.phase_index) == 2000 @test greek_expansion(cf, 1) === cf.greek[1] && greek_expansion(cf, 2000) === cf.greek[2] @test cf.phase_index[findfirst(>(550.0), λf)] == 2 @@ -143,12 +147,19 @@ @test_throws DimensionMismatch sc(greek = [g, g], B = [0.5, 0.5], index = [1, 2, 1]) @test_throws ArgumentError sc(greek = [g, g], B = [0.5, 0.5], index = [1, 3]) @test is_wavelength_dependent(sc(greek = [g, g], B = [0.5, 0.5], index = [2, 1])) - lay(; λ = [450.0, 550.0], top = 0.0, bot = 1.0, τa = [0.1, 0.1], comps = [sc()], n = 3, pol = false) = - OceanLayerOptics{Float64}(λ, top, bot, τa, comps, n, pol) + ac(τ = [0.1, 0.1]) = AbsorptionComponent("a", :total, τ) + @test_throws ArgumentError ac([-0.1, 0.1]) + lay(; λ = [450.0, 550.0], top = 0.0, bot = 1.0, abs = [ac()], comps = [sc()], + inel = InelasticComponent{Float64}[], n = 3, pol = false) = + OceanLayerOptics{Float64}(λ, top, bot, abs, comps, inel, n, pol) @test lay() isa OceanLayerOptics @test_throws ArgumentError lay(λ = [450.0, 450.0]) @test_throws ArgumentError lay(top = 1.0) - @test_throws DimensionMismatch lay(τa = [0.1]) + @test_throws DimensionMismatch lay(abs = [ac([0.1])]) + raman = WaterRaman{Float64}() + @test_throws ArgumentError lay(inel = [InelasticComponent{Float64}("WaterRaman", raman, [2], [1.0])]) + @test_throws DimensionMismatch InelasticComponent{Float64}("WaterRaman", raman, [1], Float64[]) + @test_throws ArgumentError InelasticComponent{Float64}("WaterRaman", raman, [1], [1.5]) @test_throws ArgumentError lay(n = 4) @test_throws ArgumentError lay(pol = true) @test_throws DimensionMismatch lay(comps = [sc(τ = [0.1])]) @@ -165,8 +176,8 @@ @test [l.depth_top for l in col] == [0.0, 10.0, 20.0] @test interface_depths(col) == [0.0, 10.0, 20.0, 30.0] # Equal phase functions share one phase_id and the same expansion objects. - @test allequal(only(l.components).phase_id for l in col) - @test all(only(l.components).greek[1] === only(col[1].components).greek[1] for l in col) + @test allequal(only(l.scatterers).phase_id for l in col) + @test all(only(l.scatterers).greek[1] === only(col[1].scatterers).greek[1] for l in col) colQ = column_optics(column, λ2; refractive_index = QuanFry1995(temperature = 20, salinity = 35), bottom = LambertianBottom([0.1, 0.2]), ℓ_max = 8) @test colQ.refractive_index ≈ refractive_index(QuanFry1995(temperature = 20, salinity = 35), λ2) @@ -186,9 +197,13 @@ @test_throws ArgumentError OceanColumnOptics([l1, col.layers[3]], [1.34, 1.34], BlackBottom()) end - @testset "Fluorophores are not elastic optics" begin + @testset "Inelastic processes are carried, not mixed" begin + raman = WaterRaman{Float64}() layer = OceanLayer(0.0, 5.0, AbstractOceanConstituent{Float64}[cdom]; - fluorophores = AbstractOceanInelasticProcess{Float64}[WaterRaman{Float64}()]) - @test isempty(layer_optics(layer, [500.0]; ℓ_max = 4).components) + inelastic = AbstractOceanInelasticProcess{Float64}[raman]) + o = layer_optics(layer, [500.0]; ℓ_max = 4) + @test isempty(o.scatterers) && optical_depth(o) ≈ [5absorption(cdom, 500.0)] + c = only(o.inelastic) + @test c.process === raman && c.label == "WaterRaman" && isempty(c.excitation) end end diff --git a/test/test_pigments.jl b/test/test_pigments.jl new file mode 100644 index 0000000..9e372b1 --- /dev/null +++ b/test/test_pigments.jl @@ -0,0 +1,91 @@ +@testset "Pigment partitions" begin + + @testset "Bundled spectra" begin + # Bidigare et al. (1990) chlorophyll a: Soret maximum 0.0265 m²/mg at 440 nm. + tbl = OceanOptics._BIDIGARE_SPECTRA[1] + @test tbl.λ[[1, end]] == [400.0, 750.0] && length(tbl.λ) == 176 + @test maximum(tbl.y) == 0.0265 && tbl.λ[argmax(tbl.y)] == 440 + # PROSPECT-D: Kab extends to 780 nm, Kca to 557 nm. + @test OceanOptics.linterp(OceanOptics._PROSPECT_KAB, 780.0) > 0 + @test OceanOptics.linterp(OceanOptics._PROSPECT_KAB, 781.0) == 0 + @test OceanOptics.linterp(OceanOptics._PROSPECT_KCA, 558.0) == 0 + end + + @testset "ProspectPigments" begin + pig = ProspectPigments(carotenoid_ratio = 0.3) + phyto = Phytoplankton(Chl = 0.5, pigments = pig) + @test absorption_parts(phyto) == (:chlorophyll, :carotenoids, :unassigned) + @test pigment_class(pig, :carotenoids) == :carotenoid + @test_throws ArgumentError pigment_class(pig, :fucoxanthin) + for λ in (350.0, 420.0, 450.0, 490.0, 560.0, 676.0, 790.0) + a = absorption_by_part(phyto, λ) + @test sum(a) ≈ absorption(phyto, λ) rtol = 1e-12 + @test all(≥(0), a) + end + # Shares follow Kab : r·Kca. + kab, kca = OceanOptics.linterp(OceanOptics._PROSPECT_KAB, 480.0), + OceanOptics.linterp(OceanOptics._PROSPECT_KCA, 480.0) + f = pigment_fractions(pig, 480.0) + @test f[2] / f[1] ≈ 0.3kca / kab rtol = 1e-12 + @test f[3] == 0 + # No carotenoid absorption beyond 557 nm; UV outside the table is unassigned. + @test absorption_part(phyto, :carotenoids, 600.0) == 0 + @test absorption_part(phyto, :unassigned, 350.0) == absorption(phyto, 350.0) + @test pigment_fractions(ProspectPigments(carotenoid_ratio = 0.0), 450.0) == (1.0, 0.0, 0.0) + @test_throws ArgumentError ProspectPigments(carotenoid_ratio = -0.1) + @test_throws ArgumentError absorption_part(phyto, :total, 450.0) + end + + @testset "Bidigare1990Pigments" begin + pig = Bidigare1990Pigments(chl_a = 0.5, chl_b = 0.05, chl_c = 0.1, psc = 0.3, ppc = 0.15) + phyto = Phytoplankton(Chl = 0.5, pigments = pig) + @test length(absorption_parts(phyto)) == 8 && last(absorption_parts(phyto)) == :unassigned + @test pigment_class(pig, :photoprotective_carotenoids) == :carotenoid + @test pigment_class(pig, :phycoerythrin_peb) == :phycobilin + @test pigment_class(pig, :chlorophyll_c) == :chlorophyll + for λ in (380.0, 440.0, 470.0, 550.0, 676.0, 740.0) + @test sum(absorption_by_part(phyto, λ)) ≈ absorption(phyto, λ) rtol = 1e-12 + end + # Shares are c_k a*_k / Σ c_j a*_j at a tabulated wavelength (Bidigare 1990 at 440 nm). + tbl = OceanOptics._BIDIGARE_SPECTRA + s = [c * t.y[findfirst(==(440.0), t.λ)] + for (c, t) in zip(OceanOptics._concentrations(pig), tbl)] + @test collect(pigment_fractions(pig, 440.0))[1:7] ≈ s ./ sum(s) rtol = 1e-12 + # Only ratios matter. + @test all(pigment_fractions(Bidigare1990Pigments(chl_a = 5.0, chl_b = 0.5, chl_c = 1.0, + psc = 3.0, ppc = 1.5), 470.0) .≈ + pigment_fractions(pig, 470.0)) + # Red band: chlorophyll a only; beyond it and outside the table: unassigned. + @test pigment_fractions(Bidigare1990Pigments(chl_a = 1.0, psc = 1.0), 676.0)[1] == 1 + @test last(pigment_fractions(pig, 740.0)) == 1 && last(pigment_fractions(pig, 390.0)) == 1 + @test_throws ArgumentError Bidigare1990Pigments(chl_a = 0.0) + @test_throws ArgumentError Bidigare1990Pigments(chl_a = 1.0, ppc = -0.1) + @test_throws UndefKeywordError Bidigare1990Pigments(psc = 1.0) + end + + @testset "Phytoplankton without a partition" begin + phyto = Phytoplankton(Chl = 0.5) + @test absorption_parts(phyto) == (:total,) + @test absorption_part(phyto, :total, 450.0) == absorption(phyto, 450.0) + @test absorption_parts(CDOM{Float64}()) == (:total,) + end + + @testset "Partitions take the phytoplankton's precision" begin + p32 = Phytoplankton{Float32, Bricaud1998}(Chl = 0.5, pigments = ProspectPigments(carotenoid_ratio = 0.3)) + @test p32.pigments isa ProspectPigments{Float32} + @test absorption_by_part(p32, 450.0f0) isa NTuple{3, typeof(absorption(p32, 450.0f0))} + b32 = Phytoplankton{Float32, Bricaud1998}(Chl = 0.5, pigments = Bidigare1990Pigments(chl_a = 0.5, ppc = 0.1)) + @test b32.pigments isa Bidigare1990Pigments{Float32} + end + + @testset "AD through a partition" begin + d = ForwardDiff.derivative(r -> absorption_part( + Phytoplankton(Chl = 0.5, pigments = ProspectPigments(carotenoid_ratio = r)), + :carotenoids, 480.0), 0.3) + @test d > 0 + d = ForwardDiff.derivative(c -> absorption_part( + Phytoplankton(Chl = 0.5, pigments = Bidigare1990Pigments(chl_a = 0.5, ppc = c)), + :photoprotective_carotenoids, 470.0), 0.1) + @test d > 0 + end +end diff --git a/test/test_redistribution.jl b/test/test_redistribution.jl index 285a3d4..3461f45 100644 --- a/test/test_redistribution.jl +++ b/test/test_redistribution.jl @@ -58,6 +58,27 @@ using QuadGK @test_throws ArgumentError WavenumberShiftEmission{Float64}(shift_cm_inv = 3400.0, σ_cm_inv = 0.0) end + @testset "TabulatedEmission" begin + λ = [600.0, 650.0, 700.0, 750.0] + r = TabulatedEmission(λ, [0.0, 2.0, 1.0, 0.0]; source = "test") + # Normalized to unit area; linear between points, zero outside. + @test r.density ≈ [0.0, 2.0, 1.0, 0.0] ./ 150 + @test redistribution(r, 400.0, 675.0) ≈ 1.5 / 150 + @test redistribution(r, 400.0, 599.0) == 0 && redistribution(r, 400.0, 751.0) == 0 + @test redistribution(r, 400.0, 650.0) == redistribution(r, 500.0, 650.0) # excitation-independent + x = 590.0:0.01:760.0 + @test sum(redistribution(r, 0.0, xi) for xi in x) * step(x) ≈ 1 rtol = 1e-9 + # Energy spectra become photon densities ∝ E·λ. + re = TabulatedEmission(λ, [0.0, 2.0, 1.0, 0.0]; units = :energy) + @test re.density[3] / re.density[2] ≈ (1.0 * 700) / (2.0 * 650) + @test ForwardDiff.derivative(x -> redistribution(r, 0.0, x), 625.0) ≈ (2 / 150) / 50 + @test_throws ArgumentError TabulatedEmission(λ, [0.0, -1.0, 1.0, 0.0]) + @test_throws ArgumentError TabulatedEmission(λ, zeros(4)) + @test_throws ArgumentError TabulatedEmission([600.0, 600.0], [1.0, 1.0]) + @test_throws DimensionMismatch TabulatedEmission(λ, [1.0, 1.0]) + @test_throws ArgumentError TabulatedEmission(λ, ones(4); units = :watts) + end + @testset "Forward-mode AD through redistribution" begin r = GaussianEmission{Float64}(center_nm = 685.0, σ_nm = 10.6) # ∂f/∂λ at the peak = 0 by symmetry diff --git a/test/test_tabulated.jl b/test/test_tabulated.jl index cfb63d4..fb24218 100644 --- a/test/test_tabulated.jl +++ b/test/test_tabulated.jl @@ -93,7 +93,7 @@ o = layer_optics(OceanLayer(0.0, 100.0, AbstractOceanConstituent{Float64}[ TabulatedAbsorber(λ, cases[1].a_blk; total = true), water_scat]), λ; ℓ_max = 8, polarized = true) - c = only(o.components) + c = only(o.scatterers) @test c.label == src && c.polarization == :full @test greek_expansion(c, 1).γ[3] ≈ sqrt(1.5) && greek_expansion(c, 1).δ[2] ≈ 1.5 @test backscatter_fraction(o) ≈ fill(0.5, 4) From 3366101203e7e82a67305f1b10de83d9fe582907 Mon Sep 17 00:00:00 2001 From: cfranken Date: Fri, 13 Nov 2026 10:32:16 -0800 Subject: [PATCH 2/2] Release 0.2.0: corrected physics, exposed parameters, devices, derivatives MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Changed results (see CHANGELOG, "Changed results"): - Phytoplankton{Bricaud1998} absorption is A(λ)·Chl^E(λ), as the bundled HydroLight table defines it (was A·Chl^(1−E)); it is particulate absorption (phytoplankton plus detritus). Unchanged at Chl = 1. - Water Raman is an energy conversion by default (Mobley et al. 1993, HydroLight); the photon form is PhotonConversion(). - FellMineral defaults follow Fell (1997): ω = 0.95, B = 0.036. - Pigment partitions hold the edge shares outside their tables; photoprotective carotenoids are a separate class with zero transfer. Breaking (see "Breaking" and the migration section of the docs): - layer_optics and column_optics take the element type as an optional first argument; the FT keyword is gone. - Result structs have array type parameters and Adapt rules; phase_id is a vector of content keys; Gordon1992 is removed. - WaterRaman carries its conversion units and linear_depolarization. Added: - Results and spectral tables move to device arrays with Adapt (tested on JLArrays and CUDA); Float32 models return Float32. - Model parameters can carry ForwardDiff dual numbers through layer_optics and column_optics. - Every physical parameter is a field or keyword with a documented default (docs: reference/parameters.md). - Raman phase function, conversion-unit types, table lookup types. - Tests: Aqua, JET, ExplicitImports, inference, Float32, device, published-value references, parameter exposure. Packaging: Adapt is a dependency; Interpolations is dropped; docs build is strict; version 0.2.0. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01TRfrLS11vLye7ZcoRFSe5B --- .github/workflows/CI.yml | 4 + .github/workflows/Documentation.yml | 4 + .gitignore | 5 +- CHANGELOG.md | 429 ++++++++++++++++++++++- Project.toml | 16 +- README.md | 37 +- data/bricaud_1998_A.csv | 18 +- data/bricaud_1998_E.csv | 21 +- data/fluspect_chloroplast_emission.csv | 6 +- data/prospect_d_pigment_absorption.csv | 5 +- docs/make.jl | 6 +- docs/src/consumer_api.md | 289 ++++++++++++++-- docs/src/example.md | 92 ++++- docs/src/gallery.md | 14 +- docs/src/index.md | 21 +- docs/src/reference/inelastic.md | 89 +++++ docs/src/reference/io.md | 9 + docs/src/reference/materials.md | 6 +- docs/src/reference/parameters.md | 170 +++++++++ docs/src/reference/phases.md | 2 + docs/src/reference/types.md | 4 + docs/src/vsmartmom_integration.md | 47 ++- scripts/fetch_data.jl | 17 +- src/OceanOptics.jl | 15 +- src/diagnostics/absorbed_light.jl | 149 +++++--- src/inelastic/fluorescence.jl | 54 ++- src/inelastic/processes.jl | 161 ++++++--- src/inelastic/raman.jl | 230 +++++++++---- src/inelastic/redistribution.jl | 63 +++- src/io/data_loaders.jl | 238 ++++++++++--- src/materials/cdom.jl | 38 +- src/materials/nap.jl | 86 +++-- src/materials/phytoplankton.jl | 220 +++++++----- src/materials/pigments.jl | 122 +++++-- src/materials/pure_water.jl | 192 +++++++---- src/materials/refractive_index.jl | 38 +- src/materials/tabulated.jl | 87 +++-- src/mixing/layer_assembly.jl | 125 ++++--- src/phase/abstract_phase.jl | 46 +-- src/phase/angular.jl | 16 +- src/phase/fournier_forand.jl | 96 ++++-- src/phase/henyey_greenstein.jl | 14 +- src/phase/petzold.jl | 21 +- src/phase/rayleigh_water.jl | 55 ++- src/phase/tabulated_greek.jl | 6 +- src/phase/tabulated_mueller.jl | 6 +- src/phase/wavelength_phase.jl | 38 +- src/types/abstract_types.jl | 191 +++++++--- src/types/greek.jl | 240 ++++++++++--- src/types/iop.jl | 63 +++- src/types/layer_optics.jl | 460 ++++++++++++++++++------- src/types/ocean_column.jl | 47 ++- src/types/ocean_layer.jl | 18 +- test/gpu/Project.toml | 5 + test/gpu/README.md | 12 + test/gpu/runtests.jl | 17 + test/runtests.jl | 10 + test/static_helpers.jl | 22 ++ test/test_ad.jl | 375 +++++++++++++++++++- test/test_aqua.jl | 7 + test/test_cdom.jl | 7 + test/test_column.jl | 2 +- test/test_device.jl | 227 ++++++++++++ test/test_explicit_imports.jl | 10 + test/test_float32.jl | 117 +++++++ test/test_fluorescence.jl | 68 +++- test/test_greek.jl | 13 + test/test_inference.jl | 47 +++ test/test_iop.jl | 27 ++ test/test_jet.jl | 32 ++ test/test_layer_optics.jl | 18 +- test/test_nap.jl | 12 + test/test_parameters.jl | 177 ++++++++++ test/test_phase.jl | 17 + test/test_phytoplankton.jl | 58 +++- test/test_pigments.jl | 37 +- test/test_pure_water.jl | 73 +++- test/test_raman.jl | 95 ++++- test/test_redistribution.jl | 7 +- test/test_refractive_index.jl | 8 + test/test_solver_contract.jl | 188 ++++++++++ test/test_spectral_table.jl | 66 ++++ 82 files changed, 5136 insertions(+), 1064 deletions(-) create mode 100644 docs/src/reference/parameters.md create mode 100644 test/gpu/Project.toml create mode 100644 test/gpu/README.md create mode 100644 test/gpu/runtests.jl create mode 100644 test/static_helpers.jl create mode 100644 test/test_aqua.jl create mode 100644 test/test_device.jl create mode 100644 test/test_explicit_imports.jl create mode 100644 test/test_float32.jl create mode 100644 test/test_inference.jl create mode 100644 test/test_jet.jl create mode 100644 test/test_parameters.jl create mode 100644 test/test_solver_contract.jl create mode 100644 test/test_spectral_table.jl diff --git a/.github/workflows/CI.yml b/.github/workflows/CI.yml index 64b9b45..d3767e2 100644 --- a/.github/workflows/CI.yml +++ b/.github/workflows/CI.yml @@ -1,3 +1,6 @@ +# Tests (Julia 1.10 and current stable; Linux and macOS) with coverage. +# The documentation is built by Documentation.yml: on every pull request +# (build only, no deployment) and on pushes to main and tags (build and deploy). name: CI on: @@ -56,3 +59,4 @@ jobs: files: lcov.info token: ${{ secrets.CODECOV_TOKEN }} continue-on-error: true + diff --git a/.github/workflows/Documentation.yml b/.github/workflows/Documentation.yml index a8a2405..db45aec 100644 --- a/.github/workflows/Documentation.yml +++ b/.github/workflows/Documentation.yml @@ -1,3 +1,7 @@ +# Builds the documentation (strict: doctests, cross-references, exported +# docstrings) on every pull request and push. `deploydocs` publishes only for +# pushes to main and tags; pull-request builds are checks without deployment. +# This is the only workflow that builds the docs (CI.yml runs the tests). name: Documentation on: diff --git a/.gitignore b/.gitignore index 3e6bac1..e7d85ec 100644 --- a/.gitignore +++ b/.gitignore @@ -3,6 +3,7 @@ /docs/build/ /docs/site/ /docs/Manifest.toml +/test/gpu/Manifest.toml # Coverage *.cov @@ -16,7 +17,3 @@ *.swp *.swo .DS_Store - -# Google Drive sync artefacts (this working copy lives under Drive) -.tmp.drivedownload/ -*.icloud diff --git a/CHANGELOG.md b/CHANGELOG.md index db8c5b0..eeb5ca1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,13 +4,194 @@ All notable changes to OceanOptics.jl are recorded here. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). -## [Unreleased] — 0.2.0 +## [Unreleased] + +## [0.2.0] — 2026-11-13 + +Release notes. Water Raman is an energy conversion by default and its +phase function follows Mobley et al. (1993); every physical parameter is a +field or keyword with a documented default (see the parameter reference); +model parameters can be differentiated with ForwardDiff through +`layer_optics` and `column_optics`; light absorbed per constituent, +chlorophyll fluorescence with chloroplast-level emission, and the ocean +floor were added for the coupled solver. Each entry below says what a user +must change; the "Migrating from 0.1" section of the Consumer API page shows +the code. Light absorbed per constituent, chlorophyll fluorescence with land-analogous chloroplast emission, and the ocean floor, for the fluorescence and absorbed-PAR requirements of the coupled solver. -### Changed (breaking) +### Changed results + +- **Photoprotective carotenoids no longer excite chlorophyll fluorescence by + default.** `pigment_class` gives them their own class and + `chlorophyll_fluorescence` the keyword `photoprotective_transfer = 0`; + `carotenoid_transfer` now applies to photosynthetic (and Prospect's lumped) + carotenoids only. With `Bidigare1990Pigments(chl_a = 0.5, chl_c = 0.1, + psc = 0.3, ppc = 0.15)` and `carotenoid_transfer = 0.7` the excitation + coefficient falls by the photoprotective share, 18 % at 440 nm and 12 % at + 360 nm (physics review DREV_PHYS). To keep the 0.1 result pass + `photoprotective_transfer` equal to `carotenoid_transfer`. + +- **Bricaud absorption of `Phytoplankton{Bricaud1998}`: `a = A(λ)·Chl^E(λ)`** + (formerly `A(λ)·Chl^(1−E(λ))`). The bundled tables are HydroLight's + `AEmidUVabs.txt`, whose header defines the particulate absorption + `ap(wave) = A(wave)*[chl]^E(wave)` (Bricaud et al. 1998, + `a_p(440) = 0.052 Chl^0.635`); the exponent `1 − E` belongs to the + specific-absorption form of Bricaud et al. (1995), which has other + coefficients. Results are unchanged at Chl = 1 mg m⁻³ and change + everywhere else: + + | Chl [mg m⁻³] | a(440) before | a(440) now | a(676) before | a(676) now | + |---|---|---|---|---| + | 0.03 | 0.01446 | 0.00561 | 0.01089 | 0.00114 | + | 0.1 | 0.02244 | 0.01205 | 0.01348 | 0.00306 | + | 0.5 | 0.04038 | 0.03348 | 0.01795 | 0.01148 | + | 1 | 0.05200 | 0.05200 | 0.02030 | 0.02030 | + | 10 | 0.12050 | 0.22439 | 0.03056 | 0.13483 | + + `Chl = 0` gives zero absorption (formerly `Inf` at 698–700 nm, where + `E > 1`). Everything derived from this absorption changes by the same + factors: the pigment parts (`absorption_by_part`, the absorption + components of `layer_optics`), the excitation of + `chlorophyll_fluorescence`, `absorbed_power`, `absorbed_photons` and + `absorbed_par`, and the documentation figures at Chl ≠ 1. The quantity is + the particulate absorption `a_p` (phytoplankton plus detritus), not + `a_φ`: the docstrings, data-file headers and documentation say so, and + warn that a separate `NonAlgalParticles` constituent adds detrital + absorption a second time. +- **`NonAlgalParticles{FT, FellMineral}` defaults are those of Fell (1997), + p. 120:** single-scattering albedo `ω_nap = 0.95` (formerly 0.96) and + backscatter fraction `B = 0.036` (formerly 0.03). For the default + `c_ref = 0.4 m⁻¹`: `a(440)` 0.016 → 0.020 m⁻¹ (+25 %), `b(440)` 0.384 → + 0.380 m⁻¹, `b_b(440)` 0.01152 → 0.01368 m⁻¹ (+19 %). Explicit `ω_nap` + and `B` give the same results as before. +- The particulate scattering law `b_p = 0.30·Chl^0.62·(550/λ)` is unchanged + in value; it is now attributed to Gordon & Morel (1983) (as cited by + Fell 1997, Eq. 5.5) instead of Morel & Maritorena (2001), and described + as the total particulate scattering of Case-1 water. +- `TabulatedAbsorber` and `TabulatedScatterer` with linear lookup return + the type that the query wavelength and the table promote to (formerly + always the table's precision): a `Float64` query of a `Float32` table + gives a `Float64`, for example 0.0175 at 425 nm between 0.02 (400 nm) + and 0.01 (500 nm) instead of `0.0175f0`; values of + `Float64` tables are unchanged. A `ForwardDiff.Dual` wavelength now + gives the slope of the segment (formerly a `MethodError`). + +- **Water Raman source: `b_R` is an energy conversion coefficient.** + `radiance_source_kernel(::WaterRaman, λ′, λ)` is now `b_R(λ′) f_R(λ′, λ)` + (formerly `b_R f_R λ′/λ`), the definition of Mobley et al. (1993, Problem 7 + and Eqs. A3–A4): `∫ K_E dλ = b_R(λ′)`. The Raman energy kernel and + `inelastic_emission` of a Raman component rise by the inverse of the band + mean of `λ′/λ`: ×1.135 at 350 nm excitation, ×1.165 at 417 nm (the Mobley + Problem 7 source `b_R E₀/(4π)` was 14.2 % low), ×1.199 at 488 nm, ×1.256 + at 600 nm, ×1.31 at 700 nm. The photon kernel + `inelastic_coefficient(::WaterRaman, λ′, λ)` rises by the same factors + (it is now `K_E λ/λ′`, formerly `b_R f_R`). The former behaviour is + `WaterRaman(conversion = PhotonConversion())`. Fluorescence kernels are + unchanged. +- **Default Raman depolarization 0.17** (formerly 0.14, a field that no + function used). It now sets the Raman phase function `raman_phase`. + +- **Pigment partitions outside their tables hold the edge shares.** + `pigment_fractions` of `ProspectPigments` and `Bidigare1990Pigments` below + 400 nm returns the shares at 400 nm (formerly all `:unassigned`); above the + red end of the tables the shares are all `:unassigned` under both rules, so + results there are unchanged. With + Chl = 0.5 mg m⁻³, `excitation_range = (350, 700)` and unit transfer + efficiencies, `excitation_absorption` of `chlorophyll_fluorescence` at + 399.999 nm is 5.32·10⁻⁴ m⁻¹ (formerly 0) and its 350–700 nm integral rises + by 1/0.781 = 1.281 to the unpartitioned value; the pigment rows of + `absorbed_power`, `absorbed_photons` and `layer_optics` below 400 nm change + accordingly. Results at 400–750 nm, and with the default + `excitation_range = (400, 700)`, are unchanged. The former rule is + `outside = UnassignedOutsideTable()`. + +- **`PureWater(depolarization = δ)` enters the Zhang–Hu–He scattering + magnitude** (formerly fixed at 0.039 inside the routine; only the phase + matrix used the field). Unchanged for the default `δ = 0.039` in + `Float64`; for `δ = 0.09`, `b(500 nm, 20 °C, S = 35)` is 2.785·10⁻³ m⁻¹ + (formerly 2.547·10⁻³, +9.3 %); for `δ = 0`, 2.385·10⁻³ (−6.4 %). In + `Float32` the default value is now the stored `0.039f0`, which changes + the last bit of some results (2 of 55 wavelengths at 5 °C, S = 10). + +### Breaking + +- **Integer and rational element types are rejected** with an + `ArgumentError` (`CDOM{Int}()`, `layer_optics(Rational{Int}, …)`; formerly an + `InexactError` or a silent computation in rationals). Use a floating-point + type. `IOP` of integer or rational arrays converts them to `Float64`, as the + scalar `IOP` does. +- **`Phytoplankton{FT}` rejects a scattering model of a non-floating-point + element type that `FT` cannot hold** (a dual `GordonMorel1983` in a + `Phytoplankton{Float32}`); construct it without `FT`, which then follows the + model's element type. +- **`pigment_class(::Bidigare1990Pigments, :photoprotective_carotenoids)`** is + `:photoprotective_carotenoid` (formerly `:carotenoid`). + +- **`Gordon1992` is removed.** The tag had no absorption (it threw "not yet + implemented") and its scattering was the generic Gordon & Morel law, not + Gordon's. Use `Phytoplankton{FT, Bricaud1998}`. +- **`layer_optics` rejects a layer that lists `PureWater` more than once** + (`ArgumentError`); formerly the water was counted twice. Other + constituents may repeat. +- **`PureWater` validates `depolarization ∈ [0, 1)`.** +- **`Phytoplankton` has a fifth type parameter and a field + `scattering_model`** (default `GordonMorel1983()`), and + `NonAlgalParticles` a field `spectral_exponent` (default 1); positional + constructors changed accordingly. + +- **`ProspectPigments` and `Bidigare1990Pigments` have a second type + parameter and a field `outside`** (`HoldEdgeShares()` by default, + `UnassignedOutsideTable()` for the former behaviour); the positional inner + constructors changed accordingly. + +- **`WaterRaman` has a second type parameter and a renamed field.** + `WaterRaman{FT, U<:AbstractConversionUnits}` carries the convention of + `b_R` in the new field `conversion` (default `EnergyConversion()`); + `WaterRaman{Float64}` is no longer a concrete type (`WaterRaman{Float64}()` + still constructs). The field and keyword `depolarization` is now + `linear_depolarization`: the depolarization ratio for linearly polarized + excitation (Mobley et al. 1993, Eq. 9), limited to `[0, 3/4]`. +- **Every inelastic process must define `conversion_units`.** A subtype of + `AbstractOceanInelasticProcess` without a `conversion_units` method throws + a `MethodError` in `inelastic_coefficient`, `radiance_source_kernel` and + `inelastic_emission`. + +- `layer_optics` and `column_optics` have no `FT` keyword: the element + type is the optional first positional argument, + `layer_optics(Float32, layer, λ; …)`. Passing `FT = …` is a + `MethodError`. +- `InelasticComponent{FT, P}` is host data: `efficiency` is a + `Vector{FT}` next to `excitation::Vector{Int}`, and `Adapt.adapt` + returns the component unchanged (the layer's `inelastic` vector is the + same object after `adapt`). There is no array type parameter. +- The table lookup is a type: `TabulatedAbsorber{FT, L}`, + `TabulatedScatterer{FT, P, L}` and `WavelengthDependentPhase{FT, P, L}` + with `lookup::L`, one of the new exported `ExactLookup`, `LinearLookup` + and `NearestLookup` (`<: AbstractTableLookup`). The keyword `lookup` + still accepts `:exact`, `:linear` and `:nearest`, and also the lookup + objects; the field no longer holds a `Symbol`, and the inner + constructors are `TabulatedAbsorber{FT, L}(λ, a, total, source, lookup)`, + `TabulatedScatterer{FT, P, L}(…)` and + `WavelengthDependentPhase{FT, P, L}(λ, phases, lookup)`. +- `Adapt.adapt` keeps the element type of every result struct and of + `SpectralTable`, and refuses an adaptor that changes it + (`adapt(CuArray{Float32}, col64)`, `adapt(Array{Float32}, g64)`) with an + `ArgumentError` that says to build the optics in the wanted precision; + formerly `GreekCoefficients` and `SpectralTable` converted and layers + and columns failed with a `TypeError`. +- `OceanColumnOptics(layers, n, bottom)` rejects a refractive index below 1 + (formerly any positive value), with the message of + `FixedRefractiveIndex`. +- `SpectralTable(λ, y)` rejects non-finite values `y` (formerly only + non-finite wavelengths). +- The element-type parameter of the result structs, of `OceanLayer`, + `OceanColumn` and the bottoms is bounded by `Real`: + `LambertianBottom{Any, Vector{Any}}` no longer constructs. +- The column name of `data/bricaud_1998_A.csv` is `A_per_m` (formerly + `A_m2_per_mg`). - `OceanLayerOptics` carries `absorbers` (one `AbsorptionComponent` per absorber or absorption part: `label`, `part`, `τ`), `scatterers` (the @@ -30,9 +211,195 @@ fluorescence and absorbed-PAR requirements of the coupled solver. `emission = GaussianEmission(...)`). - `layer_optics` throws if a fluorescence process is excited by an absorber that is not a constituent of the layer. +- `ScatteringComponent.phase_id` is a `Vector{UInt64}` with one content + key per entry of `greek` (formerly one `UInt64` derived from the + identity of the phase-function object). The key is the 64-bit FNV-1a + hash of the element type and coefficients, so it is equal for equal + expansions, differs with `ℓ_max`, element type, polarization treatment + and wavelength-dependent entry, and is reproducible between sessions. + The inner constructor `ScatteringComponent{FT}(label, τ, greek, B, + phase_index, polarization)` computes the keys; the `phase_id` argument + and keyword are gone. +- `layer_optics` and `column_optics` default to the element type of the + layer or column (formerly `Float64`); this changes the result only for + `Float32` layers and columns. +- `InelasticComponent{FT, P}` has the process type as a second parameter + (`process::P`). `InelasticComponent{FT}(label, process, excitation, + efficiency)` still constructs it. +- `TabulatedAbsorber` and `TabulatedScatterer` have a `lookup` field; + their inner constructors take it as the last argument. +- Exact-wavelength tables (`TabulatedAbsorber`, `TabulatedScatterer`, + `TabulatedGreekPhase`, `WavelengthDependentPhase(lookup = :exact)`) + match wavelengths to a relative tolerance of `1e-6` (formerly 8 ulp of + the less precise operand), and reject tables whose neighbouring + wavelengths are closer than twice that. +- `FixedRefractiveIndex(n)` rejects `n < 1` (formerly any positive `n` + was accepted); `n = 1` is allowed. +- `PureWater` with `IOCCG2018` absorption throws a `DomainError` naming + the composite range 350–2500 nm (formerly the range of the sub-table). +- `inelastic_emission` returns a vector whose element type is the promoted + type of the layer, the irradiance and the emission wavelengths + (formerly `Float64` for a `Float32` layer). +- `SpectralTable{T, V}` holds `λ`, `y` and the range limits `lo`, `hi` and + is interpolated by the package itself; the `itp` field and the + Interpolations.jl dependency are gone. Interpolated values are + bit-identical to 0.1.0 on all shipped tables (checked at every tabulated + wavelength and 40 000 others per table; for example pure-water + absorption at 551.3 nm, 0.05732191899999997 1/m, unchanged), and the + segment that a tabulated wavelength is assigned to is the same, so + derivatives are unchanged as well. `SpectralTable(λ, y)` accepts any real vectors + and rejects repeated wavelengths ("strictly increasing"; formerly + "sorted ascending" and `Vector{T}` arguments only). +- The result structs carry their array types as type parameters, appended + after the existing ones: `GreekCoefficients{FT, V}`, + `AbsorptionComponent{FT, V}`, `ScatteringComponent{FT, V, I}`, + `OceanLayerOptics{FT, V, I}`, + `LambertianBottom{FT, V}` and `OceanColumnOptics{FT, B, V, I}` (`V` the + array type of the floating-point fields, `I` that of `phase_index`). + `OceanLayerOptics{FT}`, `GreekCoefficients{FT}` and + `OceanColumnOptics{FT, BlackBottom}` in a signature dispatch as before, + and the `{FT}` constructors still work. No longer concrete, and to be + replaced where a concrete type is needed (struct fields, `Vector` + element types, `===` on types): `OceanLayerOptics{FT}` (now + `OceanLayerOptics{FT, Vector{FT}, Vector{Int}}` on the host), + `GreekCoefficients{FT}`, `LambertianBottom{FT}` and therefore + `OceanColumnOptics{FT, LambertianBottom{FT}}`, which matches no column: + write `OceanColumnOptics{FT, <:LambertianBottom}`. +- The inner constructors take the array types + (`GreekCoefficients{FT, V}(α, β, γ, δ, ϵ, ζ)` and likewise for the other + result structs) and store their arguments without converting them. The + `{FT}` constructors keep a dense vector of element type `FT` as it is + (formerly always a `Vector{FT}` copy made by `convert`), convert one of + another element type where it lives, and collect anything else; the + keyword and positional convenience constructors still copy. +- `phase_function_value` of `RayleighWaterPhase{Float32}`, + `PetzoldPhase{Float32}` and a `Float32` `TabulatedGreekPhase` returns + `Float64` for a `Float64` argument (formerly `Float32`: the argument was + converted to the model's type); a `Float32` argument still gives + `Float32`. +- Scalar functions of `Float32` models return `Float32` for `Float32` + arguments (formerly `Float64`): `absorption`, `scattering` and + `backscattering` of `PureWater` and `Phytoplankton`, + `phase_function_value` of `FournierForandPhase`, `emission` and + `raman_peak_wavelength` of `WaterRaman`, `redistribution` of + `GaussianEmission` and `WavenumberShiftEmission`; so do + `absorbed_photons` and `absorbed_par` of a `Float32` layer, and the + vector methods. The result + type is the model's element type promoted with the argument's, so a + `Float64` or dual-number argument still gives a `Float64` or dual result. + These functions compute in `Float64` and round once: the `Float32` value + is the correctly rounded `Float64` value for the same parameters. + `Float64` results are unchanged. ### Added +- Keyword `photoprotective_transfer` (default 0) of + `chlorophyll_fluorescence`. +- A "Migrating from 0.1" section on the Consumer API page. + +- **Derivatives with respect to model parameters by ForwardDiff.** The + element type of the elastic path is any `Real` (formerly + `AbstractFloat`): `AbstractOceanConstituent{FT}`, + `AbstractOceanPhaseFunction{FT}`, `CDOM`, `Phytoplankton`, + `GordonMorel1983`, `NonAlgalParticles`, `PureWater`, + `FournierForandPhase`, `HenyeyGreensteinPhase`, `RayleighWaterPhase`, + `TabulatedGreekPhase`, `TabulatedAbsorber`, `TabulatedScatterer`, + `FixedRefractiveIndex`, `QuanFry1995`, `IOP`, and + `layer_optics(FT, …)` / `column_optics(FT, …)`. A layer built at a dual + element type gives optical depths, single-scattering albedo, Greek + coefficients, backscatter fractions and refractive index that carry + the derivative with respect to chlorophyll, CDOM `a_ref` and `slope`, + the non-algal particle parameters, water temperature, salinity and + depolarization, layer thickness and the Fournier-Forand backscatter + fraction (the inversion `B ↦ (n, μ_j)` is linearized at its root and + the Legendre quadrature runs in dual numbers). ForwardDiff is not a + dependency. Floating-point results are unchanged bit for bit. Not + covered: inelastic processes and their emission spectra, + `PetzoldPhase` (an `ArgumentError` for a non-floating-point element + type) and `TabulatedMuellerPhase`. See "Forward-mode automatic + differentiation" in the worked example and "Derivatives" in the + consumer interface; `test/test_ad.jl` checks every parameter against + central differences (rtol 1e-6) or closed forms. +- Constructors without an explicit element type (`CDOM(…)`, + `Phytoplankton(…)`, `NonAlgalParticles(…)`, `PureWater(…)`, + `GordonMorel1983(…)`, `FournierForandPhase(…)`, + `HenyeyGreensteinPhase(…)`, `RayleighWaterPhase(…)`) take + `promote_type(Float64, …)` of their real parameters: `Float64` for + plain numbers of any precision as before, the dual type for a dual + parameter. A `BigFloat` parameter now gives a `BigFloat` model + (formerly rounded to `Float64`). +- `IOP(a, b, bb)` accepts dual numbers; three equal-typed arrays of any + `Real` element type are accepted (formerly floating point only). +- Parameter exposure: `GordonMorel1983(b_ref = 0.30, chl_exponent = 0.62, + λ_ref = 550, spectral_exponent = 1)` as `Phytoplankton(scattering_model = …)`; + `NonAlgalParticles(spectral_exponent = 1)`; keyword `roundoff_rtol` of + `absorbed_power`, `absorbed_photons`, `absorbed_par` and + `inelastic_emission`; the pure-water depolarization 0.039, the PAR limits + (400, 700) nm and the O–H stretch band (3400, 85 cm⁻¹) are each defined + once. Defaults reproduce the former `Float64` results bit for bit. +- `HoldEdgeShares` and `UnassignedOutsideTable` (`outside` keyword of the + pigment partitions). +- Documentation page "Parameters" (`docs/src/reference/parameters.md`): every + physical parameter with default, unit, source and how to set it. + +- `AbstractConversionUnits`, `PhotonConversion`, `EnergyConversion` and + `conversion_units(process)`: whether the conversion coefficient of an + inelastic process counts photons or energy; the energy and photon kernels + dispatch on it. +- `raman_phase(::WaterRaman)` (the Rayleigh-type phase function and phase + matrix of Raman emission, `β₂ = (1−ρ)/(2(1+2ρ))`) and + `natural_depolarization(::WaterRaman)` (`ρ_n = 2ρ/(1+ρ)`). + +- `layer_optics(FT, layer, λ; …)` and `column_optics(FT, column, λ; …)`: + positional element type, with an inferred return type. +- `phase_id(g::GreekCoefficients)` and `phase_id(c::ScatteringComponent, iλ)`: + the content key of an expansion. +- `zero_padded(g)`: a scalar expansion with `α, γ, δ, ϵ, ζ` as zero + vectors of length `ℓ_max + 1`, for consumers that size by `length(α)`. +- `TabulatedAbsorber(...; lookup = :linear)` and + `TabulatedScatterer(...; lookup = :linear)`: opt-in linear interpolation + between tabulated wavelengths (never extrapolation). +- `absorbed_power`, `absorbed_photons`, `absorbed_par` and + `inelastic_emission` treat negative irradiance entries down to + `−√eps · maximum(abs, E₀)` as zero; more negative entries still throw. +- `bottom_albedo` throws an `ArgumentError` naming the bottom type for + bottoms other than `BlackBottom` and `LambertianBottom` (formerly a + `MethodError`). +- Device-adaptable results: `Adapt.adapt(to, x)` for `GreekCoefficients`, + `AbsorptionComponent`, `ScatteringComponent`, `InelasticComponent`, + `OceanLayerOptics`, `LambertianBottom` and `OceanColumnOptics` moves the + numeric arrays (for example `adapt(CuArray, column)`) and keeps the + element type; labels, parts, `phase_id` keys, the component and layer + lists and the inelastic process models stay on the host. Construction + and validation of these structs, `absorption_optical_depth`, + `scattering_optical_depth`, `optical_depth`, `single_scattering_albedo`, + `backscatter_fraction(layer)` and `bottom_albedo` use reductions and + broadcasts only, so they run on device arrays with scalar indexing + disallowed. Adapt.jl is a new dependency. +- `linterp(tbl, λ::AbstractVector)`: one range check and one broadcast. + `Adapt.adapt(to, tbl)` moves a `SpectralTable` to a device, where the + vector method interpolates device wavelengths; an out-of-range + wavelength throws the `DomainError` on the host. +- Array methods of `absorption`, `scattering`, `backscattering` and + `refractive_index` are a `map` over the wavelengths (same host results); + for `CDOM`, `NonAlgalParticles`, `QuanFry1995` and `FixedRefractiveIndex` + they accept and return device arrays. `QuanFry1995{Float32}` evaluates + its polynomial in `Float64` per element and rounds once, so its array + method needs a device with `Float64` support. +- `adapt` builds the adapted result structs without validating them again + and keeps expansions that components and layers share shared (one device + array per distinct host expansion), so `GreekCoefficients` and + `LambertianBottom` can be captured by a device broadcast (the components, + layers and columns carry labels and lists and remain host containers). +- `hash(::GreekCoefficients)`, consistent with `==`, so expansions work as + `Dict` keys and in `unique`. +- Tests: Aqua, ExplicitImports and JET (`test_package`, and `test_opt` / + `test_call` on the scalar functions and expansions), `@inferred` checks + including `layer_optics`, `column_optics`, `excitation_optical_depth` + and `inelastic_emission`; `Float32` tests of the result types and of + `Float32` against `Float64` with the stated difference; device tests + (`test/test_device.jl`) in the default suite on JLArrays 0.5 with scalar + indexing disallowed, and the same file on CUDA from `test/gpu`. - Absorption parts: `absorption_parts`, `absorption_by_part`, `absorption_part`; `Phytoplankton(...; pigments)` with the pigment partitions `ProspectPigments` (chlorophyll and carotenoids with the @@ -57,6 +424,64 @@ fluorescence and absorbed-PAR requirements of the coupled solver. (both from SCOPE's Optipar2017_ProspectD) and `bidigare_1990_pigments.csv` (Ocean Optics Web Book, CC BY). +### Fixed + +- Range checks accept a dual number at their bounds. ForwardDiff 1.x + orders duals by value and then partials, so `Dual(35, 1) ≤ 35` is false and + `∂n/∂S` of `QuanFry1995` at 35 PSU, `∂n/∂T` at 30 °C, `∂/∂λ` at a table end + and `∂b/∂ω_nap` at `ω_nap = 1` threw; the checks now compare values. +- `∂b_w/∂S` of `ZhangHu2009` scattering at `S = 0` is the one-sided + derivative (1.764·10⁻⁵ m⁻¹ PSU⁻¹ at 500 nm, 20 °C) instead of `NaN`. +- Second and higher derivatives with respect to the Fournier-Forand + backscatter fraction: `d²μ_j/dB²` was 0 and `d²β₂/dB²` `NaN` without a + warning; the inversion is refined by chord steps in the dual type + (derivatives exact to fourth order) and `δ^ν` is evaluated as + `exp(ν log δ)` for duals, whose second derivative overflowed at the forward + quadrature floor. Floating-point results are unchanged. +- `Phytoplankton(; scattering_model = GordonMorel1983(b_ref = dual))` without + an element type builds a dual constituent (formerly a `Float64` one that + failed when evaluated). + +- `excitation_optical_depth` and `inelastic_emission` have inferred return + types; `pigment_fractions(::Bidigare1990Pigments, λ)` is inferred on + Julia 1.10; `greek_expansion(::PetzoldPhase{Float32}, ℓ)` runs without + runtime dispatch (the phase function returned `Float64` or `Float32` + depending on the angle). +- Static-analysis findings: an unbound type parameter in + `_pigment_shares`, a missing docstring for `quantum_yield`, implicit + imports from DocStringExtensions, and four JET reports on Julia 1.12. +- Documentation no longer claims that model parameters can be + differentiated with ForwardDiff or that optical depths are linear in + chlorophyll. +- Docstrings that disagreed with the code (no function changed): + `absorption` does not accept `Unitful` quantities (wavelengths are + numbers in nm, or vectors of them); `raman_peak_wavelength` for 440 nm + excitation and the default shift is 517.4 nm, not 491 nm; the bundled + `Kou1993` table has steps of 0.3 to 18 nm, not about 1 nm; `ZhangHu2009` + checks no range of validity; `IOP` is a standalone value type that `layer_optics` + does not use; `is_isotropic(::WaterRaman)` refers to the process's own + depolarization ratio. +- Every exported name has a docstring with a signature line (or type + definition) and an imperative first sentence, at most 92 characters per + line; `absorption`, `raman_peak_wavelength` and `fwhm_to_sigma` carry + doctests. + +### Packaging + +- `CI.yml` runs the tests only; `Documentation.yml` is the one docs build: + on pull requests it builds without deploying, on pushes to `main` and tags + it builds and deploys. JET 0.12 stays excluded from `[compat]`: it does not + load on Julia 1.12 with the current LoweredCodeUtils + (`record_termination_points!` undefined); 0.9 (Julia 1.10) and 0.13 (1.12) + are used. + +- Runtime dependencies are Adapt, DocStringExtensions and + FastGaussQuadrature; Interpolations is dropped. JLArrays 0.5 is a test + dependency. CUDA is a dependency of `test/gpu` only. +- The documentation build is strict: a missing docstring of an exported + name, an unresolved cross-reference or a failing doctest is an error + (`warnonly` removed from `docs/make.jl`). `Documentation.yml` runs it. + ## [0.1.0] — 2026-10-16 First registered release. The entries below cover the development since diff --git a/Project.toml b/Project.toml index 8d5349e..8b724ac 100644 --- a/Project.toml +++ b/Project.toml @@ -1,26 +1,34 @@ name = "OceanOptics" uuid = "81d78f2c-09e7-43ab-88c2-b5d9ea2c354a" +version = "0.2.0" authors = ["RemoteSensingTools"] -version = "0.2.0-DEV" [deps] +Adapt = "79e6a3ab-5dfb-504d-930d-738a2a938a0e" DocStringExtensions = "ffbed154-4ef7-542d-bbb7-c09d3a79fcae" FastGaussQuadrature = "442a2c76-b920-505d-bb47-c5924d526838" -Interpolations = "a98d9a8b-a2ab-59e6-89dd-64a1c18fca59" [compat] +Adapt = "4" +Aqua = "0.8" DocStringExtensions = "0.9" +ExplicitImports = "1" FastGaussQuadrature = "0.4, 0.5, 1" ForwardDiff = "0.10, 1" -Interpolations = "0.14.2, 0.15, 0.16" +JET = "0.9, 0.10, 0.11, 0.13" +JLArrays = "0.5" QuadGK = "2" Test = "1" julia = "1.10" [extras] +Aqua = "4c88cf16-eb10-579e-8560-4a9242c79595" +ExplicitImports = "7d51a73a-1435-4ff3-83d9-f097790105c7" ForwardDiff = "f6369f11-7733-5829-9624-2563aa707210" +JET = "c3a54625-cd67-489e-a8e7-0a5a0ff4e31b" +JLArrays = "27aeb0d3-9eb9-45fb-866b-73c2ecf80fcb" QuadGK = "1fd47b50-473d-5c70-9696-f719f8f3bcdc" Test = "8dfed614-e22c-5e08-85e1-65c5234f0b40" [targets] -test = ["ForwardDiff", "QuadGK", "Test"] +test = ["Aqua", "ExplicitImports", "ForwardDiff", "JET", "JLArrays", "QuadGK", "Test"] diff --git a/README.md b/README.md index 1f3a5a9..8c516b1 100644 --- a/README.md +++ b/README.md @@ -51,6 +51,16 @@ be combined with separately modelled water or CDOM absorption. pkg> add OceanOptics ``` +Julia 1.10 or later. + +## New in 0.2.0 + +- Water Raman is an energy conversion by default (no λ′/λ factor); its phase function follows Mobley et al. (1993) Eq. 9 with ρ = 0.17. +- Every physical parameter is a field or keyword with a documented default ([parameter reference](https://RemoteSensingTools.github.io/OceanOptics.jl/stable/reference/parameters/)). +- Derivatives with respect to model parameters (Chl, CDOM slope, temperature, salinity, Fournier-Forand B, …) by ForwardDiff, through `layer_optics` and `column_optics`. +- Pigment partitions hold their edge shares below 400 nm; photoprotective carotenoids no longer excite chlorophyll fluorescence by default. +- Several breaking changes (`WaterRaman`, `Phytoplankton.scattering_model`, `Gordon1992` removed): see the CHANGELOG and the "Migrating from 0.1" section of the Consumer API page. + ## Quick start ```julia @@ -86,10 +96,31 @@ E₀ = ones(n_wavelengths(o)) # stand-in for the solver's layer-mean scalar ir absorbed_par(o, E₀) # µmol photons m⁻² s⁻¹ per absorption component ``` +## Precision and devices + +The results have the element type of the layer or column (`Float64` above); +pass another as the first argument. They are host arrays, and `Adapt.adapt` +moves their numeric arrays to a device without changing the element type: + +```julia +col32 = column_optics(Float32, column, collect(400.0:5.0:700.0); + refractive_index = FixedRefractiveIndex(1.34), + bottom = BlackBottom()) +# using Adapt, CUDA; adapt(CuArray, col32) +c = col32[1].scatterers[1] +phase_id(c, 1) == phase_id(greek_expansion(c, 1)) # true +``` + +`phase_id` is a content key of an expansion (a 64-bit hash of its element +type and coefficients): equal keys mean equal coefficients in any layer, +column or session, so a solver can build phase operators once per key. + ## Documentation The [documentation](https://RemoteSensingTools.github.io/OceanOptics.jl/) covers the consumer contract (units, conventions, validation), the +[parameter reference](https://RemoteSensingTools.github.io/OceanOptics.jl/stable/reference/parameters/) +(every physical parameter with its default, unit and source), the vSmartMOM mapping with a tested adapter sketch, a comparison with the HydroLight IOP database of Loisel et al. (2023), and interactive figures. @@ -118,11 +149,11 @@ DOI, URL, retrieval date, unit changes): | `pope_fry_1997.csv` | omlc.org | Pure-water absorption, 380–727.5 nm | | `smith_baker_1981.csv` | omlc.org | Clearest natural waters, 200–800 nm | | `rottgers_2014_temperature.csv` | Röttgers et al. 2014, figshare (CC BY 4.0) | Temperature coefficient Ψ_T, 550–2500 nm | -| `bricaud_1998_A.csv`, `bricaud_1998_E.csv` | Ocean Optics Web Book (CC-BY) | Phytoplankton `A(λ)`, `E(λ)`, 300–1000 nm | +| `bricaud_1998_A.csv`, `bricaud_1998_E.csv` | Ocean Optics Web Book (CC-BY) | Particulate absorption `a_p = A(λ)·Chl^E(λ)` (phytoplankton plus detritus; HydroLight Case-1 tables), 300–1000 nm | | `petzold_sdh.csv` | Ocean Optics Web Book (CC-BY) | Petzold San Diego Harbor VSF, 0.1°–180° | | `bidigare_1990_pigments.csv` | Ocean Optics Web Book (CC-BY) | In vivo specific absorption of algal pigment groups, 400–750 nm (Bidigare et al. 1990) | -| `fluspect_chloroplast_emission.csv` | SCOPE `Optipar2017_ProspectD` (GPL-3.0; also in CliMA Land, Apache-2.0) | Chloroplast-level fluorescence emission (combined, PSI, PSII), 640–851 nm | -| `prospect_d_pigment_absorption.csv` | as above | PROSPECT-D in vivo chlorophyll and carotenoid absorption, 400–800 nm | +| `fluspect_chloroplast_emission.csv` | SCOPE parameter file `Optipar2017_ProspectD` (used there by Fluspect, Vilfan et al. 2016, 2018; original measurements not traced; data only, no SCOPE code) | Chloroplast-level fluorescence emission (combined, PSI, PSII), 640–851 nm | +| `prospect_d_pigment_absorption.csv` | same SCOPE parameter file, attributed there to PROSPECT-D (Féret et al. 2017); not compared with the authors' own distribution; data only | PROSPECT-D in vivo chlorophyll and carotenoid absorption, 400–800 nm | | `reference/loisel2023_hydrolight_iops.csv` | Loisel et al. 2023 (CC0) | HydroLight input IOPs: pure seawater and three scenarios | Cite the original papers in derived work. diff --git a/data/bricaud_1998_A.csv b/data/bricaud_1998_A.csv index 563d5df..a947565 100644 --- a/data/bricaud_1998_A.csv +++ b/data/bricaud_1998_A.csv @@ -1,23 +1,25 @@ -# Dataset: Phytoplankton specific-absorption pre-factor A(λ) in -# a_φ*(λ) = A(λ) · Chl^(-E(λ)) +# Dataset: Particulate absorption coefficient A(λ) in +# a_p(λ) = A(λ) · Chl^E(λ) [1/m], Chl in mg/m³ +# (all particles of Case-1 water: phytoplankton plus detritus; +# A(440) = 0.0520, E(440) = 0.6350) # Source: Bricaud, Morel, Babin, Allali & Claustre (1998), # "Variations of light absorption by suspended particles with # chlorophyll a concentration in oceanic (case 1) waters: # Analysis and implications for bio-optical models," # JGR 103, 31033-31044. doi:10.1029/98JC02712 +# as tabulated for HydroLight's Case-1 model (AEmidUVabs.txt), +# whose header reads "particle absorption (phytoplankton plus +# detritus) ... ap(wave) = A(wave)*[chl]^E(wave)". # UV extension: Morrison & Nelson (2004), Limnol. Oceanogr. 49, 215-224; # Vasilkov et al. (2005), Appl. Opt. 44, 2863-2869. # Retrieved: https://www.oceanopticsbook.info/packages/iws_l2h/conversion/files/AEmidUVabs.txt # (Ocean Optics Web Book; HydroLight-EcoLight v5 companion # file, C. D. Mobley, accessed 2026-04-21) # License: Creative Commons Attribution (Ocean Optics Web Book site-wide). -# Note: This is the 1998 Bricaud update (+ UV extensions), not the -# original 1995 JGR 100, 13321 table. For most applications -# the 1998 values are the community-standard replacement. # Range: 300–1000 nm, 2 nm resolution. -# Units: lambda_nm [nm], A_m2_per_mg [m²/mg]. -# Columns: lambda_nm, A_m2_per_mg -lambda_nm,A_m2_per_mg +# Units: lambda_nm [nm], A_per_m [1/m, for Chl in mg/m³]. +# Columns: lambda_nm, A_per_m +lambda_nm,A_per_m 300.0,0.0736 302.0,0.0747 304.0,0.0755 diff --git a/data/bricaud_1998_E.csv b/data/bricaud_1998_E.csv index 06601f3..6f955db 100644 --- a/data/bricaud_1998_E.csv +++ b/data/bricaud_1998_E.csv @@ -1,9 +1,20 @@ -# Dataset: Phytoplankton specific-absorption exponent E(λ) in -# a_φ*(λ) = A(λ) · Chl^(-E(λ)) -# Source: Bricaud, Morel, Babin, Allali & Claustre (1998), JGR 103, 31033. -# UV extension: Morrison & Nelson (2004); Vasilkov et al. (2005). +# Dataset: Particulate absorption exponent E(λ) in +# a_p(λ) = A(λ) · Chl^E(λ) [1/m], Chl in mg/m³ +# (all particles of Case-1 water: phytoplankton plus detritus; +# A(440) = 0.0520, E(440) = 0.6350) +# Source: Bricaud, Morel, Babin, Allali & Claustre (1998), +# "Variations of light absorption by suspended particles with +# chlorophyll a concentration in oceanic (case 1) waters: +# Analysis and implications for bio-optical models," +# JGR 103, 31033-31044. doi:10.1029/98JC02712 +# as tabulated for HydroLight's Case-1 model (AEmidUVabs.txt), +# whose header reads "particle absorption (phytoplankton plus +# detritus) ... ap(wave) = A(wave)*[chl]^E(wave)". +# UV extension: Morrison & Nelson (2004), Limnol. Oceanogr. 49, 215-224; +# Vasilkov et al. (2005), Appl. Opt. 44, 2863-2869. # Retrieved: https://www.oceanopticsbook.info/packages/iws_l2h/conversion/files/AEmidUVabs.txt -# (Ocean Optics Web Book, accessed 2026-04-21) +# (Ocean Optics Web Book; HydroLight-EcoLight v5 companion +# file, C. D. Mobley, accessed 2026-04-21) # License: Creative Commons Attribution (Ocean Optics Web Book site-wide). # Range: 300–1000 nm, 2 nm resolution. # Units: lambda_nm [nm], E [dimensionless]. diff --git a/data/fluspect_chloroplast_emission.csv b/data/fluspect_chloroplast_emission.csv index f90a759..032d756 100644 --- a/data/fluspect_chloroplast_emission.csv +++ b/data/fluspect_chloroplast_emission.csv @@ -11,8 +11,10 @@ # doi:10.1016/j.rse.2018.04.012 # Retrieved: https://raw.githubusercontent.com/Christiaanvandertol/SCOPE/master/input/fluspect_parameters/Optipar2017_ProspectD.mat # (2026-10-17), SHA-256 03bd2dfc37e11fa085f00013ce99d6c8ed5a0b427e4c65211f4d32e36f8cc596; identical values in the copy redistributed with CliMA Land -# License: SCOPE is distributed under the GNU GPL v3; CliMA Land redistributes the same file under -# Apache-2.0. See README (Data) before reusing. +# Provenance: Transcribed from the SCOPE parameter file named under "Retrieved". SCOPE uses these +# spectra in Fluspect (papers above); the measurements they derive from have not been +# traced for this package. Bundled as data with attribution; no SCOPE code (GNU GPL v3) +# is part of this package. # Convention: Photon-number densities per nm of emission wavelength: SCOPE (src/RTMs/RTMf.m) converts # excitation irradiance to photons, applies fqe * phi * kChl, and converts the emitted # photons back to energy. Each column sums to 1 on the 1 nm grid (unit area). diff --git a/data/prospect_d_pigment_absorption.csv b/data/prospect_d_pigment_absorption.csv index e5c437c..249269d 100644 --- a/data/prospect_d_pigment_absorption.csv +++ b/data/prospect_d_pigment_absorption.csv @@ -6,7 +6,10 @@ # Optipar2017_ProspectD.mat (fields wl, Kab, Kca) distributed with SCOPE # Retrieved: https://raw.githubusercontent.com/Christiaanvandertol/SCOPE/master/input/fluspect_parameters/Optipar2017_ProspectD.mat # (2026-10-17), SHA-256 03bd2dfc37e11fa085f00013ce99d6c8ed5a0b427e4c65211f4d32e36f8cc596 -# License: as for fluspect_chloroplast_emission.csv (SCOPE: GNU GPL v3; CliMA Land: Apache-2.0) +# Provenance: Transcribed from the SCOPE parameter file named under "Retrieved", which attributes +# them to PROSPECT-D (Feret et al. 2017); not compared with the PROSPECT-D authors' own +# distribution. Bundled as data with attribution; no SCOPE code (GNU GPL v3) is part of +# this package. # Range: 400-800 nm, 1 nm (Kab is zero above 780 nm, Kca above 557 nm) # Units: lambda_nm [nm]; Kab, Kca [cm^2/ug] (absorption per areal pigment content) # Columns: lambda_nm, Kab, Kca diff --git a/docs/make.jl b/docs/make.jl index 16a9087..9f3a8d8 100644 --- a/docs/make.jl +++ b/docs/make.jl @@ -20,6 +20,9 @@ makedocs( size_threshold = 400 * 2^10, size_threshold_warn = 320 * 2^10, example_size_threshold = 96 * 2^10, + # The search index includes the embedded chart tables (522 KiB with the + # parameters page; Documenter warns from 500 KiB and fails at 1 MiB). + search_size_threshold_warn = 640 * 2^10, ), pages = [ "Home" => "index.md", @@ -33,10 +36,11 @@ makedocs( "Materials" => "reference/materials.md", "Phase functions" => "reference/phases.md", "Inelastic" => "reference/inelastic.md", + "Parameters" => "reference/parameters.md", "Data loading" => "reference/io.md", ], ], - warnonly = [:missing_docs, :cross_references], + doctest = true, checkdocs = :exports, ) diff --git a/docs/src/consumer_api.md b/docs/src/consumer_api.md index 17af6fe..c6d9348 100644 --- a/docs/src/consumer_api.md +++ b/docs/src/consumer_api.md @@ -43,8 +43,8 @@ the `source` of tabulated data), its scattering optical depth `τ` per wavelength, its distinct expansions `greek` ([`GreekCoefficients`](@ref); one unless the phase function depends on wavelength, in which case `phase_index[iλ]` selects the entry at each wavelength), the backscatter -fraction of its phase function per entry, a `phase_id`, and a -`polarization` label: +fraction of its phase function per entry, a `phase_id` key per entry, +and a `polarization` label: | `polarization` | Meaning | |---|---| @@ -55,16 +55,98 @@ fraction of its phase function per entry, a `phase_id`, and a Keeping components separate lets a solver build each component's phase operators once per band and truncate them individually (as it does for aerosol types), and keeps every phase matrix's provenance visible. -Components with equal `phase_id` — in any layer of a column — have -identical expansions (`column_optics` shares the objects), so their phase -operators can be reused. Layers are ordered from the surface down; +Layers are ordered from the surface down; [`interface_depths`](@ref)`(col)` gives the layer boundaries. -**Derivatives.** Every optical depth is linear in its constituent's -concentration (`τ = b_c Δz`, `τ = a_c Δz`) and the layer mixture is -linear in the component optical depths, so derivatives with respect to -component amounts follow directly from the component split; the -assembly itself is evaluated in floating point (`FT`). +**Expansion keys.** `phase_id[j]` is the content key of `greek[j]` +([`phase_id`](@ref)`(g)`: a 64-bit FNV-1a hash of the element type and of +the lengths and values of the six coefficient vectors), and +[`phase_id`](@ref)`(c, iλ)` is the key in use at the `iλ`-th wavelength. +Equal keys mean equal coefficients, `ℓ_max` and element type — in any +component, layer, column, session or Julia version — and expansions that +differ in any of these have different keys (up to hash collisions, +probability 2⁻⁶⁴ per pair). A wavelength-dependent component has one key +per distinct expansion. A solver can therefore build its phase operators +once per `(phase_id, Fourier mode)` and store the keys in fixtures. Within +one `column_optics` call, equal phase functions also share the same +`GreekCoefficients` objects. + +**Scalar expansions.** With `polarized = false` the expansions carry `β` +only and `α, γ, δ, ϵ, ζ` are empty. A consumer that sizes its arrays by +`length(g.α)` takes [`zero_padded`](@ref)`(g)`: all six vectors of length +`ℓ_max + 1`, the five polarization vectors zero (a polarized expansion is +returned unchanged). Its key differs from that of the scalar expansion. + +**Derivatives.** The element type `FT` of constituents, layers and +results is any `Real`, so a layer can be built from ForwardDiff dual +numbers the same way a `Float32` layer is built, and `layer_optics` / +`column_optics` return optical depths, Greek coefficients, backscatter +fractions and refractive indices that carry the derivatives: + +```julia +using ForwardDiff +function τ_abs(Chl) # layer absorption optical depth + FT = typeof(Chl) + layer = OceanLayer(0.0, 5.0, AbstractOceanConstituent{FT}[ + PureWater{FT}(), CDOM{FT}(), Phytoplankton{FT}(Chl = Chl)]) + return absorption_optical_depth(layer_optics(layer, [443.0, 551.0]; ℓ_max = 16)) +end +ForwardDiff.derivative(τ_abs, 0.5) # ∂τ_a/∂Chl per wavelength +``` + +All constituents of one layer share the element type (`PureWater{FT}()` +above carries zero derivatives). A constructor without an explicit type, +`Phytoplankton(Chl = x)`, takes `promote_type(Float64, …)` of its real +parameters, so it follows a dual `x`; `Phytoplankton{Float64}(Chl = x)` +with a dual `x` is a `MethodError`. + +| differentiable with respect to | through | +|---|---| +| `Chl` (and the `GordonMorel1983` parameters) | `absorption`, `absorption_by_part`, `scattering`, `backscattering`, `layer_optics`, `column_optics` | +| CDOM `a_ref`, `slope`, `λ_ref` | the same | +| NAP `a_ref`, `slope`, `b_ref`, `spectral_exponent`, `c_ref`, `ω_nap`, `B` | the same | +| water `temperature`, `salinity`, `depolarization` | the same; `refractive_index(QuanFry1995(…), λ)` for `n` | +| Fournier-Forand `backscatter_fraction` (or `n`, `μ_j`), Henyey-Greenstein `g`, Rayleigh `depolarization` | `phase_function_value`, `phase_function_moments`, `greek_expansion`, `backscatter_fraction`, and the expansions stored by `layer_optics` | +| layer depths | `layer_optics`, `column_optics` | +| tabulated coefficients of `TabulatedAbsorber` / `TabulatedScatterer`, entries of `IOP` | their accessors and `layer_optics` | +| wavelength | scalar functions; `layer_optics(FT, layer, λ)` with a floating-point layer and a dual `FT` | +| scattering cosine `μ` | `phase_function_value` of Fournier-Forand and Henyey-Greenstein | +| irradiance | [`absorbed_power`](@ref), [`absorbed_photons`](@ref), [`absorbed_par`](@ref) | + +The Fournier-Forand backscatter fraction is carried through the +expansion: the constructor refines the root of the inversion `B ↦ (n, μ_j)` +in the number type of `B` by four chord steps with `B′(μ_j)` (each step +makes one more derivative order exact, so nested duals and Hessians up to +fourth order are exact), and the Legendre quadrature is evaluated in +dual numbers. Range checks of the constructors compare values only, so a +dual at a bound (salinity 35 PSU in `QuanFry1995`, `ω_nap = 1`) is +accepted. Element types must be floating-point types or duals of them; +integer and rational types are rejected with an `ArgumentError`. Its refinement criterion looks at the values of the +moments, not at their derivatives; the derivatives of `β_ℓ`, `ℓ ≤ 16`, +agree with central differences to better than `1e-6` relative +(`test/test_ad.jl`). + +Not differentiable: inelastic processes ([`WaterRaman`](@ref), the +fluorescence types and their emission spectra) are floating point only, +so a layer of dual element type has no inelastic processes +(`WaterRaman{FT}` with a dual `FT` is a `TypeError`, +`chlorophyll_fluorescence` of a dual `Phytoplankton` a `MethodError`); +their kernels are differentiable with respect to wavelength only. +`PetzoldPhase{FT}()` with a dual `FT` throws an `ArgumentError` (a +measured table without parameters), and `TabulatedMuellerPhase` accepts +floating-point tables only. Derivatives across a table node (wavelength) +are those of the linear segment on one side. + +Chlorophyll sensitivities are not a scale factor of a stored optical +depth: the particulate absorption and scattering are non-linear in [Chl] +(`a_p = A(λ) [Chl]^{E(λ)}`, `b_p ∝ [Chl]^{0.62}`). For components that +are linear in their parameter (CDOM in `a_ref`) the derivative equals +the stored `τ` divided by the parameter. + +**Element type.** `column_optics(FT, column, λ; …)` and +`layer_optics(FT, layer, λ; …)` return containers of element type `FT` +with an inferred return type; without `FT` the element type of the +column or layer is used. **Deep water.** Layers have finite thickness. An optically deep ocean is represented by a bottom layer thick enough for the bottom not to matter @@ -154,8 +236,14 @@ bio-optical models: entry, e.g. one band-representative phase matrix for a fine spectral grid. Each distinct entry is expanded once. -Values are defined only at their tabulated wavelengths; any other -wavelength throws. **Total absorption:** published bulk absorption that +Values are defined at their tabulated wavelengths. A query matches a +tabulated wavelength when the two agree to a relative `1e-6`, which +covers `Float32` wavelengths and grids computed from wavenumbers as +`1e7/ν`; any other wavelength throws. `TabulatedAbsorber` and +`TabulatedScatterer` accept `lookup = :linear` to interpolate linearly +between neighbouring tabulated wavelengths instead (never beyond the +table) — an explicit choice for spectral grids that do not coincide with +the table. **Total absorption:** published bulk absorption that already contains water and CDOM (e.g. `a_blk = a_p + a_y + a_w` in Chowdhary et al. 2020, Eq. 11b) is passed with `total = true`, and `layer_optics` then rejects any other absorbing constituent. @@ -193,8 +281,15 @@ paper's stated asymmetry parameters (0.95, 0.97) and backscatter ratios value or one per wavelength) or [`TabulatedLambertianBottom`](@ref)`(λ, albedo; source)` — an albedo spectrum on its own grid (e.g. measured sand or seagrass reflectance), - interpolated onto `λ`. The column always carries a `BlackBottom` or a - `LambertianBottom` with [`bottom_albedo`](@ref)`(col)` per wavelength. + interpolated onto `λ`. For these the column carries a `BlackBottom` or + a `LambertianBottom` with [`bottom_albedo`](@ref)`(col)` per wavelength. + Any other `AbstractOceanBottom` subtype passes through unchanged for a + solver that knows it, and `bottom_albedo` throws an `ArgumentError` for + it. + +`FixedRefractiveIndex(n)` requires `n ≥ 1` (`n = 1`: index-matched +interface). The column stores one real index per wavelength; reducing it +to one value per band is the solver's choice. The solver applies the floor at [`bottom_depth`](@ref)`(col)`, below the last layer: a Lambertian floor reflects intensity isotropically and @@ -218,8 +313,10 @@ the PROSPECT-D leaf spectra, by analogy with land; or [`Bidigare1990Pigments`](@ref): chlorophylls a, b, c, photosynthetic and photoprotective carotenoids and phycoerythrins). The total stays that of the phytoplankton model; each group becomes an absorption component, and -absorption that the spectra cannot attribute (e.g. in the UV) goes to -`:unassigned`. +absorption that the spectra cannot attribute (where all group spectra +vanish) goes to `:unassigned`. Outside the tabulated pigment spectra (below +400 nm) the shares of the nearest tabulated wavelength apply by default; +`outside = UnassignedOutsideTable()` leaves that absorption unassigned. A fluorescence process is excited through [`ExcitationPathway`](@ref)s, each an absorber (or absorption part) with an energy-transfer efficiency @@ -277,31 +374,165 @@ Each inelastic process is carried by its layer's [`InelasticComponent`](@ref); its kernels are evaluated by the solver against its own internal radiation field: -* [`excitation_absorption`](@ref)`(p, λ′)` — photon conversion rate +* [`conversion_units`](@ref)`(p)` — [`PhotonConversion`](@ref) (fluorescence) or + [`EnergyConversion`](@ref) (the default [`WaterRaman`](@ref)): what the + conversion coefficient counts. +* [`excitation_absorption`](@ref)`(p, λ′)` — conversion coefficient `κ` `[1/m]`; includes the quantum yield for fluorescence, is the Raman - scattering coefficient for [`WaterRaman`](@ref). Do not apply the yield - again. -* [`emission`](@ref)`(p, λ′, λ)` — photon redistribution `[1/nm]`, - `∫ f dλ = 1`. -* [`radiance_source_kernel`](@ref)`(p, λ′, λ)` — `a^I f^I λ′/λ`, the - kernel of the energy (radiance) source - `J(λ) = (1/4π) ∫ b^I (λ′/λ) E₀(λ′) dλ′` for isotropic processes, with - `E₀` the spectral scalar irradiance (total intensity over solid angle, - direct and diffuse — not the downwelling plane irradiance). -* [`is_isotropic`](@ref)`(p)` — `WaterRaman` is not: it needs the angular - excitation field. + scattering coefficient `b_R` for [`WaterRaman`](@ref). Do not apply the + yield again. +* [`emission`](@ref)`(p, λ′, λ)` — redistribution `f` `[1/nm]` of the + converted quantity, `∫ f dλ = 1`. +* [`radiance_source_kernel`](@ref)`(p, λ′, λ)` — the energy kernel `K_E` + (`κ f λ′/λ` for a photon conversion, `κ f` for an energy conversion) of + the radiance source `J(λ) = (1/4π) ∫ K_E E₀(λ′) dλ′` for isotropic + processes, with `E₀` the spectral scalar irradiance (total intensity over + solid angle, direct and diffuse — not the downwelling plane irradiance). + [`inelastic_coefficient`](@ref) is the photon kernel `K_E λ/λ′`. +* [`is_isotropic`](@ref)`(p)` — `WaterRaman` is not: its source is + `(1/4π) ∫ K_E [E₀ + β₂ P₂(μ) E₂] dλ′` in the scalar `m = 0` case, with + the phase function and phase matrix from [`raman_phase`](@ref)`(p)`. The bundled water absorption does not add a separate Raman loss; whether `b_R(λ′)` is added to the attenuation at the excitation wavelength is the solver's convention and must match the reference it is compared with. +## Precision and devices + +**Build models in the precision you like, request the element type of the +result.** `layer_optics(FT, layer, λ; …)` and `column_optics(FT, column, +λ; …)` return arrays of element type `FT`; without `FT` the element type +is that of the layer or column. Data tables and physical constants are +`Float64` on the host. A function that reads a table or evaluates a +formula with such constants (pure-water absorption and scattering, +phytoplankton, Fournier–Forand, Quan–Fry, water Raman, the emission +shapes) computes in `Float64` and rounds its result once, so a `Float32` +result is the correctly rounded `Float64` one for the same parameters; +closed forms of the model's own parameters (CDOM, non-algal particles, +Henyey–Greenstein, Rayleigh) compute in the model's precision, within a +few `eps(Float32)` of the `Float64` model. + +A scalar function returns the floating-point type that the model and the +argument imply, `promote_type(FT, typeof(float(λ)))`: + +```julia +absorption(PureWater{Float32}(), 550f0) # Float32 +absorption(PureWater{Float32}(), 550.0) # Float64 +absorption(PureWater{Float64}(), ForwardDiff.Dual(550.0, 1.0)) # Dual +``` + +The safest configuration for a single-precision solver is therefore +`Float64` models and `column_optics(Float32, column, λ; …)`: every stored +number is then one rounding away from the double-precision value. + +**Results move to a device with `Adapt.adapt`.** The numeric arrays of +`GreekCoefficients`, `AbsorptionComponent`, `ScatteringComponent`, +`OceanLayerOptics`, `LambertianBottom` and `OceanColumnOptics` are type +parameters of these structs: + +```julia +using Adapt, CUDA +col = column_optics(Float32, column, λ; refractive_index = QuanFry1995(temperature = 20, salinity = 35), ℓ_max = 32) +dev = adapt(CuArray, col) # τ, λ, Greek coefficients, B, phase_index, n, albedo on the GPU +adapt(Array, dev) # back on the host; adapt(Array, col) copies nothing +``` + +Labels, absorption parts, `phase_id` keys, the lists of components and +layers and the inelastic components (process, excitation indices and +efficiencies) stay on the host: the structs are containers, and a kernel +receives their arrays (`c.τ`, `g.β`, …). `adapt` keeps the element type and +refuses an adaptor that would change it (`CuArray{Float32}` for a `Float64` +column): request the precision from `column_optics`. Expansions that +layers share are moved once and stay shared, and the adapted structs are +not validated again. On +device arrays, construction and validation, `absorption_optical_depth`, +`scattering_optical_depth`, `optical_depth`, `single_scattering_albedo`, +`backscatter_fraction(layer)` and `bottom_albedo` run as broadcasts and +reductions without scalar indexing and agree with the host to `4 eps`. +Use `adapt`, not `cu`: `cu` converts to `Float32` whatever was requested. + +Array methods of the constituents (`absorption(c, λ)`, `scattering(c, +λ)`, `backscattering(c, λ)`, `refractive_index(m, λ)` with a vector `λ`) +are one `map`. For the models without data tables (`CDOM`, +`NonAlgalParticles`, `QuanFry1995`, `FixedRefractiveIndex`) they accept a +device array and return one. `QuanFry1995{Float32}` evaluates its +polynomial in `Float64` for each element and rounds once, so this one +needs a device with `Float64` support (CUDA has it, Metal does not); on +other devices evaluate it on the host and `adapt` the result. + +A [`SpectralTable`](@ref) is adaptable as well: `adapt(CuArray, tbl)` +moves its two vectors, and `linterp(tbl, λ)` with a device vector `λ` +checks the range once on the host (a `DomainError` outside the table) and +interpolates in one broadcast on the device. The models keep their +`Float64` host tables. + +Not available on a device: the models themselves when they read data +tables (`PureWater`, `Phytoplankton`, pigment partitions, tabulated +constituents, emission tables), the Gauss–Legendre quadrature behind +`greek_expansion`, and the functions that take a wavelength index +(`greek_expansion(o, iλ)`, `phase_id(c, iλ)`) or work per component on the +host (`absorbed_power`, `absorbed_photons`, `absorbed_par`, +`excitation_optical_depth`, `inelastic_emission`, `absorber_index`). +Assemble on the host, apply those functions there, then `adapt`. + +## Migrating from 0.1 + +Each breaking change of 0.2.0 with the code that changes. Results that +changed without an API change are listed in the CHANGELOG under "Changed +results". + +```julia +# Raman: field/keyword renamed, convention is a type parameter +WaterRaman{Float64}(depolarization = 0.14) # 0.1 +WaterRaman{Float64}(linear_depolarization = 0.17) # 0.2 (default 0.17, energy conversion) +WaterRaman{Float64}(conversion = PhotonConversion()) # 0.2, the 0.1 photon convention + +# A user-defined inelastic process declares its convention +OceanOptics.conversion_units(::MyProcess) = PhotonConversion() # new in 0.2, required + +# Gordon1992 is removed; particulate scattering is a field of Phytoplankton +Phytoplankton{Float64, Gordon1992}(Chl = 0.5) # 0.1 +Phytoplankton{Float64}(Chl = 0.5, scattering_model = GordonMorel1983()) # 0.2 + +# Element type is positional, not a keyword +layer_optics(layer, λ; FT = Float32) # 0.1 +layer_optics(Float32, layer, λ) # 0.2 + +# Layers take `inelastic` +OceanLayer(0.0, 5.0, cs; fluorophores = [sif]) # 0.1 +OceanLayer(0.0, 5.0, cs; inelastic = [sif]) # 0.2 + +# Quantum yields have no default +chlorophyll_fluorescence(phyto) # 0.1 +chlorophyll_fluorescence(phyto; quantum_yield = 0.02) # 0.2 + +# Pigment partitions: below 400 nm the edge shares apply; the 0.1 rule is +ProspectPigments(carotenoid_ratio = 0.3, outside = UnassignedOutsideTable()) + +# Photoprotective carotenoids no longer take carotenoid_transfer +chlorophyll_fluorescence(p; quantum_yield = 0.02, carotenoid_transfer = 0.7, + photoprotective_transfer = 0.7) # the 0.1 result +``` + +Further changes a caller may meet: `layer_optics` throws when a layer lists +`PureWater` twice (merge them into one); `PureWater` and `RayleighWaterPhase` +reject a depolarization outside `[0, 1)`; `pigment_class` returns +`:photoprotective_carotenoid` for the photoprotective carotenoids of +`Bidigare1990Pigments`; integer and rational element types are rejected +(`CDOM{Float64}()` instead of `CDOM{Int}()`); positional inner constructors +of `Phytoplankton`, `NonAlgalParticles`, `ProspectPigments`, +`Bidigare1990Pigments` and `WaterRaman` have the new fields (prefer the +keyword constructors, which are unchanged). The CHANGELOG lists every +change with its reason. + ## The stable contract * **Solver output:** [`column_optics`](@ref), [`OceanColumnOptics`](@ref), [`layer_optics`](@ref), [`OceanLayerOptics`](@ref), [`AbsorptionComponent`](@ref), [`ScatteringComponent`](@ref), [`InelasticComponent`](@ref), [`GreekCoefficients`](@ref) and the - accessors above; [`BlackBottom`](@ref), [`LambertianBottom`](@ref), + accessors above; [`phase_id`](@ref), [`zero_padded`](@ref); + [`BlackBottom`](@ref), [`LambertianBottom`](@ref), [`TabulatedLambertianBottom`](@ref), [`bottom_albedo`](@ref). * **Absorbed light:** [`absorbed_power`](@ref), [`absorbed_photons`](@ref), [`absorbed_par`](@ref), [`inelastic_emission`](@ref), diff --git a/docs/src/example.md b/docs/src/example.md index 0cc360d..9f31124 100644 --- a/docs/src/example.md +++ b/docs/src/example.md @@ -2,8 +2,8 @@ A realistic Case-1 water workflow: build the biogeochemistry, compute inherent optical properties over the visible, inspect the inelastic -source kernels, and differentiate the elastic-path output w.r.t. the -chlorophyll concentration. +source kernels, and differentiate the absorption coefficient with +respect to wavelength. All code blocks below are executed at documentation-build time by Documenter's `@example` machinery, so the numerical outputs in the @@ -137,8 +137,9 @@ for λ in (660.0, 685.0, 700.0, 720.0, 739.0, 760.0, 800.0) end ``` -[`radiance_source_kernel`](@ref) adds the photon-energy ratio `λ'/λ` -needed for an energy (radiance) source: +Fluorescence converts photons ([`conversion_units`](@ref)), so the energy kernel +[`radiance_source_kernel`](@ref) is the photon kernel times the photon-energy ratio +`λ'/λ`: ```@example ex radiance_source_kernel(antenna, 440.0, 685.0) / inelastic_coefficient(antenna, 440.0, 685.0) @@ -174,12 +175,24 @@ ram = WaterRaman{Float64}() emission(ram, 440.0, 517.0)) ``` +The Raman coefficient is an energy conversion coefficient (Mobley et al. 1993): the +energy kernel is `b_R f_R` without a photon-energy ratio, and the angular distribution +is the Rayleigh-type phase function for the depolarization ratio of the band: + +```@example ex +(conversion_units(ram), + radiance_source_kernel(ram, 440.0, 517.0) / (excitation_absorption(ram, 440.0) * emission(ram, 440.0, 517.0)), + phase_function_moments(raman_phase(ram), 2)) +``` + ## Forward-mode automatic differentiation -Every forward function along the elastic path is AD-transparent via -`ForwardDiff.Dual` inputs on the *wavelength* and most model -parameters. Spectral sensitivity of the total absorption coefficient -at 440 nm: +The scalar functions `absorption`, `scattering` and `backscattering` +accept a `ForwardDiff.Dual` *wavelength*; `phase_function_value` of the +Fournier-Forand and Henyey-Greenstein phase functions accepts a dual `μ`; +and `absorbed_power`, `absorbed_photons` and `absorbed_par` accept a dual +irradiance. Spectral sensitivity of the total absorption coefficient at +440 nm: ```@example ex using ForwardDiff @@ -189,16 +202,61 @@ using ForwardDiff ) ``` -Struct parameters themselves are typed `FT<:AbstractFloat`, so -differentiating with respect to e.g. the CDOM slope goes through the -analytic formula rather than the struct: +Model parameters carry dual numbers too. The element type of a +constituent is any `Real`; a constructor without an explicit type takes +it from its parameters. The derivative of the CDOM absorption with +respect to its spectral slope, against the closed form +`∂a/∂S = −(λ − λ_ref) a`: + +```@example ex +(ForwardDiff.derivative(S -> absorption(CDOM(slope = S), 500.0), 0.014), + -(500.0 - 440.0) * absorption(CDOM(slope = 0.014), 500.0)) +``` + +`layer_optics` and `column_optics` accept layers of dual element type and +return optical depths that carry the derivative. Here the derivative of +the absorption optical depth of a 5 m layer with respect to chlorophyll; +every constituent of the layer is built at the element type of `Chl`: + +```@example ex +λ_ad = [443.0, 551.0, 670.0] +function absorption_depth(Chl) + FT = typeof(Chl) + layer = OceanLayer(0.0, 5.0, AbstractOceanConstituent{FT}[ + PureWater{FT}(), CDOM{FT}(), Phytoplankton{FT}(Chl = Chl)]) + return absorption_optical_depth(layer_optics(layer, λ_ad; ℓ_max = 16)) +end +∂τ_∂Chl = ForwardDiff.derivative(absorption_depth, 0.5) +``` + +A central difference gives the same numbers, and the logarithmic +derivative of the phytoplankton part is the Bricaud exponent `E(λ) < 1`: +the absorption is not linear in chlorophyll. + +```@example ex +h = 1e-6 +(∂τ_∂Chl, (absorption_depth(0.5 + h) .- absorption_depth(0.5 - h)) ./ 2h) +``` + +The backscatter fraction of a Fournier-Forand phase function is carried +through the Legendre expansion as well (the inversion to `(n, μ_j)` is +linearized at its root, and the quadrature runs in dual numbers): ```@example ex -a_ref, λ_ref = 0.03, 440.0 -g(S) = sum(a_ref * exp(-S * (λ - λ_ref)) for λ in (500.0, 600.0, 700.0)) -ForwardDiff.derivative(g, 0.014) +ForwardDiff.derivative( + B -> phase_function_moments(FournierForandPhase(backscatter_fraction = B), 4), 0.018) ``` -See `test/test_ad.jl` for a wider set of worked AD examples, including -CDOM, Pure Water, Morel / Zhang-Hu, Fournier-Forand and -Henyey-Greenstein sensitivities. +Not differentiable with respect to parameters: the inelastic processes +(`WaterRaman`, fluorescence) and their emission spectra, which are +floating point only (their kernels accept dual wavelengths), and the +measured phase tables (`PetzoldPhase`, `TabulatedMuellerPhase`). A +constituent of fixed floating-point type cannot store a dual parameter: +`CDOM{Float64}(slope = S)` with a dual `S` is a `MethodError`. The +[consumer interface](consumer_api.md) lists every differentiable +parameter. + +`test/test_ad.jl` holds the tested cases: each parameter derivative +against a central difference or a closed form, for the scalar functions +and through `layer_optics` and `column_optics`; wavelength, +scattering-angle and irradiance derivatives; and the rejected cases. diff --git a/docs/src/gallery.md b/docs/src/gallery.md index 57a9667..c2cb462 100644 --- a/docs/src/gallery.md +++ b/docs/src/gallery.md @@ -81,7 +81,7 @@ linechart([Series("Morel 1974", λ, b_mo), Comparison target: Morel & Maritorena (2001) Fig. 8 (total absorption and scattering of Case-1 water versus chlorophyll) and IOCCG Report 5 §2.4. At 440 nm, higher Chl produces both higher total absorption -(more `a_φ`) and higher particulate scattering `b_p`, with the +(more particulate absorption `a_p`) and higher particulate scattering `b_p`, with the classical greening of `a(λ)` away from the pure-water blue minimum. ```@example gallery @@ -101,7 +101,7 @@ end phytos = [Phytoplankton{Float64, Bricaud1998}(Chl = Chl) for Chl in Chls] linechart([Series("Chl = $Chl mg/m³", λ, total_a(p)) for (Chl, p) in zip(Chls, phytos)]; - title = "Total absorption a = a_w + a_g + a_φ", xlabel = "wavelength λ [nm]", + title = "Total absorption a = a_w + a_g + a_p", xlabel = "wavelength λ [nm]", ylabel = "a(λ) [m⁻¹]", xname = "λ [nm]", ylog = true) ``` @@ -201,8 +201,10 @@ linechart([Series("Fluspect combined (default)", λ_emit, dens(chloroplast_emiss ## 7. Pigment partition of phytoplankton absorption -Chlorophyll and carotenoid shares of `a_φ(λ)` at Chl = 0.5 mg m⁻³. The -parts sum to the Bricaud (1998) total (grey); fluorescence counts the +Chlorophyll and carotenoid shares of the absorption of `Phytoplankton` at +Chl = 0.5 mg m⁻³. The parts sum to the Bricaud et al. (1998) particulate +absorption `a_p(λ)` (grey), which includes the detritus of Case-1 water, so +the pigment shares carry that detrital absorption too; fluorescence counts the carotenoid parts with their energy-transfer efficiency. First the land analogy, with the PROSPECT-D leaf spectra and a carotenoid:chlorophyll ratio of 0.3: @@ -211,7 +213,7 @@ ratio of 0.3: λp = collect(400.0:2.0:720.0) part(p, name) = [absorption_part(p, name, λ) for λ in λp] pl = Phytoplankton(Chl = 0.5, pigments = ProspectPigments(carotenoid_ratio = 0.3)) -linechart([Series("total a_φ (Bricaud 1998)", λp, absorption(pl, λp); reference = true), +linechart([Series("total a_p (Bricaud 1998)", λp, absorption(pl, λp); reference = true), Series("chlorophyll", λp, part(pl, :chlorophyll); slot = 0), Series("carotenoids", λp, part(pl, :carotenoids); slot = 1)]; title = "Land analogy (PROSPECT-D), Chl = 0.5 mg m⁻³", @@ -226,7 +228,7 @@ carotenoids 0.3, photoprotective carotenoids 0.1 mg m⁻³): ```@example gallery po = Phytoplankton(Chl = 0.5, pigments = Bidigare1990Pigments(chl_a = 0.5, chl_c = 0.1, psc = 0.3, ppc = 0.1)) -linechart([Series("total a_φ (Bricaud 1998)", λp, absorption(po, λp); reference = true), +linechart([Series("total a_p (Bricaud 1998)", λp, absorption(po, λp); reference = true), Series("chlorophyll a", λp, part(po, :chlorophyll_a); slot = 0), Series("photosynthetic carotenoids", λp, part(po, :photosynthetic_carotenoids); slot = 1), Series("photoprotective carotenoids", λp, part(po, :photoprotective_carotenoids); diff --git a/docs/src/index.md b/docs/src/index.md index 11f975f..4a8ed54 100644 --- a/docs/src/index.md +++ b/docs/src/index.md @@ -2,7 +2,7 @@ Inherent optical properties (IOPs), phase-function Legendre expansions, and inelastic source terms of natural waters from biogeochemical state — -in Julia, automatic-differentiation-transparent, and designed to feed +in Julia, and designed to feed [vSmartMOM.jl](https://github.com/RemoteSensingTools/vSmartMOM.jl)'s forthcoming `OceanSurface` boundary. @@ -14,10 +14,10 @@ publishes is stable and solver-agnostic. ## Design principles -The full architecture memo lives in +The historical design memo [`DESIGN.md`](https://github.com/RemoteSensingTools/OceanOptics.jl/blob/main/DESIGN.md) -and is the authoritative long-form document. The four load-bearing -principles are: +records the original plans; where it differs from this manual, the manual is +authoritative. The four load-bearing principles are: 1. **RT-solver neutrality.** The primary output is an [`OceanLayerOptics`](@ref) bundle consumable by any plane-parallel @@ -108,8 +108,17 @@ For a longer walk-through with numerical output, see ## Scope and non-scope OceanOptics.jl **does** produce IOPs, phase-function expansions, and -inelastic source kernels from biogeochemical state. It is AD-transparent -through ForwardDiff. +inelastic source kernels from biogeochemical state. The elastic path is +generic in its element type, so that ForwardDiff dual numbers can be +carried by the model parameters (chlorophyll, CDOM reference absorption +and slope, the non-algal particle parameters, temperature, salinity and +depolarization of water, the Fournier-Forand backscatter fraction, the +Henyey-Greenstein asymmetry, layer thickness) through `layer_optics` and +`column_optics`, in addition to derivatives with respect to wavelength, +scattering angle and irradiance. Inelastic processes and measured phase +tables are floating point only; see +[Forward-mode automatic differentiation](@ref) for what is and is not +differentiable. ForwardDiff is not a dependency of the package. OceanOptics.jl **does not** solve radiative transfer. That work lives in the consumer (e.g. `vSmartMOM.jl`), which maps the column optics onto diff --git a/docs/src/reference/inelastic.md b/docs/src/reference/inelastic.md index 0d52a91..4c85f67 100644 --- a/docs/src/reference/inelastic.md +++ b/docs/src/reference/inelastic.md @@ -4,6 +4,88 @@ Fluorescence, water Raman, and CDOM fluorescence packaged as kernels consumed by a two-pass RT solver (Fell 1997 §2.2.9), and the light absorbed per layer and component that drives them. +## Conventions + +**Conversion units.** Every process factorizes into a conversion coefficient +`κ(λ′) = `[`excitation_absorption`](@ref) `[1/m]` and a redistribution density +`f(λ′, λ) = `[`emission`](@ref) `[1/nm]` with `∫ f dλ = 1`. [`conversion_units`](@ref) +states whether `κ` counts photons or energy, and the two kernels follow by dispatch: + +| `conversion_units(p)` | energy kernel `K_E` ([`radiance_source_kernel`](@ref)) | photon kernel `K_N` ([`inelastic_coefficient`](@ref)) | processes | +|:--|:--|:--|:--| +| [`PhotonConversion`](@ref) | `κ f λ′/λ` | `κ f` | [`IsotropicFluorescence`](@ref), [`CDOMFluorescence`](@ref); `WaterRaman(conversion = PhotonConversion())` | +| [`EnergyConversion`](@ref) | `κ f` | `κ f λ/λ′` | [`WaterRaman`](@ref) (default) | + +In both cases `K_N = K_E λ/λ′`, and the power emitted per unit volume and per nm of +emission wavelength is + +```math +4\pi \bar S(\lambda) = \int K_E(\lambda', \lambda)\, E_0(\lambda')\, d\lambda' +``` + +with `E₀` the spectral scalar irradiance `[W m⁻² nm⁻¹]`. [`inelastic_emission`](@ref) +integrates the same kernel over a layer. + +**Fluorescence** is a photon conversion: `κ = φ Σ_k η_k a_k(λ′)` with the quantum yield +`φ` in photons emitted per photon delivered to the fluorescing pigment, so +`∫ K_N dλ = κ` and the emitted energy carries the photon-energy ratio `λ′/λ`. + +**Water Raman** is an energy conversion by default: the Raman scattering coefficient +`b_R(λ′) = b_R(λ_ref) (λ_ref/λ′)^n` (defaults `2.7·10⁻⁴ m⁻¹` at 488 nm, `n = 5.5`) is +defined so that `b_R(λ′) E₀(λ′)` is the power emitted over the whole Raman band per unit +volume and per nm of excitation wavelength, + +```math +\int K_E(\lambda', \lambda)\, d\lambda = b_R(\lambda') , +``` + +with no factor `λ′/λ`. This is the definition of Mobley et al. (1993, Appl. Opt. 32, +7484; Problem 7 and Eqs. A3–A4): in Problem 7 all light Raman scattered at 417 nm +appears at 486 nm and the source of radiance is `b_R E₀/(4π)` times the phase function. +`WaterRaman(conversion = PhotonConversion())` treats the same number as a photon +coefficient instead (`∫ K_N dλ = b_R`); its energy source is lower by the band mean of +`λ′/λ`: 0.881 at 350 nm excitation, 0.858 at 417 nm, 0.834 at 488 nm, 0.796 at 600 nm. + +**Raman angular distribution and depolarization.** `WaterRaman` stores the +depolarization ratio `ρ` for linearly polarized excitation (`linear_depolarization`, +default 0.17 from Mobley et al. 1993, Eq. 9). The phase function is + +```math +p_R(\cos\Theta) = \frac{1}{4\pi}\left[1 + \beta_2 P_2(\cos\Theta)\right], +\qquad \beta_2 = \frac{1-\rho}{2(1+2\rho)} = 0.3097 \ \text{for}\ \rho = 0.17 , +``` + +identical to Mobley's Eq. 9, `(3/16π) (1+3ρ)/(1+2ρ) [1 + (1−ρ)/(1+3ρ) cos²Θ]`. +The ratio for unpolarized (natural) excitation is `ρ_n = 2ρ/(1+ρ)` (0.2906; +[`natural_depolarization`](@ref)), and `β₂ = (1−ρ_n)/(2+ρ_n)` is the same number. +[`raman_phase`](@ref) returns the [`RayleighWaterPhase`](@ref) with depolarization +`ρ_n`, whose polarized Greek expansion is the Raman phase matrix. + +**Raman loss.** The bundled water absorption models do not add a separate Raman loss; +whether `b_R(λ′)` is added to the attenuation at the excitation wavelength is the +solver's convention and must match the reference it is compared with (Mobley et al. +1993 take it to be contained in the Smith & Baker absorption). + +**Pigment partitions outside their tables.** The pigment spectra of +[`ProspectPigments`](@ref) (400–800 nm) and [`Bidigare1990Pigments`](@ref) (400–750 nm) +do not cover the UV. By default (`outside = `[`HoldEdgeShares`](@ref)`()`) the shares of +the nearest tabulated wavelength apply outside the table, so absorption below 400 nm is +attributed to the pigment groups as at 400 nm and [`chlorophyll_fluorescence`](@ref) +with `excitation_range = (350, 700)` is excited continuously across 400 nm; with all +transfer efficiencies equal to 1 its excitation equals that of the unpartitioned +phytoplankton. The UV shares are an extrapolation, not data. A partition built with +`outside = `[`UnassignedOutsideTable`](@ref)`()` puts all absorption outside its table +in `:unassigned` (η = 0); the excitation then steps to zero just below 400 nm, which +removes 21.9 % of the 350–700 nm excitation integral at Chl = 0.5 mg m⁻³. Under both +rules `Bidigare1990Pigments` assigns nothing above about 732 nm, where all its group +spectra vanish. The default `excitation_range` of `chlorophyll_fluorescence` is +(400, 700) nm. + +**Absorption that excites chlorophyll fluorescence.** With [`Bricaud1998`](@ref) the +absorption of `Phytoplankton` is the particulate absorption `a_p` of Case-1 water, +detritus included; the fluorescence excitation and the pigment shares are fractions +of that total. + ## Spectral redistribution ```@docs @@ -25,17 +107,24 @@ CDOMFluorescence WaterRaman chlorophyll_fluorescence raman_peak_wavelength +raman_phase +natural_depolarization ``` ## Trait interface ```@docs AbstractOceanInelasticProcess +AbstractConversionUnits +PhotonConversion +EnergyConversion +conversion_units excitation_absorption emission excitation_range excitation_pathways is_isotropic +quantum_yield inelastic_coefficient radiance_source_kernel ``` diff --git a/docs/src/reference/io.md b/docs/src/reference/io.md index 423f0c7..04f12ac 100644 --- a/docs/src/reference/io.md +++ b/docs/src/reference/io.md @@ -11,3 +11,12 @@ linterp data_path load_spectral_csv ``` + +## Table lookups + +```@docs +AbstractTableLookup +ExactLookup +LinearLookup +NearestLookup +``` diff --git a/docs/src/reference/materials.md b/docs/src/reference/materials.md index ff08f78..28b01ca 100644 --- a/docs/src/reference/materials.md +++ b/docs/src/reference/materials.md @@ -37,7 +37,8 @@ BricaudMorelPrieur1981 Phytoplankton AbstractPhytoplanktonModel Bricaud1998 -Gordon1992 +AbstractParticleScatteringModel +GordonMorel1983 ``` ## Pigment partitions @@ -46,6 +47,9 @@ Gordon1992 AbstractPigmentPartition ProspectPigments Bidigare1990Pigments +AbstractOutOfRangeShares +HoldEdgeShares +UnassignedOutsideTable pigment_parts pigment_class pigment_fractions diff --git a/docs/src/reference/parameters.md b/docs/src/reference/parameters.md new file mode 100644 index 0000000..c6004f4 --- /dev/null +++ b/docs/src/reference/parameters.md @@ -0,0 +1,170 @@ +# Physical parameters + +Every physical parameter of the package is a field of a model type or a keyword +argument with a default. This page lists them per model with the default, the unit, +where the number comes from, and how to set it. Coefficient sets that define a +published model as a whole (the Quan–Fry polynomial, the Zhang–Hu–He formulas, the +tabulated data files) are named constants or data files; the choice between such +models is made by type. + +"Package default" marks a value that is a modelling choice of this package and not +taken from a paper that was checked for this release. + +## Pure water: [`PureWater`](@ref) + +| parameter | symbol | default | unit | source | set with | +|:--|:--|:--|:--|:--|:--| +| temperature | `T` | 20 | °C | package default | `PureWater(temperature = 5)` | +| salinity | `S` | 35 | PSU | package default | `PureWater(salinity = 0)` | +| depolarization ratio (unpolarized light, 90°) | `δ` | 0.039 | – | Farinato & Rowell (1976), as used by Zhang, Hu & He (2009) | `PureWater(depolarization = 0.09)` | +| absorption table | – | [`IOCCG2018`](@ref) | – | see the model types | `PureWater(absorption_model = PopeFry1997())` | +| scattering model | – | [`ZhangHu2009`](@ref) | – | see the model types | `PureWater(scattering_model = Morel1974())` | + +`δ` is one stored value: it sets the phase matrix ([`RayleighWaterPhase`](@ref) from +`scattering_phase`) and the magnitude of the `ZhangHu2009` scattering, +`b ∝ (6 + 6δ)/(6 − 7δ) · (2 + δ)/(1 + δ)`. `Morel1974` scattering is an empirical +seawater law and uses neither `δ`, `T` nor `S`. Temperature enters the absorption +through the coefficient `Ψ_T` of Röttgers et al. (2014), applied from 550 nm upward +relative to the 22 °C of the Pope & Fry and Kou tables; salinity does not enter the +absorption. + +Fixed coefficient sets: `Morel1974` (`0.00193 m⁻¹` at 550 nm, exponent 4.32); the +Zhang, Hu & He (2009) formulas with their auxiliary fits; the absorption tables in +`data/`. + +## Rayleigh phase function: [`RayleighWaterPhase`](@ref) + +| parameter | symbol | default | unit | source | set with | +|:--|:--|:--|:--|:--|:--| +| depolarization ratio (unpolarized light, 90°) | `ρ` | 0.039 | – | Farinato & Rowell (1976) | `RayleighWaterPhase(depolarization = 0.09)` | + +`β₂ = (1 − ρ)/(2 + ρ)`. The default is the same constant as that of `PureWater`. + +## Refractive index: [`FixedRefractiveIndex`](@ref), [`QuanFry1995`](@ref) + +| parameter | symbol | default | unit | source | set with | +|:--|:--|:--|:--|:--|:--| +| index relative to air | `n` | none (required) | – | – | `FixedRefractiveIndex(1.34)` | +| temperature | `T` | none (required) | °C | – | `QuanFry1995(temperature = 20, salinity = 35)` | +| salinity | `S` | none (required) | PSU | – | as above | + +`column_optics` has no default refractive index. The ten Quan & Fry (1995) +coefficients are a fixed set. + +## CDOM: [`CDOM`](@ref) + +`a_g(λ) = a_ref · exp(−S (λ − λ_ref))` + +| parameter | symbol | default | unit | source | set with | +|:--|:--|:--|:--|:--|:--| +| reference absorption | `a_ref` | 0.03 | m⁻¹ | package default (open ocean) | `CDOM(a_ref = 0.5)` | +| reference wavelength | `λ_ref` | 440 | nm | package default | `CDOM(λ_ref = 400)` | +| spectral slope | `S` | 0.014 | nm⁻¹ | Bricaud et al. (1981), as given by Fell (1997), Eq. 5.4 | `CDOM(slope = 0.017)` | + +## Particles of Case-1 water: [`Phytoplankton`](@ref), [`GordonMorel1983`](@ref) + +`b_p(λ) = b_ref · Chl^m · (λ_ref/λ)^γ`; absorption `a_p = A(λ) Chl^{E(λ)}` from the +[`Bricaud1998`](@ref) tables (fixed data). + +| parameter | symbol | default | unit | source | set with | +|:--|:--|:--|:--|:--|:--| +| chlorophyll-a concentration | `Chl` | none (required) | mg m⁻³ | – | `Phytoplankton(Chl = 0.5)` | +| scattering at `λ_ref` for `Chl = 1` | `b_ref` | 0.30 | m⁻¹ | Gordon & Morel (1983) as cited by Fell (1997), Eq. 5.5 (`0.30 ± 0.15`) | `Phytoplankton(Chl = 0.5, scattering_model = GordonMorel1983(b_ref = 0.45))` | +| chlorophyll exponent | `m` | 0.62 | – | same | `GordonMorel1983(chl_exponent = 0.766)` | +| reference wavelength | `λ_ref` | 550 | nm | same | `GordonMorel1983(λ_ref = 660)` | +| spectral exponent | `γ` | 1 | – | same | `GordonMorel1983(spectral_exponent = 0.5)` | +| backscatter fraction of the Fournier–Forand phase function | `B` | 0.01 | – | package default; equals `b_bph/b_ph` of the database of Loisel et al. (2023) | `Phytoplankton(Chl = 0.5, B = 0.015)` | +| carotenoid-to-chlorophyll ratio | – | none (required) | – | – | `ProspectPigments(carotenoid_ratio = 0.3)` | +| pigment concentrations | – | `chl_a` required, others 0 | mg m⁻³ | – | `Bidigare1990Pigments(chl_a = 0.5, ppc = 0.1)` | +| shares outside the pigment tables | – | [`HoldEdgeShares`](@ref) | – | package default | `ProspectPigments(carotenoid_ratio = 0.3, outside = UnassignedOutsideTable())` | + +## Non-algal particles: [`NonAlgalParticles`](@ref) + +[`BabinBricaud2003`](@ref): `a(λ) = a_ref · exp(−S (λ − λ_ref))`, +`b(λ) = b_ref · (λ_ref/λ)^γ`. + +| parameter | symbol | default | unit | source | set with | +|:--|:--|:--|:--|:--|:--| +| reference absorption | `a_ref` | 0.05 | m⁻¹ | package default | `NonAlgalParticles(a_ref = 0.1)` | +| reference scattering | `b_ref` | 0.45 | m⁻¹ | package default | `NonAlgalParticles(b_ref = 0.6)` | +| reference wavelength | `λ_ref` | 443 | nm | package default | `NonAlgalParticles(λ_ref = 440)` | +| absorption slope | `S` | 0.011 | nm⁻¹ | package default (Babin et al. 2003 was not available for checking) | `NonAlgalParticles(slope = 0.0123)` | +| spectral exponent of scattering | `γ` | 1 | – | package default | `NonAlgalParticles(spectral_exponent = 0.5)` | +| backscatter fraction | `B` | 0.02 | – | package default | `NonAlgalParticles(B = 0.03)` | + +[`FellMineral`](@ref): `c(λ) = c_ref · (λ_ref/λ)^γ`, `a = (1 − ω) c`, `b = ω c`. + +| parameter | symbol | default | unit | source | set with | +|:--|:--|:--|:--|:--|:--| +| beam attenuation at `λ_ref` | `c_ref` | 0.40 | m⁻¹ | package default | `NonAlgalParticles{Float64, FellMineral}(c_ref = 1.0)` | +| single-scattering albedo | `ω₀` | 0.95 | – | Fell (1997), Eq. 5.11 | `…(ω_nap = 0.9)` | +| reference wavelength | `λ_ref` | 440 | nm | Fell (1997), Eq. 5.10 | `…(λ_ref = 550)` | +| spectral exponent of attenuation | `γ` | 1 | – | Fell (1997), Eq. 5.10 | `…(spectral_exponent = 0.5)` | +| backscatter fraction | `B` | 0.036 | – | Fell (1997), §5.1.4 | `…(B = 0.02)` | + +## Phase-function parameters + +| model | parameter | symbol | default | source | set with | +|:--|:--|:--|:--|:--|:--| +| [`HenyeyGreensteinPhase`](@ref) | asymmetry parameter | `g` | 0.85 | package default | `HenyeyGreensteinPhase(g = 0.9)` | +| [`FournierForandPhase`](@ref) | real refractive index of the particles | `n` | from `B` | Mobley, Sundman & Boss (2002) | `FournierForandPhase{Float64}(1.10, 3.5835)` | +| [`FournierForandPhase`](@ref) | Junge slope | `μ_j` | from `B` | same | as above | +| [`FournierForandPhase`](@ref) | backscatter fraction | `B` | none (required in this form) | – | `FournierForandPhase(backscatter_fraction = 0.0183)` | + +`backscatter_fraction = B` selects `(n, μ_j)` on the family +`n = 1.01 + 0.1542 (μ_j − 3)` of Mobley, Sundman & Boss (2002), a fixed coefficient +set. [`PetzoldPhase`](@ref) is tabulated data. + +## Water Raman scattering: [`WaterRaman`](@ref) + +`b_R(λ′) = b_ref (λ_ref/λ′)^n`; emission band Gaussian in wavenumber at `ν′ − Δν`. + +| parameter | symbol | default | unit | source | set with | +|:--|:--|:--|:--|:--|:--| +| Stokes shift | `Δν` | 3400 | cm⁻¹ | attributed to Haltrin & Kattawar (1993); not in a paper checked for this release | `WaterRaman(shift_cm_inv = 3357)` | +| band standard deviation | `σ_ν` | 85 | cm⁻¹ | same | `WaterRaman(σ_cm_inv = 90)` | +| scattering coefficient at `λ_ref` | `b_ref` | 2.7·10⁻⁴ | m⁻¹ | attributed to Bartlett et al. (1998); not checked. The HydroLight runs of Loisel et al. (2023) are reproduced with 2.6·10⁻⁴ | `WaterRaman(cross_section_ref = 2.6e-4)` | +| reference wavelength | `λ_ref` | 488 | nm | same | `WaterRaman(cross_section_λ_ref = 488)` | +| exponent | `n` | 5.5 | – | attributed to Bartlett et al. (1998), energy units; not checked | `WaterRaman(cross_section_n = 5.3)` | +| depolarization ratio, linearly polarized excitation | `ρ` | 0.17 | – | Mobley et al. (1993), Eq. 9 | `WaterRaman(linear_depolarization = 0.2)` | +| excitation window | – | (350, 700) | nm | package default | `WaterRaman(excitation_range = (300, 700))` | +| convention of `b_R` | – | [`EnergyConversion`](@ref) | – | Mobley et al. (1993), Problem 7 and Appendix A | `WaterRaman(conversion = PhotonConversion())` | + +The shift and width defaults are shared with [`WavenumberShiftEmission`](@ref) +(`WavenumberShiftEmission(shift_cm_inv = …, σ_cm_inv = …)`). Mobley's Problem 7 is +`WaterRaman(cross_section_ref = 0.0063, cross_section_λ_ref = 417)`. + +## Fluorescence parameters + +| model | parameter | symbol | default | unit | source | set with | +|:--|:--|:--|:--|:--|:--|:--| +| [`chlorophyll_fluorescence`](@ref) | quantum yield | `φ` | none (required) | – | 0.01–0.05 in situ; HydroLight 0.02 (Loisel et al. 2023) | `chlorophyll_fluorescence(phyto; quantum_yield = 0.02)` | +| | excitation window | – | (400, 700) | nm | PAR limits | `…; excitation_range = (350, 700))` | +| | carotenoid transfer efficiency | `η` | none (required with carotenoids) | – | – | `…; carotenoid_transfer = 0.5)` | +| | phycobilin transfer efficiency | `η` | 1 | – | package default | `…; phycobilin_transfer = 0.8)` | +| | photoprotective-carotenoid transfer efficiency | `η` | 0 | – | photoprotective pigments dissipate absorbed energy | `…; photoprotective_transfer = 0.1)` | +| | emission spectrum | `f` | [`chloroplast_emission`](@ref) | nm⁻¹ | Fluspect (data) | `…; emission = GaussianEmission())` | +| [`GaussianEmission`](@ref) | band centre | – | 685 | nm | Fell (1997), §2.2.9 | `GaussianEmission(center_nm = 683)` | +| | band standard deviation | `σ` | 10.6 | nm | Fell (1997), §2.2.9 | `GaussianEmission(σ_nm = 12)` | +| [`chloroplast_emission`](@ref) | photosystem I share | – | combined spectrum | – | Fluspect | `chloroplast_emission(psi_share = 0.3)` | +| [`CDOMFluorescence`](@ref) | quantum yield | `φ` | none (required) | – | – | `CDOMFluorescence(cdom; emission, quantum_yield = 0.01)` | +| | excitation window | – | (300, 400) | nm | package default | `…; excitation_range = (310, 390))` | +| [`ExcitationPathway`](@ref) | transfer efficiency | `η` | 1 | – | – | `ExcitationPathway(phyto, :carotenoids, 0.5)` | + +## Absorbed-light parameters + +| function | parameter | default | unit | source | set with | +|:--|:--|:--|:--|:--|:--| +| [`absorbed_par`](@ref) | integration limits | (400, 700) | nm | PAR limits; the same constant as the default excitation window of `chlorophyll_fluorescence` | `absorbed_par(o, E₀; range = (400, 690))` | +| [`inelastic_emission`](@ref) | excitation limits | `excitation_range(p)` | nm | the process | `inelastic_emission(o, j, E₀, λ; range = (370, 690))` | +| [`absorbed_power`](@ref), [`absorbed_photons`](@ref), [`absorbed_par`](@ref), [`inelastic_emission`](@ref) | negative irradiance treated as round-off, relative to the largest entry | `√eps` (1.5·10⁻⁸ in `Float64`) | – | package default | `absorbed_power(o, E₀; roundoff_rtol = 0)` | + +## Numerical settings that affect results + +| setting | default | set with | +|:--|:--|:--| +| number of expansion moments | `ℓ_max = 64` | `layer_optics(layer, λ; ℓ_max = 128)` | +| wavelength match of [`ExactLookup`](@ref) tables | relative `1e-6` | fixed constant of the package | +| normalization tolerance of [`TabulatedMuellerPhase`](@ref) | `1e-3` | `TabulatedMuellerPhase(…; normalization_tolerance = 1e-4)` | + +Universal constants (`h`, `c`, `N_A`, SI 2019 values) are named constants. diff --git a/docs/src/reference/phases.md b/docs/src/reference/phases.md index f83e2e5..17b0dad 100644 --- a/docs/src/reference/phases.md +++ b/docs/src/reference/phases.md @@ -18,6 +18,8 @@ WavelengthDependentPhase GreekCoefficients resize_moments depolarized +zero_padded +phase_id mix_greek evaluate_scattering_matrix ``` diff --git a/docs/src/reference/types.md b/docs/src/reference/types.md index 1cfb00c..a596d8c 100644 --- a/docs/src/reference/types.md +++ b/docs/src/reference/types.md @@ -43,6 +43,10 @@ fell_column ## Solver output +The numeric arrays of these structs are type parameters, and +`Adapt.adapt(to, x)` moves them to a device; see "Precision and devices" +in the [Consumer API](../consumer_api.md). + ```@docs layer_optics column_optics diff --git a/docs/src/vsmartmom_integration.md b/docs/src/vsmartmom_integration.md index c4fbf7c..25eed80 100644 --- a/docs/src/vsmartmom_integration.md +++ b/docs/src/vsmartmom_integration.md @@ -8,8 +8,8 @@ documentation, not part of either package. ## Compatibility * OceanOptics' dependency bounds include the versions vSmartMOM resolves - to (`Interpolations` 0.16, `FastGaussQuadrature` 0.5 through its - CanopyOptics dependency); the OceanOptics test suite passes with them. + to (`FastGaussQuadrature` 0.5 through its CanopyOptics dependency, + `Adapt` 4); the OceanOptics test suite passes with them. * No exported names collide, so `using vSmartMOM, OceanOptics` works without qualification. (vSmartMOM's own `greek_coefficients`, `phase_function` and `scattering_matrix` refer to its analytic phase @@ -85,6 +85,34 @@ cores = [layer_core_optics(l, μ_water, m, S.Stokes_IQUV(), l_trunc) for l in co nodes and the total-internal-reflection interval, which the interface implementation defines. +## Precision and devices + +The models are evaluated on the host; the solver chooses the element type +and the device of the results: + +```julia +using Adapt +col = column_optics(FT, column, λ; refractive_index = index, ℓ_max = l_trunc) # FT = Float32 or Float64 +dev = adapt(architecture_array_type, col) # e.g. CuArray; `Array` returns `col` without copying +``` + +Build the constituents in `Float64` and request `FT` here: tables and +constants are `Float64`, and each stored value is rounded once. `adapt` +moves every numeric array (`λ`, the `τ` of each component, the Greek +coefficients, backscatter fractions, `phase_index`, refractive index, +bottom albedo) and keeps the element type; labels, `phase_id` keys and +the component and layer lists stay host objects, so the adapter loops +over components on the host and hands their arrays to the kernels. +`absorption_optical_depth(layer)`, `scattering_optical_depth(layer)`, +`single_scattering_albedo(layer)` and `bottom_albedo(col)` work on the +adapted column and return device arrays. + +Out of scope on a device: the quadrature that produces the Greek +coefficients (`greek_expansion`), the constituent, phase-function and +inelastic model structs (they hold or read host tables), and the absorbed +light and emission diagnostics. Compute these on the host, before `adapt` +(see "Precision and devices" in the [Consumer API](consumer_api.md)). + ## Points for the solver side * **δ-BGE with vanishing elements.** vSmartMOM's `truncate_phase(δBGE…)` @@ -99,6 +127,13 @@ implementation defines. `phase_id`. A wavelength-dependent component stores its distinct expansions plus `phase_index`, so `Z` is needed only per distinct entry (e.g. per band with `WavelengthDependentPhase(...; lookup = :nearest)`). + `phase_id` holds one content key per entry of `greek` + ([`phase_id`](@ref)`(c, iλ)` at a wavelength): equal keys mean equal + coefficients, `ℓ_max` and element type, so `(phase_id, m)` is a valid + cache key for `Z` before truncation. +* **Scalar expansions.** `GreekCoefs`-based code that sizes by + `length(α)` needs [`zero_padded`](@ref)`(g)` for expansions computed with + `polarized = false`. * **Forward peaks.** Particle expansions (Fournier-Forand, hydrosol matrices) are not converged at practical `ℓ_max` — e.g. the Chowdhary AOS-IV hydrosols still have `β₁₀₀₀/2001 ≈ 3×10⁻³` — so truncation is @@ -112,8 +147,12 @@ implementation defines. diagnostics and the reference fluorescence budget; energy closure (net irradiance below the surface = absorbed in the layers + absorbed by the floor) is the test. -* **Inelastic sources** follow the photon contract on the - [Consumer API](@ref) page ([`radiance_source_kernel`](@ref)). For +* **Inelastic sources**: [`radiance_source_kernel`](@ref) is the energy + kernel of every process, and [`conversion_units`](@ref) says whether the + photon-energy factor λ′/λ enters it ([`PhotonConversion`](@ref) for + fluorescence, [`EnergyConversion`](@ref) for the default + [`WaterRaman`](@ref)); the kernel already contains that factor, so a + solver must not apply λ′/λ again (see the [Consumer API](@ref) page). For fluorescence, [`excitation_optical_depth`](@ref)`(layer, j)` gives the excitation optical depth on the layer grid from the linked absorption components; [`excitation_absorption`](@ref) gives the same coefficient diff --git a/scripts/fetch_data.jl b/scripts/fetch_data.jl index b1570b1..26e56a3 100644 --- a/scripts/fetch_data.jl +++ b/scripts/fetch_data.jl @@ -20,11 +20,18 @@ # pope_fry_1997.csv ← omlc.org/spectra/water/data/pope97.txt # smith_baker_1981.csv ← omlc.org/spectra/water/data/smith81.txt # -# Tables *not* fetched by this script (no stable redistributable URL; must -# be transcribed from the original publication): -# mason_cone_fry_2016.csv — Appl. Opt. 55, 7163, Table 2 -# bricaud_1995.csv — JGR 100, 13321, Table 2 -# petzold_sdh.csv — Mobley (1994) "Light and Water" Appendix A.4 +# The other files in `data/` are not fetched by this script; each one's +# header names its source, retrieval URL and checksum: +# bricaud_1998_A.csv, bricaud_1998_E.csv — Bricaud et al. (1998), JGR 103, +# 31033, as tabulated for HydroLight (AEmidUVabs.txt) +# bidigare_1990_pigments.csv — Bidigare et al. (1990), Ocean Optics Web Book +# petzold_sdh.csv — Petzold (1972), Ocean Optics Web Book +# kou_1993.csv — Kou, Labrie & Chylek (1993), omlc.org kou93b.txt +# ioccg_2018_pure_water.csv — IOCCG (2018) composite, from the Loisel et al. +# (2023) HydroLight database (Dryad, CC0) +# rottgers_2014_temperature.csv — Röttgers, McKee & Utschig (2014), figshare +# fluspect_chloroplast_emission.csv, prospect_d_pigment_absorption.csv +# — Fluspect / PROSPECT-D parameter file (SCOPE) # # Unit conventions # ---------------- diff --git a/src/OceanOptics.jl b/src/OceanOptics.jl index dd5cc88..f12d5ba 100644 --- a/src/OceanOptics.jl +++ b/src/OceanOptics.jl @@ -26,9 +26,9 @@ Units, conventions and validation rules are on the *Consumer API* docs page. """ module OceanOptics -using DocStringExtensions +using Adapt: Adapt, adapt +using DocStringExtensions: DocStringExtensions, TYPEDEF, TYPEDFIELDS using FastGaussQuadrature: gausslegendre -using Interpolations: linear_interpolation, Flat # ----------------------------------------------------------------------------- # Type spine @@ -101,7 +101,8 @@ export PureWater export AbstractPureWaterAbsorptionModel, IOCCG2018, PopeFry1997, Kou1993, SmithBaker1981 export AbstractPureWaterScatteringModel, Morel1974, ZhangHu2009 export CDOM, AbstractCDOMModel, BricaudMorelPrieur1981 -export Phytoplankton, AbstractPhytoplanktonModel, Bricaud1998, Gordon1992 +export Phytoplankton, AbstractPhytoplanktonModel, Bricaud1998 +export AbstractParticleScatteringModel, GordonMorel1983 export NonAlgalParticles, AbstractNAPModel, BabinBricaud2003, FellMineral export TabulatedAbsorber, TabulatedScatterer export absorption, scattering, backscattering, attenuation, scattering_phase, is_total_absorption @@ -109,6 +110,7 @@ export absorption_parts, absorption_by_part, absorption_part # Pigment partitions of phytoplankton absorption export ProspectPigments, Bidigare1990Pigments, pigment_parts, pigment_class, pigment_fractions +export AbstractOutOfRangeShares, HoldEdgeShares, UnassignedOutsideTable # Refractive index of seawater export FixedRefractiveIndex, QuanFry1995, refractive_index @@ -116,7 +118,8 @@ export FixedRefractiveIndex, QuanFry1995, refractive_index # Phase functions and expansions export FournierForandPhase, RayleighWaterPhase, HenyeyGreensteinPhase, PetzoldPhase export TabulatedGreekPhase, TabulatedMuellerPhase, WavelengthDependentPhase -export GreekCoefficients, resize_moments, depolarized, mix_greek, evaluate_scattering_matrix +export GreekCoefficients, resize_moments, depolarized, zero_padded, mix_greek +export evaluate_scattering_matrix, phase_id export phase_function_value, phase_function_moments, greek_expansion export depolarizing_greek_expansion export backscatter_fraction, asymmetry_parameter, is_polarizable, is_wavelength_dependent @@ -135,6 +138,7 @@ export single_scattering_albedo, bottom_albedo, interface_depths # Data loading (power-user API) export SpectralTable, linterp, data_path, load_spectral_csv +export AbstractTableLookup, ExactLookup, LinearLookup, NearestLookup # Inelastic processes export GaussianEmission, WavenumberShiftEmission, TabulatedEmission, fwhm_to_sigma @@ -142,7 +146,8 @@ export ExcitationPathway, IsotropicFluorescence, CDOMFluorescence, WaterRaman export chlorophyll_fluorescence, chloroplast_emission export excitation_absorption, excitation_range, excitation_pathways, emission, is_isotropic export quantum_yield, inelastic_coefficient, radiance_source_kernel, redistribution -export raman_peak_wavelength +export raman_peak_wavelength, raman_phase, natural_depolarization +export AbstractConversionUnits, EnergyConversion, PhotonConversion, conversion_units # Light absorbed per component export absorbed_power, absorbed_photons, absorbed_par, inelastic_emission diff --git a/src/diagnostics/absorbed_light.jl b/src/diagnostics/absorbed_light.jl index fd81c73..d2d117e 100644 --- a/src/diagnostics/absorbed_light.jl +++ b/src/diagnostics/absorbed_light.jl @@ -19,6 +19,11 @@ # interpolant of the integrand on the layer's wavelength grid exactly (the # trapezoidal rule, with the end intervals clipped at lo and hi); a solver # with its own bin weights may integrate itself. +# +# A solver's irradiance can be negative at round-off level where the field +# has decayed. Entries no more negative than `roundoff_rtol` (default √eps of +# the irradiance's float type) times the largest |Ē₀| of the layer are set to +# zero; anything more negative is an error. # ============================================================================= # h c N_A in J m mol⁻¹ (SI 2019 exact constants) @@ -27,61 +32,88 @@ const _LIGHT_SI = 299_792_458.0 # m s⁻¹ const _AVOGADRO_SI = 6.02214076e23 # mol⁻¹ "Photon flux per unit power at wavelength `λ` `[nm]`: µmol photons J⁻¹." -_µmol_per_joule(λ) = λ * 1e-9 / (_PLANCK_SI * _LIGHT_SI * _AVOGADRO_SI) * 1e6 - -function _check_irradiance(o::OceanLayerOptics, E₀::AbstractVector, who) +_µmol_per_joule(λ) = + convert(typeof(float(λ)), _wide(λ) * 1e-9 / (_PLANCK_SI * _LIGHT_SI * _AVOGADRO_SI) * 1e6) + +# Default relative size of negative irradiance entries treated as round-off: √eps of +# the irradiance's float type. +_roundoff_rtol(::AbstractVector{T}) where {T<:Real} = sqrt(eps(float(T))) + +# The irradiance with round-off negatives set to zero; throws on anything else +# that is not a finite, non-negative spectrum on the layer grid. +function _checked_irradiance(o::OceanLayerOptics, E₀::AbstractVector{T}, who, + roundoff_rtol) where {T<:Real} + roundoff_rtol ≥ 0 || + throw(ArgumentError("$who: roundoff_rtol must be non-negative, got $roundoff_rtol")) length(E₀) == n_wavelengths(o) || throw(DimensionMismatch("$who: $(length(E₀)) irradiance values for " * "$(n_wavelengths(o)) wavelengths")) - all(x -> isfinite(x) && x ≥ 0, E₀) || - throw(ArgumentError("$who: scalar irradiance must be finite and non-negative")) - return nothing + all(isfinite, E₀) || throw(ArgumentError("$who: scalar irradiance must be finite")) + allowance = roundoff_rtol * maximum(abs, E₀) + lowest = minimum(E₀) + lowest ≥ -allowance || + throw(ArgumentError("$who: scalar irradiance must be non-negative; its lowest entry, " * + "$lowest, is below the round-off allowance −$allowance " * + "(roundoff_rtol = $roundoff_rtol times the largest entry). " * + "Check the sign and units of the field")) + return [max(x, zero(x)) for x in E₀] end """ - absorbed_power(o::OceanLayerOptics, E₀) -> Matrix - -Spectral power absorbed by each absorption component of layer `o`, -`A[c, k] = τ_c(λ_k) · E₀[k]`, given the layer-mean spectral scalar -irradiance `E₀[k]` at `o.λ[k]` (`(1/Δz) ∫ E₀ dz` over the layer, total -intensity over all directions, direct and diffuse). Rows follow -`o.absorbers`; units are those of `E₀` (`W m⁻² nm⁻¹` ⇒ absorbed -`W m⁻² nm⁻¹` per layer). + absorbed_power(o::OceanLayerOptics, E₀; roundoff_rtol = √eps) -> Matrix + +Return the spectral power absorbed by each absorption component of layer `o`, +`A[c, k] = τ_c(λ_k) · E₀[k]`. + +`E₀[k]` is the layer-mean spectral scalar irradiance at `o.λ[k]` (`(1/Δz) ∫ E₀ dz` over +the layer, total intensity over all directions, direct and diffuse). Rows follow +`o.absorbers`; units are those of `E₀` (`W m⁻² nm⁻¹` ⇒ absorbed `W m⁻² nm⁻¹` per layer). + +`E₀` must be finite and non-negative. Negative entries at round-off level, +`E₀[k] ≥ −roundoff_rtol · maximum(abs, E₀)`, are treated as zero; more negative +entries throw an `ArgumentError`. The default `roundoff_rtol` is `√eps(T)` with `T` the +float type of `E₀` (`1.5e-8` in `Float64`); `roundoff_rtol = 0` rejects every negative +entry. The same rule and keyword apply in +[`absorbed_photons`](@ref), [`absorbed_par`](@ref) and +[`inelastic_emission`](@ref). """ -function absorbed_power(o::OceanLayerOptics, E₀::AbstractVector{<:Real}) - _check_irradiance(o, E₀, "absorbed_power") - return [c.τ[k] * E₀[k] for c in o.absorbers, k in eachindex(o.λ)] +function absorbed_power(o::OceanLayerOptics, E₀::AbstractVector{<:Real}; + roundoff_rtol::Real = _roundoff_rtol(E₀)) + E = _checked_irradiance(o, E₀, "absorbed_power", roundoff_rtol) + return [c.τ[k] * E[k] for c in o.absorbers, k in eachindex(o.λ)] end """ absorbed_photons(o::OceanLayerOptics, E₀) -> Matrix -[`absorbed_power`](@ref) in photon units: µmol photons m⁻² s⁻¹ nm⁻¹ per +Return [`absorbed_power`](@ref) in photon units: µmol photons m⁻² s⁻¹ nm⁻¹ per absorption component, for `E₀` in `W m⁻² nm⁻¹` (photon energy `hc/λ`). """ -function absorbed_photons(o::OceanLayerOptics, E₀::AbstractVector{<:Real}) - A = absorbed_power(o, E₀) +function absorbed_photons(o::OceanLayerOptics, E₀::AbstractVector{<:Real}; + roundoff_rtol::Real = _roundoff_rtol(E₀)) + A = absorbed_power(o, E₀; roundoff_rtol) return A .* _µmol_per_joule.(permutedims(o.λ)) end """ - absorbed_par(o::OceanLayerOptics, E₀; range = (400, 700)) -> Vector + absorbed_par(o::OceanLayerOptics, E₀; range = (400, 700), roundoff_rtol = √eps) -> Vector -Photosynthetically available radiation absorbed by each absorption -component of layer `o`: [`absorbed_photons`](@ref) integrated over -`range` `[nm]`, in µmol photons m⁻² s⁻¹. The integral is that of the -linear interpolant on the layer grid (trapezoidal rule, end intervals -clipped at the range limits), so the grid must span `range` but need not -contain its limits. Entries follow `o.absorbers`; see -[`absorber_index`](@ref). +Return the photosynthetically available radiation absorbed by each absorption component +of layer `o`: [`absorbed_photons`](@ref) integrated over `range` `[nm]`, in +µmol photons m⁻² s⁻¹. + +The integral is that of the linear interpolant on the layer grid (trapezoidal rule, end +intervals clipped at the range limits), so the grid must span `range` but need not +contain its limits. Entries follow `o.absorbers`; see [`absorber_index`](@ref). For phytoplankton with a pigment partition this gives the PAR absorbed by each pigment group, e.g. by chlorophyll. """ function absorbed_par(o::OceanLayerOptics, E₀::AbstractVector{<:Real}; - range::Tuple{<:Real, <:Real} = (400, 700)) + range::Tuple{<:Real, <:Real} = _PAR_RANGE_NM, + roundoff_rtol::Real = _roundoff_rtol(E₀)) w = _window_weights(o.λ, range, "absorbed_par") - N = absorbed_photons(o, E₀) + N = absorbed_photons(o, E₀; roundoff_rtol) return N * w end @@ -113,15 +145,20 @@ end """ excitation_optical_depth(o::OceanLayerOptics, j) -> Vector -Excitation optical depth `τᴵ(λ) = aᴵ(λ) Δz` of the layer's `j`-th -inelastic component on the layer grid. For a process with excitation -pathways (fluorescence) it is formed from the stored absorption -components, `quantum_yield(p) · Σ_k efficiency[k] · absorbers[excitation[k]].τ`, -which equals `Δz · excitation_absorption(p, λ)`; otherwise (water Raman) -it is `Δz · excitation_absorption(p, λ)`. +Return the excitation optical depth `τᴵ(λ) = aᴵ(λ) Δz` of the layer's `j`-th inelastic +component on the layer grid. + +For a process with excitation pathways (fluorescence) it is formed from the stored +absorption components, `quantum_yield(p) · Σ_k efficiency[k] · absorbers[excitation[k]].τ`, +which equals `Δz · excitation_absorption(p, λ)`; otherwise (water Raman) it is +`Δz · excitation_absorption(p, λ)`. """ -function excitation_optical_depth(o::OceanLayerOptics{FT}, j::Integer) where {FT} - c = o.inelastic[j] +excitation_optical_depth(o::OceanLayerOptics{FT}, j::Integer) where {FT} = + _excitation_optical_depth(o, o.inelastic[j])::Vector{FT} + +# `o.inelastic` holds components of different process types, so the callers +# dispatch here at run time and assert the result type. +function _excitation_optical_depth(o::OceanLayerOptics{FT}, c::InelasticComponent) where {FT} isempty(c.excitation) && return [FT(thickness(o) * excitation_absorption(c.process, λ)) for λ in o.λ] τ = zeros(FT, n_wavelengths(o)) @@ -132,14 +169,19 @@ function excitation_optical_depth(o::OceanLayerOptics{FT}, j::Integer) where {FT end """ - inelastic_emission(o::OceanLayerOptics, j, E₀, λ_em; range = excitation_range(p)) -> Vector + inelastic_emission(o::OceanLayerOptics, j, E₀, λ_em; + range = excitation_range(p), roundoff_rtol = √eps) -> Vector -Spectral power `[W m⁻² nm⁻¹]` emitted in all directions by layer `o` -through its `j`-th inelastic component (process `p`), at emission -wavelengths `λ_em` `[nm]`: +Return the spectral power `[W m⁻² nm⁻¹]` emitted in all directions by layer `o` through +its `j`-th inelastic component (process `p`), at emission wavelengths `λ_em` `[nm]`: -`P(λ) = ∫ τᴵ(λ′) Ē₀(λ′) f(λ′, λ) λ′/λ dλ′ = Δz ∫ radiance_source_kernel(p, λ′, λ) Ē₀(λ′) dλ′`, +``` +P(λ) = Δz ∫ radiance_source_kernel(p, λ′, λ) Ē₀(λ′) dλ′ + = ∫ τᴵ(λ′) Ē₀(λ′) f(λ′, λ) λ′/λ dλ′ (photon conversion: fluorescence) + = ∫ τᴵ(λ′) Ē₀(λ′) f(λ′, λ) dλ′ (energy conversion: default water Raman) +``` +according to [`conversion_units`](@ref)`(p)`, with `τᴵ` from [`excitation_optical_depth`](@ref) (the layer's stored absorption components) and `E₀` the layer-mean scalar irradiance on the layer grid (as in [`absorbed_power`](@ref)), integrated over `range` as @@ -154,12 +196,21 @@ radiative transfer. """ function inelastic_emission(o::OceanLayerOptics{FT}, j::Integer, E₀::AbstractVector{<:Real}, λ_em::AbstractVector{<:Real}; - range::Tuple{<:Real, <:Real} = excitation_range(o.inelastic[j].process)) where {FT} - _check_irradiance(o, E₀, "inelastic_emission") - p = o.inelastic[j].process + range::Tuple{<:Real, <:Real} = excitation_range(o.inelastic[j].process), + roundoff_rtol::Real = _roundoff_rtol(E₀)) where {FT} + E = _checked_irradiance(o, E₀, "inelastic_emission", roundoff_rtol) + T = promote_type(FT, eltype(E), float(eltype(λ_em))) + return _inelastic_emission(T, o, o.inelastic[j], E, λ_em, range)::Vector{T} +end + +function _inelastic_emission(::Type{T}, o::OceanLayerOptics, c::InelasticComponent, E, λ_em, + range) where {T} + p = c.process w = _window_weights(o.λ, range, "inelastic_emission") - x = w .* excitation_optical_depth(o, j) .* E₀ # excitation per grid point + x = w .* _excitation_optical_depth(o, c) .* E # excitation per grid point ks = [k for k in eachindex(o.λ) if x[k] != 0] - return [sum(x[k] * emission(p, o.λ[k], λ) * o.λ[k] / λ for k in ks; init = zero(FT) * zero(float(λ))) - for λ in λ_em] + u = conversion_units(p) + return T[sum(_energy_kernel(u, x[k] * emission(p, o.λ[k], λ), o.λ[k], λ) for k in ks; + init = zero(T)) + for λ in λ_em] end diff --git a/src/inelastic/fluorescence.jl b/src/inelastic/fluorescence.jl index 6de7fce..b1e8876 100644 --- a/src/inelastic/fluorescence.jl +++ b/src/inelastic/fluorescence.jl @@ -76,8 +76,8 @@ end """ excitation_pathways(p::AbstractOceanInelasticProcess) -> Tuple -The [`ExcitationPathway`](@ref)s whose absorbed photons drive `p`; empty -for processes not driven by absorption (water Raman). +Return the [`ExcitationPathway`](@ref)s whose absorbed photons drive `p`; the tuple is +empty for processes not driven by absorption (water Raman). """ excitation_pathways(::AbstractOceanInelasticProcess) = () @@ -167,6 +167,13 @@ emission(p::IsotropicFluorescence, λ_prime::Real, λ::Real) = excitation_range(p::IsotropicFluorescence) = p.excitation_range excitation_pathways(p::IsotropicFluorescence) = p.excitation is_isotropic(::IsotropicFluorescence) = true +conversion_units(::IsotropicFluorescence) = PhotonConversion() +""" + quantum_yield(p) + +Return the fluorescence quantum yield of process `p`: photons emitted per photon +delivered to the fluorescing pigment. +""" quantum_yield(p::IsotropicFluorescence) = p.quantum_yield function Base.show(io::IO, p::IsotropicFluorescence{FT}) where {FT} @@ -185,8 +192,10 @@ const _FLUSPECT_SOURCE = "Fluspect Optipar2017_ProspectD (SCOPE; Vilfan et al. """ chloroplast_emission([FT = Float64]; psi_share = nothing) -> TabulatedEmission -Chlorophyll fluorescence emission at the photosystem (chloroplast) level, -before any reabsorption, as used for leaves by Fluspect +Return the chlorophyll fluorescence emission spectrum at the photosystem (chloroplast) +level, before any reabsorption. + +The spectra are those used for leaves by Fluspect (`data/fluspect_chloroplast_emission.csv`, 640–851 nm): - `psi_share = nothing`: Fluspect's combined spectrum `phi` (the default @@ -216,23 +225,31 @@ function chloroplast_emission(::Type{FT} = Float64; return TabulatedEmission(FT.(λ), FT.(shape); source) end +"Limits of photosynthetically available radiation `[nm]`." +const _PAR_RANGE_NM = (400.0, 700.0) + """ chlorophyll_fluorescence(phyto::Phytoplankton; quantum_yield, carotenoid_transfer = nothing, phycobilin_transfer = 1, - transfer = (;), emission = chloroplast_emission(FT), + photoprotective_transfer = 0, transfer = (;), emission = chloroplast_emission(FT), excitation_range = (400, 700)) -> IsotropicFluorescence -Chlorophyll-a fluorescence of `phyto`, with one excitation pathway per -absorption part of `phyto`: +Build the chlorophyll-a fluorescence process of `phyto`, with one excitation pathway per +absorption part of `phyto`. | part | default η | |:-----|:----------| | `:total` (no pigment partition) | 1: all phytoplankton absorption | | chlorophylls | 1 | -| carotenoids | `carotenoid_transfer`: required when the partition has carotenoids | -| phycobilins | `phycobilin_transfer` (phycobilisomes are a photosystem II antenna; the default 1 is a modelling choice) | +| carotenoids (photosynthetic, or Prospect's lumped carotenoids) | `carotenoid_transfer`: required when the partition has them | +| photoprotective carotenoids | `photoprotective_transfer` (0) | +| phycobilins | `phycobilin_transfer` | | `:unassigned` | 0 | +Phycobilisomes are a photosystem II antenna; the default `phycobilin_transfer = 1` is a +modelling choice. Photoprotective carotenoids dissipate the energy they absorb instead of +passing it on to chlorophyll, hence `photoprotective_transfer = 0`. + `transfer` overrides η for named parts, e.g. `(photosynthetic_carotenoids = 0.8, photoprotective_carotenoids = 0.0)` for [`Bidigare1990Pigments`](@ref). `carotenoid_transfer = 0` is @@ -241,9 +258,19 @@ chlorophyll share of leaf absorption); `1` makes carotenoids a lossless antenna; values between give the share that is passed on rather than quenched. +The pigment spectra of the partitions start at 400 nm. With the default +[`HoldEdgeShares`](@ref) rule the shares at 400 nm apply below, so excitation in the UV +(`excitation_range` starting below 400 nm) is attributed to the pigments as at 400 nm +and nothing is dropped; a partition built with `outside = UnassignedOutsideTable()` +has no excitation outside its table. Without a partition, all absorption within +`excitation_range` excites. With +[`Bricaud1998`](@ref) the absorption is the particulate absorption, detritus included, +and all of it enters the excitation. + `quantum_yield` (φ) has no default: in situ values range over roughly -0.01–0.05 (Loisel et al. 2023, who use HydroLight's 0.02). The default emission is Fluspect's chloroplast-level spectrum -([`chloroplast_emission`](@ref)), the default excitation window PAR. +0.01–0.05 (Loisel et al. 2023, who use HydroLight's 0.02). The default emission is +Fluspect's chloroplast-level spectrum ([`chloroplast_emission`](@ref)), the default +excitation window PAR. `phyto` must also be a constituent of every layer the process is in; see [`layer_optics`](@ref). @@ -258,9 +285,10 @@ function chlorophyll_fluorescence(phyto::Phytoplankton{FT}; quantum_yield::Real, carotenoid_transfer::Union{Nothing, Real} = nothing, phycobilin_transfer::Real = 1, + photoprotective_transfer::Real = 0, transfer::NamedTuple = NamedTuple(), emission::AbstractSpectralRedistribution{FT} = chloroplast_emission(FT), - excitation_range::Tuple{<:Real, <:Real} = (FT(400), FT(700)), + excitation_range::Tuple{<:Real, <:Real} = _PAR_RANGE_NM, ) where {FT<:AbstractFloat} parts = absorption_parts(phyto) for k in keys(transfer) @@ -278,6 +306,7 @@ function chlorophyll_fluorescence(phyto::Phytoplankton{FT}; class = pigment_class(phyto.pigments, part) class === :chlorophyll && return 1 class === :phycobilin && return phycobilin_transfer + class === :photoprotective_carotenoid && return photoprotective_transfer class === :unassigned && return 0 carotenoid_transfer === nothing && throw(ArgumentError("chlorophyll_fluorescence: choose the carotenoid energy " * @@ -348,6 +377,7 @@ emission(p::CDOMFluorescence, λ_prime::Real, λ::Real) = excitation_range(p::CDOMFluorescence) = p.excitation_range excitation_pathways(p::CDOMFluorescence) = (ExcitationPathway(p.cdom),) is_isotropic(::CDOMFluorescence) = true +conversion_units(::CDOMFluorescence) = PhotonConversion() quantum_yield(p::CDOMFluorescence) = p.quantum_yield function Base.show(io::IO, p::CDOMFluorescence{FT}) where {FT} diff --git a/src/inelastic/processes.jl b/src/inelastic/processes.jl index a64cbe1..d98128f 100644 --- a/src/inelastic/processes.jl +++ b/src/inelastic/processes.jl @@ -4,7 +4,7 @@ # # An inelastic source term couples *excitation* irradiance at wavelength # λ' into *emission* radiance at wavelength λ. In the Fell factorization -# (DESIGN §7.1, eq. 2.86–2.94), +# (Fell 1997, Eqs. 2.86–2.94), # # J^I(τ, μ, φ, λ) = (1/c(τ)) · ∫_{λ'} b^I(λ', λ) · ⟨L(λ')⟩_Ω # · p^I(cos θ; λ', λ) dλ' @@ -20,67 +20,135 @@ # # Concrete process types implement the three trait functions exported here. # -# Photon conventions (the contract a solver relies on): -# * a^I(λ') is a *photon* conversion rate: for fluorescence it already -# includes the quantum yield, a^I = φ·a_absorber; for Raman it is the -# Raman scattering coefficient b_R(λ'). Do not apply φ again. -# * f^I(λ', λ) redistributes photons, per nm of emission wavelength. -# * An energy (radiance) source therefore needs the photon-energy ratio -# λ'/λ: `radiance_source_kernel(p, λ', λ) = a^I f^I λ'/λ`. +# Conversion units (the contract a solver relies on): +# * Each process declares, through `conversion_units(p)`, whether a^I(λ') +# converts photons (`PhotonConversion`) or energy (`EnergyConversion`), +# and f^I(λ', λ) redistributes that same quantity per nm of emission +# wavelength, ∫ f^I dλ = 1. +# * Fluorescence is a photon conversion: a^I = φ·a_absorber already +# includes the quantum yield (photons per photon). Do not apply φ again. +# * Water Raman is an energy conversion by default: b_R(λ') E₀(λ') is the +# power emitted over the Raman band per unit volume and per nm of +# excitation wavelength (Mobley et al. 1993, Problem 7 and Appendix A). +# * `radiance_source_kernel` is the energy kernel and +# `inelastic_coefficient` the photon kernel; they differ by the +# photon-energy ratio λ'/λ, applied on the side that the convention of +# the process requires. # * The bundled water absorption models do not add a separate Raman loss; # whether b_R(λ') is added to the attenuation at λ' is the solver's # convention and must match the reference it is compared with. # # Note the scope: this file is *data and kernels only*. The two-pass # elastic→inelastic solve itself lives in the radiative-transfer -# machinery (vSmartMOM.jl; see DESIGN §2.2.9 and the `OceanRS` extension -# planned in §7.3). +# machinery (vSmartMOM.jl), which calls the kernels of this file. # ============================================================================= # AbstractOceanInelasticProcess is declared in `src/types/abstract_types.jl` # so that `OceanLayer` can reference it before this file is included. # This file provides the kernel interface only. +""" + AbstractConversionUnits + +Quantity that the conversion coefficient of an inelastic process counts: +[`PhotonConversion`](@ref) or [`EnergyConversion`](@ref). + +See [`conversion_units`](@ref). +""" +abstract type AbstractConversionUnits end + +""" + PhotonConversion() + +Conversion units of a process whose coefficient `a^I(λ′)` `[1/m]` counts photons: +`a^I(λ′) f^I(λ′, λ)` is the number of photons emitted per nm at `λ` per unit photon +fluence at `λ′`. + +The emitted energy carries the photon-energy ratio `λ′/λ`. Fluorescence, defined by a +quantum yield in photons per photon, is a photon conversion. +""" +struct PhotonConversion <: AbstractConversionUnits end + +""" + EnergyConversion() + +Conversion units of a process whose coefficient `a^I(λ′)` `[1/m]` counts energy: +`a^I(λ′) f^I(λ′, λ) E₀(λ′)` is the power emitted per unit volume and per nm at `λ` for +the spectral scalar irradiance `E₀(λ′)` `[W m⁻² nm⁻¹]`, with no photon-energy ratio. + +This is the definition of the Raman scattering coefficient `b_R` of Mobley et al. +(1993, Appl. Opt. 32, 7484; Problem 7 and Eqs. A3–A4), in which the radiance source is +`b_R E₀ / (4π)` times the angular and spectral distributions. +""" +struct EnergyConversion <: AbstractConversionUnits end + +""" + conversion_units(p::AbstractOceanInelasticProcess) -> AbstractConversionUnits + +Return whether the coefficient [`excitation_absorption`](@ref) of `p` converts photons +([`PhotonConversion`](@ref)) or energy ([`EnergyConversion`](@ref)). + +With `κ = excitation_absorption(p, λ′)` and `f = emission(p, λ′, λ)`, `∫ f dλ = 1`: + +| units | energy kernel [`radiance_source_kernel`](@ref) | photon kernel [`inelastic_coefficient`](@ref) | +|:------|:-----------|:-----------| +| `PhotonConversion` | `κ f λ′/λ` | `κ f` | +| `EnergyConversion` | `κ f` | `κ f λ/λ′` | + +# Implementation +Every concrete process defines a method; there is no default. +""" +function conversion_units end + +# Energy and photon kernels from the conversion kernel κ·f of a process. +_energy_kernel(::PhotonConversion, κf, λ_prime, λ) = κf * λ_prime / λ +_energy_kernel(::EnergyConversion, κf, λ_prime, λ) = κf +_photon_kernel(::PhotonConversion, κf, λ_prime, λ) = κf +_photon_kernel(::EnergyConversion, κf, λ_prime, λ) = κf * λ / λ_prime + """ excitation_absorption(p::AbstractOceanInelasticProcess, λ_prime) -> FT -Absorption-side coefficient `a^I(λ')` `[1/m]` in Fell's factorization -`b^I(λ', λ) = a^I(λ') · f^I(λ', λ)`. +Return the absorption-side coefficient `a^I(λ')` `[1/m]` of the factorization +`b^I(λ', λ) = a^I(λ') · f^I(λ', λ)` of Fell (1997). For fluorescence this is the quantum-yield-weighted absorption of the -fluorescing material (`φ · a_absorber(λ')`); for Raman it is the -Raman-scattering cross-section `b_w^R(λ')` taken in the "absorption -role" of the inelastic-source operator. +fluorescing material (`φ · a_absorber(λ')`), a photon conversion; for Raman it is the +Raman scattering coefficient `b_R(λ')`. [`conversion_units`](@ref) says whether the +coefficient counts photons or energy. """ function excitation_absorption end """ emission(p::AbstractOceanInelasticProcess, λ_prime, λ) -> FT -Spectral redistribution density of emitted *photons* `f^I(λ', λ)` -`[1/nm]` (per nm of emission wavelength), normalized so that -`∫ f(λ', λ) dλ = 1` over all emission wavelengths for every `λ'`. A finite -emission grid captures only part of this integral; the solver accounts for -the remainder. +Return the spectral redistribution density `f^I(λ', λ)` `[1/nm]` (per nm of emission +wavelength) of the quantity that `p` converts: photons for a +[`PhotonConversion`](@ref), energy for an [`EnergyConversion`](@ref). + +It is normalized so that `∫ f(λ', λ) dλ = 1` over all emission wavelengths for every +`λ'`. A finite emission grid captures only part of this integral; the solver accounts +for the remainder. """ function emission end """ excitation_range(p::AbstractOceanInelasticProcess) -> (λ_min, λ_max) -Wavelength window `[nm]` over which the excitation integral should be -taken. Outside this window `excitation_absorption` is understood to be -negligible, allowing integrators to skip unnecessary grid points. +Return the wavelength window `[nm]` over which the excitation integral is taken. + +Outside this window `excitation_absorption` is treated as negligible, so integrators can +skip those grid points. """ function excitation_range end """ is_isotropic(p::AbstractOceanInelasticProcess) -> Bool -Whether the process emits isotropically in angle. Isotropic emission -projects onto the `m = 0` azimuthal Fourier mode only, which the Fell -machinery exploits to halve the work. Fluorescence of solution-phase -molecules (chlorophyll, CDOM, most pigments) is isotropic; +Return whether the process emits isotropically in angle. + +Isotropic emission projects onto the `m = 0` azimuthal Fourier mode only. Fluorescence +of solution-phase molecules (chlorophyll, CDOM, most pigments) is isotropic; polarization-preserving Raman is not. """ is_isotropic(::AbstractOceanInelasticProcess) = true @@ -88,31 +156,42 @@ is_isotropic(::AbstractOceanInelasticProcess) = true """ inelastic_coefficient(p, λ_prime, λ) -> FT -Combined `b^I(λ', λ) = a^I(λ') · f^I(λ', λ)` `[1/m/nm]`, the kernel of -the excitation integral that an RT solver convolves against the -pass-1 scalar irradiance `E°(τ, λ')`. Default: the product of -[`excitation_absorption`](@ref) and [`emission`](@ref). Override only -if a process supplies a joint closed form cheaper than the product. +Return the photon kernel `K_N(λ', λ)` `[1/m/nm]`: photons emitted per nm at `λ` per unit +photon fluence at `λ'`. + +With `κ = excitation_absorption(p, λ')` and `f = emission(p, λ', λ)` it is `κ f` for a +[`PhotonConversion`](@ref) and `κ f λ/λ'` for an [`EnergyConversion`](@ref) +(see [`conversion_units`](@ref)). For fluorescence its integral over `λ` is +`φ Σ_k η_k a_k(λ')`. """ inelastic_coefficient(p::AbstractOceanInelasticProcess, λ_prime, λ) = - excitation_absorption(p, λ_prime) * emission(p, λ_prime, λ) + _photon_kernel(conversion_units(p), + excitation_absorption(p, λ_prime) * emission(p, λ_prime, λ), λ_prime, λ) """ radiance_source_kernel(p, λ_prime, λ) -> FT -Kernel `b^I(λ', λ) · λ'/λ` `[1/m/nm]` that converts excitation spectral -irradiance into emitted *energy*: for an isotropic process the volume -source of spectral radiance is +Return the energy kernel `K_E(λ', λ)` `[1/m/nm]` that converts excitation spectral +irradiance into emitted energy. + +The power emitted per unit volume and per nm at `λ` is `∫ K_E(λ', λ) E₀(λ') dλ'`, with +`E₀` the spectral scalar irradiance `[W m⁻² nm⁻¹]` (total intensity integrated over +solid angle, direct and diffuse). For an isotropic process the volume source of +spectral radiance is ```math -J(\\lambda) = \\frac{1}{4\\pi} \\int b^I(\\lambda', \\lambda) \\frac{\\lambda'}{\\lambda} E_0(\\lambda')\\, d\\lambda' +J(\\lambda) = \\frac{1}{4\\pi} \\int K_E(\\lambda', \\lambda) E_0(\\lambda')\\, d\\lambda' ``` -with `E₀` the spectral scalar irradiance `[W m⁻² nm⁻¹]` (total intensity -integrated over solid angle, direct and diffuse). [`inelastic_coefficient`](@ref) -is the photon kernel; the factor `λ'/λ` is the ratio of photon energies. +With `κ = excitation_absorption(p, λ')` and `f = emission(p, λ', λ)`, `K_E = κ f λ'/λ` +for a [`PhotonConversion`](@ref) (fluorescence; `λ'/λ` is the ratio of photon energies) +and `K_E = κ f` for an [`EnergyConversion`](@ref) (see [`conversion_units`](@ref)). For +the default [`WaterRaman`](@ref), an energy conversion, `∫ K_E dλ = b_R(λ')`. +[`inelastic_coefficient`](@ref) is the photon kernel `K_N = K_E λ/λ'`. + On a discrete grid the solver integrates with its own bin weights and, in wavenumber, the Jacobian `|dλ/dν| = 10⁷/ν²`. """ radiance_source_kernel(p::AbstractOceanInelasticProcess, λ_prime, λ) = - inelastic_coefficient(p, λ_prime, λ) * λ_prime / λ + _energy_kernel(conversion_units(p), + excitation_absorption(p, λ_prime) * emission(p, λ_prime, λ), λ_prime, λ) diff --git a/src/inelastic/raman.jl b/src/inelastic/raman.jl index 9fc7d1c..7092e5a 100644 --- a/src/inelastic/raman.jl +++ b/src/inelastic/raman.jl @@ -2,101 +2,146 @@ # Water Raman scattering as an inelastic process # ============================================================================= # -# In the inelastic-source formalism, water Raman is the one "scattering- -# that-shifts-wavelength" process in pure water. It has: +# Water Raman scattering (the O-H stretch band of liquid water) shifts light +# from the excitation wavenumber ν' to ν' − Δν. The process is described by # -# * a fixed Stokes shift `Δν ≈ 3400 cm⁻¹` between excitation and -# emission wavenumbers (the symmetric O-H stretch of liquid water), -# * a Gaussian-like emission band of width ~200 cm⁻¹ FWHM (σ_ν ≈ 85 -# cm⁻¹) at a given excitation, -# * a wavelength-dependent scattering cross-section -# `b_w^R(λ') = b_R(λ_ref) · (λ_ref / λ')^n` with `n ≈ 5.5` per -# Haltrin & Kattawar (1991, Appl. Opt. 30, 630; 1993, Appl. Opt. 32, -# 5356) and Bartlett et al. (1998, JGR 103, 17875), -# * a Cabannes-depolarized phase function (anisotropic Rayleigh-like). +# * the Stokes shift Δν and a Gaussian band of standard deviation σ_ν in +# wavenumber, +# * the Raman scattering coefficient b_R(λ') = b_R(λ_ref)·(λ_ref/λ')^n, +# * the convention of b_R (energy or photon conversion, a type parameter), +# * a Rayleigh-type phase function set by the depolarization ratio ρ. # -# In Fell's factorization the Raman cross-section plays the role of -# `a^I(λ')` in `b^I = a^I · f^I`, i.e. the "absorption-equivalent" that -# removes photons from the excitation field and deposits them in the -# emission band. +# In Fell's factorization b_R takes the role of a^I(λ') in b^I = a^I · f^I. # ============================================================================= """ $(TYPEDEF) -Water Raman scattering as an inelastic process. Emission spectrum is a -Gaussian in wavenumber centred at `ν' − shift_cm_inv`; cross-section -follows a Haltrin-Kattawar power law. +Water Raman scattering as an inelastic process: a Gaussian emission band in wavenumber +centred at `ν' − shift_cm_inv`, with the scattering coefficient + +``b_R(λ') = b_R(λ_\\mathrm{ref}) (λ_\\mathrm{ref}/λ')^n`` `[1/m]`. + +# Convention of `b_R` + +The type parameter `U` (field `conversion`) states what `b_R` converts +(see [`conversion_units`](@ref)): + +- [`EnergyConversion`](@ref) (default): `b_R(λ') E₀(λ')` is the power emitted over the + whole Raman band per unit volume and per nm of excitation wavelength. The energy + kernel is `K_E(λ', λ) = b_R(λ') f_R(λ', λ)` with `∫ K_E dλ = b_R(λ')`, and the photon + kernel is `K_N = K_E λ/λ'`. This is the definition of Mobley et al. (1993, Appl. Opt. + 32, 7484), whose Problem 7 source is `b_R E₀/(4π)` for the 417 → 486 nm transfer. +- [`PhotonConversion`](@ref): `b_R` counts photons, `K_N = b_R f_R` with + `∫ K_N dλ = b_R(λ')`, and `K_E = K_N λ'/λ`. Its energy source is 12 % (excitation at + 350 nm) to 24 % (700 nm) below that of the energy convention for the same `b_R`. + +# Angular distribution + +``p_R(\\cos Θ) = \\frac{1}{4π}\\left[1 + β_2 P_2(\\cos Θ)\\right]``, +``β_2 = \\frac{1 - ρ}{2 (1 + 2ρ)}`` + +(Mobley et al. 1993, Eq. 9), with `ρ = linear_depolarization` the depolarization ratio +for linearly polarized excitation; `β₂ = 0.3097` for `ρ = 0.17`. See +[`raman_phase`](@ref) for the phase function and phase matrix. # Fields $(TYPEDFIELDS) -# Construction - -```julia -# Default: Haltrin-Kattawar/Bartlett parameterization -WaterRaman{Float64}() - -# Customize (e.g. with Bartlett salt- and temperature-aware values) -WaterRaman{Float64}( - shift_cm_inv = 3400.0, - σ_cm_inv = 85.0, - cross_section_ref = 2.7e-4, # 1/m at reference wavelength - cross_section_λ_ref = 488.0, # nm - cross_section_n = 5.5, - depolarization = 0.14, # Cabannes ρ for liquid water - excitation_range = (350.0, 700.0), -) +# Parameters and their sources + +| field | default | source | +|:------|:--------|:-------| +| `shift_cm_inv`, `σ_cm_inv` | 3400, 85 cm⁻¹ | single-Gaussian band attributed to Haltrin & Kattawar (1993, Appl. Opt. 32, 5356) | +| `cross_section_ref` at `cross_section_λ_ref` | 2.7·10⁻⁴ m⁻¹ at 488 nm | attributed to Bartlett et al. (1998, JGR 103, 17875); the HydroLight runs of Loisel et al. (2023) are reproduced with 2.6·10⁻⁴ m⁻¹ | +| `cross_section_n` | 5.5 | attributed to Bartlett et al. (1998), for `b_R` in energy units | +| `linear_depolarization` | 0.17 | Mobley et al. (1993), Eq. 9 and Problem 7 | +| `excitation_range` | (350, 700) nm | choice of this package; emission then starts at 397 nm | + +# Examples +```jldoctest +julia> ram = WaterRaman(); + +julia> conversion_units(ram) +EnergyConversion() + +julia> round(excitation_absorption(ram, 417.0); sigdigits = 4) +0.0006411 + +julia> WaterRaman(conversion = PhotonConversion()) isa WaterRaman{Float64, PhotonConversion} +true ``` """ -struct WaterRaman{FT<:AbstractFloat} <: AbstractOceanInelasticProcess{FT} +struct WaterRaman{FT<:AbstractFloat, U<:AbstractConversionUnits} <: AbstractOceanInelasticProcess{FT} "Stokes shift between excitation and emission wavenumbers `[1/cm]`" shift_cm_inv::FT - "Gaussian standard deviation in wavenumber space `[1/cm]`" + "Gaussian standard deviation of the emission band in wavenumber `[1/cm]`" σ_cm_inv::FT - "Raman cross-section `b_w^R` at the reference wavelength `[1/m]`" + "Raman scattering coefficient `b_R` at the reference wavelength `[1/m]`" cross_section_ref::FT - "Reference wavelength for the cross-section power law `[nm]`" + "Reference wavelength of the power law `[nm]`" cross_section_λ_ref::FT - "Exponent `n` in `b_w^R(λ') = b_ref · (λ_ref / λ')^n`" + "Exponent `n` of `b_R(λ') = b_ref (λ_ref / λ')^n`" cross_section_n::FT - "Cabannes depolarization ratio ρ_Cab (≈ 0.14 for liquid water)" - depolarization::FT + "Depolarization ratio `ρ` for linearly polarized excitation, observed at 90°" + linear_depolarization::FT "Excitation-wavelength integration window `[nm]`" excitation_range::Tuple{FT, FT} + "Quantity that `b_R` converts: `EnergyConversion()` or `PhotonConversion()`" + conversion::U end """ WaterRaman{FT}(; shift_cm_inv=3400, σ_cm_inv=85, cross_section_ref=2.7e-4, cross_section_λ_ref=488, - cross_section_n=5.5, depolarization=0.14, - excitation_range=(350, 700)) + cross_section_n=5.5, linear_depolarization=0.17, + excitation_range=(350, 700), conversion=EnergyConversion()) + +Construct the water Raman process; `WaterRaman(; ...)` is `WaterRaman{Float64}(; ...)`. + +# Arguments +- `shift_cm_inv`: Stokes shift `[1/cm]`. +- `σ_cm_inv`: standard deviation of the Gaussian band `[1/cm]`, positive. +- `cross_section_ref`: `b_R` `[1/m]` at `cross_section_λ_ref` `[nm]`, non-negative. +- `cross_section_n`: exponent of the power law. +- `linear_depolarization`: depolarization ratio `ρ` for linearly polarized excitation, + in `[0, 3/4]`; the natural-light ratio is `ρ_n = 2ρ/(1+ρ)`. +- `excitation_range`: `(lo, hi)` `[nm]`. +- `conversion`: [`EnergyConversion`](@ref)`()` or [`PhotonConversion`](@ref)`()`. """ function WaterRaman{FT}(; - shift_cm_inv = FT(3400.0), - σ_cm_inv = FT(85.0), + shift_cm_inv = FT(_OH_STRETCH_SHIFT_CM_INV), + σ_cm_inv = FT(_OH_STRETCH_SIGMA_CM_INV), cross_section_ref = FT(2.7e-4), cross_section_λ_ref = FT(488.0), cross_section_n = FT(5.5), - depolarization = FT(0.14), + linear_depolarization = FT(0.17), excitation_range::Tuple{<:Real, <:Real} = (FT(350), FT(700)), + conversion::AbstractConversionUnits = EnergyConversion(), ) where {FT<:AbstractFloat} FT(σ_cm_inv) > zero(FT) || throw(ArgumentError("WaterRaman: σ_cm_inv must be positive, got $σ_cm_inv")) FT(cross_section_ref) ≥ zero(FT) || throw(ArgumentError("WaterRaman: cross_section_ref must be non-negative, got $cross_section_ref")) - zero(FT) ≤ FT(depolarization) < one(FT) || - throw(ArgumentError("WaterRaman: depolarization must be in [0, 1), got $depolarization")) + FT(cross_section_λ_ref) > zero(FT) || + throw(ArgumentError("WaterRaman: cross_section_λ_ref must be positive, got $cross_section_λ_ref")) + # ρ = 3/4 is the largest ratio a Raman band can have (fully depolarized line). + zero(FT) ≤ FT(linear_depolarization) ≤ FT(0.75) || + throw(ArgumentError("WaterRaman: linear_depolarization (the ratio for linearly " * + "polarized excitation) must be in [0, 3/4], got " * + "$linear_depolarization; a natural-light ratio ρ_n converts as " * + "ρ = ρ_n/(2 − ρ_n)")) excitation_range[1] < excitation_range[2] || throw(ArgumentError("WaterRaman: excitation_range must be (lo < hi)")) - return WaterRaman{FT}( + return WaterRaman{FT, typeof(conversion)}( FT(shift_cm_inv), FT(σ_cm_inv), FT(cross_section_ref), FT(cross_section_λ_ref), FT(cross_section_n), - FT(depolarization), - (FT(excitation_range[1]), FT(excitation_range[2]))) + FT(linear_depolarization), + (FT(excitation_range[1]), FT(excitation_range[2])), + conversion) end WaterRaman(; kwargs...) = WaterRaman{Float64}(; kwargs...) @@ -105,17 +150,19 @@ WaterRaman(; kwargs...) = WaterRaman{Float64}(; kwargs...) # Trait implementations # ----------------------------------------------------------------------------- +conversion_units(p::WaterRaman) = p.conversion + """ excitation_absorption(p::WaterRaman, λ_prime) -> FT -Raman "absorption-role" cross-section at excitation wavelength `λ'`, -using the Haltrin-Kattawar power law +Return the Raman scattering coefficient `[1/m]` at excitation wavelength `λ'` `[nm]`, ``` -b_w^R(λ') = b_ref · (λ_ref / λ')^n +b_R(λ') = b_ref · (λ_ref / λ')^n ``` -in units of `[1/m]`. +an energy or a photon conversion coefficient according to +[`conversion_units`](@ref)`(p)`. """ excitation_absorption(p::WaterRaman, λ_prime::Real) = p.cross_section_ref * (p.cross_section_λ_ref / λ_prime)^p.cross_section_n @@ -123,45 +170,86 @@ excitation_absorption(p::WaterRaman, λ_prime::Real) = """ emission(p::WaterRaman, λ_prime, λ) -> FT -Gaussian redistribution in wavenumber space centered at `ν' − shift`, -evaluated against the Jacobian `|dν/dλ| = 10⁷/λ²` so that -`∫ f(λ', λ) dλ = 1`. +Return the Raman redistribution density `[1/nm]`: a Gaussian in wavenumber centered at +`ν' − shift`, times the Jacobian `|dν/dλ| = 10⁷/λ²` so that `∫ f(λ', λ) dλ = 1`. """ emission(p::WaterRaman{FT}, λ_prime::Real, λ::Real) where {FT} = - redistribution(WavenumberShiftEmission{FT}(p.shift_cm_inv, p.σ_cm_inv), - λ_prime, λ) + convert(_result_type(FT, λ_prime, λ), + _wavenumber_shift_density(_wide(p.shift_cm_inv), _wide(p.σ_cm_inv), + _wide(λ_prime), _wide(λ))) excitation_range(p::WaterRaman) = p.excitation_range """ is_isotropic(p::WaterRaman) -> Bool -Water Raman is Cabannes-depolarized: the re-emitted angular -distribution is Rayleigh-like with depolarization `ρ_Cab ≈ 0.14`. -Strictly, that is not isotropic, so we report `false`. Solvers -targeting scalar RT can still project onto the `m = 0` mode with a -small (sub-percent) error. +Return `false`: water Raman emission follows the Rayleigh-type phase function of +[`raman_phase`](@ref). """ is_isotropic(p::WaterRaman) = false +""" + natural_depolarization(p::WaterRaman) -> FT + +Return the depolarization ratio for unpolarized (natural) excitation, +`ρ_n = 2ρ/(1 + ρ)`, with `ρ = p.linear_depolarization` the ratio for linearly polarized +excitation. + +`ρ_n = 0.2906` for the default `ρ = 0.17`. `ρ_n` is the ratio that +[`RayleighWaterPhase`](@ref) takes. +""" +natural_depolarization(p::WaterRaman) = + 2 * p.linear_depolarization / (1 + p.linear_depolarization) + +""" + raman_phase(p::WaterRaman) -> RayleighWaterPhase + +Return the angular distribution of Raman emission as the Rayleigh-type phase function +with the natural-light depolarization ratio [`natural_depolarization`](@ref)`(p)`. + +In the normalization of this package (`½ ∫ p dμ = 1`) it is + +``p(\\cos Θ) = 1 + β_2 P_2(\\cos Θ)``, +``β_2 = \\frac{1 - ρ_n}{2 + ρ_n} = \\frac{1 - ρ}{2 (1 + 2ρ)}`` + +which is `4π` times Eq. 9 of Mobley et al. (1993), +`(3/16π) (1+3ρ)/(1+2ρ) [1 + (1−ρ)/(1+3ρ) cos²Θ]`. `phase_function_value`, +`phase_function_moments` and `greek_expansion(...; polarized = true)` of the returned +object give the phase function, its Legendre moments and the Greek coefficients of the +phase matrix (the Rayleigh matrix with depolarization `ρ_n`). + +# Examples +```jldoctest +julia> round(phase_function_moments(raman_phase(WaterRaman()), 2)[3]; digits = 4) +0.3097 +``` +""" +raman_phase(p::WaterRaman{FT}) where {FT} = + RayleighWaterPhase{FT}(depolarization = natural_depolarization(p)) + function Base.show(io::IO, p::WaterRaman{FT}) where {FT} print(io, "WaterRaman{$FT}(Δν=", p.shift_cm_inv, " 1/cm, σ=", p.σ_cm_inv, " 1/cm, b_R(", Int(round(p.cross_section_λ_ref)), ")=", - p.cross_section_ref, " 1/m)") + p.cross_section_ref, " 1/m, ", nameof(typeof(p.conversion)), ")") end """ raman_peak_wavelength(p::WaterRaman, λ_prime::Real) -> FT -Emission-peak wavelength `[nm]` for excitation at `λ_prime`: +Return the wavelength `[nm]` of the emission peak for excitation at `λ_prime` `[nm]`: ``` ν_emission = ν' - Δν, λ_peak = 10⁷ / ν_emission ``` -Diagnostic helper — for `λ' = 440 nm` and the default `Δν = 3400 cm⁻¹` -this returns ≈ 491 nm. +with wavenumbers in `1/cm`. + +# Examples +```jldoctest +julia> round(raman_peak_wavelength(WaterRaman(), 440.0); digits = 1) +517.4 +``` """ -raman_peak_wavelength(p::WaterRaman, λ_prime::Real) = - 1e7 / (1e7 / λ_prime - p.shift_cm_inv) +raman_peak_wavelength(p::WaterRaman{FT}, λ_prime::Real) where {FT} = + convert(_result_type(FT, λ_prime), 1e7 / (1e7 / _wide(λ_prime) - _wide(p.shift_cm_inv))) diff --git a/src/inelastic/redistribution.jl b/src/inelastic/redistribution.jl index f62accf..0c1851e 100644 --- a/src/inelastic/redistribution.jl +++ b/src/inelastic/redistribution.jl @@ -2,8 +2,8 @@ # Spectral redistribution functions f^I(λ', λ) # ============================================================================= # -# In Fell's (1997) factorization of an inelastic source operator (DESIGN -# §7.1), +# In Fell's (1997) factorization of an inelastic source operator (his +# Eqs. 2.86–2.94), # # b^I(τ; λ', λ) = a^I(τ; λ') · f^I(λ', λ) # @@ -48,9 +48,10 @@ abstract type AbstractSpectralRedistribution{FT<:AbstractFloat} end """ redistribution(r, λ_prime, λ) -> FT -Evaluate the redistribution density `f(λ', λ)` `[1/nm]`. Must be -normalized so `∫ f(λ', λ) dλ = 1` for every `λ'` inside the -physically meaningful range of `r`. +Evaluate the redistribution density `f(λ', λ)` `[1/nm]` of `r`. + +A method must be normalized so that `∫ f(λ', λ) dλ = 1` for every `λ'` in the range +where `r` applies. """ function redistribution end @@ -95,13 +96,13 @@ GaussianEmission{FT}(; center_nm = FT(685.0), σ_nm = FT(10.6)) where {FT<:Abstr GaussianEmission{FT}(FT(center_nm), FT(σ_nm)) GaussianEmission(; kwargs...) = GaussianEmission{Float64}(; kwargs...) -function redistribution(r::GaussianEmission, λ_prime::Real, λ::Real) +function redistribution(r::GaussianEmission{FT}, λ_prime::Real, λ::Real) where {FT} # `λ_prime` is unused — the emission shape is excitation-independent for # this redistribution class. Keeping it in the signature matches the # abstract contract so callers can dispatch uniformly. - σ = r.σ_nm - μ = r.center_nm - return inv(σ * sqrt(2π)) * exp(-((λ - μ) / σ)^2 / 2) + σ = _wide(r.σ_nm) + μ = _wide(r.center_nm) + return convert(_result_type(FT, λ), inv(σ * sqrt(2π)) * exp(-((_wide(λ) - μ) / σ)^2 / 2)) end # ----------------------------------------------------------------------------- @@ -171,11 +172,14 @@ function TabulatedEmission(λ::AbstractVector{<:Real}, shape::AbstractVector{<:R return TabulatedEmission{FT}(x, y ./ area, String(source)) end -_trapezoid(x, y) = sum((x[i+1] - x[i]) * (y[i] + y[i+1]) / 2 for i in 1:length(x)-1) +function _trapezoid(x, y) + Base.require_one_based_indexing(x, y) + return sum((x[i+1] - x[i]) * (y[i] + y[i+1]) / 2 for i in 1:length(x)-1) +end function redistribution(r::TabulatedEmission, λ_prime::Real, λ::Real) x, y = r.λ, r.density - first(x) ≤ λ ≤ last(x) || return zero(promote_type(eltype(y), typeof(float(λ)))) + _within(λ, first(x), last(x)) || return zero(promote_type(eltype(y), typeof(float(λ)))) i = clamp(searchsortedlast(x, λ), 1, length(x) - 1) t = (λ - x[i]) / (x[i+1] - x[i]) return (1 - t) * y[i] + t * y[i+1] @@ -227,18 +231,28 @@ struct WavenumberShiftEmission{FT<:AbstractFloat} <: AbstractSpectralRedistribut end end -WavenumberShiftEmission{FT}(; shift_cm_inv = FT(3400.0), - σ_cm_inv = FT(85.0)) where {FT<:AbstractFloat} = +# O–H stretch band of liquid water as a single Gaussian (attributed to Haltrin & +# Kattawar 1993): Stokes shift and standard deviation [1/cm]. Shared by the defaults +# of `WavenumberShiftEmission` and `WaterRaman`. +const _OH_STRETCH_SHIFT_CM_INV = 3400.0 +const _OH_STRETCH_SIGMA_CM_INV = 85.0 + +WavenumberShiftEmission{FT}(; shift_cm_inv = FT(_OH_STRETCH_SHIFT_CM_INV), + σ_cm_inv = FT(_OH_STRETCH_SIGMA_CM_INV)) where {FT<:AbstractFloat} = WavenumberShiftEmission{FT}(FT(shift_cm_inv), FT(σ_cm_inv)) WavenumberShiftEmission(; kwargs...) = WavenumberShiftEmission{Float64}(; kwargs...) -function redistribution(r::WavenumberShiftEmission, λ_prime::Real, λ::Real) - # Convert wavelengths to wavenumbers, evaluate Gaussian, then apply the - # |dν/dλ| = 10⁷/λ² Jacobian so ∫ f(λ',λ) dλ = 1 holds in wavelength space. +redistribution(r::WavenumberShiftEmission{FT}, λ_prime::Real, λ::Real) where {FT} = + convert(_result_type(FT, λ_prime, λ), + _wavenumber_shift_density(_wide(r.shift_cm_inv), _wide(r.σ_cm_inv), + _wide(λ_prime), _wide(λ))) + +# Gaussian in wavenumber around the shifted excitation wavenumber, times the +# |dν/dλ| = 10⁷/λ² Jacobian so that ∫ f(λ′, λ) dλ = 1 in wavelength space. +function _wavenumber_shift_density(shift, σ, λ_prime, λ) ν_prime = 1e7 / λ_prime ν = 1e7 / λ - ν_center = ν_prime - r.shift_cm_inv - σ = r.σ_cm_inv + ν_center = ν_prime - shift g_ν = inv(σ * sqrt(2π)) * exp(-((ν - ν_center) / σ)^2 / 2) return g_ν * (1e7 / λ^2) end @@ -247,5 +261,16 @@ end # Convenience: FWHM ↔ σ conversion (useful for user-facing constructors) # ----------------------------------------------------------------------------- -"Convert Gaussian FWHM `[nm or 1/cm]` to standard deviation in the same unit." +""" + fwhm_to_sigma(fwhm) + +Convert the full width at half maximum of a Gaussian to its standard deviation, +`σ = FWHM / (2 √(2 ln 2))`, in the unit of `fwhm`. + +# Examples +```jldoctest +julia> round(fwhm_to_sigma(25.0); digits = 3) +10.617 +``` +""" fwhm_to_sigma(fwhm::Real) = fwhm / (2 * sqrt(2 * log(2))) diff --git a/src/io/data_loaders.jl b/src/io/data_loaders.jl index 535017d..25b6fb0 100644 --- a/src/io/data_loaders.jl +++ b/src/io/data_loaders.jl @@ -3,67 +3,118 @@ # ============================================================================= # # All tabulated optical data in OceanOptics.jl is loaded from the `data/` -# directory as provenance-commented CSV files (see DESIGN §3.4). Every file +# directory as provenance-commented CSV files. Every file # opens with a comment block giving the source citation, DOI, download URL # and date, the spectral range and resolution, and the units of the stored # values. `load_spectral_csv` strips those comments and returns a typed -# `SpectralTable`; `linterp` performs piecewise-linear interpolation via -# `Interpolations.jl`'s `linear_interpolation` with `Flat()` boundary -# extrapolation (AD-transparent: ForwardDiff `Dual` inputs propagate -# through the interior and receive zero partials outside the grid). +# `SpectralTable`; `linterp` interpolates it linearly and never beyond its +# range. # ============================================================================= """ $(TYPEDEF) -Tabulated spectral quantity `y(λ)` with monotone `λ` axis, backed by an -`Interpolations.linear_interpolation` object for efficient repeated -queries. Columns are always named `λ` and `y` regardless of the physical -quantity stored; the unit interpretation is fixed by the loader's -provenance header and by the consumer that dispatches on it. +Tabulated spectral quantity `y(λ)` on a strictly increasing wavelength +grid, for piecewise-linear interpolation with [`linterp`](@ref). Columns +are always named `λ` and `y` regardless of the physical quantity stored; +the unit interpretation is fixed by the loader's provenance header and by +the consumer that dispatches on it. + +`SpectralTable(λ, y)` checks the grid and stores dense vectors of the +promoted floating-point type. The two vectors share the array type `V`, +and `Adapt.adapt(to, tbl)` moves them to a device; the range limits `lo` +and `hi` are stored as numbers, so a range check never reads a device +array. # Fields $(TYPEDFIELDS) """ -struct SpectralTable{T<:AbstractFloat, I} - "Wavelengths `[nm]`, sorted ascending." - λ::Vector{T} +struct SpectralTable{T<:AbstractFloat, V<:AbstractVector{T}} + "Wavelengths `[nm]`, strictly increasing." + λ::V "Tabulated value at each λ (units fixed by consumer)." - y::Vector{T} - "Cached `Interpolations.jl` linear interpolant (queries are range-checked by `linterp`)." - itp::I + y::V + "First tabulated wavelength `[nm]`." + lo::T + "Last tabulated wavelength `[nm]`." + hi::T + + # Stores its arguments as they are; `SpectralTable(λ, y)` validates. + SpectralTable{T, V}(λ, y, lo, hi) where {T<:AbstractFloat, V<:AbstractVector{T}} = + new{T, V}(λ, y, lo, hi) end -function SpectralTable(λ::Vector{T}, y::Vector{T}) where {T<:AbstractFloat} +function SpectralTable(λ::AbstractVector{<:Real}, y::AbstractVector{<:Real}) + T = float(promote_type(eltype(λ), eltype(y))) length(λ) == length(y) || - throw(ArgumentError("SpectralTable: λ and y must have equal length")) + throw(DimensionMismatch("SpectralTable: $(length(λ)) wavelengths for $(length(y)) values")) length(λ) ≥ 2 || throw(ArgumentError("SpectralTable: need at least two points for interpolation")) - issorted(λ) || - throw(ArgumentError("SpectralTable: λ must be sorted ascending")) - itp = linear_interpolation(λ, y; extrapolation_bc = Flat()) - return SpectralTable{T, typeof(itp)}(λ, y, itp) + x, v = _dense(T, λ), _dense(T, y) + Base.require_one_based_indexing(x, v) + all(isfinite, x) || throw(ArgumentError("SpectralTable: wavelengths must be finite")) + all(isfinite, v) || throw(ArgumentError("SpectralTable: values must be finite")) + _is_strictly_increasing(x) || + throw(ArgumentError("SpectralTable: λ must be strictly increasing; sort the table " * + "and merge repeated wavelengths")) + lo, hi = extrema(x) + return SpectralTable{T, typeof(x)}(x, v, lo, hi) +end + +function Adapt.adapt_structure(to, t::SpectralTable{T}) where {T} + λ = adapt(to, t.λ) + _check_adapt_eltype(to, T, λ) + return SpectralTable{T, typeof(λ)}(λ, adapt(to, t.y), t.lo, t.hi) end Base.length(t::SpectralTable) = length(t.λ) function Base.show(io::IO, t::SpectralTable{T}) where {T} - print(io, "SpectralTable{$T}(", length(t), " pts, λ ∈ [", - first(t.λ), ", ", last(t.λ), "])") + print(io, "SpectralTable{$T}(", length(t), " pts, λ ∈ [", t.lo, ", ", t.hi, "])") +end + +# Linear interpolant of the table at `x`, without a range check: outside +# [lo, hi] the first or last segment is continued. A tabulated wavelength +# other than the first belongs to the segment that ends there; both +# segments give the tabulated value. Reads four elements, so it runs per +# element inside a broadcast on the device that holds the table. +function _interpolate(t::SpectralTable, x) + λ, y = t.λ, t.y + i = clamp(searchsortedfirst(λ, x) - 1, firstindex(λ), lastindex(λ) - 1) + f = (x - λ[i]) / (λ[i+1] - λ[i]) + return (1 - f) * y[i] + f * y[i+1] end +_throw_outside_table(t::SpectralTable, x) = + throw(DomainError(x, "outside the tabulated range $(t.lo)–$(t.hi) nm")) + """ - linterp(tbl::SpectralTable, x) -> value + linterp(tbl::SpectralTable, x) + +Return the piecewise-linear interpolant of `tbl.y` at the wavelength or vector of +wavelengths `x` `[nm]`. + +Throws a `DomainError` outside `[tbl.lo, tbl.hi]`: a table never supplies values +beyond its data. A `ForwardDiff.Dual` wavelength gives the slope of the +segment as derivative. At a tabulated wavelength the interpolant has a +kink, and the derivative is the slope of one of the two segments that +meet there, whichever the number type's ordering against the tabulated +value selects. -Piecewise-linear interpolation of `tbl.y` at wavelength `x`, delegating -to `Interpolations.jl`. Throws a `DomainError` outside -`[tbl.λ[1], tbl.λ[end]]`: a table never supplies values beyond its data. -ForwardDiff `Dual` inputs propagate through the interpolation. +The vector method checks the range of `x` once and interpolates in one +broadcast; `tbl` and `x` must live on the same device. """ -function linterp(tbl::SpectralTable, x) - first(tbl.λ) ≤ x ≤ last(tbl.λ) || - throw(DomainError(x, "outside the tabulated range $(first(tbl.λ))–$(last(tbl.λ)) nm")) - return tbl.itp(x) +function linterp(tbl::SpectralTable, x::Real) + _within(x, tbl.lo, tbl.hi) || _throw_outside_table(tbl, x) + return _interpolate(tbl, x) +end + +function linterp(tbl::SpectralTable, x::AbstractVector{<:Real}) + isempty(x) && return _interpolate.(Ref(tbl), x) + xmin, xmax = extrema(x) + _within(xmin, tbl.lo, tbl.hi) || _throw_outside_table(tbl, xmin) + _within(xmax, tbl.lo, tbl.hi) || _throw_outside_table(tbl, xmax) + return _interpolate.(Ref(tbl), x) end # ============================================================================= @@ -73,9 +124,8 @@ end """ data_path(filename) -> String -Absolute path to `filename` under the package's bundled `data/` directory. -Used both by the materials code (to load shipped tables at module init) -and by the `scripts/fetch_data.jl` reproducibility script. +Return the absolute path of `filename` in the `data/` directory bundled with the +package. """ data_path(filename::AbstractString) = normpath(joinpath(@__DIR__, "..", "..", "data", filename)) @@ -83,7 +133,8 @@ data_path(filename::AbstractString) = """ load_spectral_csv(path; col_λ=1, col_y=2) -> SpectralTable{Float64} -Parse a provenance-commented CSV and return a sorted `SpectralTable`. +Parse a provenance-commented CSV and return a [`SpectralTable`](@ref) sorted by +wavelength. Recognized structure: * Comment lines begin with `#` and are discarded. @@ -117,7 +168,7 @@ function load_spectral_csv(path::AbstractString; col_λ::Int = 1, col_y::Int = 2 isempty(λs) && throw(ArgumentError("No numeric rows parsed from $path")) - # Guarantee sorted output for downstream searchsortedlast. + # `SpectralTable` needs an increasing grid. if !issorted(λs) perm = sortperm(λs) λs .= λs[perm] @@ -156,11 +207,16 @@ end # ----------------------------------------------------------------------------- # # Tabulated benchmark inputs are defined only at their published -# wavelengths. These helpers validate such grids and look wavelengths up -# exactly — to a few ulps of the less precise of table and query, so that -# range-generated grids such as `400:0.1:500` and Float32 queries of a -# Float64 table still match. Any other wavelength is an error rather than -# an interpolation. +# wavelengths. These helpers validate such grids and match a query λ to the +# tabulated wavelength λ_tab with |λ − λ_tab| ≤ `_λ_MATCH_RTOL`·λ_tab. The +# tolerance covers the round-off of single-precision wavelengths (a few +# 1e-7), of grids computed as 1e7/ν from wavenumbers, and of range-generated +# grids such as `400:0.1:500`; it is far below the spacing of any published +# table. Any other wavelength is an error unless the table's owner +# interpolates explicitly. + +"Relative tolerance of the match between a query wavelength and a tabulated one." +const _λ_MATCH_RTOL = 1e-6 function _check_exact_λ_grid(λ::AbstractVector{<:Real}, who::AbstractString) isempty(λ) && throw(ArgumentError("$who: empty wavelength grid")) @@ -168,20 +224,96 @@ function _check_exact_λ_grid(λ::AbstractVector{<:Real}, who::AbstractString) throw(ArgumentError("$who: wavelengths must be finite and positive")) _is_strictly_increasing(λ) || throw(ArgumentError("$who: wavelengths must be strictly increasing")) + # Farther apart than twice the match tolerance: a query matches at most one. + all(i -> λ[i+1] - λ[i] > 2 * _λ_MATCH_RTOL * λ[i+1], firstindex(λ):lastindex(λ)-1) || + throw(ArgumentError("$who: neighbouring wavelengths must differ by more than " * + "$(2 * _λ_MATCH_RTOL) of their value (the wavelength-match " * + "tolerance); check the table for duplicated rows")) return nothing end -function _exact_λ_index(λ_tab::AbstractVector{FT}, λ::Real, - who::AbstractString) where {FT} - i = searchsortedfirst(λ_tab, λ) - tol = 8 * _λ_match_eps(FT, λ) +# Index of the tabulated wavelength that matches `λ`, or `nothing`. +function _matching_λ_index(λ_tab::AbstractVector, λ::Real) + i = searchsortedfirst(λ_tab, λ) for k in (i - 1, i) - checkbounds(Bool, λ_tab, k) && abs(λ_tab[k] - λ) ≤ tol * λ_tab[k] && return k + checkbounds(Bool, λ_tab, k) && abs(λ_tab[k] - λ) ≤ _λ_MATCH_RTOL * λ_tab[k] && return k + end + return nothing +end + +function _exact_λ_index(λ_tab::AbstractVector, λ::Real, who::AbstractString) + k = _matching_λ_index(λ_tab, λ) + k === nothing || return k + shown = string(join(first(λ_tab, 8), ", "), length(λ_tab) > 8 ? ", …" : "") + throw(ArgumentError("$who: λ = $λ nm is not a tabulated wavelength (tabulated: $shown; " * + "match tolerance $(_λ_MATCH_RTOL) relative); this table is not " * + "interpolated")) +end + +""" +$(TYPEDEF) + +How a table defined at discrete wavelengths answers a query between them. + +[`ExactLookup`](@ref) admits tabulated wavelengths only, [`LinearLookup`](@ref) +interpolates linearly between neighbours and [`NearestLookup`](@ref) takes the nearest +entry. Constructors accept the names `:exact`, `:linear` and `:nearest` for them. +""" +abstract type AbstractTableLookup end + +""" +$(TYPEDEF) + +Table lookup that admits tabulated wavelengths only (to a relative `1e-6`); any other +wavelength throws. +""" +struct ExactLookup <: AbstractTableLookup end + +""" +$(TYPEDEF) + +Table lookup that interpolates linearly between neighbouring tabulated wavelengths, +never beyond the table. +""" +struct LinearLookup <: AbstractTableLookup end + +""" +$(TYPEDEF) + +Table lookup that uses the entry of the nearest tabulated wavelength. +""" +struct NearestLookup <: AbstractTableLookup end + +_lookup_name(::ExactLookup) = :exact +_lookup_name(::LinearLookup) = :linear +_lookup_name(::NearestLookup) = :nearest + +# The lookup named by `lookup` (a name or a lookup object), which must be one of +# the instances in `allowed`. +function _table_lookup(lookup, allowed::Tuple, who::AbstractString) + for l in allowed + (lookup === l || lookup === _lookup_name(l)) && return l end - shown = join(first(λ_tab, 8), ", ") * (length(λ_tab) > 8 ? ", …" : "") - throw(ArgumentError("$who: λ = $λ nm is not a tabulated wavelength " * - "(tabulated: $shown); exact-wavelength tables are not interpolated")) + throw(ArgumentError("$who: lookup must be " * + join((":$(_lookup_name(l))" for l in allowed), " or ") * + ", got $(repr(lookup))")) end -_λ_match_eps(::Type{FT}, λ::AbstractFloat) where {FT} = max(eps(FT), eps(typeof(λ))) -_λ_match_eps(::Type{FT}, ::Real) where {FT} = eps(FT) +# Value of the table `(λ_tab, y)` at `λ`. `ExactLookup`: the entry of the +# matching wavelength, in the table's precision. `LinearLookup`: that entry, +# or else the linear interpolant between the two neighbouring entries (never +# beyond the table), in the type that `λ` and the table promote to. +_tabulated_value(::ExactLookup, λ_tab::AbstractVector{FT}, y::AbstractVector{FT}, λ::Real, + who::AbstractString) where {FT} = y[_exact_λ_index(λ_tab, λ, who)] + +function _tabulated_value(::LinearLookup, λ_tab::AbstractVector{FT}, y::AbstractVector{FT}, + λ::Real, who::AbstractString) where {FT} + k = _matching_λ_index(λ_tab, λ) + k === nothing || return convert(_result_type(FT, λ), y[k]) + first(λ_tab) < λ < last(λ_tab) || + throw(DomainError(λ, "$who: outside the tabulated range $(first(λ_tab))–" * + "$(last(λ_tab)) nm; tables are interpolated, never extrapolated")) + i = searchsortedlast(λ_tab, λ) + t = (λ - λ_tab[i]) / (λ_tab[i+1] - λ_tab[i]) + return convert(_result_type(FT, λ), (1 - t) * y[i] + t * y[i+1]) +end diff --git a/src/materials/cdom.jl b/src/materials/cdom.jl index 9b67d82..4cd9bd1 100644 --- a/src/materials/cdom.jl +++ b/src/materials/cdom.jl @@ -22,11 +22,9 @@ """ $(TYPEDEF) -Bricaud, Morel & Prieur (1981) exponential-decay CDOM absorption, -`a_g(λ) = a_g(λ_ref) · exp(-slope · (λ - λ_ref))`. Currently the only -parameterization shipped; future additions (e.g. separate slopes for the -UV and visible hinge regions) can subtype `AbstractCDOMModel` without -altering `CDOM` itself. +Exponential CDOM absorption of Bricaud, Morel & Prieur (1981), +`a_g(λ) = a_g(λ_ref) · exp(−slope · (λ − λ_ref))`, with `a_g` in `1/m`, `λ` in nm and +`slope` in `1/nm`. """ struct BricaudMorelPrieur1981 <: AbstractCDOMModel end @@ -66,34 +64,34 @@ end """ CDOM{FT}(; model=BricaudMorelPrieur1981(), a_ref=0.03, λ_ref=440, slope=0.014) -Construct a CDOM absorber. Default values reproduce the Bricaud, Morel & -Prieur (1981) open-ocean average. `slope` outside the Babin et al. (2003) -global survey range of 0.005–0.030 nm⁻¹ triggers a non-fatal warning. +Construct a CDOM absorber with absorption `a_ref` `[1/m]` at `λ_ref` `[nm]` and spectral +slope `slope` `[1/nm]`. + +The defaults are the open-ocean average of Bricaud, Morel & Prieur (1981). A `slope` +outside 0.005–0.030 nm⁻¹, the range of the survey of Babin et al. (2003), logs a warning. """ function CDOM{FT}(; model::AbstractCDOMModel = BricaudMorelPrieur1981(), - a_ref = FT(0.03), - λ_ref = FT(440), - slope = FT(0.014), -) where {FT<:AbstractFloat} + a_ref = 0.03, + λ_ref = 440, + slope = 0.014, +) where {FT<:Real} + _check_parameter_type(FT) a_ref ≥ zero(a_ref) || throw(ArgumentError("CDOM: a_ref must be non-negative, got $a_ref")) λ_ref > zero(λ_ref) || throw(ArgumentError("CDOM: λ_ref must be positive, got $λ_ref")) - (FT(0.005) ≤ slope ≤ FT(0.030)) || + _within(slope, 0.005, 0.030) || @warn "CDOM: slope $slope [1/nm] outside typical 0.005-0.030 range" return CDOM{FT, typeof(model)}(model, FT(a_ref), FT(λ_ref), FT(slope)) end -CDOM(; kwargs...) = CDOM{Float64}(; kwargs...) +CDOM(; kwargs...) = CDOM{_parameter_type(values(kwargs))}(; kwargs...) -# Absorption — analytic, branch-free, AD-transparent. -# -# The returned type is `promote_type(FT, typeof(λ))`: passing a plain -# `Float64` gives `FT`; passing a `ForwardDiff.Dual` gives `Dual` so the -# derivative w.r.t. λ is tracked through `exp`. +# a_g(λ) = a_ref exp(−S (λ − λ_ref)). The result has the type that the +# parameters and `λ` promote to, so dual numbers in either are carried. absorption(c::CDOM, λ::Real) = c.a_ref * exp(-c.slope * (λ - c.λ_ref)) -absorption(c::CDOM, λ::AbstractVector) = [absorption(c, λi) for λi in λ] +absorption(c::CDOM, λ::AbstractVector) = map(Base.Fix1(absorption, c), λ) function Base.show(io::IO, c::CDOM{FT, M}) where {FT, M} print(io, "CDOM{$FT}(", nameof(M), ", a($(c.λ_ref))=$(c.a_ref), S=$(c.slope))") diff --git a/src/materials/nap.jl b/src/materials/nap.jl index 8bb4b1d..2da9be3 100644 --- a/src/materials/nap.jl +++ b/src/materials/nap.jl @@ -16,31 +16,39 @@ # # Typical S ≈ 0.011 1/nm (compare CDOM S ≈ 0.014). # -# FellMineral — crude beam-attenuation for mineral-dominated waters -# (Fell 1997 §5.1.4): c(λ) = c_ref · (440/λ) -# Split into a = a_ref·(440/λ), b = (c_ref − a_ref)·(440/λ) -# using a fixed single-scattering albedo ϖ_NAP. +# FellMineral — beam attenuation of inorganic suspended matter +# (Fell 1997 §5.1.4, Eqs. 5.10-5.11): c(λ) = c_ref · (440/λ) +# with a fixed single-scattering albedo ω₀ = 0.95, so that +# a = (1 − ω₀)·c and b = ω₀·c, and a backscatter +# probability of 0.036. # # Both parameterizations scatter into a Fournier-Forand phase function -# with a larger backscatter fraction than living phytoplankton (typical -# B ≈ 0.02 for detritus, 0.03 for minerals) — DESIGN §6.1 and Mobley -# (2002) justify FF over Petzold. +# with a larger backscatter fraction than living phytoplankton (default +# B = 0.02 for BabinBricaud2003, 0.036 for FellMineral): Mobley, Sundman & +# Boss (2002) recommend FF over Petzold. Fell (1997) used a Petzold San Diego +# Harbor phase function modified to the same backscatter probability. # ============================================================================= """ $(TYPEDEF) -Babin et al. (2003) detritus + minerals absorption model with Morel & -Maritorena (2001)-style particulate scattering. +Babin et al. (2003) detritus + minerals absorption model, +`a = a_ref exp(−S (λ − λ_ref))`, with the particulate scattering law +`b = b_ref (λ_ref/λ)^γ` (`γ = spectral_exponent`, default 1). """ struct BabinBricaud2003 <: AbstractNAPModel end """ $(TYPEDEF) -Fell (1997) §5.1.4 mineral-dominated beam-attenuation model `c = c_ref -· (440/λ)`, split into absorption and scattering by a fixed single- -scattering albedo. +Fell (1997) §5.1.4 beam-attenuation model of inorganic suspended matter, +`c = c_ref · (λ_ref/λ)^γ` with `λ_ref = 440` nm and `γ = spectral_exponent = 1` +(Eq. 5.10), split into absorption and scattering by a fixed single-scattering albedo. + +The defaults are the thesis values: single-scattering albedo `ω_nap = 0.95` +(Eq. 5.11) and backscatter fraction `B = 0.036` (p. 120). The phase function is +Fournier-Forand with that backscatter fraction; Fell used a Petzold San Diego +Harbor phase function modified to it. """ struct FellMineral <: AbstractNAPModel end @@ -62,7 +70,7 @@ nap = NonAlgalParticles{Float64}() # Mineral-dominated case per Fell (1997) nap = NonAlgalParticles{Float64, FellMineral}( c_ref = 0.40, # beam attenuation at 440 nm - ω_nap = 0.96, # single-scattering albedo + ω_nap = 0.95, # single-scattering albedo (the default) ) ``` """ @@ -82,6 +90,8 @@ struct NonAlgalParticles{FT, M<:AbstractNAPModel, c_ref::FT "Single-scattering albedo at 440 nm (FellMineral)" ω_nap::FT + "Exponent `γ` of the `(λ_ref/λ)^γ` law of scattering (BabinBricaud2003) or attenuation (FellMineral)" + spectral_exponent::FT "Particulate-scattering phase function" phase::P end @@ -89,46 +99,50 @@ end # BabinBricaud2003 constructor -------------------------------------------------- function NonAlgalParticles{FT, BabinBricaud2003}(; - a_ref = FT(0.05), - b_ref = FT(0.45), - λ_ref = FT(443), - slope = FT(0.011), - B = FT(0.02), -) where {FT<:AbstractFloat} + a_ref = 0.05, + b_ref = 0.45, + λ_ref = 443, + slope = 0.011, + B = 0.02, + spectral_exponent = 1, +) where {FT<:Real} + _check_parameter_type(FT) a_ref ≥ zero(a_ref) || throw(ArgumentError("NAP: a_ref must be non-negative, got $a_ref")) b_ref ≥ zero(b_ref) || throw(ArgumentError("NAP: b_ref must be non-negative, got $b_ref")) - (FT(0.005) ≤ slope ≤ FT(0.020)) || + _within(slope, 0.005, 0.020) || @warn "NAP: BabinBricaud2003 slope $slope 1/nm outside typical 0.005-0.020 range" phase = FournierForandPhase{FT}(backscatter_fraction = FT(B)) return NonAlgalParticles{FT, BabinBricaud2003, typeof(phase)}( BabinBricaud2003(), FT(a_ref), FT(b_ref), FT(λ_ref), FT(slope), - zero(FT), zero(FT), phase) + zero(FT), zero(FT), FT(spectral_exponent), phase) end # FellMineral constructor ------------------------------------------------------- function NonAlgalParticles{FT, FellMineral}(; - c_ref = FT(0.40), - ω_nap = FT(0.96), - λ_ref = FT(440), - B = FT(0.03), -) where {FT<:AbstractFloat} + c_ref = 0.40, + ω_nap = 0.95, + λ_ref = 440, + B = 0.036, + spectral_exponent = 1, +) where {FT<:Real} + _check_parameter_type(FT) c_ref ≥ zero(c_ref) || throw(ArgumentError("NAP: c_ref must be non-negative, got $c_ref")) - (zero(ω_nap) ≤ ω_nap ≤ one(ω_nap)) || + _within(ω_nap, 0, 1) || throw(ArgumentError("NAP: single-scattering albedo ω_nap must be in [0, 1], got $ω_nap")) phase = FournierForandPhase{FT}(backscatter_fraction = FT(B)) return NonAlgalParticles{FT, FellMineral, typeof(phase)}( FellMineral(), zero(FT), zero(FT), FT(λ_ref), zero(FT), - FT(c_ref), FT(ω_nap), phase) + FT(c_ref), FT(ω_nap), FT(spectral_exponent), phase) end # Default model tag is BabinBricaud2003 -NonAlgalParticles{FT}(; kwargs...) where {FT<:AbstractFloat} = +NonAlgalParticles{FT}(; kwargs...) where {FT<:Real} = NonAlgalParticles{FT, BabinBricaud2003}(; kwargs...) -NonAlgalParticles(; kwargs...) = NonAlgalParticles{Float64}(; kwargs...) +NonAlgalParticles(; kwargs...) = NonAlgalParticles{_parameter_type(values(kwargs))}(; kwargs...) scattering_phase(nap::NonAlgalParticles) = nap.phase @@ -141,7 +155,7 @@ function absorption(nap::NonAlgalParticles{FT, BabinBricaud2003}, λ::Real) wher end function scattering(nap::NonAlgalParticles{FT, BabinBricaud2003}, λ::Real) where {FT} - return nap.b_ref * (nap.λ_ref / λ) + return nap.b_ref * (nap.λ_ref / λ)^nap.spectral_exponent end # ----------------------------------------------------------------------------- @@ -149,12 +163,12 @@ end # ----------------------------------------------------------------------------- function absorption(nap::NonAlgalParticles{FT, FellMineral}, λ::Real) where {FT} - c = nap.c_ref * (nap.λ_ref / λ) + c = nap.c_ref * (nap.λ_ref / λ)^nap.spectral_exponent return (one(FT) - nap.ω_nap) * c end function scattering(nap::NonAlgalParticles{FT, FellMineral}, λ::Real) where {FT} - c = nap.c_ref * (nap.λ_ref / λ) + c = nap.c_ref * (nap.λ_ref / λ)^nap.spectral_exponent return nap.ω_nap * c end @@ -162,13 +176,13 @@ end # Shared vectorized forms + backscattering # ----------------------------------------------------------------------------- -absorption(nap::NonAlgalParticles, λ::AbstractVector) = [absorption(nap, λi) for λi in λ] -scattering(nap::NonAlgalParticles, λ::AbstractVector) = [scattering(nap, λi) for λi in λ] +absorption(nap::NonAlgalParticles, λ::AbstractVector) = map(Base.Fix1(absorption, nap), λ) +scattering(nap::NonAlgalParticles, λ::AbstractVector) = map(Base.Fix1(scattering, nap), λ) backscattering(nap::NonAlgalParticles, λ::Real) = scattering(nap, λ) * backscatter_fraction(nap.phase) backscattering(nap::NonAlgalParticles, λ::AbstractVector) = - [backscattering(nap, λi) for λi in λ] + map(Base.Fix1(backscattering, nap), λ) function Base.show(io::IO, nap::NonAlgalParticles{FT, M}) where {FT, M} print(io, "NonAlgalParticles{$FT}(", nameof(M), ", B=", diff --git a/src/materials/phytoplankton.jl b/src/materials/phytoplankton.jl index 2460609..abf1f87 100644 --- a/src/materials/phytoplankton.jl +++ b/src/materials/phytoplankton.jl @@ -1,24 +1,20 @@ # ============================================================================= -# Phytoplankton absorption and scattering +# Phytoplankton-bearing Case-1 water: particulate absorption and scattering # ============================================================================= # -# The phytoplankton absorption spectrum a_φ(λ) is the single biggest -# moving piece of ocean optics in the visible. The canonical empirical -# parameterization is Bricaud's power-law: +# Absorption is the chlorophyll power law of Bricaud et al. (1998, JGR 103, +# 31033) for the particulate absorption of Case-1 water, phytoplankton plus +# co-varying detritus: # -# a_φ*(λ) = A(λ) · Chl^(-E(λ)) [m²/mg] -# a_φ(λ) = a_φ*(λ) · Chl [1/m] +# a_p(λ) = A(λ) · Chl^E(λ) [1/m], Chl in mg/m³ # -# where `A(λ)` and `E(λ)` are spectral coefficients fit to globally -# distributed HPLC + spectrophotometer samples. Two generations ship: -# the original Bricaud et al. 1995 JGR fit (visible only; NOT bundled), -# and the 1998 update (Bricaud, Morel, Babin, Allali, Claustre JGR 103, -# 31033) extended to UV by Morrison & Nelson (2004) and Vasilkov et al. -# (2005). The 1998 update is the community-standard replacement and is -# the version bundled here as `data/bricaud_1998_{A,E}.csv`. +# with A(440) = 0.0520 and E(440) = 0.6350. `data/bricaud_1998_{A,E}.csv` hold +# A(λ) and E(λ) as tabulated for HydroLight's Case-1 model (`AEmidUVabs.txt`), +# which extends the 1998 fit to the UV after Morrison & Nelson (2004) and +# Vasilkov et al. (2005). # -# Particulate scattering uses the Morel & Maritorena (2001, JGR 106, -# 7163) Case-1 form: +# Scattering is the total particulate scattering of Case-1 water of Gordon & +# Morel (1983), as cited by Fell (1997), Eq. 5.5: # # b_p(λ) = 0.30 · Chl^0.62 · (550/λ) [1/m] # @@ -29,32 +25,98 @@ """ $(TYPEDEF) -Bricaud et al. (1998, JGR 103, 31033) power-law phytoplankton absorption, -extended to UV by Morrison & Nelson (2004) and Vasilkov et al. (2005). -Bundled as `data/bricaud_1998_A.csv` and `data/bricaud_1998_E.csv`, -covering 300–1000 nm at 2 nm resolution. +Particulate absorption of Case-1 water after Bricaud et al. (1998, JGR 103, 31033). + +The absorption is ``a_p(λ) = A(λ) Chl^{E(λ)}`` in `1/m` with `Chl` in `mg/m³` +(`A(440) = 0.0520`, `E(440) = 0.6350`). It is the absorption of all particles, +phytoplankton plus the detritus that co-varies with it, not of phytoplankton alone: +adding a separate [`NonAlgalParticles`](@ref) constituent counts detrital absorption +twice, unless a detrital or mineral load beyond the Case-1 background is intended. + +`A(λ)` and `E(λ)` are the tables of HydroLight's Case-1 model (`AEmidUVabs.txt`), +bundled as `data/bricaud_1998_A.csv` and `data/bricaud_1998_E.csv`: 300–1000 nm at +2 nm, with the UV part after Morrison & Nelson (2004) and Vasilkov et al. (2005). +`Chl = 0` gives zero absorption. """ struct Bricaud1998 <: AbstractPhytoplanktonModel end """ $(TYPEDEF) -Gordon (1992) broadband-averaged phytoplankton absorption (simpler, -less accurate, but historical baseline). Reserved as a model tag; -implementation stubbed for future release. +Scattering law of the particles of a [`Phytoplankton`](@ref) constituent. +""" +abstract type AbstractParticleScatteringModel end + +""" +$(TYPEDEF) + +Total particulate scattering of Case-1 water after Gordon & Morel (1983), as cited by +Fell (1997), Eq. 5.5: + +``b_p(λ) = b_\\mathrm{ref}\\, Chl^{m}\\, (λ_\\mathrm{ref}/λ)^{γ}`` `[1/m]`, `Chl` in `mg/m³`, + +with `b_ref = 0.30` m⁻¹ at `λ_ref = 550` nm, `m = 0.62` and `γ = 1`. Fell gives +`b_ref = 0.30 ± 0.15`. It is the scattering of all particles that co-vary with +chlorophyll, not of living cells alone; in coastal or turbid water the particulate +scattering can be larger by a factor of 2 or more. + +# Fields +$(TYPEDFIELDS) """ -struct Gordon1992 <: AbstractPhytoplanktonModel end +struct GordonMorel1983{FT<:Real} <: AbstractParticleScatteringModel + "Scattering coefficient at `λ_ref` for `Chl = 1 mg/m³` `[1/m]`" + b_ref::FT + "Exponent `m` of the chlorophyll concentration" + chl_exponent::FT + "Reference wavelength `[nm]`" + λ_ref::FT + "Exponent `γ` of the spectral law `(λ_ref/λ)^γ`" + spectral_exponent::FT + + function GordonMorel1983{FT}(b_ref, chl_exponent, λ_ref, spectral_exponent) where {FT<:Real} + _check_parameter_type(FT) + b_ref ≥ 0 || throw(ArgumentError("GordonMorel1983: b_ref must be non-negative, got $b_ref")) + λ_ref > 0 || throw(ArgumentError("GordonMorel1983: λ_ref must be positive, got $λ_ref")) + new{FT}(b_ref, chl_exponent, λ_ref, spectral_exponent) + end +end + +GordonMorel1983{FT}(; b_ref = 0.30, chl_exponent = 0.62, λ_ref = 550, + spectral_exponent = 1) where {FT<:Real} = + GordonMorel1983{FT}(b_ref, chl_exponent, λ_ref, spectral_exponent) +GordonMorel1983(; kwargs...) = GordonMorel1983{_parameter_type(values(kwargs))}(; kwargs...) + +# A Phytoplankton constructed without an explicit element type promotes with the element +# type of its scattering model, as with its real parameters (a dual model gives a dual +# constituent). +_promote_reals(::Type{T}, m::GordonMorel1983{S}, rest...) where {T, S} = + _promote_reals(promote_type(T, S), rest...) + +# A floating-point scattering model is evaluated in double precision and converted to +# the constituent's type; a model of any other element type (a dual) must be reachable +# from the constituent's type by promotion, or its derivative could not be stored. +_check_model_precision(::Type, ::AbstractParticleScatteringModel) = nothing +function _check_model_precision(::Type{FT}, m::GordonMorel1983{S}) where {FT, S} + S <: AbstractFloat || promote_type(FT, S) === FT || + throw(ArgumentError("Phytoplankton{$FT}: the scattering model has element type $S, " * + "which $FT cannot hold; construct Phytoplankton{$(promote_type(FT, S))} " * + "or omit the element type so that it follows the model")) + return nothing +end """ $(TYPEDEF) -Phytoplankton (living algal cells) as an absorbing scatterer. +Particles of Case-1 water (phytoplankton and co-varying detritus) as an absorbing +scatterer, parameterized by the chlorophyll-a concentration. -`Chl` is the near-surface chlorophyll-a concentration `[mg/m³]`. The -model tag `M` selects the absorption parameterization; scattering -currently uses Morel & Maritorena (2001) irrespective of `M`, and the -phase function defaults to `FournierForandPhase` with backscatter -fraction 0.01 (typical open-ocean living phytoplankton). +`Chl` is the chlorophyll-a concentration `[mg/m³]`. The model tag `M` selects the +absorption parameterization; with [`Bricaud1998`](@ref) it is the particulate +absorption ``a_p = A(λ) Chl^{E(λ)}``, which includes detritus (see there before +combining with [`NonAlgalParticles`](@ref)). Scattering is the total particulate +scattering of Case-1 water given by `scattering_model`, by default +[`GordonMorel1983`](@ref), ``b_p = 0.30 Chl^{0.62} (550/λ)``, and the phase function +defaults to `FournierForandPhase` with backscatter fraction `B = 0.01`. An optional pigment partition ([`ProspectPigments`](@ref), [`Bidigare1990Pigments`](@ref)) attributes the absorption to pigment @@ -78,10 +140,13 @@ phyto = Phytoplankton{Float64, Bricaud1998}(Chl = 2.0, B = 0.015) # Absorption attributed to chlorophyll and carotenoids phyto = Phytoplankton(Chl = 0.5, pigments = ProspectPigments(carotenoid_ratio = 0.3)) absorption_parts(phyto) # (:chlorophyll, :carotenoids, :unassigned) + +phyto = Phytoplankton(Chl = 0.5, scattering_model = GordonMorel1983(b_ref = 0.45)) ``` """ struct Phytoplankton{FT, M<:AbstractPhytoplanktonModel, P<:AbstractOceanPhaseFunction{FT}, - G<:Union{Nothing, AbstractPigmentPartition}} <: AbstractAbsorbingScatterer{FT} + G<:Union{Nothing, AbstractPigmentPartition}, + S<:AbstractParticleScatteringModel} <: AbstractAbsorbingScatterer{FT} "Parameterization-model tag (e.g. `Bricaud1998()`)" model::M "Chlorophyll-a concentration `[mg/m³]`" @@ -90,93 +155,90 @@ struct Phytoplankton{FT, M<:AbstractPhytoplanktonModel, P<:AbstractOceanPhaseFun phase::P "Pigment partition of the absorption, or `nothing` (a single part, `:total`)" pigments::G + "Scattering law and its parameters (default [`GordonMorel1983`](@ref))" + scattering_model::S end """ - Phytoplankton{FT, M}(; Chl, B = 0.01, pigments = nothing) + Phytoplankton{FT, M}(; Chl, B = 0.01, pigments = nothing, + scattering_model = GordonMorel1983()) + +Construct a [`Phytoplankton`](@ref) with chlorophyll-a concentration `Chl` `[mg/m³]`, a +Fournier-Forand phase function of backscatter fraction `B`, optionally a pigment +partition of its absorption, and the scattering law `scattering_model`. -Construct a `Phytoplankton` instance with Fournier-Forand phase function -parameterized by backscatter fraction `B`, and optionally a pigment -partition of its absorption. +The parameters of `scattering_model` are kept in the precision they are given in +(double by default); the scattering coefficient is evaluated in double precision and +returned in the precision of the constituent. """ -function Phytoplankton{FT, M}(; Chl, B = FT(0.01), - pigments::Union{Nothing, AbstractPigmentPartition} = nothing - ) where {FT<:AbstractFloat, M<:AbstractPhytoplanktonModel} +function Phytoplankton{FT, M}(; Chl, B = 0.01, + pigments::Union{Nothing, AbstractPigmentPartition} = nothing, + scattering_model::AbstractParticleScatteringModel = GordonMorel1983() + ) where {FT<:Real, M<:AbstractPhytoplanktonModel} + _check_parameter_type(FT) + _check_model_precision(FT, scattering_model) Chl ≥ zero(Chl) || throw(ArgumentError("Phytoplankton: Chl must be non-negative, got $Chl")) phase = FournierForandPhase{FT}(backscatter_fraction = FT(B)) pg = _partition_precision(FT, pigments) - return Phytoplankton{FT, M, typeof(phase), typeof(pg)}(M(), FT(Chl), phase, pg) + return Phytoplankton{FT, M, typeof(phase), typeof(pg), typeof(scattering_model)}( + M(), FT(Chl), phase, pg, scattering_model) end # Floating-point partitions take the phytoplankton's precision, so that the # absorption parts have the type of the total; dual numbers (AD) pass through. _partition_precision(::Type{FT}, p) where {FT} = p -_partition_precision(::Type{FT}, p::ProspectPigments{<:AbstractFloat}) where {FT} = - ProspectPigments{FT}(p.carotenoid_ratio) -_partition_precision(::Type{FT}, p::Bidigare1990Pigments{<:AbstractFloat}) where {FT} = - Bidigare1990Pigments{FT}(_concentrations(p)...) +_partition_precision(::Type{FT}, p::ProspectPigments{<:AbstractFloat, X}) where {FT, X} = + ProspectPigments{FT, X}(p.carotenoid_ratio, p.outside) +_partition_precision(::Type{FT}, p::Bidigare1990Pigments{<:AbstractFloat, X}) where {FT, X} = + Bidigare1990Pigments{FT, X}(p.outside, _concentrations(p)...) -Phytoplankton{FT}(; kwargs...) where {FT<:AbstractFloat} = +Phytoplankton{FT}(; kwargs...) where {FT<:Real} = Phytoplankton{FT, Bricaud1998}(; kwargs...) -Phytoplankton(; kwargs...) = Phytoplankton{Float64}(; kwargs...) +Phytoplankton(; kwargs...) = Phytoplankton{_parameter_type(values(kwargs))}(; kwargs...) scattering_phase(p::Phytoplankton) = p.phase # ----------------------------------------------------------------------------- -# Absorption — Bricaud (1998) + UV extensions +# Absorption — Bricaud et al. (1998) particulate absorption, HydroLight tables # ----------------------------------------------------------------------------- -"A(λ) spectral pre-factor, Bricaud 1998 + UV extensions, 300–1000 nm." +"Coefficient `A(λ)` `[1/m]` of `a_p = A·Chl^E`, 300–1000 nm (HydroLight `AEmidUVabs.txt`)." const _BRICAUD_1998_A_TABLE = load_spectral_csv(data_path("bricaud_1998_A.csv")) -"E(λ) spectral exponent, Bricaud 1998 + UV extensions, 300–1000 nm." +"Exponent `E(λ)` of `a_p = A·Chl^E`, 300–1000 nm (HydroLight `AEmidUVabs.txt`)." const _BRICAUD_1998_E_TABLE = load_spectral_csv(data_path("bricaud_1998_E.csv")) function absorption(p::Phytoplankton{FT, Bricaud1998}, λ::Real) where {FT} - # a_φ*(λ) = A(λ) · Chl^{-E(λ)}, a_φ(λ) = a_φ*(λ) · Chl = A · Chl^{1-E} - A_λ = linterp(_BRICAUD_1998_A_TABLE, λ) - E_λ = linterp(_BRICAUD_1998_E_TABLE, λ) - return A_λ * p.Chl^(one(FT) - E_λ) -end - -function absorption(p::Phytoplankton{FT, Gordon1992}, λ::Real) where {FT} - error("Phytoplankton{Gordon1992} absorption is not yet implemented. ", - "Use Phytoplankton{$(nameof(FT)), Bricaud1998} with the bundled ", - "Bricaud 1998 + UV-extended tables, or wait for a future release.") + # a_p(λ) = A(λ) · Chl^E(λ); E > 0 over the whole table, so Chl = 0 gives 0. + x = _wide(λ) + A_λ = linterp(_BRICAUD_1998_A_TABLE, x) + E_λ = linterp(_BRICAUD_1998_E_TABLE, x) + return convert(_result_type(FT, λ), A_λ * _wide(p.Chl)^E_λ) end -absorption(p::Phytoplankton, λ::AbstractVector) = [absorption(p, λi) for λi in λ] +absorption(p::Phytoplankton, λ::AbstractVector) = map(Base.Fix1(absorption, p), λ) absorption_parts(p::Phytoplankton) = p.pigments === nothing ? (:total,) : pigment_parts(p.pigments) function absorption_by_part(p::Phytoplankton, λ::Real) a = absorption(p, λ) - return p.pigments === nothing ? (a,) : map(f -> f * a, pigment_fractions(p.pigments, λ)) + pig = p.pigments + return pig === nothing ? (a,) : map(f -> f * a, pigment_fractions(pig, λ)) end # ----------------------------------------------------------------------------- -# Scattering — Morel & Maritorena (2001) Case-1 particulate form +# Scattering — the law of the constituent's `scattering_model` # ----------------------------------------------------------------------------- -# -# b_p(λ) = 0.30 · Chl^0.62 · (550/λ) [1/m] -# -# Integrated over living-cell size distribution; intended for open-ocean -# Case-1 waters. In coastal / turbid waters this can underestimate the -# particulate scattering by a factor of 2 or more and should be paired -# with an explicit `NonAlgalParticles` constituent. - -const _MORELMARITORENA_COEFF = 0.30 -const _MORELMARITORENA_EXPONENT = 0.62 -const _MORELMARITORENA_λ0 = 550.0 # [nm] - -function scattering(p::Phytoplankton{FT}, λ::Real) where {FT} - # All-literal arithmetic promotes correctly for `ForwardDiff.Dual` inputs. - return _MORELMARITORENA_COEFF * p.Chl^_MORELMARITORENA_EXPONENT * - (_MORELMARITORENA_λ0 / λ) -end -scattering(p::Phytoplankton, λ::AbstractVector) = [scattering(p, λi) for λi in λ] +scattering(p::Phytoplankton{FT}, λ::Real) where {FT} = + convert(_result_type(FT, λ), _particle_scattering(p.scattering_model, _wide(p.Chl), _wide(λ))) + +# b_p(λ) = b_ref · Chl^m · (λ_ref/λ)^γ +_particle_scattering(m::GordonMorel1983, Chl, λ) = + m.b_ref * Chl^m.chl_exponent * (m.λ_ref / λ)^m.spectral_exponent + +scattering(p::Phytoplankton, λ::AbstractVector) = map(Base.Fix1(scattering, p), λ) # Backscatter — phase-function-determined. Delegates to the configured # Fournier-Forand's closed-form `backscatter_fraction`. @@ -184,7 +246,7 @@ function backscattering(p::Phytoplankton{FT}, λ::Real) where {FT} return scattering(p, λ) * backscatter_fraction(p.phase) end -backscattering(p::Phytoplankton, λ::AbstractVector) = [backscattering(p, λi) for λi in λ] +backscattering(p::Phytoplankton, λ::AbstractVector) = map(Base.Fix1(backscattering, p), λ) function Base.show(io::IO, p::Phytoplankton{FT, M}) where {FT, M} print(io, "Phytoplankton{$FT}(", nameof(M), ", Chl=$(p.Chl) mg/m³, ", diff --git a/src/materials/pigments.jl b/src/materials/pigments.jl index 01ddd87..ca13bbe 100644 --- a/src/materials/pigments.jl +++ b/src/materials/pigments.jl @@ -12,14 +12,18 @@ # # from in vivo specific absorption spectra a*_k of the groups and their # relative contents c_k. The total a_ph — packaging included — still comes -# from the phytoplankton model; only its attribution is added. The shares +# from the phytoplankton model; only its attribution is added. With +# `Bricaud1998` that total is the particulate absorption a_p, detritus +# included, and the shares apply to all of it. The shares # come from unpackaged spectra, so packaging is assumed to flatten all # groups alike at each wavelength. # -# Where every group spectrum is zero, or outside the tabulated range, the -# absorption goes to the part `:unassigned` instead of being guessed (the -# shares jump there). Fluorescence counts `:unassigned` with η = 0 unless -# told otherwise. +# Outside the tabulated range of the pigment spectra the shares are those of +# the nearest tabulated wavelength (`HoldEdgeShares`, the default), so that no +# absorption is dropped there; `UnassignedOutsideTable` instead puts all of +# it in the part `:unassigned`. Where every group spectrum is zero the +# absorption is `:unassigned` in both cases. Fluorescence counts +# `:unassigned` with η = 0 unless told otherwise. # # Two partitions are bundled: # ProspectPigments — land analogy: chlorophyll a+b and carotenoids with @@ -43,15 +47,17 @@ abstract type AbstractPigmentPartition end """ pigment_parts(p::AbstractPigmentPartition) -> Tuple{Vararg{Symbol}} -Names of the pigment groups of `p`; the last is `:unassigned`. +Return the names of the pigment groups of `p`; the last is `:unassigned`. """ function pigment_parts end """ pigment_class(p::AbstractPigmentPartition, part::Symbol) -> Symbol -`:chlorophyll`, `:carotenoid`, `:phycobilin` or `:unassigned`: the role -that sets the default energy-transfer efficiency of the part in +Return the role of `part`: `:chlorophyll`, `:carotenoid` (photosynthetic or lumped +carotenoids), `:photoprotective_carotenoid`, `:phycobilin` or `:unassigned`. + +The role sets the default energy-transfer efficiency of the part in [`chlorophyll_fluorescence`](@ref). """ function pigment_class end @@ -59,20 +65,59 @@ function pigment_class end """ pigment_fractions(p::AbstractPigmentPartition, λ) -> Tuple -Share of phytoplankton absorption attributed to each part of +Return the share of phytoplankton absorption attributed to each part of [`pigment_parts`](@ref)`(p)` at `λ` `[nm]`; the shares sum to one. + +Outside the tabulated pigment spectra (both bundled partitions start at 400 nm) the +result depends on the partition's `outside` rule: with [`HoldEdgeShares`](@ref) (the +default) the shares of the nearest tabulated wavelength apply, so absorption in the UV +is attributed as at 400 nm; with [`UnassignedOutsideTable`](@ref) it is all +`:unassigned`, and [`chlorophyll_fluorescence`](@ref) then has no excitation there +(`:unassigned` has η = 0). Where all group spectra vanish the absorption is +`:unassigned` under both rules. """ function pigment_fractions end # Shares c_k a*_k / Σ c_j a*_j, or everything unassigned where the sum is zero. -function _pigment_shares(s::NTuple{N, T}) where {N, T} +function _pigment_shares(s::Tuple{T, Vararg{T}}) where {T} S = sum(s) - S > 0 || return (ntuple(_ -> zero(T), Val(N))..., one(T)) + S > 0 || return (map(_ -> zero(T), s)..., one(T)) return (map(x -> x / S, s)..., zero(T)) end _unassigned_shares(::Val{N}, ::Type{T}) where {N, T} = (ntuple(_ -> zero(T), Val(N))..., one(T)) +""" + AbstractOutOfRangeShares + +Rule for the pigment shares at wavelengths outside the tabulated pigment spectra: +[`HoldEdgeShares`](@ref) or [`UnassignedOutsideTable`](@ref). +""" +abstract type AbstractOutOfRangeShares end + +""" + HoldEdgeShares() + +Outside the tabulated range the pigment shares are those of the nearest tabulated +wavelength (the default of the bundled partitions). + +The partition then attributes all absorption at every wavelength; the shares below +400 nm are an extrapolation, not data. +""" +struct HoldEdgeShares <: AbstractOutOfRangeShares end + +""" + UnassignedOutsideTable() + +Outside the tabulated range all absorption goes to the part `:unassigned`, which +[`chlorophyll_fluorescence`](@ref) counts with zero transfer efficiency by default. +""" +struct UnassignedOutsideTable <: AbstractOutOfRangeShares end + +# Wavelength at which the share tables are read, or `nothing` for "all unassigned". +_share_wavelength(::HoldEdgeShares, λ, lo, hi) = clamp(λ, lo, hi) +_share_wavelength(::UnassignedOutsideTable, λ, lo, hi) = _within(λ, lo, hi) ? λ : nothing + # ----------------------------------------------------------------------------- # Land analogy: PROSPECT-D chlorophyll and carotenoid spectra # ----------------------------------------------------------------------------- @@ -88,8 +133,9 @@ Land-analogous partition into chlorophyll (a + b) and carotenoids, with the in vivo specific absorption spectra `Kab` and `Kca` of the leaf model PROSPECT-D (Féret et al. 2017) that Fluspect uses (`data/prospect_d_pigment_absorption.csv`, 400–800 nm). Parts: -`(:chlorophyll, :carotenoids, :unassigned)`; outside 400–800 nm all -absorption is `:unassigned`. +`(:chlorophyll, :carotenoids, :unassigned)`. Outside 400–800 nm the shares at +400 nm or 800 nm apply (`outside = HoldEdgeShares()`, the default), or all +absorption is `:unassigned` (`outside = UnassignedOutsideTable()`). # Fields $(TYPEDFIELDS) @@ -103,20 +149,23 @@ SCOPE's default leaf has 40 µg cm⁻² chlorophyll and 10 µg cm⁻² carotenoids, a ratio of 0.25; phytoplankton ratios differ between groups and with light history. """ -struct ProspectPigments{FT<:Real} <: AbstractPigmentPartition +struct ProspectPigments{FT<:Real, X<:AbstractOutOfRangeShares} <: AbstractPigmentPartition "Carotenoid-to-chlorophyll mass ratio" carotenoid_ratio::FT + "Rule for the shares outside the tabulated 400–800 nm" + outside::X - function ProspectPigments{FT}(carotenoid_ratio) where {FT<:Real} + function ProspectPigments{FT, X}(carotenoid_ratio, outside::X) where {FT<:Real, X} isfinite(carotenoid_ratio) && carotenoid_ratio ≥ 0 || throw(ArgumentError("ProspectPigments: carotenoid_ratio must be finite and " * "non-negative, got $carotenoid_ratio")) - new{FT}(carotenoid_ratio) + new{FT, X}(carotenoid_ratio, outside) end end -ProspectPigments(; carotenoid_ratio::Real) = - ProspectPigments{float(typeof(carotenoid_ratio))}(carotenoid_ratio) +ProspectPigments(; carotenoid_ratio::Real, + outside::AbstractOutOfRangeShares = HoldEdgeShares()) = + ProspectPigments{float(typeof(carotenoid_ratio)), typeof(outside)}(carotenoid_ratio, outside) pigment_parts(::ProspectPigments) = (:chlorophyll, :carotenoids, :unassigned) @@ -127,9 +176,10 @@ pigment_class(p::ProspectPigments, part::Symbol) = function pigment_fractions(p::ProspectPigments, λ::Real) T = promote_type(typeof(p.carotenoid_ratio), typeof(float(λ))) - first(_PROSPECT_KAB.λ) ≤ λ ≤ last(_PROSPECT_KAB.λ) || return _unassigned_shares(Val(2), T) - return _pigment_shares((T(linterp(_PROSPECT_KAB, λ)), - T(p.carotenoid_ratio * linterp(_PROSPECT_KCA, λ)))) + x = _share_wavelength(p.outside, λ, first(_PROSPECT_KAB.λ), last(_PROSPECT_KAB.λ)) + x === nothing && return _unassigned_shares(Val(2), T) + return _pigment_shares((T(linterp(_PROSPECT_KAB, x)), + T(p.carotenoid_ratio * linterp(_PROSPECT_KCA, x)))) end function Base.show(io::IO, p::ProspectPigments) @@ -156,9 +206,11 @@ their ratios matter, since the total comes from the phytoplankton model. Parts: `(:chlorophyll_a, :chlorophyll_b, :chlorophyll_c, :photosynthetic_carotenoids, :photoprotective_carotenoids, -:phycoerythrin_peb, :phycoerythrin_pub, :unassigned)`. Outside -400–750 nm, and where all group spectra vanish (above the chlorophyll a -red band, ≈ 732 nm), all absorption is `:unassigned`. +:phycoerythrin_peb, :phycoerythrin_pub, :unassigned)`. Below 400 nm the +shares at 400 nm apply (`outside = HoldEdgeShares()`, the default) or all +absorption is `:unassigned` (`outside = UnassignedOutsideTable()`). Where all +group spectra vanish (above the chlorophyll a red band, ≈ 732 nm, and so +also above 750 nm) all absorption is `:unassigned` under both rules. # Fields $(TYPEDFIELDS) @@ -170,7 +222,7 @@ phyto = Phytoplankton(Chl = 0.5, pigments = pig) absorption_part(phyto, :photoprotective_carotenoids, 470.0) ``` """ -struct Bidigare1990Pigments{FT<:Real} <: AbstractPigmentPartition +struct Bidigare1990Pigments{FT<:Real, X<:AbstractOutOfRangeShares} <: AbstractPigmentPartition "Chlorophyll a `[mg m⁻³]`" chl_a::FT "Chlorophyll b `[mg m⁻³]`" @@ -185,22 +237,25 @@ struct Bidigare1990Pigments{FT<:Real} <: AbstractPigmentPartition pe_peb::FT "Phycoerythrin rich in phycourobilin (Synechococcus WH8103 type) `[mg m⁻³]`" pe_pub::FT + "Rule for the shares outside the tabulated 400–750 nm" + outside::X - function Bidigare1990Pigments{FT}(c...) where {FT<:Real} + function Bidigare1990Pigments{FT, X}(outside::X, c...) where {FT<:Real, X} all(x -> isfinite(x) && x ≥ 0, c) || throw(ArgumentError("Bidigare1990Pigments: concentrations must be finite and " * "non-negative, got $c")) any(>(0), c) || throw(ArgumentError("Bidigare1990Pigments: at least one concentration must be positive")) - new{FT}(c...) + new{FT, X}(c..., outside) end end function Bidigare1990Pigments(; chl_a::Real, chl_b::Real = 0, chl_c::Real = 0, psc::Real = 0, - ppc::Real = 0, pe_peb::Real = 0, pe_pub::Real = 0) + ppc::Real = 0, pe_peb::Real = 0, pe_pub::Real = 0, + outside::AbstractOutOfRangeShares = HoldEdgeShares()) c = (chl_a, chl_b, chl_c, psc, ppc, pe_peb, pe_pub) FT = float(promote_type(map(typeof, c)...)) - return Bidigare1990Pigments{FT}(map(FT, c)...) + return Bidigare1990Pigments{FT, typeof(outside)}(outside, map(FT, c)...) end pigment_parts(::Bidigare1990Pigments) = @@ -209,7 +264,8 @@ pigment_parts(::Bidigare1990Pigments) = function pigment_class(p::Bidigare1990Pigments, part::Symbol) part in (:chlorophyll_a, :chlorophyll_b, :chlorophyll_c) && return :chlorophyll - part in (:photosynthetic_carotenoids, :photoprotective_carotenoids) && return :carotenoid + part === :photosynthetic_carotenoids && return :carotenoid + part === :photoprotective_carotenoids && return :photoprotective_carotenoid part in (:phycoerythrin_peb, :phycoerythrin_pub) && return :phycobilin part === :unassigned && return :unassigned return _unknown_pigment(p, part) @@ -220,8 +276,10 @@ _concentrations(p::Bidigare1990Pigments) = (p.chl_a, p.chl_b, p.chl_c, p.psc, p. function pigment_fractions(p::Bidigare1990Pigments{FT}, λ::Real) where {FT} T = promote_type(FT, typeof(float(λ))) tbl = first(_BIDIGARE_SPECTRA) - first(tbl.λ) ≤ λ ≤ last(tbl.λ) || return _unassigned_shares(Val(7), T) - return _pigment_shares(map((c, t) -> T(c * linterp(t, λ)), _concentrations(p), _BIDIGARE_SPECTRA)) + x = _share_wavelength(p.outside, λ, first(tbl.λ), last(tbl.λ)) + x === nothing && return _unassigned_shares(Val(7), T) + c = _concentrations(p) + return _pigment_shares(ntuple(i -> T(c[i] * linterp(_BIDIGARE_SPECTRA[i], x)), Val(7))) end function Base.show(io::IO, p::Bidigare1990Pigments) diff --git a/src/materials/pure_water.jl b/src/materials/pure_water.jl index 5d9a377..b7c170a 100644 --- a/src/materials/pure_water.jl +++ b/src/materials/pure_water.jl @@ -46,26 +46,42 @@ methods dispatch on `M` to pick the right one. abstract type AbstractPureWaterAbsorptionModel end """ -Smith & Baker (1981), 200–800 nm, 10 nm resolution: upper bounds for the -clearest natural waters. Below ~420 nm it is several times higher than -modern pure-water measurements. No temperature correction is applied. +$(TYPEDEF) + +Absorption of Smith & Baker (1981), 200–800 nm at 10 nm: upper bounds for the clearest +natural waters. + +Below about 420 nm it is several times higher than modern pure-water measurements. No +temperature correction is applied. """ struct SmithBaker1981 <: AbstractPureWaterAbsorptionModel end -"Pope & Fry (1997), 380–727.5 nm, 2.5 nm resolution, measured at 22 °C." +""" +$(TYPEDEF) + +Absorption of Pope & Fry (1997), 380–727.5 nm at 2.5 nm, measured at 22 °C. +""" struct PopeFry1997 <: AbstractPureWaterAbsorptionModel end -"Kou, Labrie & Chylek (1993), 667–2500 nm, ~1 nm resolution, measured at 22 °C." +""" +$(TYPEDEF) + +Absorption of Kou, Labrie & Chylek (1993), 667–2500 nm, measured at 22 °C. + +The bundled table has 548 points with steps of 0.3 to 18 nm. +""" struct Kou1993 <: AbstractPureWaterAbsorptionModel end """ -IOCCG Protocol Series (2018) recommended pure-water absorption: Morel et al. -(2007) for 340–415 nm, Pope & Fry (1997) for 420–725 nm and Kou et al. -(1993) for 730–750 nm, at 5 nm resolution over 350–750 nm as used for the -HydroLight database of Loisel et al. (2023); continued with Kou et al. -(1993) up to 2500 nm. The composite's 730–750 nm values differ from the -bundled Kou table by up to 0.8 % (0.06 % step at the 750 nm junction). -The default model. +$(TYPEDEF) + +Pure-water absorption recommended by the IOCCG Protocol Series (2018); the default model. + +It combines Morel et al. (2007) for 340–415 nm, Pope & Fry (1997) for 420–725 nm and Kou +et al. (1993) for 730–750 nm, at 5 nm over 350–750 nm as used for the HydroLight database +of Loisel et al. (2023), and is continued with Kou et al. (1993) up to 2500 nm. The +composite's 730–750 nm values differ from the bundled Kou table by up to 0.8 % (0.06 % +step at the 750 nm junction). """ struct IOCCG2018 <: AbstractPureWaterAbsorptionModel end @@ -76,15 +92,41 @@ struct IOCCG2018 <: AbstractPureWaterAbsorptionModel end """ $(TYPEDEF) -Pure-water scattering model. `ZhangHu2009` is the modern default; the -older `Morel1974` is kept for reproducing legacy codes. +Pure-water scattering model: [`ZhangHu2009`](@ref) (the default) or [`Morel1974`](@ref). """ abstract type AbstractPureWaterScatteringModel end -"Morel (1974). Salinity-independent: b_w(λ) = 0.00193 (550/λ)^4.32." +""" +$(TYPEDEF) + +Power law fitted to the seawater scattering of Morel (1974), + +``b_w(λ) = 0.00193\\,(550/λ)^{4.32}`` `[1/m]`, `λ` in nm. + +The formula represents seawater and does not depend on the `salinity`, `temperature` +or `depolarization` of the [`PureWater`](@ref): with `salinity = 0` it still returns +the seawater value, about 30 % above fresh water (compare [`ZhangHu2009`](@ref), +1.958·10⁻³ m⁻¹ at 500 nm for S = 0 against 2.913·10⁻³ here). It is a smooth fit, not +Morel's table: against the pure-sea-water values that Mobley et al. (1993, Problem 7) +quote from Smith & Baker (1981), 0.0063 m⁻¹ at 417 nm and 0.0032 m⁻¹ at 486 nm, it +gives 0.00638 (+1.3 %) and 0.00329 (+2.9 %); the printed values carry two digits. It +is 7–16 % above [`ZhangHu2009`](@ref) at S = 35 over 350–750 nm. +""" struct Morel1974 <: AbstractPureWaterScatteringModel end -"Zhang, Hu & He (2009). Includes salinity and temperature dependence. 200–1100 nm." +""" +$(TYPEDEF) + +Scattering of seawater after Zhang, Hu & He (2009), a function of wavelength, +temperature and salinity. + +The Rayleigh magnitude uses the `depolarization` of the [`PureWater`](@ref) (default +0.039) in the Cabannes factor `(6 + 6δ)/(6 − 7δ)` and in the angular integral. + +No range of validity is checked: the routine returns values at any wavelength, +temperature and salinity. The refractive index inside it is the Quan & Fry (1995) fit +(400–700 nm, 0–30 °C, 0–35 PSU); outside those ranges the result is an extrapolation. +""" struct ZhangHu2009 <: AbstractPureWaterScatteringModel end # ----------------------------------------------------------------------------- @@ -126,23 +168,26 @@ struct PureWater{FT, temperature::FT "Salinity [PSU] (Practical Salinity Unit)" salinity::FT - "Depolarization ratio for the Rayleigh-type scattering phase function" + "Depolarization ratio `δ` (unpolarized light, 90°) of the phase matrix and of the `ZhangHu2009` scattering magnitude" depolarization::FT end function PureWater{FT}(; absorption_model = IOCCG2018(), scattering_model = ZhangHu2009(), - temperature = FT(20), - salinity = FT(35), - depolarization = FT(0.039), + temperature = 20, + salinity = 35, + depolarization = _WATER_DEPOLARIZATION, ) where {FT} + _check_parameter_type(FT) + _within(FT(depolarization), 0, 1) && FT(depolarization) < one(FT) || + throw(ArgumentError("PureWater: depolarization must be in [0, 1), got $depolarization")) PureWater{FT, typeof(absorption_model), typeof(scattering_model)}( absorption_model, scattering_model, FT(temperature), FT(salinity), FT(depolarization)) end -PureWater(; kwargs...) = PureWater{Float64}(; kwargs...) +PureWater(; kwargs...) = PureWater{_parameter_type(values(kwargs))}(; kwargs...) # Phase function interface — water scatters as depolarized Rayleigh. scattering_phase(w::PureWater{FT}) where {FT} = @@ -162,23 +207,25 @@ scattering_phase(w::PureWater{FT}) where {FT} = """ absorption(w::PureWater, λ) -> FT -Pure-water absorption coefficient [1/m] at wavelength `λ` [nm] from the -configured `absorption_model`, linearly interpolated; throws outside the -model's tabulated range. The temperature correction -`a(T) = a(T_ref) + Ψ_T (T − T_ref)` uses the Röttgers et al. (2014) -coefficients `Ψ_T` for `λ ≥ 550 nm` (up to 0.016 m⁻¹ K⁻¹ near 740 nm) and is -applied relative to the table's measurement temperature `T_ref`. Salinity -effects on absorption are not modelled. +Return the pure-water absorption coefficient `[1/m]` at wavelength `λ` `[nm]`. + +The table of the water's `absorption_model` is interpolated linearly; a wavelength +outside the tabulated range throws. The temperature correction +`a(T) = a(T_ref) + Ψ_T (T − T_ref)` uses the coefficients `Ψ_T` of Röttgers et al. (2014) +for `λ ≥ 550 nm` (up to 0.016 m⁻¹ K⁻¹ near 740 nm), relative to the measurement +temperature `T_ref` of the table. Salinity effects on absorption are not modelled. """ function absorption(w::PureWater{FT, A, S}, λ::Real) where {FT, A, S} - a₀ = _interpolate_pure_water_absorption(A(), λ) + T = _result_type(FT, λ) + x = _wide(λ) + a₀ = _interpolate_pure_water_absorption(A(), x) T_ref = _reference_temperature(A()) - T_ref === nothing && return a₀ - return a₀ + _temperature_coefficient(λ) * (w.temperature - FT(T_ref)) + T_ref === nothing && return convert(T, a₀) + return convert(T, a₀ + _temperature_coefficient(x) * (_wide(w.temperature) - T_ref)) end # Vectorized convenience -absorption(w::PureWater, λ::AbstractVector) = [absorption(w, λi) for λi in λ] +absorption(w::PureWater, λ::AbstractVector) = map(Base.Fix1(absorption, w), λ) # ----------------------------------------------------------------------------- # Spectral reference tables @@ -202,20 +249,27 @@ const _IOCCG_2018_TABLE = load_spectral_csv(data_path("ioccg_2018_pure_wat _interpolate_pure_water_absorption(::SmithBaker1981, λ) = linterp(_SMITH_BAKER_1981_TABLE, λ) _interpolate_pure_water_absorption(::PopeFry1997, λ) = linterp(_POPE_FRY_1997_TABLE, λ) _interpolate_pure_water_absorption(::Kou1993, λ) = linterp(_KOU_1993_TABLE, λ) -_interpolate_pure_water_absorption(::IOCCG2018, λ) = - λ ≤ 750 ? linterp(_IOCCG_2018_TABLE, λ) : linterp(_KOU_1993_TABLE, λ) +function _interpolate_pure_water_absorption(::IOCCG2018, λ) + lo, hi = first(_IOCCG_2018_TABLE.λ), last(_KOU_1993_TABLE.λ) + _within(λ, lo, hi) || + throw(DomainError(λ, "IOCCG2018 pure-water absorption covers $(lo)–$(hi) nm (the " * + "IOCCG 2018 table up to 750 nm, Kou et al. 1993 above); choose " * + "another absorption model or restrict the wavelength grid")) + return λ ≤ last(_IOCCG_2018_TABLE.λ) ? linterp(_IOCCG_2018_TABLE, λ) : linterp(_KOU_1993_TABLE, λ) +end # Measurement temperature [°C] each table refers to; `nothing`: no correction. _reference_temperature(::SmithBaker1981) = nothing _reference_temperature(::PopeFry1997) = 22.0 _reference_temperature(::Kou1993) = 22.0 -_reference_temperature(::IOCCG2018) = 22.0 # Pope & Fry / Kou in 600–800 nm +_reference_temperature(::IOCCG2018) = _reference_temperature(Kou1993()) # Pope & Fry / Kou in 600–800 nm # Röttgers, McKee & Utschig (2014) temperature coefficient Ψ_T [1/(m K)], -# 550–2500 nm; zero below 550 nm, where it is below the measurement -# uncertainty (and crosses zero near 550 nm, so there is no step). +# 550–2500 nm; zero below the first wavelength of the table (550 nm), where it is +# below the measurement uncertainty (and crosses zero near 550 nm, so there is no step). const _ROTTGERS_2014_PSI_T = load_spectral_csv(data_path("rottgers_2014_temperature.csv")) -_temperature_coefficient(λ) = λ < 550 ? zero(λ) : linterp(_ROTTGERS_2014_PSI_T, λ) +_temperature_coefficient(λ) = + λ < _ROTTGERS_2014_PSI_T.lo ? zero(λ) : linterp(_ROTTGERS_2014_PSI_T, λ) # ============================================================================= # Scattering dispatch — one method per model tag @@ -224,18 +278,22 @@ _temperature_coefficient(λ) = λ < 550 ? zero(λ) : linterp(_ROTTGERS_2014_PSI_ """ scattering(w::PureWater, λ) -> FT -Pure-(sea)water scattering coefficient [1/m] at wavelength `λ` [nm]. -Dispatches on the `scattering_model` tag. +Return the scattering coefficient `[1/m]` of pure water or seawater at wavelength `λ` +`[nm]`, from the model named by the water's `scattering_model`. """ -scattering(w::PureWater{FT, A, Morel1974}, λ::Real) where {FT, A} = _morel_1974_scattering(λ) +scattering(w::PureWater{FT, A, Morel1974}, λ::Real) where {FT, A} = + convert(_result_type(FT, λ), _morel_1974_scattering(_wide(λ))) scattering(w::PureWater{FT, A, ZhangHu2009}, λ::Real) where {FT, A} = - _zhang_hu_2009_scattering(λ, w.temperature, w.salinity) + convert(_result_type(FT, λ), + _zhang_hu_2009_scattering(_wide(λ), _wide(w.temperature), _wide(w.salinity), + _wide(w.depolarization))) -# Morel (1974) pure-water scattering, salinity-independent power law -# b_w(λ) = 0.00193 · (550/λ)^4.32 [1/m], with λ in [nm] -# Left un-annotated for AD transparency — integer/float literals promote -# against any `Real` (including `ForwardDiff.Dual`) input. -_morel_1974_scattering(λ) = 0.00193 * (550 / λ)^4.32 +# Morel (1974) seawater power law b_w(λ) = b_ref (λ_ref/λ)^n: b_ref [1/m], λ_ref [nm], n. +const _MOREL_1974_B_REF = 0.00193 +const _MOREL_1974_λ_REF = 550 +const _MOREL_1974_EXPONENT = 4.32 +# Un-annotated so that any `Real` wavelength (including `ForwardDiff.Dual`) promotes. +_morel_1974_scattering(λ) = _MOREL_1974_B_REF * (_MOREL_1974_λ_REF / λ)^_MOREL_1974_EXPONENT # Zhang, Hu & He (2009) seawater scattering — faithful port # ---------------------------------------------------------- @@ -272,8 +330,11 @@ _morel_1974_scattering(λ) = 0.00193 * (550 / λ)^4.32 # ion_functions/data/matlab_scripts/flort/betasw_ZHH2009.m # ============================================================================= -const _ZHH_Na = 6.0221417930e23 # Avogadro's constant [1/mol] -const _ZHH_Kbz = 1.3806503e-23 # Boltzmann constant [J/K] +# CODATA-2006 values of Avogadro's [1/mol] and Boltzmann's [J/K] constants as written in +# betasw_ZHH2009.m, kept for bit-reproduction of that code (the SI-2019 values differ by +# 3e-8 and 9e-7 relative). +const _ZHH_2009_AVOGADRO = 6.0221417930e23 +const _ZHH_2009_BOLTZMANN = 1.3806503e-23 const _ZHH_M0 = 18e-3 # Molecular weight of water [kg/mol] "Refractive index of seawater (Quan-Fry 1995 + Ciddor 1996) and `∂n_sw/∂S`." @@ -319,39 +380,46 @@ function _zhh_dlna_dS(Tc, S) 2 * (-2.31065e-6 - 1.37674e-9*Tc - 1.93316e-11*Tc^2) * S end -"Proutière-Megnassan-Hucteau density derivative `ρ ∂n²/∂ρ = (n²-1)·[1 + (2/3)(n²+2)·((n²-1)/(3n))²]`." +""" + _zhh_pmh(n) + +Return the density derivative of Proutière, Megnassan & Hucteau, +`ρ ∂n²/∂ρ = (n²-1)·[1 + (2/3)(n²+2)·((n²-1)/(3n))²]`. +""" function _zhh_pmh(n) n2 = n^2 return (n2 - 1) * (1 + (2/3) * (n2 + 2) * (n/3 - 1/(3n))^2) end """ - _zhang_hu_2009_scattering(λ_nm, Tc, S; δ = 0.039) -> FT + _zhang_hu_2009_scattering(λ_nm, Tc, S, δ) -Total seawater scattering coefficient `b_sw` `[1/m]` at wavelength -`λ_nm` `[nm]`, temperature `Tc` `[°C]` and practical salinity `S` `[PSU]`, -with depolarization ratio `δ` (Farinato & Rowell 1976 value 0.039). +Return the total seawater scattering coefficient `b_sw` `[1/m]` at wavelength `λ_nm` +`[nm]`, temperature `Tc` `[°C]`, practical salinity `S` `[PSU]` and depolarization +ratio `δ` (0.039 in Zhang, Hu & He 2009, after Farinato & Rowell 1976). -Valid range: `λ ∈ [220, 1100] nm`, `T ∈ [0, 30] °C`, `S ∈ [0, 40] PSU`. +No range of validity is checked. """ -function _zhang_hu_2009_scattering(λ_nm, Tc, S) - δ = 0.039 # Farinato & Rowell (1976) +function _zhang_hu_2009_scattering(λ_nm, Tc, S, δ) Tk = Tc + 273.15 nsw, dnds = _zhh_refractive_index(λ_nm, Tc, S) β_T = _zhh_isothermal_compressibility(Tc, S) ρ_sw = _zhh_density(Tc, S) - dlna_dS = _zhh_dlna_dS(Tc, S) + # ∂ln a/∂S has a √S term whose derivative is infinite at S = 0, where it multiplies + # S = 0 in `flu_con`; evaluating it at `zero(S)` there gives the one-sided derivative + # of the product (a dual S = 0 would otherwise give 0·∞ = NaN). Same value. + dlna_dS = _zhh_dlna_dS(Tc, _within(S, 0, 0) ? zero(S) : S) DFRI = _zhh_pmh(nsw) λm = λ_nm * 1e-9 # nm → m cabannes = (6 + 6δ) / (6 - 7δ) # Density-fluctuation contribution to β(90°) - β_df = (π^2 / 2) * λm^(-4) * _ZHH_Kbz * Tk * β_T * DFRI^2 * cabannes + β_df = (π^2 / 2) * λm^(-4) * _ZHH_2009_BOLTZMANN * Tk * β_T * DFRI^2 * cabannes # Concentration-fluctuation contribution to β(90°) - flu_con = S * _ZHH_M0 * dnds^2 / ρ_sw / (-dlna_dS) / _ZHH_Na + flu_con = S * _ZHH_M0 * dnds^2 / ρ_sw / (-dlna_dS) / _ZHH_2009_AVOGADRO β_cf = 2 * π^2 * λm^(-4) * nsw^2 * flu_con * cabannes β_90 = β_df + β_cf @@ -359,7 +427,7 @@ function _zhang_hu_2009_scattering(λ_nm, Tc, S) return (8π / 3) * β_90 * (2 + δ) / (1 + δ) end -scattering(w::PureWater, λ::AbstractVector) = [scattering(w, λi) for λi in λ] +scattering(w::PureWater, λ::AbstractVector) = map(Base.Fix1(scattering, w), λ) # ============================================================================= # Backscatter fraction — Rayleigh-like, exactly 1/2 for any depolarization @@ -369,4 +437,4 @@ scattering(w::PureWater, λ::AbstractVector) = [scattering(w, λi) for λi in λ # exactly 1/2 for any depolarization (the phase function is symmetric # forward/back), so `b_b = b/2`. backscattering(w::PureWater{FT}, λ::Real) where {FT} = FT(0.5) * scattering(w, λ) -backscattering(w::PureWater, λ::AbstractVector) = [backscattering(w, λi) for λi in λ] +backscattering(w::PureWater, λ::AbstractVector) = map(Base.Fix1(backscattering, w), λ) diff --git a/src/materials/refractive_index.jl b/src/materials/refractive_index.jl index d5f38f1..8c7effe 100644 --- a/src/materials/refractive_index.jl +++ b/src/materials/refractive_index.jl @@ -16,23 +16,32 @@ # is chosen explicitly. # ============================================================================= -"Model for the real refractive index of seawater relative to air." +""" +$(TYPEDEF) + +Model for the real refractive index of seawater relative to air; see +[`refractive_index`](@ref). +""" abstract type AbstractRefractiveIndexModel end """ $(TYPEDEF) -Wavelength-independent refractive index of seawater relative to air. +Wavelength-independent refractive index of seawater relative to air, +`n ≥ 1` (`n = 1` is an index-matched interface). # Fields $(TYPEDFIELDS) """ -struct FixedRefractiveIndex{FT<:AbstractFloat} <: AbstractRefractiveIndexModel +struct FixedRefractiveIndex{FT<:Real} <: AbstractRefractiveIndexModel "Index relative to air" n::FT - function FixedRefractiveIndex{FT}(n::FT) where {FT<:AbstractFloat} - isfinite(n) && n > 0 || throw(ArgumentError("FixedRefractiveIndex: n must be positive, got $n")) + function FixedRefractiveIndex{FT}(n::FT) where {FT<:Real} + isfinite(n) && n ≥ 1 || + throw(ArgumentError("FixedRefractiveIndex: the index of seawater relative to air " * + "must be finite and ≥ 1, got n = $n; check that it is " * + "n_water / n_air and not its inverse")) new{FT}(n) end end @@ -55,7 +64,7 @@ $(TYPEDFIELDS) Queries outside the fitted domain throw unless `extrapolate = true`. """ -struct QuanFry1995{FT<:AbstractFloat} <: AbstractRefractiveIndexModel +struct QuanFry1995{FT<:Real} <: AbstractRefractiveIndexModel "Temperature `[°C]`" temperature::FT "Salinity `[PSU]`" @@ -66,7 +75,7 @@ end function QuanFry1995(; temperature::Real, salinity::Real, extrapolate::Bool = false) FT = float(promote_type(typeof(temperature), typeof(salinity))) - extrapolate || (0 ≤ temperature ≤ 30 && 0 ≤ salinity ≤ 35) || + extrapolate || (_within(temperature, 0, 30) && _within(salinity, 0, 35)) || throw(DomainError((temperature, salinity), "QuanFry1995 is fitted to 0–30 °C and 0–35 PSU; pass extrapolate = true to use it outside")) return QuanFry1995{FT}(FT(temperature), FT(salinity), extrapolate) @@ -75,17 +84,20 @@ end """ refractive_index(model, λ) -> FT -Real refractive index of seawater relative to air at wavelength `λ` `[nm]` +Return the real refractive index of seawater relative to air at wavelength `λ` `[nm]` (a number or a vector). """ refractive_index(m::FixedRefractiveIndex, λ::Real) = m.n -refractive_index(m::AbstractRefractiveIndexModel, λ::AbstractVector) = [refractive_index(m, x) for x in λ] +refractive_index(m::AbstractRefractiveIndexModel, λ::AbstractVector) = + map(Base.Fix1(refractive_index, m), λ) +# The message is one literal: this method also runs per element in a device +# broadcast, where a string cannot be built. function refractive_index(m::QuanFry1995{FT}, λ::Real) where {FT} - m.extrapolate || 400 ≤ λ ≤ 700 || - throw(DomainError(λ, "QuanFry1995 is fitted to 400–700 nm; pass extrapolate = true " * - "to use it outside, or use FixedRefractiveIndex")) - return FT(_quan_fry_index(λ, m.temperature, m.salinity)) + m.extrapolate || _within(λ, 400, 700) || + throw(DomainError(λ, "QuanFry1995 is fitted to 400–700 nm; pass extrapolate = true to use it outside, or use FixedRefractiveIndex")) + return convert(_result_type(FT, λ), + _quan_fry_index(_wide(λ), _wide(m.temperature), _wide(m.salinity))) end # Quan & Fry (1995) Eq. (4) coefficients; relative to air, λ in nm. diff --git a/src/materials/tabulated.jl b/src/materials/tabulated.jl index 812d27f..4be8d2e 100644 --- a/src/materials/tabulated.jl +++ b/src/materials/tabulated.jl @@ -8,8 +8,10 @@ # `layer_optics` through the ordinary absorber / scatterer roles, so that a # published case runs without any of the package's bio-optical defaults. # -# Values are defined only at their tabulated wavelengths; any other -# wavelength is an error, never an interpolation. +# Values are defined at their tabulated wavelengths (matched within a +# relative tolerance of 1e-6). Any other wavelength is an error, unless the +# constituent was built with `lookup = :linear`, which interpolates linearly +# between neighbouring tabulated wavelengths and never extrapolates. # # Absorption scope # ---------------- @@ -32,13 +34,23 @@ $(TYPEDFIELDS) # Construction - TabulatedAbsorber(λ, a; total = false, source = "") + TabulatedAbsorber(λ, a; total = false, source = "", lookup = :exact) `λ` `[nm]` must be strictly increasing; `a` `[1/m]` finite and non-negative. Set `total = true` when `a` is the bulk absorption of the whole layer (all absorbers, including water): [`layer_optics`](@ref) then requires every other constituent in the layer to have zero absorption. +A query wavelength matches a tabulated one when they agree to a relative +`1e-6`, which absorbs the round-off of `Float32` wavelengths and of grids +computed from wavenumbers as `1e7/ν`. With `lookup = :exact` any other +wavelength throws; with `lookup = :linear` the coefficient is interpolated +linearly between the neighbouring tabulated wavelengths (a `DomainError` +outside the table). `lookup` also accepts an [`ExactLookup`](@ref) or +[`LinearLookup`](@ref); the choice is the type parameter `L`. Exact lookups return +the table's precision; interpolated values have the type that the query and the +table promote to, so a `ForwardDiff.Dual` wavelength gives the slope of the segment. + # Example ```julia @@ -50,7 +62,7 @@ absorption(a_blk, 450.0) # 0.0092 absorption(a_blk, 500.0) # ArgumentError: not a tabulated wavelength ``` """ -struct TabulatedAbsorber{FT} <: AbstractAbsorber{FT} +struct TabulatedAbsorber{FT, L<:AbstractTableLookup} <: AbstractAbsorber{FT} "Wavelengths `[nm]`, strictly increasing" λ::Vector{FT} "Absorption coefficient `[1/m]` at each `λ`" @@ -59,18 +71,25 @@ struct TabulatedAbsorber{FT} <: AbstractAbsorber{FT} total::Bool "Provenance: citation, table, and any transformation applied" source::String + "`ExactLookup()` (tabulated wavelengths only) or `LinearLookup()` (interpolate between them)" + lookup::L - function TabulatedAbsorber{FT}(λ, a, total, source) where {FT<:AbstractFloat} - c = new{FT}(λ, a, total, source) + function TabulatedAbsorber{FT, L}(λ, a, total, source, + lookup) where {FT<:Real, + L<:Union{ExactLookup, LinearLookup}} + c = new{FT, L}(λ, a, total, source, lookup) _check_tabulated_coefficients(c.λ, c.a, "TabulatedAbsorber", "a") return c end end function TabulatedAbsorber(λ::AbstractVector, a::AbstractVector; - total::Bool = false, source::AbstractString = "") + total::Bool = false, source::AbstractString = "", + lookup = :exact) FT = float(promote_type(eltype(λ), eltype(a))) - return TabulatedAbsorber{FT}(collect(FT, λ), collect(FT, a), total, String(source)) + l = _table_lookup(lookup, (ExactLookup(), LinearLookup()), "TabulatedAbsorber") + return TabulatedAbsorber{FT, typeof(l)}(collect(FT, λ), collect(FT, a), total, + String(source), l) end """ @@ -84,16 +103,18 @@ $(TYPEDFIELDS) # Construction - TabulatedScatterer(λ, b, phase; source = "") + TabulatedScatterer(λ, b, phase; source = "", lookup = :exact) `λ` `[nm]` must be strictly increasing; `b` `[1/m]` finite and -non-negative. `phase` is any [`AbstractOceanPhaseFunction`](@ref); a +non-negative; wavelengths are matched, and with `lookup = :linear` +interpolated, as for [`TabulatedAbsorber`](@ref) (the phase function keeps +its own wavelength lookup). `phase` is any [`AbstractOceanPhaseFunction`](@ref); a wavelength-dependent [`TabulatedGreekPhase`](@ref) must tabulate every wavelength in `λ`. The backscattering coefficient is derived from the phase function, `b_b = b · B`, so the two can never disagree; for a `TabulatedGreekPhase`, `B` is that of the tabulated (possibly truncated) -expansion. Model an -absorbing component as a `TabulatedAbsorber` plus a `TabulatedScatterer`. +expansion. Model an absorbing component as a `TabulatedAbsorber` plus a +`TabulatedScatterer`. # Example @@ -105,7 +126,8 @@ water_scat = TabulatedScatterer([350.0, 450.0, 550.0, 650.0], source = "Chowdhary et al. 2020, Table 2") ``` """ -struct TabulatedScatterer{FT, P<:AbstractOceanPhaseFunction{FT}} <: AbstractScatterer{FT} +struct TabulatedScatterer{FT, P<:AbstractOceanPhaseFunction{FT}, + L<:AbstractTableLookup} <: AbstractScatterer{FT} "Wavelengths `[nm]`, strictly increasing" λ::Vector{FT} "Scattering coefficient `[1/m]` at each `λ`" @@ -114,10 +136,14 @@ struct TabulatedScatterer{FT, P<:AbstractOceanPhaseFunction{FT}} <: AbstractScat phase::P "Provenance: citation, table, and any transformation applied" source::String - - function TabulatedScatterer{FT, P}(λ, b, phase, source) where {FT<:AbstractFloat, - P<:AbstractOceanPhaseFunction{FT}} - c = new{FT, P}(λ, b, phase, source) + "`ExactLookup()` (tabulated wavelengths only) or `LinearLookup()` (interpolate between them)" + lookup::L + + function TabulatedScatterer{FT, P, L}(λ, b, phase::P, source, + lookup) where {FT<:Real, + P<:AbstractOceanPhaseFunction{FT}, + L<:Union{ExactLookup, LinearLookup}} + c = new{FT, P, L}(λ, b, phase, source, lookup) _check_tabulated_coefficients(c.λ, c.b, "TabulatedScatterer", "b") if is_wavelength_dependent(phase) for λi in c.λ # every tabulated wavelength must have a phase column @@ -130,9 +156,10 @@ end function TabulatedScatterer(λ::AbstractVector, b::AbstractVector, phase::AbstractOceanPhaseFunction{FT}; - source::AbstractString = "") where {FT} - return TabulatedScatterer{FT, typeof(phase)}(collect(FT, λ), collect(FT, b), phase, - String(source)) + source::AbstractString = "", lookup = :exact) where {FT} + l = _table_lookup(lookup, (ExactLookup(), LinearLookup()), "TabulatedScatterer") + return TabulatedScatterer{FT, typeof(phase), typeof(l)}(collect(FT, λ), collect(FT, b), + phase, String(source), l) end function _check_tabulated_coefficients(λ::AbstractVector, x::AbstractVector, @@ -146,17 +173,18 @@ function _check_tabulated_coefficients(λ::AbstractVector, x::AbstractVector, return nothing end -absorption(c::TabulatedAbsorber, λ::Real) = c.a[_exact_λ_index(c.λ, λ, "TabulatedAbsorber")] -absorption(c::TabulatedAbsorber, λ::AbstractVector) = [absorption(c, λi) for λi in λ] +absorption(c::TabulatedAbsorber, λ::Real) = + _tabulated_value(c.lookup, c.λ, c.a, λ, "TabulatedAbsorber") +absorption(c::TabulatedAbsorber, λ::AbstractVector) = map(Base.Fix1(absorption, c), λ) scattering(c::TabulatedScatterer, λ::Real) = - c.b[_exact_λ_index(c.λ, λ, "TabulatedScatterer")] -scattering(c::TabulatedScatterer, λ::AbstractVector) = [scattering(c, λi) for λi in λ] + _tabulated_value(c.lookup, c.λ, c.b, λ, "TabulatedScatterer") +scattering(c::TabulatedScatterer, λ::AbstractVector) = map(Base.Fix1(scattering, c), λ) backscattering(c::TabulatedScatterer, λ::Real) = scattering(c, λ) * backscatter_fraction(c.phase, λ) backscattering(c::TabulatedScatterer, λ::AbstractVector) = - [backscattering(c, λi) for λi in λ] + map(Base.Fix1(backscattering, c), λ) scattering_phase(c::TabulatedScatterer) = c.phase @@ -165,16 +193,17 @@ _component_label(c::TabulatedScatterer) = isempty(c.source) ? "TabulatedScattere """ is_total_absorption(c::AbstractOceanConstituent) -> Bool -Whether `c`'s absorption is the bulk absorption of its whole layer, so -that no other constituent in the layer may absorb. Only a -[`TabulatedAbsorber`](@ref) built with `total = true` returns `true`. +Return whether the absorption of `c` is the bulk absorption of its whole layer, so that +no other constituent in the layer may absorb. + +Only a [`TabulatedAbsorber`](@ref) built with `total = true` returns `true`. """ is_total_absorption(::AbstractOceanConstituent) = false is_total_absorption(c::TabulatedAbsorber) = c.total function Base.show(io::IO, c::TabulatedAbsorber{FT}) where {FT} print(io, "TabulatedAbsorber{$FT}(", length(c.λ), " λ", - c.total ? ", total" : "", + c.total ? ", total" : "", c.lookup isa ExactLookup ? "" : ", $(_lookup_name(c.lookup))", isempty(c.source) ? "" : ", \"$(c.source)\"", ")") end diff --git a/src/mixing/layer_assembly.jl b/src/mixing/layer_assembly.jl index f77cfa5..278754d 100644 --- a/src/mixing/layer_assembly.jl +++ b/src/mixing/layer_assembly.jl @@ -13,11 +13,13 @@ # ============================================================================= """ - layer_optics(layer, λ; ℓ_max = 64, polarized = false, - scalar_phase_approximation = nothing, FT = Float64) -> OceanLayerOptics + layer_optics([FT,] layer, λ; ℓ_max = 64, polarized = false, + scalar_phase_approximation = nothing) -> OceanLayerOptics{FT} -Optical properties of one [`OceanLayer`](@ref) at wavelengths `λ` `[nm]` -(strictly monotone, increasing or decreasing). +Compute the optical properties of one [`OceanLayer`](@ref) at wavelengths `λ` `[nm]`. + +`λ` is strictly monotone, increasing or decreasing. The element type `FT` of the result +defaults to that of `layer`. # Keywords - `ℓ_max` — highest expansion order. The expansions are exact through @@ -31,7 +33,6 @@ Optical properties of one [`OceanLayer`](@ref) at wavelengths `λ` `[nm]` completely depolarizing approximation, labelled `:depolarizing` on the component. Applies to every such scatterer, even one with zero scattering. Ignored when `polarized = false`. -- `FT` — floating-point type of the result. # Result An [`OceanLayerOptics`](@ref) with, in constituent order, @@ -63,21 +64,31 @@ optical_depth(opt), single_scattering_albedo(opt) opt.scatterers[2].label # "Phytoplankton" ``` """ -function layer_optics(layer::OceanLayer, λ_grid::AbstractVector{<:Real}; +function layer_optics(::Type{FT}, layer::OceanLayer, λ_grid::AbstractVector{<:Real}; ℓ_max::Integer = 64, polarized::Bool = false, - scalar_phase_approximation::Union{Nothing, Symbol} = nothing, - FT::Type{<:AbstractFloat} = Float64) + scalar_phase_approximation::Union{Nothing, Symbol} = nothing) where {FT<:Real} + _check_parameter_type(FT) return _layer_optics(layer, λ_grid, ℓ_max, polarized, scalar_phase_approximation, FT, - Dict{Any, Any}()) + _expansion_cache(FT)) end -# `cache` maps (phase_id, ℓ_max, FT, phase key) to (expansion, backscatter -# fraction), so that each distinct expansion is computed once — per layer, -# or per column when `column_optics` shares it between layers (which then -# share the same GreekCoefficients objects). +layer_optics(layer::OceanLayer{T}, λ_grid::AbstractVector{<:Real}; kwargs...) where {T} = + layer_optics(T, layer, λ_grid; kwargs...) + +# Key of one expansion: (phase function identity, polarization label, ℓ_max, +# phase key); the phase key is `nothing` for a wavelength-independent phase. +const _ExpansionKey = Tuple{UInt, Symbol, Int, Any} + +# Maps an `_ExpansionKey` to (expansion, backscatter fraction), so that each +# expansion is computed once — per layer, or per column when `column_optics` +# shares the cache between layers (which then share the same +# GreekCoefficients objects). One cache serves one element type. +_expansion_cache(::Type{FT}) where {FT} = + Dict{_ExpansionKey, Tuple{GreekCoefficients{FT, Vector{FT}}, FT}}() + function _layer_optics(layer::OceanLayer, λ_grid, ℓ_max, polarized, - scalar_phase_approximation, FT, cache) + scalar_phase_approximation, ::Type{FT}, cache) where {FT} ℓ_max ≥ 0 || throw(ArgumentError("ℓ_max must be non-negative, got $ℓ_max")) scalar_phase_approximation in (nothing, :depolarizing) || throw(ArgumentError("scalar_phase_approximation must be `nothing` or " * @@ -88,6 +99,11 @@ function _layer_optics(layer::OceanLayer, λ_grid, ℓ_max, polarized, "strictly monotone")) Δz = FT(thickness(layer)) constituents = layer.constituents + n_water = count(c -> c isa PureWater, constituents) + n_water ≤ 1 || + throw(ArgumentError("layer_optics: the layer lists PureWater $n_water times, which " * + "would count the water absorption and scattering $n_water " * + "times; check the constituent list and keep one PureWater")) # --- absorption components ----------------------------------------------- absorbing = [c for c in constituents if c isa AbstractAbsorber] @@ -95,15 +111,15 @@ function _layer_optics(layer::OceanLayer, λ_grid, ℓ_max, polarized, length(i_total) ≤ 1 || throw(ArgumentError("layer_optics: $(length(i_total)) constituents declare total " * "(bulk) absorption; at most one can")) - i_bulk = isempty(i_total) ? 0 : only(i_total) - absorbers = AbsorptionComponent{FT}[] + i_bulk::Int = isempty(i_total) ? 0 : only(i_total) + absorbers = AbsorptionComponent{FT, Vector{FT}}[] first_part = Int[] # index of each absorber's first component for (i, c) in enumerate(absorbing) parts = absorption_parts(c) τ = zeros(FT, length(parts), length(λ)) for (k, λk) in enumerate(λ) a = absorption_by_part(c, λk) - if i_bulk != 0 && i != i_bulk && any(!iszero, a) + if i_bulk != 0 && i != i_bulk && any(!iszero, a)::Bool throw(ArgumentError("layer_optics: $(absorbing[i_bulk]) is the total " * "absorption of the layer, but $(nameof(typeof(c))) also " * "absorbs (a = $(sum(a)) 1/m at λ = $λk nm); this would " * @@ -115,7 +131,7 @@ function _layer_optics(layer::OceanLayer, λ_grid, ℓ_max, polarized, end push!(first_part, length(absorbers) + 1) for (j, part) in enumerate(parts) - push!(absorbers, AbsorptionComponent{FT}(_component_label(c), part, τ[j, :])) + push!(absorbers, AbsorptionComponent{FT, Vector{FT}}(_component_label(c), part, τ[j, :])) end end @@ -143,27 +159,26 @@ function _layer_optics(layer::OceanLayer, λ_grid, ℓ_max, polarized, "a TabulatedMuellerPhase or polarized TabulatedGreekPhase) or " * "pass `scalar_phase_approximation = :depolarizing`.")) end - components = [_scattering_component(c, λ, Δz, ℓ_max, polarized, FT, cache) - for c in scatterers] - return OceanLayerOptics{FT}(λ, FT(layer.depth_top), FT(layer.depth_bottom), absorbers, - components, collect(InelasticComponent{FT}, inelastic), - ℓ_max + 1, polarized) + components = ScatteringComponent{FT, Vector{FT}, Vector{Int}}[ + _scattering_component(c, λ, Δz, ℓ_max, polarized, FT, cache) for c in scatterers] + return OceanLayerOptics{FT, Vector{FT}, Vector{Int}}( + λ, FT(layer.depth_top), FT(layer.depth_bottom), absorbers, components, + collect(InelasticComponent{FT}, inelastic), ℓ_max + 1, polarized) end function _scattering_component(c, λ::Vector{FT}, Δz::FT, ℓ_max, polarized, ::Type{FT}, cache) where {FT} pf = scattering_phase(c) label = !polarized ? :scalar : is_polarizable(pf) ? :full : :depolarizing - pid = hash((objectid(pf), label)) expand(args...) = label === :scalar ? greek_expansion(pf, ℓ_max, args...) : label === :full ? greek_expansion(pf, ℓ_max, args...; polarized = true) : depolarizing_greek_expansion(pf, ℓ_max, args...) - entry(key, args...) = get!(cache, (pid, ℓ_max, FT, key)) do + entry(key, args...) = get!(cache, (objectid(pf), label, Int(ℓ_max), key)) do (_convert_greek(FT, expand(args...)), FT(backscatter_fraction(pf, args...))) end if is_wavelength_dependent(pf) keys = [_phase_key(pf, λk) for λk in λ] - slot = Dict{Any, Int}() + slot = Dict{eltype(keys), Int}() first_λ = Int[] for (k, key) in enumerate(keys) haskey(slot, key) || (slot[key] = length(slot) + 1; push!(first_λ, k)) @@ -174,10 +189,11 @@ function _scattering_component(c, λ::Vector{FT}, Δz::FT, ℓ_max, polarized, : entries = [entry(nothing)] index = Int[] end - greek = [e[1] for e in entries] - B = [e[2] for e in entries] - τ = [FT(scattering(c, λk)) * Δz for λk in λ] - return ScatteringComponent{FT}(_component_label(c), pid, τ, greek, B, index, label) + greek = GreekCoefficients{FT, Vector{FT}}[e[1] for e in entries] + B = FT[e[2] for e in entries] + τ = FT[FT(scattering(c, λk)) * Δz for λk in λ] + return ScatteringComponent{FT, Vector{FT}, Vector{Int}}(_component_label(c), τ, greek, B, + index, label) end _component_label(c::AbstractOceanConstituent) = string(nameof(typeof(c))) @@ -205,15 +221,23 @@ _convert_greek(::Type{FT}, g::GreekCoefficients) where {FT} = GreekCoefficients{FT}((FT.(getfield(g, f)) for f in fieldnames(GreekCoefficients))...) """ - column_optics(column, λ; refractive_index, bottom, ℓ_max = 64, polarized = false, - scalar_phase_approximation = nothing, FT = Float64) -> OceanColumnOptics + column_optics([FT,] column, λ; refractive_index, bottom, ℓ_max = 64, + polarized = false, + scalar_phase_approximation = nothing) -> OceanColumnOptics{FT} -Optical description of an [`OceanColumn`](@ref) for a coupled -atmosphere–ocean solver: [`layer_optics`](@ref) for every layer on the -same grid and settings, the interface refractive index, and the bottom. +Compute the optical description of an [`OceanColumn`](@ref) for a coupled +atmosphere–ocean solver. + +The result holds [`layer_optics`](@ref) of every layer on the same grid and settings, +the interface refractive index, and the bottom. The element type `FT` defaults to that +of `column`. Components with the same phase function and polarization treatment share -one `phase_id` and the same expansion objects across layers. +the same expansion objects across layers; their `phase_id` keys are equal +because the coefficients are. + +The model is evaluated on the host; the result holds `Vector`s. Move it to +a device with `Adapt.adapt(to, col)` (see [`OceanColumnOptics`](@ref)). `refractive_index` (an [`AbstractRefractiveIndexModel`](@ref), e.g. `FixedRefractiveIndex(1.34)` or `QuanFry1995(; temperature, salinity)`) @@ -225,34 +249,43 @@ which is interpolated onto `λ`. # Example ```julia water = PureWater{Float64}() -column = uniform_column(AbstractOceanConstituent{Float64}[water]; n_layers = 4, depth = 20.0) -col = column_optics(column, [450.0, 550.0]; refractive_index = FixedRefractiveIndex(1.34), +column = uniform_column(AbstractOceanConstituent{Float64}[water]; + n_layers = 4, depth = 20.0) +col = column_optics(column, [450.0, 550.0]; + refractive_index = FixedRefractiveIndex(1.34), bottom = BlackBottom(), polarized = true) ``` """ -function column_optics(column::OceanColumn, λ_grid::AbstractVector{<:Real}; +function column_optics(::Type{FT}, column::OceanColumn, λ_grid::AbstractVector{<:Real}; refractive_index::AbstractRefractiveIndexModel, bottom::AbstractOceanBottom, ℓ_max::Integer = 64, polarized::Bool = false, - scalar_phase_approximation::Union{Nothing, Symbol} = nothing, - FT::Type{<:AbstractFloat} = Float64) - cache = Dict{Any, Any}() - layers = [_layer_optics(l, λ_grid, ℓ_max, polarized, scalar_phase_approximation, FT, cache) - for l in column] + scalar_phase_approximation::Union{Nothing, Symbol} = nothing) where {FT<:Real} + _check_parameter_type(FT) + cache = _expansion_cache(FT) + layers = OceanLayerOptics{FT, Vector{FT}, Vector{Int}}[ + _layer_optics(l, λ_grid, ℓ_max, polarized, scalar_phase_approximation, FT, cache) + for l in column] λ = first(layers).λ - n = FT.(OceanOptics.refractive_index(refractive_index, λ)) + n = FT.(_index_on_grid(refractive_index, λ)) return OceanColumnOptics(layers, n, _resolve_bottom(bottom, λ, FT)) end +column_optics(column::OceanColumn{T}, λ_grid::AbstractVector{<:Real}; kwargs...) where {T} = + column_optics(T, column, λ_grid; kwargs...) + _resolve_bottom(b::AbstractOceanBottom, λ, FT) = b _resolve_bottom(b::LambertianBottom, λ, FT) = LambertianBottom(FT.(b.albedo)) function _resolve_bottom(b::TabulatedLambertianBottom, λ, FT) lo, hi = first(b.λ), last(b.λ) - all(x -> lo ≤ x ≤ hi, λ) || + all(x -> _within(x, lo, hi), λ) || throw(DomainError(extrema(λ), "TabulatedLambertianBottom" * (isempty(b.source) ? "" : " ($(b.source))") * " covers $(lo)–$(hi) nm, " * "the column grid $(minimum(λ))–$(maximum(λ)) nm")) tbl = SpectralTable(FT.(b.λ), FT.(b.albedo)) return LambertianBottom(FT[linterp(tbl, x) for x in λ]) end + +# The keyword `refractive_index` of `column_optics` shadows the function. +_index_on_grid(model::AbstractRefractiveIndexModel, λ) = refractive_index(model, λ) diff --git a/src/phase/abstract_phase.jl b/src/phase/abstract_phase.jl index 8ac50c5..1d7230a 100644 --- a/src/phase/abstract_phase.jl +++ b/src/phase/abstract_phase.jl @@ -44,12 +44,12 @@ New phase functions implement `phase_function_value` (or override `phase_function_moments`); phase matrices also implement `is_polarizable(pf) = true` and `_polarized_greek(pf, ℓ_max)`. """ -abstract type AbstractOceanPhaseFunction{FT<:AbstractFloat} end +abstract type AbstractOceanPhaseFunction{FT<:Real} end """ phase_function_value(pf, μ) -> FT -Phase function `p(μ)` at scattering cosine `μ`, normalized as +Return the phase function `p(μ)` at scattering cosine `μ`, normalized as `(1/2) ∫₋₁¹ p dμ = 1`. """ function phase_function_value end @@ -81,7 +81,7 @@ _normalization_tolerance(::Type{FT}) where {FT} = max(1e-8, 8 * eps(FT)) """ phase_function_moments(pf, ℓ_max[, λ]) -> Vector{FT} -Legendre expansion coefficients `β_ℓ`, `ℓ = 0:ℓ_max` (index 1 is `ℓ = 0`), +Return the Legendre expansion coefficients `β_ℓ`, `ℓ = 0:ℓ_max` (index 1 is `ℓ = 0`), with `p(μ) = Σ_ℓ β_ℓ P_ℓ(μ)` and `β₀ = 1`. The default evaluates `β_ℓ = (2ℓ+1)/2 ∫₀^π p(θ) P_ℓ(cos θ) sin θ dθ` by @@ -113,11 +113,12 @@ phase_function_moments(pf::AbstractOceanPhaseFunction, ℓ_max::Integer, λ::Rea """ greek_expansion(pf, ℓ_max[, λ]; polarized = false) -> GreekCoefficients -Expansion of `pf` up to `ℓ_max`. With `polarized = false` this is the -phase function only (`β`); with `polarized = true` it is the full phase -matrix, available only when [`is_polarizable`](@ref)`(pf)`. For -scalar-only phase functions the completely depolarizing approximation is -available explicitly through [`depolarizing_greek_expansion`](@ref). +Return the expansion of `pf` up to order `ℓ_max`. + +With `polarized = false` this is the phase function only (`β`); with `polarized = true` +it is the full phase matrix, available only when [`is_polarizable`](@ref)`(pf)`. For +scalar-only phase functions the completely depolarizing approximation is available +explicitly through [`depolarizing_greek_expansion`](@ref). """ function greek_expansion(pf::AbstractOceanPhaseFunction, ℓ_max::Integer; polarized::Bool = false) @@ -134,10 +135,11 @@ end """ depolarizing_greek_expansion(pf, ℓ_max[, λ]) -> GreekCoefficients -The phase function of `pf` with the *completely depolarizing* phase matrix -`diag(p(Θ), 0, 0, 0)` (see [`depolarized`](@ref)) — an explicit -approximation for scatterers whose phase matrix is unknown, not their -actual polarization behavior. +Return the expansion of `pf` with the *completely depolarizing* phase matrix +`diag(p(Θ), 0, 0, 0)` (see [`depolarized`](@ref)). + +This is an explicit approximation for scatterers whose phase matrix is unknown, not +their actual polarization behavior. """ depolarizing_greek_expansion(pf::AbstractOceanPhaseFunction, ℓ_max::Integer) = depolarized(greek_expansion(pf, ℓ_max)) @@ -157,7 +159,8 @@ _scalar_only_error(pf::AbstractOceanPhaseFunction) = """ backscatter_fraction(pf[, λ]) -> FT -Fraction of scattering into the back hemisphere, `B = (1/2)∫₋₁⁰ p(μ) dμ`. +Return the fraction of scattering into the back hemisphere, `B = (1/2)∫₋₁⁰ p(μ) dμ`. + The default integrates `p` numerically; closed forms override it. """ function backscatter_fraction(pf::AbstractOceanPhaseFunction{FT}) where {FT} @@ -175,7 +178,7 @@ backscatter_fraction(pf::AbstractOceanPhaseFunction, λ::Real) = backscatter_fra """ asymmetry_parameter(pf[, λ]) -> FT -Mean cosine of the scattering angle, `g = ⟨μ⟩ = β₁ / 3`. +Return the mean cosine of the scattering angle, `g = ⟨μ⟩ = β₁ / 3`. """ asymmetry_parameter(pf::AbstractOceanPhaseFunction{FT}) where {FT} = phase_function_moments(pf, 1)[2] / FT(3) @@ -185,7 +188,7 @@ asymmetry_parameter(pf::AbstractOceanPhaseFunction, λ::Real) = asymmetry_parame """ is_polarizable(pf) -> Bool -Whether `pf` provides a full phase matrix, so that +Return whether `pf` provides a full phase matrix, so that `greek_expansion(pf, ℓ_max; polarized = true)` is defined. """ is_polarizable(::AbstractOceanPhaseFunction) = false @@ -193,8 +196,9 @@ is_polarizable(::AbstractOceanPhaseFunction) = false """ is_wavelength_dependent(pf) -> Bool -Whether `pf` differs between wavelengths; such phase functions must be -queried with an explicit wavelength. Default `false`. +Return whether `pf` differs between wavelengths (`false` unless a type says otherwise). + +A wavelength-dependent phase function must be queried with an explicit wavelength. """ is_wavelength_dependent(::AbstractOceanPhaseFunction) = false @@ -209,13 +213,13 @@ _requires_wavelength(pf) = is_wavelength_dependent(pf) && """ _reconstruct_from_moments(β, μ) -> FT -`p(μ) = Σₗ βₗ Pₗ(μ)` by the three-term Legendre recurrence. +Return `p(μ) = Σₗ βₗ Pₗ(μ)` by the three-term Legendre recurrence. """ function _reconstruct_from_moments(β::AbstractVector{FT}, μ::Real) where {FT} - x = FT(μ) - p = β[1] + x = float(μ) + p = β[1] * one(x) length(β) == 1 && return p - P_prev, P = one(FT), x + P_prev, P = one(x), x p += β[2] * P for ℓ in 2:length(β)-1 P_prev, P = P, ((2ℓ - 1) * x * P - (ℓ - 1) * P_prev) / ℓ diff --git a/src/phase/angular.jl b/src/phase/angular.jl index a15c374..5347b83 100644 --- a/src/phase/angular.jl +++ b/src/phase/angular.jl @@ -114,13 +114,14 @@ _scaled(v::Tuple, ℓ_max) = reduce(vcat, (_scaled(x, ℓ_max) for x in v)) # ----------------------------------------------------------------------------- """ - _legendre_moments(fvals, θ, w, ℓ_max) -> Vector{Float64} + _legendre_moments(fvals, θ, w, ℓ_max) -> Vector -`β_ℓ = (2ℓ+1)/2 ∫₀^π f(θ) P_ℓ(cos θ) sin θ dθ` for `ℓ = 0:ℓ_max`. +`β_ℓ = (2ℓ+1)/2 ∫₀^π f(θ) P_ℓ(cos θ) sin θ dθ` for `ℓ = 0:ℓ_max`, in the element type of +`fvals` promoted with `Float64` (the nodes and weights). """ function _legendre_moments(fvals::AbstractVector, θ::AbstractVector, w::AbstractVector, ℓ_max::Integer) - β = zeros(ℓ_max + 1) + β = zeros(promote_type(eltype(fvals), Float64), ℓ_max + 1) @inbounds for i in eachindex(θ) x = cos(θ[i]) fw = fvals[i] * w[i] @@ -208,9 +209,10 @@ end """ evaluate_scattering_matrix(g::GreekCoefficients, μ) -> NamedTuple -Angular scattering matrix reconstructed from the expansion at scattering -cosines `μ`, in the standard convention (Hansen & Travis 1974; -Mishchenko et al. 2002: `F₁₂ < 0` for Rayleigh scattering at 90°): +Return the angular scattering matrix of the expansion `g` at the scattering cosines `μ`. + +The elements are in the standard convention (Hansen & Travis 1974; Mishchenko et al. +2002: `F₁₂ < 0` for Rayleigh scattering at 90°): ``` F = [F11 F12 0 0 @@ -219,7 +221,7 @@ F = [F11 F12 0 0 0 0 -F34 F44] ``` -normalized so that `(1/2)∫ F11 dμ = 1`. Returns `(; F11)` for a scalar +normalized so that `(1/2)∫ F11 dμ = 1`. The result is `(; F11)` for a scalar expansion and `(; F11, F12, F22, F33, F34, F44)` otherwise. """ function evaluate_scattering_matrix(g::GreekCoefficients{FT}, μ::AbstractVector{<:Real}) where {FT} diff --git a/src/phase/fournier_forand.jl b/src/phase/fournier_forand.jl index 0257020..d231935 100644 --- a/src/phase/fournier_forand.jl +++ b/src/phase/fournier_forand.jl @@ -25,6 +25,9 @@ # - Mobley, Sundman & Boss, Appl. Opt. 41, 1035 (2002) # ============================================================================= +# Open interval of the Junge slope μ_j over which the phase function is defined. +const _FF_JUNGE_SLOPE_RANGE = (3.0, 5.0) + """ $(TYPEDEF) @@ -42,7 +45,9 @@ FournierForandPhase{Float64}(backscatter_fraction = 0.01) # Mobley et al. (2002 With `backscatter_fraction = B`, `(n, μ_j)` are found on the family `n = 1.01 + 0.1542 (μ_j − 3)` of Mobley, Sundman & Boss (2002); `B` must -lie in the range that family spans for `3 < μ_j < 5`. The field is called +lie in the range that family spans for `3 < μ_j < 5`. A dual-number `B` gives dual +`(n, μ_j)` with the derivative of that inversion, which the phase function, its +backscatter fraction and its Legendre expansion carry. The field is called `μ_j` (Junge slope) because `μ` denotes `cos θ` throughout this package. """ struct FournierForandPhase{FT} <: AbstractOceanPhaseFunction{FT} @@ -51,22 +56,24 @@ struct FournierForandPhase{FT} <: AbstractOceanPhaseFunction{FT} "Junge slope of the particle size distribution, 3 < μ_j < 5" μ_j::FT - function FournierForandPhase{FT}(n::FT, μ_j::FT) where {FT<:AbstractFloat} + function FournierForandPhase{FT}(n::FT, μ_j::FT) where {FT<:Real} + _check_parameter_type(FT) # n < 1.5 keeps clear of the poles of the closed form at δ₉₀ = 1 # (n ≈ 1.82) and δ₁₈₀ = 1 (n ≈ 2.15); ocean particles have n ≲ 1.3. 1 < n < 1.5 || throw(ArgumentError("FournierForand: n must lie in (1, 1.5), got $n")) - FT(3) < μ_j < FT(5) || - throw(ArgumentError("FournierForand: Junge slope must lie in (3, 5), got $μ_j")) + FT(first(_FF_JUNGE_SLOPE_RANGE)) < μ_j < FT(last(_FF_JUNGE_SLOPE_RANGE)) || + throw(ArgumentError("FournierForand: Junge slope must lie in $(_FF_JUNGE_SLOPE_RANGE), got $μ_j")) new{FT}(n, μ_j) end end function FournierForandPhase{FT}(; n = nothing, μ_j = nothing, - backscatter_fraction = nothing) where {FT<:AbstractFloat} + backscatter_fraction = nothing) where {FT<:Real} + _check_parameter_type(FT) if backscatter_fraction !== nothing (n === nothing && μ_j === nothing) || throw(ArgumentError("FournierForand: give either (n, μ_j) or backscatter_fraction")) - nn, mj = _ff_mobley_parameters(Float64(backscatter_fraction)) + nn, mj = _ff_mobley_parameters(backscatter_fraction) return FournierForandPhase{FT}(FT(nn), FT(mj)) end (n === nothing || μ_j === nothing) && @@ -74,7 +81,7 @@ function FournierForandPhase{FT}(; n = nothing, μ_j = nothing, return FournierForandPhase{FT}(FT(n), FT(μ_j)) end -FournierForandPhase(; kwargs...) = FournierForandPhase{Float64}(; kwargs...) +FournierForandPhase(; kwargs...) = FournierForandPhase{_parameter_type(values(kwargs))}(; kwargs...) # p as a function of s = sin²(θ/2), normalized as (1/2)∫p dμ = 1. function _ff_value(n, μ_j, s) @@ -82,7 +89,7 @@ function _ff_value(n, μ_j, s) ν = (3 - μ_j) / 2 c = 3 * (n - 1)^2 / 4 # δ = s / c δ = s / c - δ_ν = δ^ν + δ_ν = _ff_power(δ, s, c, ν) x = 1 - δ main = if abs(x) < 1e-2 _ff_main_series(ν, c, x) / (4π * δ_ν) # removable 0/0 at δ = 1 @@ -94,6 +101,13 @@ function _ff_value(n, μ_j, s) return 4π * (main + back) end +# δ^ν for δ = s/c. Floating-point arguments use `^`. Any other number (a dual) takes +# exp(ν (log s − log c)): ForwardDiff's rule for x^y forms x^(y−1) and, in a second +# derivative, x^(y−2), which overflows at the forward floor s ≈ 1e-200 and gives +# ∞·0 = NaN, although every derivative of δ^ν is of the size of δ^ν log^k δ. +_ff_power(δ::AbstractFloat, s, c::AbstractFloat, ν::AbstractFloat) = δ^ν +_ff_power(δ, s, c, ν) = exp(ν * (log(s) - log(c))) + # Numerator of the main term divided by (1 − δ)², as a power series in # x = 1 − δ: with 1 − (1−x)^ν = Σ bₖ xᵏ, # N / x² = Σ_{k≥2} [−bₖ + (bₖ − ν)/c] x^(k−2), @@ -116,11 +130,13 @@ end """ phase_function_value(pf::FournierForandPhase, μ) -Fournier & Jonasz (1999) phase function, normalized as -`(1/2)∫₋₁¹ p dμ = 1`. Diverges (integrably) at `μ → 1`; values there are -large but finite. +Return the phase function of Fournier & Jonasz (1999) at scattering cosine `μ`, +normalized as `(1/2)∫₋₁¹ p dμ = 1`. + +It diverges (integrably) for `μ → 1`; values there are large but finite. """ -phase_function_value(pf::FournierForandPhase, μ::Real) = _ff_value(pf.n, pf.μ_j, (1 - μ) / 2) +phase_function_value(pf::FournierForandPhase{FT}, μ::Real) where {FT} = + convert(_result_type(FT, μ), _ff_value(_wide(pf.n), _wide(pf.μ_j), (1 - _wide(μ)) / 2)) _phase_at_angle(pf::FournierForandPhase, θ::Real) = _ff_value(pf.n, pf.μ_j, sin(θ / 2)^2) @@ -130,8 +146,8 @@ _forward_exponent(pf::FournierForandPhase) = pf.μ_j - 5 """ backscatter_fraction(pf::FournierForandPhase) -> FT -Closed form (Fournier & Jonasz 1999; Mobley et al. 2002 Eq. 10): -`B = 1 − [1 − δ₉₀^(ν+1) − ½(1 − δ₉₀^ν)] / [(1 − δ₉₀) δ₉₀^ν]`. +Return the backscatter fraction in closed form (Fournier & Jonasz 1999; Mobley et al. +2002 Eq. 10): `B = 1 − [1 − δ₉₀^(ν+1) − ½(1 − δ₉₀^ν)] / [(1 − δ₉₀) δ₉₀^ν]`. """ backscatter_fraction(pf::FournierForandPhase{FT}) where {FT} = FT(_ff_backscatter(pf.n, pf.μ_j)) @@ -141,18 +157,55 @@ function _ff_backscatter(n, μ_j) return 1 - (1 - δ_90^(ν + 1) - (1 - δ_90^ν) / 2) / ((1 - δ_90) * δ_90^ν) end -# Mobley, Sundman & Boss (2002) parameter family. -_ff_mobley_n(μ_j) = 1.01 + 0.1542 * (μ_j - 3) +# Mobley, Sundman & Boss (2002) parameter family n = n₀ + s (μ_j − μ₀), μ_j ∈ (μ₀, 5). +const _FF_MOBLEY_2002_N0 = 1.01 +const _FF_MOBLEY_2002_SLOPE = 0.1542 +const _FF_MOBLEY_2002_μ0 = first(_FF_JUNGE_SLOPE_RANGE) # the family starts at μ_j = 3 +_ff_mobley_n(μ_j) = _FF_MOBLEY_2002_N0 + _FF_MOBLEY_2002_SLOPE * (μ_j - _FF_MOBLEY_2002_μ0) """ _ff_mobley_parameters(B) -> (n, μ_j) -Solve `B(n(μ_j), μ_j) = B` on the Mobley et al. (2002) family by bisection -in `μ_j ∈ (3, 5)`; `B` is monotone along it. +Solve `B(n(μ_j), μ_j) = B` on the Mobley et al. (2002) family; `B` is monotone along it. + +The root `μ₀` is found by bisection in `μ_j ∈ (3, 5)`. For a `B` that is not a +floating-point number (a dual number) the root is refined in the number type of `B` by +the chord iteration `μ ← μ − (B(μ) − B) / B′(μ₀)`, started at `μ₀`, with `B′(μ₀)` +from the complex-step derivative. The value stays `μ₀` (to round-off); each step makes +one more order of derivative exact, so the `_FF_CHORD_STEPS` steps give exact +derivatives of `μ_j` with respect to `B` up to that order (nested duals, Hessians). +""" +function _ff_mobley_parameters(B::AbstractFloat) + μ = _ff_mobley_root(Float64(B)) + return _ff_mobley_n(μ), μ +end + +function _ff_mobley_parameters(B::Real) + μ₀ = _ff_mobley_root(B) + B₀ = _ff_backscatter(_ff_mobley_n(μ₀), μ₀) + # B′(μ₀) along the family by the complex-step derivative, exact to round-off. + z = complex(μ₀, _COMPLEX_STEP) + dB = imag(_ff_backscatter(_ff_mobley_n(z), z)) / _COMPLEX_STEP + μ = μ₀ + (B - B₀) / dB + for _ in 2:_FF_CHORD_STEPS + μ -= (_ff_backscatter(_ff_mobley_n(μ), μ) - B) / dB + end + return _ff_mobley_n(μ), μ +end + """ -function _ff_mobley_parameters(B::Float64) +Number of chord steps of `_ff_mobley_parameters(B::Real)`; derivatives of `μ_j(B)` up +to this order are exact, higher ones are not. +""" +const _FF_CHORD_STEPS = 4 + +"Imaginary increment of the complex-step derivative `f′(x) ≈ Im f(x + ih) / h`." +const _COMPLEX_STEP = 1e-20 + +# Root μ₀::Float64 of B(n(μ), μ) = B by bisection; only the value of `B` is compared. +function _ff_mobley_root(B::Real) f(μ) = _ff_backscatter(_ff_mobley_n(μ), μ) - B - lo, hi = 3.0 + 1e-9, 5.0 - 1e-9 + lo, hi = first(_FF_JUNGE_SLOPE_RANGE) + 1e-9, last(_FF_JUNGE_SLOPE_RANGE) - 1e-9 flo, fhi = f(lo), f(hi) flo < 0 < fhi || throw(ArgumentError("FournierForand: backscatter fraction $B is outside the range " * @@ -163,6 +216,5 @@ function _ff_mobley_parameters(B::Float64) f(mid) < 0 ? (lo = mid) : (hi = mid) hi - lo < 1e-14 && break end - μ = (lo + hi) / 2 - return _ff_mobley_n(μ), μ + return (lo + hi) / 2 end diff --git a/src/phase/henyey_greenstein.jl b/src/phase/henyey_greenstein.jl index 43a349e..8c291e2 100644 --- a/src/phase/henyey_greenstein.jl +++ b/src/phase/henyey_greenstein.jl @@ -35,16 +35,17 @@ struct HenyeyGreensteinPhase{FT} <: AbstractOceanPhaseFunction{FT} "Asymmetry parameter `g = ⟨μ⟩ = β₁`, must satisfy `|g| < 1`" g::FT - function HenyeyGreensteinPhase{FT}(g::FT) where {FT<:AbstractFloat} + function HenyeyGreensteinPhase{FT}(g::FT) where {FT<:Real} + _check_parameter_type(FT) abs(g) < one(FT) || throw(ArgumentError("HenyeyGreenstein: |g| must be strictly less than 1, got g=$g")) new{FT}(g) end end -HenyeyGreensteinPhase{FT}(; g = FT(0.85)) where {FT<:AbstractFloat} = - HenyeyGreensteinPhase{FT}(FT(g)) -HenyeyGreensteinPhase(; kwargs...) = HenyeyGreensteinPhase{Float64}(; kwargs...) +HenyeyGreensteinPhase{FT}(; g = 0.85) where {FT<:Real} = + (_check_parameter_type(FT); HenyeyGreensteinPhase{FT}(FT(g))) +HenyeyGreensteinPhase(; kwargs...) = HenyeyGreensteinPhase{_parameter_type(values(kwargs))}(; kwargs...) # ----------------------------------------------------------------------------- # Phase function value and moments @@ -79,14 +80,13 @@ asymmetry_parameter(pf::HenyeyGreensteinPhase) = pf.g """ backscatter_fraction(pf::HenyeyGreensteinPhase) -> FT -Closed form derived from direct integration of `(1/2) ∫₋₁⁰ p(μ) dμ` with -substitution `u = 1 + g² - 2gμ`: +Return the backscatter fraction `(1/2) ∫₋₁⁰ p(μ) dμ` in closed form: ``` B(g) = (1-g²)/(2g) · [ 1/√(1+g²) - 1/(1+g) ] ``` -At `g = 0` the expression is 0/0; we short-circuit to `B = 1/2` (isotropic). +At `g = 0` the expression is 0/0 and the isotropic value `B = 1/2` is returned. """ function backscatter_fraction(pf::HenyeyGreensteinPhase{FT}) where {FT} g = pf.g diff --git a/src/phase/petzold.jl b/src/phase/petzold.jl index ff08b2b..a0e860d 100644 --- a/src/phase/petzold.jl +++ b/src/phase/petzold.jl @@ -51,22 +51,31 @@ end PetzoldPhase() = PetzoldPhase{Float64}() +# The table is a measurement without parameters; its quadrature break points +# are floating-point numbers. +PetzoldPhase{FT}() where {FT<:Real} = + throw(ArgumentError("PetzoldPhase{$FT}: the Petzold table has no parameter to " * + "differentiate and is available in floating-point types only; " * + "use a parametric phase function (FournierForandPhase, " * + "HenyeyGreensteinPhase) in a layer that carries dual numbers")) + _petzold_forward_exponent(pf::PetzoldPhase) = log(pf.p[2] / pf.p[1]) / log(pf.θ[2] / pf.θ[1]) -function _phase_at_angle(pf::PetzoldPhase, θ::Real) +function _phase_at_angle(pf::PetzoldPhase{FT}, θ::Real) where {FT} + T = promote_type(FT, typeof(float(θ))) θs, ps = pf.θ, pf.p - if θ ≤ first(θs) # power-law forward peak; finite at θ = 0 - return first(ps) * (max(θ, 1e-300) / first(θs))^_petzold_forward_exponent(pf) + if θ ≤ first(θs) # power-law forward peak; `floatmin` avoids 0^a at θ = 0 + return T(first(ps) * (max(θ, floatmin(T)) / first(θs))^_petzold_forward_exponent(pf)) end - θ ≥ last(θs) && return last(ps) + θ ≥ last(θs) && return T(last(ps)) i = searchsortedlast(θs, θ) t = log(θ / θs[i]) / log(θs[i+1] / θs[i]) - return ps[i] * (ps[i+1] / ps[i])^t + return T(ps[i] * (ps[i+1] / ps[i])^t) end phase_function_value(pf::PetzoldPhase{FT}, μ::Real) where {FT} = - FT(_phase_at_angle(pf, acos(clamp(μ, -1, 1)))) + convert(_result_type(FT, μ), _phase_at_angle(pf, acos(clamp(μ, -1, 1)))) _angular_breaks(pf::PetzoldPhase) = pf.θ _forward_exponent(pf::PetzoldPhase) = _petzold_forward_exponent(pf) diff --git a/src/phase/rayleigh_water.jl b/src/phase/rayleigh_water.jl index 620a7d9..a8daa6c 100644 --- a/src/phase/rayleigh_water.jl +++ b/src/phase/rayleigh_water.jl @@ -2,30 +2,25 @@ # Depolarized Rayleigh phase function for pure water # ============================================================================= # -# Pure water molecules scatter light nearly — but not exactly — as Rayleigh -# scatterers. The depolarization ratio ρ ≠ 0 accounts for anisotropic -# polarizability. +# Molecular scattering by water is Rayleigh scattering with a depolarization +# ratio ρ > 0 (anisotropic polarizability); ρ is the ratio for unpolarized +# incident light observed at 90°. # -# The classical Morel (1974) value is ρ = 0.09, but more recent work -# (Farinato & Rowell 1976, and the Zhang et al. 2009 line) gives -# ρ ≈ 0.039 for pure seawater at 500 nm. We use ρ = 0.039 as the default; -# the user can override. +# Scalar phase function, normalized to (1/2) ∫₋₁¹ p dμ = 1: # -# The phase function in the intensity-only (scalar) form is: +# p(μ) = 1 + β₂ P₂(μ), β₂ = Δ/2, Δ = (1 − ρ)/(1 + ρ/2), +# P₂(μ) = (3μ² − 1)/2 # -# p(μ) = 3 / [2 (2 + σ)] · [(1 + σ) + (1 - σ) μ²] +# which is the Cabannes form (3/(4(1+2γ))) [(1+3γ) + (1−γ) μ²] with +# γ = ρ/(2−ρ). All other Legendre moments vanish. # -# where σ = 2ρ/(1 - ρ) is the Kahn & Arking "anisotropy factor". The -# normalization (1/2) ∫₋₁¹ p dμ = 1 is exact. -# -# Legendre moments are closed-form: β₀ = 1, β₂ = (1-σ)/(10·(...)), -# all other β_ℓ = 0 for ℓ ≠ 0, 2. -# -# The full phase matrix also has a closed-form Greek expansion (Hansen & -# Travis 1974), available through `greek_expansion(pf, ℓ_max; -# polarized = true)`. +# The phase matrix has the closed-form Greek expansion of Hansen & Travis +# (1974), available through `greek_expansion(pf, ℓ_max; polarized = true)`. # ============================================================================= +"Depolarization ratio of pure water, Farinato & Rowell (1976), as used by Zhang, Hu & He (2009)." +const _WATER_DEPOLARIZATION = 0.039 + """ $(TYPEDEF) @@ -34,28 +29,31 @@ Rayleigh-type phase function for pure water, with depolarization. # Fields $(TYPEDFIELDS) -Default `depolarization = 0.039` follows Farinato & Rowell (1976) and is -consistent with the Zhang, Hu & He (2009) pure-seawater model. The -Morel (1974) older value `ρ = 0.09` can be selected explicitly: +The phase function is `p(μ) = 1 + β₂ P₂(μ)` with `β₂ = (1 − ρ)/(2 + ρ)`, `ρ` the +depolarization ratio for unpolarized incident light at 90°. The default `ρ = 0.039` +follows Farinato & Rowell (1976) and is the value of the Zhang, Hu & He (2009) +pure-seawater model. The older value `ρ = 0.09` (Morel 1974) can be selected +explicitly: ```julia RayleighWaterPhase{Float64}(depolarization = 0.09) ``` """ struct RayleighWaterPhase{FT} <: AbstractOceanPhaseFunction{FT} - "Depolarization ratio ρ = I_⟂ / I_∥ at 90°" + "Depolarization ratio ρ = I_⟂ / I_∥ at 90° for unpolarized incident light" depolarization::FT - function RayleighWaterPhase{FT}(depolarization::FT) where {FT<:AbstractFloat} - (zero(FT) ≤ depolarization < FT(1)) || + function RayleighWaterPhase{FT}(depolarization::FT) where {FT<:Real} + _check_parameter_type(FT) + (_within(depolarization, 0, 1) && depolarization < FT(1)) || throw(ArgumentError("depolarization must be in [0, 1), got $depolarization")) new{FT}(depolarization) end end -RayleighWaterPhase{FT}(; depolarization = FT(0.039)) where {FT<:AbstractFloat} = - RayleighWaterPhase{FT}(FT(depolarization)) -RayleighWaterPhase(; kwargs...) = RayleighWaterPhase{Float64}(; kwargs...) +RayleighWaterPhase{FT}(; depolarization = _WATER_DEPOLARIZATION) where {FT<:Real} = + (_check_parameter_type(FT); RayleighWaterPhase{FT}(FT(depolarization))) +RayleighWaterPhase(; kwargs...) = RayleighWaterPhase{_parameter_type(values(kwargs))}(; kwargs...) # ----------------------------------------------------------------------------- @@ -69,9 +67,8 @@ function phase_function_value(pf::RayleighWaterPhase{FT}, cosθ::Real) where {FT # De Haan convention: p(μ) = Σ β_ℓ P_ℓ(μ). For Rayleigh only β_0 = 1 # and β_2 = ½·dpl_p are non-zero, giving # p(μ) = 1 + β₂ · (3μ² − 1)/2 - μ = FT(cosθ) β₂ = FT(0.5) * _rayleigh_dpl_p(pf.depolarization) - return one(FT) + β₂ * (FT(3) * μ^2 - one(FT)) / FT(2) + return one(FT) + β₂ * (FT(3) * cosθ^2 - one(FT)) / FT(2) end function phase_function_moments(pf::RayleighWaterPhase{FT}, ℓ_max::Integer) where {FT} diff --git a/src/phase/tabulated_greek.jl b/src/phase/tabulated_greek.jl index 336a145..2dc66f8 100644 --- a/src/phase/tabulated_greek.jl +++ b/src/phase/tabulated_greek.jl @@ -45,13 +45,13 @@ greek_expansion(pf, 8; polarized = true).γ[3] # √(3/2) """ struct TabulatedGreekPhase{FT} <: AbstractOceanPhaseFunction{FT} "The expansion" - greek::GreekCoefficients{FT} + greek::GreekCoefficients{FT, Vector{FT}} "Provenance: citation, table, and any transformation applied" source::String - function TabulatedGreekPhase{FT}(g::GreekCoefficients{FT}, source::String) where {FT<:AbstractFloat} + function TabulatedGreekPhase{FT}(g::GreekCoefficients{FT}, source::String) where {FT<:Real} B = backscatter_fraction(g) - 0 ≤ B ≤ 1 || + _within(B, 0, 1) || throw(ArgumentError("TabulatedGreekPhase: the expansion has backscatter fraction " * "$B ∉ [0, 1] and is not a valid phase function (table " * "truncated before convergence?)")) diff --git a/src/phase/tabulated_mueller.jl b/src/phase/tabulated_mueller.jl index 3e57f04..8571b91 100644 --- a/src/phase/tabulated_mueller.jl +++ b/src/phase/tabulated_mueller.jl @@ -190,11 +190,11 @@ function _mueller_at(pf::TabulatedMuellerPhase, θs::AbstractVector) h = pf.θ[i+1] - pf.θ[i] f11 = exp(_hermite(log(pf.F11[i]), log(pf.F11[i+1]), pf.slopes[1][i], pf.slopes[1][i+1], h, t)) F.F11[j] = f11 - for (s, k) in enumerate((:F12, :F22, :F33, :F34, :F44)) - v = getfield(pf, k) + for (s, v, out) in zip(1:5, (pf.F12, pf.F22, pf.F33, pf.F34, pf.F44), + (F.F12, F.F22, F.F33, F.F34, F.F44)) r = _hermite(v[i] / pf.F11[i], v[i+1] / pf.F11[i+1], pf.slopes[s+1][i], pf.slopes[s+1][i+1], h, t) - getfield(F, k)[j] = r * f11 + out[j] = r * f11 end end return F diff --git a/src/phase/wavelength_phase.jl b/src/phase/wavelength_phase.jl index 9dbef7e..0031e70 100644 --- a/src/phase/wavelength_phase.jl +++ b/src/phase/wavelength_phase.jl @@ -26,41 +26,46 @@ $(TYPEDFIELDS) functions of one float type. With `lookup = :exact` every query must name a tabulated wavelength (`phase_function_moments(pf, ℓ_max, λ)` etc.) and other wavelengths throw; with `lookup = :nearest` the phase function of -the nearest tabulated wavelength is used. The phase function is -polarizable only if all entries are. +the nearest tabulated wavelength is used. `lookup` also accepts an +[`ExactLookup`](@ref) or [`NearestLookup`](@ref); the choice is the type parameter +`L`. The phase function is polarizable only if all entries are. """ -struct WavelengthDependentPhase{FT, P<:AbstractOceanPhaseFunction{FT}} <: AbstractOceanPhaseFunction{FT} +struct WavelengthDependentPhase{FT, P<:AbstractOceanPhaseFunction{FT}, + L<:AbstractTableLookup} <: AbstractOceanPhaseFunction{FT} "Wavelengths `[nm]`, strictly increasing" λ::Vector{FT} "Phase function at each wavelength" phases::Vector{P} - "`:exact` or `:nearest`" - lookup::Symbol + "`ExactLookup()` or `NearestLookup()`" + lookup::L - function WavelengthDependentPhase{FT, P}(λ, phases, lookup) where {FT, P} - lookup in (:exact, :nearest) || - throw(ArgumentError("WavelengthDependentPhase: lookup must be :exact or :nearest")) + function WavelengthDependentPhase{FT, P, L}(λ, phases, + lookup) where {FT, P, + L<:Union{ExactLookup, NearestLookup}} _check_exact_λ_grid(λ, "WavelengthDependentPhase") length(phases) == length(λ) || throw(DimensionMismatch("WavelengthDependentPhase: $(length(phases)) phase " * "functions for $(length(λ)) wavelengths")) any(is_wavelength_dependent, phases) && throw(ArgumentError("WavelengthDependentPhase: entries must be wavelength independent")) - new{FT, P}(λ, phases, lookup) + new{FT, P, L}(λ, phases, lookup) end end function WavelengthDependentPhase(λ::AbstractVector, phases::AbstractVector{<:AbstractOceanPhaseFunction{FT}}; - lookup::Symbol = :exact) where {FT} + lookup = :exact) where {FT} P = typeintersect(eltype(phases), AbstractOceanPhaseFunction{FT}) - return WavelengthDependentPhase{FT, P}(collect(FT, λ), collect(P, phases), lookup) + l = _table_lookup(lookup, (ExactLookup(), NearestLookup()), "WavelengthDependentPhase") + return WavelengthDependentPhase{FT, P, typeof(l)}(collect(FT, λ), collect(P, phases), l) end is_wavelength_dependent(::WavelengthDependentPhase) = true is_polarizable(pf::WavelengthDependentPhase) = all(is_polarizable, pf.phases) -function _phase_entry(pf::WavelengthDependentPhase, λ::Real) - pf.lookup === :exact && return _exact_λ_index(pf.λ, λ, "WavelengthDependentPhase") +_phase_entry(pf::WavelengthDependentPhase{FT, P, ExactLookup}, λ::Real) where {FT, P} = + _exact_λ_index(pf.λ, λ, "WavelengthDependentPhase") + +function _phase_entry(pf::WavelengthDependentPhase{FT, P, NearestLookup}, λ::Real) where {FT, P} i = clamp(searchsortedfirst(pf.λ, λ), 1, length(pf.λ)) return (i > 1 && abs(pf.λ[i-1] - λ) ≤ abs(pf.λ[i] - λ)) ? i - 1 : i end @@ -75,9 +80,10 @@ greek_expansion(pf::WavelengthDependentPhase, ℓ_max::Integer, λ::Real; polari backscatter_fraction(pf::WavelengthDependentPhase, λ::Real) = backscatter_fraction(_phase_at(pf, λ)) asymmetry_parameter(pf::WavelengthDependentPhase, λ::Real) = asymmetry_parameter(_phase_at(pf, λ)) -for f in (:phase_function_moments, :greek_expansion) - @eval $f(pf::WavelengthDependentPhase, ℓ_max::Integer; kwargs...) = _requires_wavelength(pf) -end +phase_function_moments(pf::WavelengthDependentPhase, ℓ_max::Integer; kwargs...) = + _requires_wavelength(pf) +greek_expansion(pf::WavelengthDependentPhase, ℓ_max::Integer; kwargs...) = + _requires_wavelength(pf) backscatter_fraction(pf::WavelengthDependentPhase) = _requires_wavelength(pf) asymmetry_parameter(pf::WavelengthDependentPhase) = _requires_wavelength(pf) phase_function_value(pf::WavelengthDependentPhase, μ::Real) = _requires_wavelength(pf) diff --git a/src/types/abstract_types.jl b/src/types/abstract_types.jl index 0866326..bab7ef5 100644 --- a/src/types/abstract_types.jl +++ b/src/types/abstract_types.jl @@ -29,8 +29,7 @@ # └── SmithBaker1981 # # AbstractPhytoplanktonModel -# ├── Gordon1992 -# ├── Bricaud1998 # aph* power law +# ├── Bricaud1998 # a_p = A·Chl^E # └── MobleyNewCase1 # HydroLight 5 default # # A concrete `Phytoplankton` struct carries a *model* as a type parameter, so @@ -42,7 +41,7 @@ # Chl::FT # end # absorption(p::Phytoplankton{FT, Bricaud1998}, λ) # dispatches on M -# absorption(p::Phytoplankton{FT, Gordon1992}, λ) # different method +# absorption(p::Phytoplankton{FT, OtherModel}, λ) # different method # # This means swapping a parameterization is a single-symbol change at the # call site, not a rewrite of the struct. @@ -54,8 +53,13 @@ $(TYPEDEF) Root of the ocean-constituent type hierarchy. Any material present in the water column that contributes to absorption, scattering, or emission subtypes this. + +`FT` is the element type of the constituent's parameters and results: a floating-point +type, or any other `Real` that promotes with `Float64` such as a `ForwardDiff.Dual`, +which carries derivatives with respect to the parameters through the scalar functions +and [`layer_optics`](@ref). The constituents of one layer share one `FT`. """ -abstract type AbstractOceanConstituent{FT<:AbstractFloat} end +abstract type AbstractOceanConstituent{FT<:Real} end """ $(TYPEDEF) @@ -82,15 +86,9 @@ Constituents that both absorb and scatter (phytoplankton, non-algal particles, pure water). Must implement both [`absorption`](@ref) and [`scattering`](@ref), and provide a [`scattering_phase`](@ref). -Subtypes [`AbstractAbsorber`](@ref): any `AbstractAbsorbingScatterer` is -dispatchable wherever an `AbstractAbsorber` is required. DESIGN §4.1 -called for joint inheritance from both `AbstractAbsorber` and -`AbstractScatterer`, which Julia's single-inheritance model cannot -express; we pick `AbstractAbsorber` as the parent because the bulk of -downstream code (inelastic source operators in §7, constituent-mixing -helpers) dispatches through absorption-centric slots. Scatterer-centric -behavior is still reachable via specific methods on each concrete -absorbing-scatterer type. +The type subtypes [`AbstractAbsorber`](@ref), so an absorbing scatterer is accepted +wherever an absorber is required. It is not an [`AbstractScatterer`](@ref): the +scattering side is reached through the methods of each concrete type. """ abstract type AbstractAbsorbingScatterer{FT} <: AbstractAbsorber{FT} end @@ -100,7 +98,7 @@ abstract type AbstractAbsorbingScatterer{FT} <: AbstractAbsorber{FT} end # These are empty singleton types used as type parameters on the concrete # constituent structs. They exist solely to drive multiple dispatch so that # `absorption(p::Phytoplankton{FT, Bricaud1998}, λ)` and -# `absorption(p::Phytoplankton{FT, Gordon1992}, λ)` resolve to different +# `absorption(p::Phytoplankton{FT, OtherModel}, λ)` resolve to different # methods with zero runtime branching. # Pure water carries two distinct model axes (absorption + scattering) and @@ -108,13 +106,25 @@ abstract type AbstractAbsorbingScatterer{FT} <: AbstractAbsorber{FT} end # (`AbstractPureWaterAbsorptionModel`, `AbstractPureWaterScatteringModel`) # declared in `src/materials/pure_water.jl`. -"Parameterization-model tag for phytoplankton IOPs." +""" +$(TYPEDEF) + +Parameterization-model tag for phytoplankton IOPs. +""" abstract type AbstractPhytoplanktonModel end -"Parameterization-model tag for CDOM absorption." +""" +$(TYPEDEF) + +Parameterization-model tag for CDOM absorption. +""" abstract type AbstractCDOMModel end -"Parameterization-model tag for non-algal particle (NAP) IOPs." +""" +$(TYPEDEF) + +Parameterization-model tag for non-algal particle (NAP) IOPs. +""" abstract type AbstractNAPModel end # ============================================================================= @@ -125,35 +135,43 @@ abstract type AbstractNAPModel end """ absorption(c::AbstractAbsorber, λ) -> FT -Spectral absorption coefficient `a(λ)` `[1/m]` contributed by constituent `c`. +Return the absorption coefficient `a(λ)` `[1/m]` of constituent `c`. -`λ` may be a plain number (interpreted as nm), a `Unitful.Quantity` with -spectral units (nm, µm, cm⁻¹, …), or an `AbstractVector` of either. +`λ` is a wavelength in nm, or a vector of wavelengths. + +# Examples +```jldoctest +julia> absorption(CDOM(), 440.0) +0.03 +``` """ function absorption end """ scattering(c::AbstractScatterer, λ) -> FT -Spectral scattering coefficient `b(λ)` `[1/m]`. +Return the scattering coefficient `b(λ)` `[1/m]` of constituent `c`. + +`λ` is a wavelength in nm, or a vector of wavelengths. """ function scattering end """ backscattering(c::AbstractScatterer, λ) -> FT -Backscattering coefficient `b_b(λ)` `[1/m]` — the integral of the volume -scattering function over the back hemisphere. Equals `b(λ) * B` where `B` -is the backscatter fraction determined by the phase function. +Return the backscattering coefficient `b_b(λ)` `[1/m]` of constituent `c`. + +It is the integral of the volume scattering function over the back hemisphere, +`b_b = b(λ) · B` with `B` the backscatter fraction of the phase function. """ function backscattering end """ attenuation(c::AbstractOceanConstituent, λ) -> FT -Beam attenuation `c(λ) = a(λ) + b(λ)` `[1/m]`. Default implementation sums -`absorption` and `scattering`; specific constituents (pure absorbers, -pure scatterers) should override. +Return the beam attenuation coefficient `c(λ) = a(λ) + b(λ)` `[1/m]`. + +The method for absorbing scatterers sums [`absorption`](@ref) and [`scattering`](@ref). """ attenuation(c::AbstractAbsorbingScatterer, λ) = absorption(c, λ) + scattering(c, λ) attenuation(c::AbstractAbsorber, λ) = absorption(c, λ) @@ -168,10 +186,10 @@ backscattering(::AbstractAbsorber{FT}, λ) where {FT} = zero(FT) """ scattering_phase(c::AbstractScatterer) -> AbstractOceanPhaseFunction -The phase function associated with this scatterer. Returns an -[`AbstractOceanPhaseFunction`](@ref) — the phase function itself owns the -knowledge of what `p(μ)` and its Legendre moments are; the scatterer just -says which one to use. +Return the phase function of scatterer `c`. + +The phase function owns `p(μ)` and its Legendre moments; the scatterer names which one +applies. """ function scattering_phase end @@ -188,17 +206,19 @@ function scattering_phase end """ absorption_parts(c::AbstractAbsorber) -> Tuple{Vararg{Symbol}} -Names of the parts into which `c` attributes its absorption, in the order -of [`absorption_by_part`](@ref). `(:total,)` unless `c` splits its -absorption, as [`Phytoplankton`](@ref) does with a pigment partition. +Return the names of the parts into which `c` attributes its absorption. + +The order is that of [`absorption_by_part`](@ref). The result is `(:total,)` unless `c` +splits its absorption, as [`Phytoplankton`](@ref) does with a pigment partition. """ absorption_parts(::AbstractAbsorber) = (:total,) """ absorption_by_part(c::AbstractAbsorber, λ) -> Tuple -Absorption coefficient `[1/m]` of each part in -[`absorption_parts`](@ref)`(c)` at `λ` `[nm]`; the parts sum to +Return the absorption coefficient `[1/m]` of each part of `c` at `λ` `[nm]`. + +The parts are those of [`absorption_parts`](@ref)`(c)`; they sum to [`absorption`](@ref)`(c, λ)`. """ absorption_by_part(c::AbstractAbsorber, λ::Real) = (absorption(c, λ),) @@ -206,7 +226,7 @@ absorption_by_part(c::AbstractAbsorber, λ::Real) = (absorption(c, λ),) """ absorption_part(c::AbstractAbsorber, part::Symbol, λ) -> FT -Absorption coefficient `[1/m]` of one part of `c` at `λ` `[nm]`. +Return the absorption coefficient `[1/m]` of one part of `c` at `λ` `[nm]`. """ function absorption_part(c::AbstractAbsorber, part::Symbol, λ::Real) i = findfirst(==(part), absorption_parts(c)) @@ -228,10 +248,95 @@ end """ $(TYPEDEF) -Root of the inelastic-source hierarchy (DESIGN §4.4 / §7.1). Concrete -subtypes — `IsotropicFluorescence`, `WaterRaman`, `CDOMFluorescence` — -describe one excitation-to-emission channel apiece and implement the -Fell (1997) factorization primitives `excitation_absorption(p, λ')`, -`emission(p, λ', λ)`, `excitation_range(p)`, and `is_isotropic(p)`. +Root of the inelastic-source hierarchy. + +A concrete subtype ([`IsotropicFluorescence`](@ref), [`WaterRaman`](@ref), +[`CDOMFluorescence`](@ref)) describes one excitation-to-emission channel and implements +the primitives of the factorization of Fell (1997): [`excitation_absorption`](@ref) +`(p, λ')`, [`emission`](@ref)`(p, λ', λ)`, [`excitation_range`](@ref)`(p)`, +[`is_isotropic`](@ref)`(p)` and [`conversion_units`](@ref)`(p)`, which states whether the +excitation coefficient counts photons or energy. +""" +abstract type AbstractOceanInelasticProcess{FT<:Real} end + +# ============================================================================= +# Precision of scalar results +# ============================================================================= +# +# A model holds its parameters in its element type `FT`; data tables and +# fitted constants are `Float64`. A scalar function whose formula contains +# such constants evaluates in at least double precision and rounds its +# result once to the type that the model and the query argument imply, so +# that a `Float32` model queried at a `Float32` wavelength returns `Float32` +# with the rounding error of one conversion. + +""" + _result_type(FT, x...) + +Return the type of a scalar result of a model with element type `FT` queried at `x...`. + +It is `FT` promoted with the floating-point type of each argument. +Dual numbers and floats wider than `FT` therefore pass through. +""" +_result_type(::Type{FT}, x) where {FT} = promote_type(FT, typeof(float(x))) +_result_type(::Type{FT}, x, y) where {FT} = promote_type(FT, typeof(float(x)), typeof(float(y))) + +""" + _wide(x) + +Return `x` in at least double precision. + +`Float16` and `Float32` are widened to `Float64` (exactly); any other number, a dual +number included, is returned as it is and promotes with the `Float64` constants of the +formula. +""" +_wide(x::Union{Float16, Float32}) = Float64(x) +_wide(x::Real) = x + +""" + _within(x, lo, hi) -> Bool + +Return `true` when the value of `x` lies in the closed interval `[lo, hi]`. + +For a floating-point `x` this is `lo ≤ x ≤ hi`. Any other real `x` (an integer, a dual +number) is compared with the floating-point neighbours `prevfloat(lo) < x < nextfloat(hi)`: +ForwardDiff 1.x orders dual numbers lexicographically by value and then partials, so +`Dual(35, 1) ≤ 35` is `false` and `≤` would reject a dual at an upper bound; a strict +comparison with the neighbour is decided by the value alone. For a dual whose value +has more precision than `lo` and `hi`, the interval is widened by one unit in the last +place of the bounds. +""" +_within(x::AbstractFloat, lo, hi) = lo ≤ x ≤ hi +_within(x::Real, lo, hi) = prevfloat(float(lo)) < x < nextfloat(float(hi)) + +""" + _check_parameter_type(FT) + +Throw an `ArgumentError` when `FT` is an integer or rational type. + +Models and optical properties are computed in a floating-point type or in a dual number +of one. An integer type fails at the first fractional default, a rational type would +compute in exact rationals. +""" +function _check_parameter_type(::Type{FT}) where {FT} + FT <: Union{Integer, Rational} && + throw(ArgumentError("element type $FT: models and optical properties need a " * + "floating-point type (Float64, Float32) or a dual number of " * + "one; use $(float(FT)) instead")) + return nothing +end + +""" + _parameter_type(parameters::NamedTuple) + +Return the element type of a model constructed without an explicit one. + +It is `Float64` promoted with the type of every real-valued parameter, so that plain +numbers of any precision give a `Float64` model and a dual number (or a `BigFloat`) +gives a model that carries it. """ -abstract type AbstractOceanInelasticProcess{FT<:AbstractFloat} end +_parameter_type(parameters::NamedTuple) = _promote_reals(Float64, values(parameters)...) +_promote_reals(::Type{T}) where {T} = T +_promote_reals(::Type{T}, x::Real, rest...) where {T} = + _promote_reals(promote_type(T, typeof(x)), rest...) +_promote_reals(::Type{T}, x, rest...) where {T} = _promote_reals(T, rest...) diff --git a/src/types/greek.jl b/src/types/greek.jl index 167f50f..962b50a 100644 --- a/src/types/greek.jl +++ b/src/types/greek.jl @@ -15,6 +15,37 @@ # (γ₂ = +√(3/2) for Rayleigh). A scalar expansion carries β only. # ============================================================================= +# Dense storage for an array field of a result struct. A dense vector of +# element type `FT` (a `Vector`, a device array) is stored as it is; one of +# another element type is converted where it lives; anything else (a range, +# a view, a tuple, a generator) is collected on the host. +_dense(::Type{FT}, x::DenseVector{FT}) where {FT} = x +_dense(::Type{FT}, x::DenseVector) where {FT} = map(FT, x) +_dense(::Type{FT}, x) where {FT} = collect(FT, x) + +# As `_dense`, but never the array that was passed in. +_dense_copy(::Type{FT}, x::DenseVector) where {FT} = map(FT, x) +_dense_copy(::Type{FT}, x) where {FT} = collect(FT, x) + +# Host copy of an array, for code that reads single elements. +_host(x::Array) = x +_host(x::AbstractArray) = Array(x) + +# First argument of the inner constructors that store their arguments without +# validation. Only the `Adapt` rules use them: an adapted struct holds the +# values of a validated one, and a backend's kernel adaptor must be able to +# rebuild the struct without running reductions. +struct _Unchecked end + +# The `Adapt` rules move arrays and keep the element type `FT`; `x` is one +# adapted array of the struct. +_check_adapt_eltype(to, ::Type{FT}, x) where {FT} = + eltype(x) === FT || + throw(ArgumentError("adapt: $to changes the element type from $FT to $(eltype(x)); " * + "build the optics in the wanted precision (for example " * + "`column_optics(Float32, …)`) and adapt with an array type " * + "without element type, such as `CuArray`")) + """ $(TYPEDEF) @@ -45,26 +76,57 @@ constructor checks finiteness, `β₀ = 1` within `√eps`, `|β_ℓ| ≤ 2ℓ+1 for `ℓ < 2`, where their generalized spherical functions are identically zero. These are necessary conditions, not a proof of a correct import: compare `asymmetry_parameter` with published values as well. + + GreekCoefficients{FT}(α, β, γ, δ, ϵ, ζ) + +All six vectors by position (empty `α, γ, δ, ϵ, ζ` for a scalar +expansion), stored in the array type of `β`. + +# Devices + +The six vectors share one array type `V`. `Adapt.adapt(to, g)` moves them +to the device of `to` (for example `adapt(CuArray, g)`), keeps the element +type (an adaptor that changes it, such as `CuArray{Float32}` for a `Float64` +expansion, is refused) and does not validate again, so the expansion can be +captured by a device broadcast or kernel. Everything else that reads single +coefficients ([`phase_id`](@ref), [`backscatter_fraction`](@ref), +[`asymmetry_parameter`](@ref), [`mix_greek`](@ref), +[`evaluate_scattering_matrix`](@ref)) is a host operation. """ -struct GreekCoefficients{FT<:Real} +struct GreekCoefficients{FT<:Real, V<:AbstractVector{FT}} "α_ℓ: B[2,2] (empty when scalar)" - α::Vector{FT} + α::V "β_ℓ: B[1,1], the phase-function expansion" - β::Vector{FT} + β::V "γ_ℓ: B[1,2] = B[2,1] (empty when scalar)" - γ::Vector{FT} + γ::V "δ_ℓ: B[4,4] (empty when scalar)" - δ::Vector{FT} + δ::V "ϵ_ℓ: B[3,4] = −B[4,3] (empty when scalar)" - ϵ::Vector{FT} + ϵ::V "ζ_ℓ: B[3,3] (empty when scalar)" - ζ::Vector{FT} + ζ::V - function GreekCoefficients{FT}(α, β, γ, δ, ϵ, ζ) where {FT<:Real} - g = new{FT}(α, β, γ, δ, ϵ, ζ) + function GreekCoefficients{FT, V}(α, β, γ, δ, ϵ, ζ) where {FT<:Real, V<:AbstractVector{FT}} + g = new{FT, V}(α, β, γ, δ, ϵ, ζ) _validate_greek(g) return g end + + GreekCoefficients{FT, V}(::_Unchecked, α, β, γ, δ, ϵ, ζ) where {FT<:Real, V<:AbstractVector{FT}} = + new{FT, V}(α, β, γ, δ, ϵ, ζ) +end + +function GreekCoefficients{FT}(α, β, γ, δ, ϵ, ζ) where {FT<:Real} + b = _dense(FT, β) + return GreekCoefficients{FT, typeof(b)}(α, b, γ, δ, ϵ, ζ) +end + +function Adapt.adapt_structure(to, g::GreekCoefficients{FT}) where {FT} + β = adapt(to, g.β) + _check_adapt_eltype(to, FT, β) + return GreekCoefficients{FT, typeof(β)}(_Unchecked(), adapt(to, g.α), β, adapt(to, g.γ), + adapt(to, g.δ), adapt(to, g.ϵ), adapt(to, g.ζ)) end function GreekCoefficients(β::AbstractVector; α = nothing, γ = nothing, δ = nothing, @@ -76,16 +138,37 @@ function GreekCoefficients(β::AbstractVector; α = nothing, γ = nothing, δ = throw(ArgumentError("GreekCoefficients: pass all of α, γ, δ, ϵ, ζ for a phase " * "matrix or none for a phase function; got only " * join(names, ", "))) - vec(x) = x === nothing ? FT[] : collect(FT, x) - return GreekCoefficients{FT}(vec(α), collect(FT, β), vec(γ), vec(δ), vec(ϵ), vec(ζ)) + vec(x) = x === nothing ? FT[] : _dense_copy(FT, x) + return GreekCoefficients{FT}(vec(α), _dense_copy(FT, β), vec(γ), vec(δ), vec(ϵ), vec(ζ)) end +# The conditions on β_ℓ and on the polarized coefficients below ℓ = 2, per +# element, so that the validation is one broadcast and one reduction on the +# device that holds the coefficients. +_admissible_β(x, ℓ, tol) = + isfinite(x) & (ℓ == 0 ? abs(x - 1) ≤ tol : abs(x) ≤ (2ℓ + 1) * (1 + tol)) +_vanishes_below_2(x, ℓ, tol) = isfinite(x) & ((ℓ ≥ 2) | (abs(x) ≤ tol)) + function _validate_greek(g::GreekCoefficients{FT}) where {FT} - who = "GreekCoefficients" (; β) = g - isempty(β) && throw(ArgumentError("$who: β needs at least the ℓ = 0 term")) - all(isfinite, β) || throw(ArgumentError("$who: β contains non-finite values")) + isempty(β) && throw(ArgumentError("GreekCoefficients: β needs at least the ℓ = 0 term")) + Base.require_one_based_indexing(β) tol = sqrt(eps(float(FT))) + ℓ = 0:length(β)-1 + pol = (g.α, g.γ, g.δ, g.ϵ, g.ζ) + valid = all(_admissible_β.(β, ℓ, tol)) && + (all(isempty, pol) || + (all(v -> length(v) == length(β), pol) && all(isfinite, g.δ) && + all(v -> all(_vanishes_below_2.(v, ℓ, tol)), (g.α, g.γ, g.ϵ, g.ζ)))) + valid || _throw_greek_error(g, tol) + return nothing +end + +# Says which condition of `_validate_greek` failed and where, on host copies. +function _throw_greek_error(g::GreekCoefficients, tol) + who = "GreekCoefficients" + β = _host(g.β) + all(isfinite, β) || throw(ArgumentError("$who: β contains non-finite values")) abs(β[1] - 1) ≤ tol || throw(ArgumentError("$who: β₀ = $(β[1]); phase functions must be normalized so " * "that β₀ = 1 (tolerance $tol)")) @@ -95,9 +178,8 @@ function _validate_greek(g::GreekCoefficients{FT}) where {FT} "non-negative phase function allows this (was the (2ℓ+1) " * "factor applied twice?)")) end - pol = (α = g.α, γ = g.γ, δ = g.δ, ϵ = g.ϵ, ζ = g.ζ) + pol = (α = _host(g.α), γ = _host(g.γ), δ = _host(g.δ), ϵ = _host(g.ϵ), ζ = _host(g.ζ)) nonempty = [k for (k, v) in pairs(pol) if !isempty(v)] - isempty(nonempty) && return nothing length(nonempty) == 5 || throw(ArgumentError("$who: polarized coefficients need all of α, γ, δ, ϵ, ζ; " * "got only " * join(nonempty, ", "))) @@ -107,60 +189,133 @@ function _validate_greek(g::GreekCoefficients{FT}) where {FT} all(isfinite, v) || throw(ArgumentError("$who: $k contains non-finite values")) end for k in (:α, :γ, :ϵ, :ζ), ℓ in 0:min(1, length(β) - 1) - abs(getfield(g, k)[ℓ+1]) ≤ tol || - throw(ArgumentError("$who: $(k)_$ℓ = $(getfield(g, k)[ℓ+1]) must be zero (its " * + abs(pol[k][ℓ+1]) ≤ tol || + throw(ArgumentError("$who: $(k)_$ℓ = $(pol[k][ℓ+1]) must be zero (its " * "generalized spherical function vanishes for ℓ < 2); is " * "the table shifted by a row?")) end - return nothing + throw(ArgumentError("$who: invalid coefficients")) end -"Number of expansion terms, `ℓ_max + 1`." +""" + n_moments(x) + +Return the number of expansion terms, `ℓ_max + 1`, of an expansion, a scattering +component, a layer or a column. +""" n_moments(g::GreekCoefficients) = length(g.β) -"Whether `g` carries all six phase-matrix coefficients." +""" + is_polarized(g::GreekCoefficients) + +Return whether `g` carries all six phase-matrix coefficients. +""" is_polarized(g::GreekCoefficients) = !isempty(g.α) Base.:(==)(a::GreekCoefficients, b::GreekCoefficients) = all(f -> getfield(a, f) == getfield(b, f), fieldnames(GreekCoefficients)) +# Consistent with `==`, which compares values across element types; `phase_id` +# separates element types and cannot serve here. +Base.hash(g::GreekCoefficients, h::UInt) = + hash(map(_host, (g.α, g.β, g.γ, g.δ, g.ϵ, g.ζ)), hash(:GreekCoefficients, h)) Base.isapprox(a::GreekCoefficients, b::GreekCoefficients; kwargs...) = all(f -> isapprox(getfield(a, f), getfield(b, f); kwargs...), fieldnames(GreekCoefficients)) """ resize_moments(g::GreekCoefficients, ℓ_max) -> GreekCoefficients -Expansion with terms `ℓ = 0:ℓ_max`: truncated, or padded with zeros (exact -for the expansion as given). Truncation applies no δ-M or other +Return the expansion `g` with terms `ℓ = 0:ℓ_max`, truncated or padded with zeros. + +Padding is exact for the expansion as given. Truncation applies no δ-M or other correction; that is the solver's choice. """ function resize_moments(g::GreekCoefficients{FT}, ℓ_max::Integer) where {FT} ℓ_max ≥ 0 || throw(ArgumentError("ℓ_max must be non-negative, got $ℓ_max")) n = ℓ_max + 1 - fit = v -> isempty(v) ? v : (length(v) ≥ n ? v[1:n] : [v; zeros(FT, n - length(v))]) + fit = v -> isempty(v) ? v : length(v) ≥ n ? v[1:n] : + vcat(v, fill!(similar(v, n - length(v)), zero(FT))) return GreekCoefficients{FT}(fit(g.α), fit(g.β), fit(g.γ), fit(g.δ), fit(g.ϵ), fit(g.ζ)) end """ depolarized(g::GreekCoefficients) -> GreekCoefficients -The *completely depolarizing* phase matrix with phase function `β`: -`α = γ = δ = ϵ = ζ = 0`, i.e. `diag(p(Θ), 0, 0, 0)`. Scattered light is -unpolarized and its intensity does not depend on the incident -polarization. An explicit modelling approximation for scatterers whose -phase matrix is unknown. +Return the *completely depolarizing* phase matrix with the phase function of `g`. + +The result has `α = γ = δ = ϵ = ζ = 0`, i.e. the matrix `diag(p(Θ), 0, 0, 0)`: scattered +light is unpolarized and its intensity does not depend on the incident polarization. It +is an explicit modelling approximation for scatterers whose phase matrix is unknown. """ function depolarized(g::GreekCoefficients{FT}) where {FT} - z = zeros(FT, n_moments(g)) + z = zero(g.β) return GreekCoefficients{FT}(copy(z), copy(g.β), copy(z), copy(z), copy(z), z) end +""" + zero_padded(g::GreekCoefficients) + +Return `g` with all six coefficient vectors of length `ℓ_max + 1`. + +A polarized `g` is returned as it is; a scalar expansion gets +`α = γ = δ = ϵ = ζ = 0` (equal to [`depolarized`](@ref)`(g)`). For +consumers that size their arrays by `length(g.α)`; the zeros carry no +polarization information. +""" +zero_padded(g::GreekCoefficients) = is_polarized(g) ? g : depolarized(g) + +# FNV-1a (64 bit) over the bytes of the content: defined by the algorithm +# alone, so keys do not depend on the session, the Julia version or the +# identity of the arrays. +const _FNV_OFFSET = 0xcbf29ce484222325 +const _FNV_PRIME = 0x00000100000001b3 + +_fnv1a(h::UInt64, x::UInt8) = (h ⊻ x) * _FNV_PRIME +function _fnv1a(h::UInt64, x::Unsigned) # little-endian byte order + for shift in 0:8:(8 * sizeof(x) - 8) + h = _fnv1a(h, (x >> shift) % UInt8) + end + return h +end +_fnv1a(h::UInt64, s::AbstractString) = foldl(_fnv1a, codeunits(s); init = h) +# `x + zero(x)` maps −0.0 to 0.0, so that values equal under `==` share a key. +_fnv1a(h::UInt64, x::Union{Float16, Float32, Float64}) = _fnv1a(h, reinterpret(Unsigned, x + zero(x))) +_fnv1a(h::UInt64, x::Real) = _fnv1a(h, string(x)) + +""" + phase_id(g::GreekCoefficients) -> key + +Return the content key of the expansion `g`, a `UInt64`. + +The key is the 64-bit FNV-1a hash of the element type name and of the length and +values of `α, β, γ, δ, ϵ, ζ`, in that order. + +Expansions that are `==` and have the same element type have the same +key, in every session and Julia version; expansions that differ in a +coefficient, in `ℓ_max`, in element type or in being scalar or polarized +have different keys (up to the 2⁻⁶⁴ collision probability of the hash). +A solver can therefore cache phase operators by `(phase_id, Fourier mode)`. +The key of coefficients held on a device is computed from a host copy and +equals the key of that copy. +""" +function phase_id(g::GreekCoefficients{FT}) where {FT} + h = _fnv1a(_FNV_OFFSET, string(FT)) + for v in map(_host, (g.α, g.β, g.γ, g.δ, g.ϵ, g.ζ)) + h = _fnv1a(h, UInt64(length(v))) + for x in v + h = _fnv1a(h, x) + end + end + return h +end + """ mix_greek(weights, gs) -> GreekCoefficients -Weighted mixture `Σ wᵢ gᵢ / Σ wᵢ` of expansions with equal length and -polarization — the mixing law for scatterers in one volume, with weights -proportional to their scattering coefficients. Weights must be -non-negative with a positive sum. +Return the weighted mixture `Σ wᵢ gᵢ / Σ wᵢ` of expansions of equal length and +polarization. + +This is the mixing law for scatterers in one volume, with weights proportional to their +scattering coefficients. Weights must be non-negative with a positive sum. """ function mix_greek(weights::AbstractVector{<:Real}, gs::AbstractVector{<:GreekCoefficients}) length(weights) == length(gs) || @@ -181,14 +336,19 @@ end """ backscatter_fraction(g::GreekCoefficients) -> FT -Backscatter fraction `B = (1/2)∫₋₁⁰ p(μ) dμ` of the finite expansion, -evaluated exactly term by term. For a truncated expansion of a strongly -peaked phase function this differs from the backscatter fraction of the -phase function itself. +Return the backscatter fraction `B = (1/2)∫₋₁⁰ p(μ) dμ` of the finite expansion `g`. + +The integral is evaluated exactly term by term. For a truncated expansion of a strongly +peaked phase function it differs from the backscatter fraction of the phase function +itself. """ backscatter_fraction(g::GreekCoefficients) = _backscatter_fraction_from_moments(g.β) -"Asymmetry parameter `g = ⟨cos Θ⟩ = β₁ / 3` of the expansion." +""" + asymmetry_parameter(g::GreekCoefficients) + +Return the asymmetry parameter `⟨cos Θ⟩ = β₁ / 3` of the expansion `g`. +""" asymmetry_parameter(g::GreekCoefficients{FT}) where {FT} = n_moments(g) ≥ 2 ? g.β[2] / 3 : zero(FT) @@ -200,7 +360,7 @@ end """ _backscatter_fraction_from_moments(β) -> FT -`B = (1/2) [β₀ − Σ_{ℓ odd} βₗ Iₗ]` with `Iₗ = ∫₀¹ Pₗ dμ = +Return `B = (1/2) [β₀ − Σ_{ℓ odd} βₗ Iₗ]` with `Iₗ = ∫₀¹ Pₗ dμ = (P_{ℓ-1}(0) − P_{ℓ+1}(0)) / (2ℓ+1)`; even orders ℓ ≥ 2 integrate to zero over a hemisphere. """ diff --git a/src/types/iop.jl b/src/types/iop.jl index 9df2b72..e7799aa 100644 --- a/src/types/iop.jl +++ b/src/types/iop.jl @@ -1,13 +1,12 @@ """ $(TYPEDEF) -Bundle of inherent optical properties at one wavelength (or one wavelength -grid). This is the neutral currency of the package: every constituent -produces an `IOP`, constituents mix via `+`, and layers reduce to a single -`IOP` before being expanded into an [`OceanLayerOptics`](@ref). +Absorption, scattering and backscattering coefficients `[1/m]` at one wavelength (number +fields) or on a wavelength grid (array fields). -An `IOP` is **wavelength-local**: the scalar-field version describes one λ; -the vector-field version describes a λ grid. Same struct, parametric fields. +`IOP`s of constituents in one volume add with `+` and scale with `*`. The type is a +standalone value: [`layer_optics`](@ref) does not use it and reports optical depths per +component in an [`OceanLayerOptics`](@ref). # Fields $(TYPEDFIELDS) @@ -17,10 +16,10 @@ $(TYPEDFIELDS) ```julia iop1 = IOP(0.1, 0.05, 0.018) # pure water at 550 nm iop2 = IOP(0.03, 0.30, 0.012) # phytoplankton contribution -total = iop1 + iop2 # correctly energy-weights backscatter +total = iop1 + iop2 # a, b and bb add; B = bb/b is scattering-weighted ``` """ -struct IOP{FT<:AbstractFloat, A<:Union{FT, AbstractArray{FT}}} +struct IOP{FT<:Real, A<:Union{FT, AbstractArray{FT}}} "Absorption coefficient `a(λ)` `[1/m]`" a::A "Scattering coefficient `b(λ)` `[1/m]`" @@ -31,17 +30,27 @@ end # Lightweight constructors ---------------------------------------------------- -"Scalar IOP for one wavelength." -IOP(a::FT, b::FT, bb::FT) where {FT<:AbstractFloat} = IOP{FT, FT}(a, b, bb) +""" + IOP(a, b, bb) + +Construct an `IOP` from absorption `a`, scattering `b` and backscattering `bb` `[1/m]`. + +Three numbers describe one wavelength and are promoted to a common floating-point type (dual numbers are kept); three +arrays of one type describe a wavelength grid. +""" +function IOP(a::FT, b::FT, bb::FT) where {FT<:Real} + T = float(FT) + return IOP{T, T}(T(a), T(b), T(bb)) +end -"Per-wavelength-grid IOP backed by identically-typed vectors/matrices." -IOP(a::A, b::A, bb::A) where {FT<:AbstractFloat, A<:AbstractArray{FT}} = +IOP(a::A, b::A, bb::A) where {FT<:Real, A<:AbstractArray{FT}} = IOP{FT, A}(a, b, bb) +# Integer and rational arrays are converted to floating point, as the scalar method does. +IOP(a::A, b::A, bb::A) where {FT<:Union{Integer, Rational}, A<:AbstractArray{FT}} = + IOP(float.(a), float.(b), float.(bb)) -"Mixed-type convenience: promote to a common `AbstractFloat`." function IOP(a::Real, b::Real, bb::Real) - FT = promote_type(typeof(a), typeof(b), typeof(bb)) - FT <: AbstractFloat || (FT = float(FT)) + FT = float(promote_type(typeof(a), typeof(b), typeof(bb))) return IOP(FT(a), FT(b), FT(bb)) end @@ -53,17 +62,29 @@ IOP_scatterer(b, B) = IOP(zero(b), b, b * B) # Accessors ------------------------------------------------------------------- -"Beam attenuation `c = a + b`." +""" + attenuation(iop::IOP) + +Return the beam attenuation `c = a + b` `[1/m]`. +""" attenuation(iop::IOP) = iop.a .+ iop.b -"Single-scattering albedo `ϖ = b / (a + b)`; zero when `a = b = 0`." +""" + single_scattering_albedo(iop::IOP) + +Return the single-scattering albedo `ϖ = b / (a + b)`, zero when `a = b = 0`. +""" function single_scattering_albedo(iop::IOP{FT}) where {FT} c = attenuation(iop) # Broadcast-safe form; works for scalar or array IOPs. return @. ifelse(c > zero(FT), iop.b / c, zero(FT)) end -"Backscatter fraction `B = b_b / b`; zero when `b = 0`." +""" + backscatter_fraction(iop::IOP) + +Return the backscatter fraction `B = b_b / b`, zero when `b = 0`. +""" function backscatter_fraction(iop::IOP{FT}) where {FT} return @. ifelse(iop.b > zero(FT), iop.bb / iop.b, zero(FT)) end @@ -80,7 +101,11 @@ end Base.:+(x::IOP, y::IOP) = IOP(x.a .+ y.a, x.b .+ y.b, x.bb .+ y.bb) Base.zero(iop::IOP) = IOP(zero(iop.a), zero(iop.b), zero(iop.bb)) -"Multiply all IOPs by a scalar (e.g. to scale by layer thickness)." +""" + *(s::Real, iop::IOP) + +Multiply the three coefficients of `iop` by the number `s`. +""" Base.:*(s::Real, iop::IOP) = IOP(s .* iop.a, s .* iop.b, s .* iop.bb) Base.:*(iop::IOP, s::Real) = s * iop diff --git a/src/types/layer_optics.jl b/src/types/layer_optics.jl index 3f5c5a8..25d9d2e 100644 --- a/src/types/layer_optics.jl +++ b/src/types/layer_optics.jl @@ -13,11 +13,24 @@ # aerosol types; lets it report the light absorbed by each constituent # (absorbed PAR, fluorescence excitation); and keeps the provenance of # every phase matrix visible. +# +# The numeric arrays of every result struct have the array type `V` (and `I` +# for integer indices) as a type parameter, and `Adapt.adapt(to, x)` moves +# them to a device. Labels, symbols, content keys, the lists of components +# and layers, and the inelastic components stay on the host: the +# structs are containers, a kernel receives their arrays. `adapt` keeps the +# element type, keeps expansions that components share shared, and builds the +# components without validating them again. Validation and +# the per-wavelength derived quantities are reductions and broadcasts, so +# they run where the arrays live; functions that take a wavelength index +# `iλ` read single elements and are host operations. # ============================================================================= -_is_strictly_increasing(x::AbstractVector) = all(i -> x[i] < x[i+1], firstindex(x):lastindex(x)-1) +# Neighbour comparisons as one broadcast over two views and a reduction. +_is_strictly_increasing(x::AbstractVector) = + length(x) < 2 || all(@views x[begin+1:end] .> x[begin:end-1]) _is_strictly_monotone(x::AbstractVector) = - _is_strictly_increasing(x) || all(i -> x[i] > x[i+1], firstindex(x):lastindex(x)-1) + _is_strictly_increasing(x) || all(@views x[begin+1:end] .< x[begin:end-1]) const _POLARIZATION_LABELS = (:scalar, :full, :depolarizing) @@ -35,46 +48,79 @@ otherwise `phase_index[iλ]` names the entry used at each wavelength of the layer. See [`greek_expansion`](@ref)`(c, iλ)` and [`is_wavelength_dependent`](@ref)`(c)`. -`phase_id` identifies the phase function and polarization treatment: -components with equal `phase_id` (in any layer of a column) have identical -expansions — [`column_optics`](@ref) shares the same objects — so a solver -can build their phase operators once. +`phase_id[j]` is the content key of `greek[j]` (see [`phase_id`](@ref)): +entries with equal keys — in any component, layer, column or session — +hold equal coefficients, and entries that differ in any coefficient, in +`ℓ_max` or in element type have different keys, so a solver can build +phase operators once per distinct key. `polarization` records how the phase-matrix coefficients were obtained: `:scalar` (phase function only, `β`), `:full` (the constituent's phase matrix), or `:depolarizing` (its phase function with the completely depolarizing approximation, selected explicitly). """ -struct ScatteringComponent{FT} +struct ScatteringComponent{FT<:Real, V<:AbstractVector{FT}, I<:AbstractVector{Int}} "Constituent the component came from (type name, or the source of tabulated data)" label::String - "Identity of the phase function and polarization treatment (equal ⇒ identical expansions)" - phase_id::UInt64 + "Content key of each entry of `greek` (equal ⇔ equal coefficients, `ℓ_max` and element type)" + phase_id::Vector{UInt64} "Scattering optical depth `b·Δz` per wavelength" - τ::Vector{FT} + τ::V "Distinct phase-matrix expansions" - greek::Vector{GreekCoefficients{FT}} + greek::Vector{GreekCoefficients{FT, V}} "Backscatter fraction of the phase function (not of its truncated expansion), per entry of `greek`" - backscatter_fraction::Vector{FT} + backscatter_fraction::V "Entry of `greek` used at each wavelength; empty when there is a single entry" - phase_index::Vector{Int} + phase_index::I "`:scalar`, `:full` or `:depolarizing`" polarization::Symbol - function ScatteringComponent{FT}(label, phase_id, τ, greek, backscatter_fraction, - phase_index, polarization) where {FT} - c = new{FT}(label, phase_id, τ, greek, backscatter_fraction, phase_index, polarization) + function ScatteringComponent{FT, V, I}(label, τ, greek, backscatter_fraction, phase_index, + polarization) where {FT, V<:AbstractVector{FT}, + I<:AbstractVector{Int}} + c = new{FT, V, I}(label, map(phase_id, greek), τ, greek, backscatter_fraction, + phase_index, polarization) _validate_component(c) return c end + + ScatteringComponent{FT, V, I}(::_Unchecked, label, ids, τ, greek, backscatter_fraction, + phase_index, + polarization) where {FT, V<:AbstractVector{FT}, + I<:AbstractVector{Int}} = + new{FT, V, I}(label, ids, τ, greek, backscatter_fraction, phase_index, polarization) +end + +# The array types are those of `τ` and `phase_index`. +function ScatteringComponent{FT}(label, τ, greek, backscatter_fraction, phase_index, + polarization) where {FT} + t, index = _dense(FT, τ), _dense(Int, phase_index) + return ScatteringComponent{FT, typeof(t), typeof(index)}(label, t, greek, backscatter_fraction, + index, polarization) end function ScatteringComponent(label::AbstractString, τ::AbstractVector{FT}, - greek::AbstractVector{GreekCoefficients{FT}}, B::AbstractVector, - polarization::Symbol; phase_index::AbstractVector{<:Integer} = Int[], - phase_id::Integer = hash((label, polarization))) where {FT} - return ScatteringComponent{FT}(String(label), UInt64(phase_id), collect(τ), collect(greek), - collect(FT, B), collect(Int, phase_index), polarization) + greek::AbstractVector{<:GreekCoefficients{FT}}, B::AbstractVector, + polarization::Symbol; + phase_index::AbstractVector{<:Integer} = Int[]) where {FT} + return ScatteringComponent{FT}(String(label), _dense_copy(FT, τ), collect(greek), + _dense_copy(FT, B), _dense_copy(Int, phase_index), polarization) +end + +Adapt.adapt_structure(to, c::ScatteringComponent) = _adapt_scatterer(to, c, IdDict{Any, Any}()) + +# `shared` maps each host expansion to its adapted copy, so that expansions +# shared between components and layers are moved once and stay shared. The +# `phase_id` keys are those of the host arrays, which hold the same values. +function _adapt_scatterer(to, c::ScatteringComponent{FT}, shared::IdDict) where {FT} + τ, index = adapt(to, c.τ), adapt(to, c.phase_index) + _check_adapt_eltype(to, FT, τ) + _check_adapt_eltype(to, Int, index) + V = typeof(τ) + greek = GreekCoefficients{FT, V}[get!(() -> adapt(to, g), shared, g) for g in c.greek] + return ScatteringComponent{FT, V, typeof(index)}( + _Unchecked(), c.label, c.phase_id, τ, greek, adapt(to, c.backscatter_fraction), index, + c.polarization) end function _validate_component(c::ScatteringComponent) @@ -96,7 +142,8 @@ function _validate_component(c::ScatteringComponent) length(c.phase_index) == length(c.τ) || throw(DimensionMismatch("$who: phase_index has $(length(c.phase_index)) entries " * "for $(length(c.τ)) wavelengths")) - all(i -> 1 ≤ i ≤ length(c.greek), c.phase_index) || + n = length(c.greek) # the reduction captures a number, not the component + all(i -> 1 ≤ i ≤ n, c.phase_index) || throw(ArgumentError("$who: phase_index refers to missing expansions")) end g1 = first(c.greek) @@ -109,17 +156,19 @@ function _validate_component(c::ScatteringComponent) return nothing end -"Number of expansion terms (`ℓ_max + 1`)." n_moments(c::ScatteringComponent) = n_moments(first(c.greek)) -"Whether the component's phase matrix differs between wavelengths." +""" + is_wavelength_dependent(c::ScatteringComponent) + +Return whether the phase matrix of component `c` differs between wavelengths. +""" is_wavelength_dependent(c::ScatteringComponent) = !isempty(c.phase_index) -"Whether the component carries phase-matrix coefficients." is_polarized(c::ScatteringComponent) = c.polarization != :scalar """ greek_expansion(c::ScatteringComponent, iλ) -> GreekCoefficients -Expansion of component `c` at the `iλ`-th wavelength of its layer. +Return the expansion of component `c` at the `iλ`-th wavelength of its layer. """ greek_expansion(c::ScatteringComponent, iλ::Integer) = is_wavelength_dependent(c) ? c.greek[c.phase_index[iλ]] : first(c.greek) @@ -128,6 +177,20 @@ backscatter_fraction(c::ScatteringComponent, iλ::Integer) = is_wavelength_dependent(c) ? c.backscatter_fraction[c.phase_index[iλ]] : first(c.backscatter_fraction) +# Backscatter fraction at every wavelength of the layer: gathered through +# `phase_index`, or the single entry, which broadcasts against the grid. +_backscatter_on_grid(c::ScatteringComponent) = + is_wavelength_dependent(c) ? c.backscatter_fraction[c.phase_index] : c.backscatter_fraction + +""" + phase_id(c::ScatteringComponent, iλ) -> key + +Return the content key of the expansion of component `c` at the `iλ`-th wavelength of +its layer, equal to [`phase_id`](@ref)`(greek_expansion(c, iλ))`. +""" +phase_id(c::ScatteringComponent, iλ::Integer) = + is_wavelength_dependent(c) ? c.phase_id[c.phase_index[iλ]] : first(c.phase_id) + # ============================================================================= # Absorption and inelastic components # ============================================================================= @@ -141,24 +204,38 @@ Absorption by one constituent of a layer, or by one part of it (see # Fields $(TYPEDFIELDS) """ -struct AbsorptionComponent{FT} +struct AbsorptionComponent{FT<:Real, V<:AbstractVector{FT}} "Constituent the component came from (type name, or the source of tabulated data)" label::String "Absorption part of the constituent (`:total` unless it splits its absorption)" part::Symbol "Absorption optical depth `a·Δz` per wavelength" - τ::Vector{FT} + τ::V - function AbsorptionComponent{FT}(label, part, τ) where {FT} + function AbsorptionComponent{FT, V}(label, part, τ) where {FT, V<:AbstractVector{FT}} all(x -> isfinite(x) && x ≥ 0, τ) || throw(ArgumentError("AbsorptionComponent \"$label\" (:$part): absorption optical " * "depths must be finite and non-negative")) - new{FT}(label, part, τ) + new{FT, V}(label, part, τ) end + + AbsorptionComponent{FT, V}(::_Unchecked, label, part, τ) where {FT, V<:AbstractVector{FT}} = + new{FT, V}(label, part, τ) +end + +function AbsorptionComponent{FT}(label, part, τ) where {FT} + t = _dense(FT, τ) + return AbsorptionComponent{FT, typeof(t)}(label, part, t) end AbsorptionComponent(label::AbstractString, part::Symbol, τ::AbstractVector{FT}) where {FT} = - AbsorptionComponent{FT}(String(label), part, collect(τ)) + AbsorptionComponent{FT}(String(label), part, _dense_copy(FT, τ)) + +function Adapt.adapt_structure(to, c::AbsorptionComponent{FT}) where {FT} + τ = adapt(to, c.τ) + _check_adapt_eltype(to, FT, τ) + return AbsorptionComponent{FT, typeof(τ)}(_Unchecked(), c.label, c.part, τ) +end """ $(TYPEDEF) @@ -175,27 +252,39 @@ that the excitation coefficient on the layer grid is `quantum_yield(process) · Σ_k efficiency[k] · absorbers[excitation[k]].τ / Δz` — the same as [`excitation_absorption`](@ref)`(process, λ)`. Water Raman has no excitation components. + +The component is host data: `excitation` and `efficiency` have one entry per +excitation pathway and are read together, and `Adapt.adapt` returns the component +unchanged. """ -struct InelasticComponent{FT} +struct InelasticComponent{FT<:Real, P<:AbstractOceanInelasticProcess} "Process type name" label::String "The process, with its kernels (excitation, emission, quantum yield)" - process::AbstractOceanInelasticProcess + process::P "Indices of the layer's absorption components that excite the process" excitation::Vector{Int} "Energy-transfer efficiency η of each excitation component" efficiency::Vector{FT} - function InelasticComponent{FT}(label, process, excitation, efficiency) where {FT} + function InelasticComponent{FT, P}(label, process, excitation, efficiency) where {FT, P} length(excitation) == length(efficiency) || throw(DimensionMismatch("InelasticComponent \"$label\": $(length(efficiency)) " * "efficiencies for $(length(excitation)) excitation components")) all(η -> isfinite(η) && 0 ≤ η ≤ 1, efficiency) || throw(ArgumentError("InelasticComponent \"$label\": efficiencies must lie in [0, 1]")) - new{FT}(label, process, excitation, efficiency) + new{FT, P}(label, process, excitation, efficiency) end end +InelasticComponent{FT}(label, process::P, excitation, + efficiency) where {FT, P<:AbstractOceanInelasticProcess} = + InelasticComponent{FT, P}(label, process, excitation, efficiency) + +# The process is a model description; it stays on the host with the indices +# and efficiencies of its excitation pathways. +Adapt.adapt_structure(to, c::InelasticComponent) = c + # ============================================================================= # Layer # ============================================================================= @@ -227,18 +316,34 @@ every component on the same wavelength grid; scattering components with `n_moments` terms and the layer's polarization; inelastic components referring to existing absorption components. Arrays are checked at construction; mutating them afterwards is not re-checked. + +# Devices + +`λ` and the arrays of the components have the array type `V` (integer +indices `I`). `Adapt.adapt(to, o)` returns the layer with these arrays on +the device of `to`, for example `adapt(CuArray, o)`; labels, parts, +`phase_id` keys, the component lists and the inelastic components +stay on the host. The element type is kept: an adaptor that changes it +(`CuArray{Float32}` for a `Float64` layer) is refused; build the optics with +`layer_optics(Float32, …)` instead. Expansions shared by components stay +shared. On a device, +[`absorption_optical_depth`](@ref), [`scattering_optical_depth`](@ref), +[`optical_depth`](@ref), [`single_scattering_albedo`](@ref) and +[`backscatter_fraction`](@ref)`(o)` return device arrays. Functions of a +wavelength index (`greek_expansion(o, iλ)`) and the absorbed-light and +inelastic diagnostics are host operations: apply them before `adapt`. """ -struct OceanLayerOptics{FT} +struct OceanLayerOptics{FT<:Real, V<:AbstractVector{FT}, I<:AbstractVector{Int}} "Wavelengths `[nm]`, strictly monotone" - λ::Vector{FT} + λ::V "Depth of the layer top below the surface `[m]`" depth_top::FT "Depth of the layer bottom below the surface `[m]`" depth_bottom::FT "Absorption components, one per absorber or absorption part" - absorbers::Vector{AbsorptionComponent{FT}} + absorbers::Vector{AbsorptionComponent{FT, V}} "Scattering components, one per scattering constituent" - scatterers::Vector{ScatteringComponent{FT}} + scatterers::Vector{ScatteringComponent{FT, V, I}} "Inelastic processes, with the absorption components that excite them" inelastic::Vector{InelasticComponent{FT}} "Number of expansion terms, `ℓ_max + 1`" @@ -246,15 +351,49 @@ struct OceanLayerOptics{FT} "Whether every scattering component carries phase-matrix coefficients" polarized::Bool - function OceanLayerOptics{FT}(λ, depth_top, depth_bottom, absorbers, scatterers, inelastic, - n_moments, polarized) where {FT} - o = new{FT}(λ, depth_top, depth_bottom, absorbers, scatterers, inelastic, n_moments, - polarized) + function OceanLayerOptics{FT, V, I}(λ, depth_top, depth_bottom, absorbers, scatterers, + inelastic, n_moments, + polarized) where {FT, V<:AbstractVector{FT}, + I<:AbstractVector{Int}} + o = new{FT, V, I}(λ, depth_top, depth_bottom, absorbers, scatterers, inelastic, + n_moments, polarized) _validate_layer(o) return o end end +# The array type is that of `λ`; the index type that of the scattering +# components, `Vector{Int}` if their vector does not fix it. +function OceanLayerOptics{FT}(λ, depth_top, depth_bottom, absorbers, scatterers, inelastic, + n_moments, polarized) where {FT} + x = _dense(FT, λ) + return OceanLayerOptics{FT, typeof(x), _index_type(scatterers)}( + x, depth_top, depth_bottom, absorbers, scatterers, inelastic, n_moments, polarized) +end + +_index_type(::AbstractVector{ScatteringComponent{FT, V, I}}) where {FT, V, I} = I +_index_type(::AbstractVector) = Vector{Int} + +Adapt.adapt_structure(to, o::OceanLayerOptics) = _adapt_layer(to, o, IdDict{Any, Any}()) + +function _adapt_layer(to, o::OceanLayerOptics{FT}, shared::IdDict) where {FT} + λ = adapt(to, o.λ) + index = adapt(to, _phase_index_prototype(o)) + _check_adapt_eltype(to, FT, λ) + _check_adapt_eltype(to, Int, index) + V, I = typeof(λ), typeof(index) + return OceanLayerOptics{FT, V, I}( + λ, o.depth_top, o.depth_bottom, + AbsorptionComponent{FT, V}[adapt(to, c) for c in o.absorbers], + ScatteringComponent{FT, V, I}[_adapt_scatterer(to, c, shared) for c in o.scatterers], + o.inelastic, o.n_moments, o.polarized) +end + +# An index array of the layer's index type, to find its type after `adapt` +# also when the layer has no scattering component. +_phase_index_prototype(o::OceanLayerOptics) = + isempty(o.scatterers) ? Int[] : first(o.scatterers).phase_index + function _validate_layer(o::OceanLayerOptics) who = "OceanLayerOptics" nλ = length(o.λ) @@ -291,28 +430,31 @@ function _validate_layer(o::OceanLayerOptics) return nothing end -"Geometric thickness `[m]`." thickness(o::OceanLayerOptics) = o.depth_bottom - o.depth_top -"Number of wavelengths." +""" + n_wavelengths(x) + +Return the number of wavelengths of the grid of a layer's or a column's optics. +""" n_wavelengths(o::OceanLayerOptics) = length(o.λ) -"Number of expansion terms, `ℓ_max + 1`." n_moments(o::OceanLayerOptics) = o.n_moments """ is_polarized(x) -> Bool -Whether `x` (layer, column, component or [`GreekCoefficients`](@ref)) -carries all six phase-matrix coefficients. +Return whether `x` (layer, column, component or [`GreekCoefficients`](@ref)) carries +phase-matrix coefficients in addition to the phase function. """ is_polarized(o::OceanLayerOptics) = o.polarized """ absorber_index(o::OceanLayerOptics, label, part = :total) -> Int -Index in `o.absorbers` (and in the rows of [`absorbed_power`](@ref) and -the entries of [`absorbed_par`](@ref)) of the absorption component with -`label` and `part`, e.g. `absorber_index(o, "Phytoplankton", :chlorophyll)`. -Throws if there is no such component or more than one. +Return the index in `o.absorbers` of the absorption component with `label` and `part`, +e.g. `absorber_index(o, "Phytoplankton", :chlorophyll)`. + +The same index names the rows of [`absorbed_power`](@ref) and the entries of +[`absorbed_par`](@ref). Throws if there is no such component or more than one. """ function absorber_index(o::OceanLayerOptics, label::AbstractString, part::Symbol = :total) i = findall(c -> c.label == label && c.part === part, o.absorbers) @@ -324,65 +466,80 @@ function absorber_index(o::OceanLayerOptics, label::AbstractString, part::Symbol "give equal constituents distinct sources or index o.absorbers directly")) end -"Absorption optical depth per wavelength, summed over absorption components." -function absorption_optical_depth(o::OceanLayerOptics{FT}) where {FT} - τ = zeros(FT, n_wavelengths(o)) - for c in o.absorbers +# Sum of the components' optical depths, in an array like `λ`. +function _summed_optical_depth(λ::AbstractVector, components) + τ = zero(λ) + for c in components τ .+= c.τ end return τ end -"Scattering optical depth per wavelength, summed over scattering components." -function scattering_optical_depth(o::OceanLayerOptics{FT}) where {FT} - τ = zeros(FT, n_wavelengths(o)) - for c in o.scatterers - τ .+= c.τ - end - return τ -end +""" + absorption_optical_depth(o::OceanLayerOptics) + +Return the absorption optical depth of the layer per wavelength, summed over its +absorption components. +""" +absorption_optical_depth(o::OceanLayerOptics) = _summed_optical_depth(o.λ, o.absorbers) + +""" + scattering_optical_depth(o::OceanLayerOptics) -"Total (extinction) optical depth `τ_abs + τ_scat` per wavelength." +Return the scattering optical depth of the layer per wavelength, summed over its +scattering components. +""" +scattering_optical_depth(o::OceanLayerOptics) = _summed_optical_depth(o.λ, o.scatterers) + +""" + optical_depth(o::OceanLayerOptics) + +Return the extinction optical depth `τ_abs + τ_scat` of the layer per wavelength. +""" optical_depth(o::OceanLayerOptics) = absorption_optical_depth(o) .+ scattering_optical_depth(o) """ - single_scattering_albedo(o::OceanLayerOptics) -> Vector + single_scattering_albedo(o::OceanLayerOptics) -> AbstractVector -`ϖ = τ_scat / (τ_abs + τ_scat)` per wavelength; zero where `τ = 0`. +Return the single-scattering albedo `ϖ = τ_scat / (τ_abs + τ_scat)` of the layer per +wavelength, zero where `τ = 0`. """ function single_scattering_albedo(o::OceanLayerOptics{FT}) where {FT} τs = scattering_optical_depth(o) τ = absorption_optical_depth(o) .+ τs - return [τ[i] > 0 ? τs[i] / τ[i] : zero(FT) for i in eachindex(τ)] + return ifelse.(τ .> 0, τs ./ τ, zero(FT)) end """ - backscatter_fraction(o::OceanLayerOptics) -> Vector + backscatter_fraction(o::OceanLayerOptics) -> AbstractVector -Scattering-weighted backscatter fraction of the components' phase -functions per wavelength; zero where the layer does not scatter. +Return the scattering-weighted backscatter fraction of the components' phase functions +per wavelength, zero where the layer does not scatter. """ function backscatter_fraction(o::OceanLayerOptics{FT}) where {FT} τs = scattering_optical_depth(o) - B = zeros(FT, n_wavelengths(o)) - for c in o.scatterers, i in eachindex(B) - B[i] += c.τ[i] * backscatter_fraction(c, i) + B = zero(o.λ) + for c in o.scatterers + B .+= c.τ .* _backscatter_on_grid(c) end - return [τs[i] > 0 ? B[i] / τs[i] : zero(FT) for i in eachindex(B)] + return ifelse.(τs .> 0, B ./ τs, zero(FT)) end """ greek_expansion(o::OceanLayerOptics, iλ) -> GreekCoefficients -Expansion of the layer's mixed phase matrix at its `iλ`-th wavelength: the -components weighted by their scattering optical depths. Where the layer -does not scatter, the isotropic expansion `β = [1, 0, …]` (zero -polarization terms). +Return the expansion of the layer's mixed phase matrix at its `iλ`-th wavelength: the +components weighted by their scattering optical depths. + +Where the layer does not scatter, the result is the isotropic expansion `β = [1, 0, …]` +with zero polarization terms. """ function greek_expansion(o::OceanLayerOptics{FT}, iλ::Integer) where {FT} w = [c.τ[iλ] for c in o.scatterers] if isempty(w) || sum(w) == 0 - β = zeros(FT, o.n_moments); β[1] = one(FT) + # `fill`, not `zeros(FT, n)`: for the abstract `FT` of a not fully typed layer + # inference (and JET) cannot exclude the `zeros` method that returns a matrix. + β = fill(zero(FT), o.n_moments); β[1] = one(FT) g = GreekCoefficients(β) return o.polarized ? depolarized(g) : g end @@ -401,10 +558,18 @@ end # Bottom boundary descriptors # ============================================================================= -"Lower boundary of an ocean column (for the solver to apply)." +""" +$(TYPEDEF) + +Lower boundary of an ocean column, for the solver to apply. +""" abstract type AbstractOceanBottom end -"Perfectly absorbing bottom." +""" +$(TYPEDEF) + +Perfectly absorbing bottom. +""" struct BlackBottom <: AbstractOceanBottom end """ @@ -416,21 +581,35 @@ wavelength (or one value for all wavelengths), in `[0, 1]`. # Fields $(TYPEDFIELDS) """ -struct LambertianBottom{FT} <: AbstractOceanBottom +struct LambertianBottom{FT<:Real, V<:AbstractVector{FT}} <: AbstractOceanBottom "Albedo: one value, or one per wavelength of the column" - albedo::Vector{FT} + albedo::V - function LambertianBottom{FT}(albedo::Vector{FT}) where {FT} + function LambertianBottom{FT, V}(albedo) where {FT, V<:AbstractVector{FT}} isempty(albedo) && throw(ArgumentError("LambertianBottom: no albedo")) all(a -> isfinite(a) && 0 ≤ a ≤ 1, albedo) || throw(ArgumentError("LambertianBottom: albedo must lie in [0, 1]")) - new{FT}(albedo) + new{FT, V}(albedo) end + + LambertianBottom{FT, V}(::_Unchecked, albedo) where {FT, V<:AbstractVector{FT}} = + new{FT, V}(albedo) +end + +function LambertianBottom{FT}(albedo) where {FT} + a = _dense(FT, albedo) + return LambertianBottom{FT, typeof(a)}(a) end LambertianBottom(albedo::Real) = LambertianBottom{float(typeof(albedo))}([float(albedo)]) LambertianBottom(albedo::AbstractVector{<:Real}) = - LambertianBottom{float(eltype(albedo))}(collect(float(eltype(albedo)), albedo)) + LambertianBottom{float(eltype(albedo))}(_dense_copy(float(eltype(albedo)), albedo)) + +function Adapt.adapt_structure(to, b::LambertianBottom{FT}) where {FT} + albedo = adapt(to, b.albedo) + _check_adapt_eltype(to, FT, albedo) + return LambertianBottom{FT, typeof(albedo)}(_Unchecked(), albedo) +end """ $(TYPEDEF) @@ -448,7 +627,7 @@ $(TYPEDFIELDS) TabulatedLambertianBottom(λ, albedo; source = "") """ -struct TabulatedLambertianBottom{FT} <: AbstractOceanBottom +struct TabulatedLambertianBottom{FT<:Real} <: AbstractOceanBottom "Wavelengths `[nm]`, strictly increasing" λ::Vector{FT} "Albedo at each `λ`, in `[0, 1]`" @@ -496,25 +675,56 @@ $(TYPEDFIELDS) Layers share `λ`, `n_moments` and polarization; the first starts at the surface and each starts where the previous one ends. `refractive_index` is real and given per wavelength. + +# Devices + +`Adapt.adapt(to, col)` returns the column with every numeric array (the +layers' arrays, `refractive_index`, the albedo of a `LambertianBottom`) +on the device of `to`, in the same element type; see +[`OceanLayerOptics`](@ref) for what stays on the host. Expansions that +layers share on the host are moved once and stay shared on the device. """ -struct OceanColumnOptics{FT, B<:AbstractOceanBottom} +struct OceanColumnOptics{FT<:Real, B<:AbstractOceanBottom, V<:AbstractVector{FT}, + I<:AbstractVector{Int}} "Layers, surface first" - layers::Vector{OceanLayerOptics{FT}} + layers::Vector{OceanLayerOptics{FT, V, I}} "Refractive index of the surface water relative to air, per wavelength" - refractive_index::Vector{FT} + refractive_index::V "Lower boundary" bottom::B - function OceanColumnOptics{FT, B}(layers, refractive_index, bottom) where {FT, B} - col = new{FT, B}(layers, refractive_index, bottom) + function OceanColumnOptics{FT, B, V, I}(layers, refractive_index, + bottom) where {FT, B, V<:AbstractVector{FT}, + I<:AbstractVector{Int}} + col = new{FT, B, V, I}(layers, refractive_index, bottom) _validate_column(col) return col end end -OceanColumnOptics(layers::Vector{OceanLayerOptics{FT}}, n::AbstractVector, - bottom::B) where {FT, B<:AbstractOceanBottom} = - OceanColumnOptics{FT, B}(layers, collect(FT, n), bottom) +# The array types are those of the layers. +OceanColumnOptics{FT, B}(layers::AbstractVector{OceanLayerOptics{FT, V, I}}, refractive_index, + bottom) where {FT, B, V, I} = + OceanColumnOptics{FT, B, V, I}(layers, refractive_index, bottom) + +# The element type of `layers` need not fix the array types: the first layer does. +function OceanColumnOptics(layers::AbstractVector{<:OceanLayerOptics}, n::AbstractVector, + bottom::AbstractOceanBottom) + isempty(layers) && throw(ArgumentError("OceanColumnOptics: no layers")) + return _column_optics(convert(Vector{typeof(first(layers))}, layers), n, bottom) +end + +_column_optics(layers::Vector{OceanLayerOptics{FT, V, I}}, n, bottom::B) where {FT, V, I, B} = + OceanColumnOptics{FT, B, V, I}(layers, _dense_copy(FT, n), bottom) + +function Adapt.adapt_structure(to, col::OceanColumnOptics{FT}) where {FT} + n = adapt(to, col.refractive_index) + _check_adapt_eltype(to, FT, n) + shared = IdDict{Any, Any}() + layers = map(l -> _adapt_layer(to, l, shared), col.layers) + bottom = adapt(to, col.bottom) + return OceanColumnOptics{FT, typeof(bottom)}(layers, n, bottom) +end function _validate_column(col::OceanColumnOptics) who = "OceanColumnOptics" @@ -533,41 +743,59 @@ function _validate_column(col::OceanColumnOptics) nλ = length(l1.λ) length(col.refractive_index) == nλ || throw(DimensionMismatch("$who: $(length(col.refractive_index)) refractive indices for $nλ wavelengths")) - all(n -> isfinite(n) && n > 0, col.refractive_index) || - throw(ArgumentError("$who: refractive indices must be finite and positive")) - if col.bottom isa LambertianBottom - length(col.bottom.albedo) in (1, nλ) || - throw(DimensionMismatch("$who: bottom albedo needs 1 or $nλ values")) - end - col.bottom isa TabulatedLambertianBottom && - throw(ArgumentError("$who: a TabulatedLambertianBottom must be interpolated onto the " * - "column grid; pass it to column_optics")) + all(n -> isfinite(n) && n ≥ 1, col.refractive_index) || + throw(ArgumentError("$who: the refractive index of water relative to air must be " * + "finite and ≥ 1; check that it is n_water / n_air and not its " * + "inverse")) + _check_bottom(col.bottom, nλ) return nothing end -"Number of layers." +# What a column requires of its bottom on a grid of `nλ` wavelengths. +_check_bottom(::AbstractOceanBottom, nλ) = nothing +_check_bottom(b::LambertianBottom, nλ) = + length(b.albedo) in (1, nλ) || + throw(DimensionMismatch("OceanColumnOptics: bottom albedo needs 1 or $nλ values")) +_check_bottom(::TabulatedLambertianBottom, nλ) = + throw(ArgumentError("OceanColumnOptics: a TabulatedLambertianBottom must be interpolated " * + "onto the column grid; pass it to column_optics")) + n_layers(col::OceanColumnOptics) = length(col.layers) -"Depths of the layer interfaces `[m]`, from the surface (0) to the bottom." +""" + interface_depths(col::OceanColumnOptics) + +Return the depths `[m]` of the layer interfaces, from the surface (0) to the bottom. +""" interface_depths(col::OceanColumnOptics) = [first(col.layers).depth_top; [l.depth_bottom for l in col.layers]] -"Depth of the column bottom `[m]`." bottom_depth(col::OceanColumnOptics) = last(col.layers).depth_bottom -"Wavelength grid `[nm]`." +""" + wavelengths(col::OceanColumnOptics) + +Return the wavelength grid `[nm]` of the column. +""" wavelengths(col::OceanColumnOptics) = first(col.layers).λ n_wavelengths(col::OceanColumnOptics) = length(wavelengths(col)) n_moments(col::OceanColumnOptics) = first(col.layers).n_moments is_polarized(col::OceanColumnOptics) = first(col.layers).polarized """ - bottom_albedo(col::OceanColumnOptics) -> Vector + bottom_albedo(col::OceanColumnOptics) -> AbstractVector -Bottom albedo per wavelength: zeros for a [`BlackBottom`](@ref). +Return the bottom albedo per wavelength: zeros for a [`BlackBottom`](@ref), the stored +albedo for a [`LambertianBottom`](@ref). + +Any other bottom type has no Lambertian albedo and throws an `ArgumentError`. """ -bottom_albedo(col::OceanColumnOptics{FT, BlackBottom}) where {FT} = zeros(FT, n_wavelengths(col)) -function bottom_albedo(col::OceanColumnOptics{FT, <:LambertianBottom}) where {FT} - a = col.bottom.albedo - return length(a) == 1 ? fill(FT(only(a)), n_wavelengths(col)) : FT.(a) -end +bottom_albedo(col::OceanColumnOptics{FT, BlackBottom}) where {FT<:Real} = zero(wavelengths(col)) +bottom_albedo(col::OceanColumnOptics) = + throw(ArgumentError("bottom_albedo: a $(typeof(col.bottom)) has no Lambertian albedo; " * + "only BlackBottom and LambertianBottom do. Check `col.bottom` and " * + "treat this bottom type in the solver, or define " * + "`bottom_albedo(::OceanColumnOptics{FT, <:$(nameof(typeof(col.bottom)))})`")) +# One albedo broadcasts against the grid; one per wavelength is copied. +bottom_albedo(col::OceanColumnOptics{FT, <:LambertianBottom}) where {FT<:Real} = + FT.(col.bottom.albedo) .+ zero(wavelengths(col)) Base.length(col::OceanColumnOptics) = n_layers(col) Base.getindex(col::OceanColumnOptics, i) = col.layers[i] diff --git a/src/types/ocean_column.jl b/src/types/ocean_column.jl index 8eb1ab4..373cb8b 100644 --- a/src/types/ocean_column.jl +++ b/src/types/ocean_column.jl @@ -35,7 +35,7 @@ overlaps) is enforced at construction time. # Fields $(TYPEDFIELDS) """ -struct OceanColumn{FT} +struct OceanColumn{FT<:Real} "Surface-first, contiguous list of layers" layers::Vector{OceanLayer{FT}} @@ -53,7 +53,7 @@ function _validate_column_contiguity(layers::Vector{<:OceanLayer}) layers[1].depth_top == 0 || throw(ArgumentError("OceanColumn: first layer must start at z = 0 " * "(got $(layers[1].depth_top))")) - @inbounds for i in 1:length(layers)-1 + for i in firstindex(layers):lastindex(layers)-1 layers[i].depth_bottom == layers[i+1].depth_top || throw(ArgumentError("OceanColumn: layers $i and $(i+1) are not " * "contiguous: depth_bottom=$(layers[i].depth_bottom) " * @@ -64,19 +64,35 @@ end # --- Basic accessors --------------------------------------------------------- -"Number of layers in the column." +""" + n_layers(col) + +Return the number of layers of an [`OceanColumn`](@ref) or [`OceanColumnOptics`](@ref). +""" n_layers(col::OceanColumn) = length(col.layers) -"Total geometric thickness `[m]` — surface to column bottom." thickness(col::OceanColumn) = col.layers[end].depth_bottom - col.layers[1].depth_top -"Depth of the column bottom `[m]`." +""" + bottom_depth(col) + +Return the depth `[m]` of the bottom of an [`OceanColumn`](@ref) or +[`OceanColumnOptics`](@ref). +""" bottom_depth(col::OceanColumn) = col.layers[end].depth_bottom -"Per-layer midpoint depths `[m]`." +""" + midpoint_depths(col::OceanColumn) + +Return the midpoint depth `[m]` of every layer of `col`. +""" midpoint_depths(col::OceanColumn) = [midpoint_depth(l) for l in col.layers] -"Per-layer thicknesses `[m]`." +""" + layer_thicknesses(col::OceanColumn) + +Return the thickness `[m]` of every layer of `col`. +""" layer_thicknesses(col::OceanColumn) = [thickness(l) for l in col.layers] # --- Collection interface --------------------------------------------------- @@ -101,9 +117,10 @@ end """ uniform_column(constituents; n_layers=10, depth=50.0, inelastic=[]) -Build an `OceanColumn` with `n_layers` equal-thickness layers spanning -0 → `depth` metres. Each layer carries the same `constituents` and -`inelastic` lists. +Build an [`OceanColumn`](@ref) of `n_layers` layers of equal thickness from the surface +to `depth` `[m]`. + +Every layer carries the same `constituents` and `inelastic` processes. """ function uniform_column(constituents::AbstractVector; n_layers::Integer = 10, @@ -130,10 +147,10 @@ end """ fell_column(constituents; depth=60.0, inelastic=[]) -Build an `OceanColumn` following Fell (1997) §5.2.1: 1 m layers in -0–10 m, 2 m layers in 10–20 m, 5 m layers below. Truncates gracefully -if `depth < 20`; the deepest layer is trimmed so `depth_bottom == -depth` exactly. +Build an [`OceanColumn`](@ref) on the vertical grid of Fell (1997) §5.2.1. + +Layers are 1 m thick in 0–10 m, 2 m in 10–20 m and 5 m below, down to `depth` `[m]`. +The deepest layer is trimmed so that it ends at `depth` exactly, also for `depth < 20`. """ function fell_column(constituents::AbstractVector; depth::Real = 60.0, @@ -160,6 +177,8 @@ function fell_column(constituents::AbstractVector; end """ + _append_staircase!(boundaries, D, Δ, upper) + Append grid points `(last_boundary + Δ, last_boundary + 2Δ, …)` up to `upper` (capped at the column bottom `D`). Caller invariant: the previous stage's last boundary is already in `boundaries`. diff --git a/src/types/ocean_layer.jl b/src/types/ocean_layer.jl index 07e2f46..70574d1 100644 --- a/src/types/ocean_layer.jl +++ b/src/types/ocean_layer.jl @@ -14,15 +14,15 @@ One vertically-homogeneous ocean layer. # Fields $(TYPEDFIELDS) """ -struct OceanLayer{FT} +struct OceanLayer{FT<:Real} "Depth of layer top [m], 0 at surface" depth_top::FT "Depth of layer bottom [m]" depth_bottom::FT "Elastic optical constituents active in this layer" - constituents::Vector{<:AbstractOceanConstituent{FT}} + constituents::Vector{AbstractOceanConstituent{FT}} "Inelastic processes (fluorescence, Raman) active in this layer" - inelastic::Vector{<:AbstractOceanInelasticProcess{FT}} + inelastic::Vector{AbstractOceanInelasticProcess{FT}} function OceanLayer{FT}(depth_top, depth_bottom, constituents, inelastic) where {FT} @@ -52,10 +52,18 @@ end _constituent_float_type(::AbstractOceanConstituent{FT}) where {FT} = FT _inelastic_float_type(::AbstractOceanInelasticProcess{FT}) where {FT} = FT -"Geometric thickness [m]" +""" + thickness(x) + +Return the geometric thickness `[m]` of a layer, a column or the optics of a layer. +""" thickness(layer::OceanLayer) = layer.depth_bottom - layer.depth_top -"Midpoint depth [m]" +""" + midpoint_depth(layer::OceanLayer) + +Return the depth `[m]` of the middle of `layer`. +""" midpoint_depth(layer::OceanLayer) = (layer.depth_top + layer.depth_bottom) / 2 function Base.show(io::IO, layer::OceanLayer{FT}) where {FT} diff --git a/test/gpu/Project.toml b/test/gpu/Project.toml new file mode 100644 index 0000000..364e337 --- /dev/null +++ b/test/gpu/Project.toml @@ -0,0 +1,5 @@ +[deps] +Adapt = "79e6a3ab-5dfb-504d-930d-738a2a938a0e" +CUDA = "052768ef-5323-5732-b1bb-66c8b64840ba" +OceanOptics = "81d78f2c-09e7-43ab-88c2-b5d9ea2c354a" +Test = "8dfed614-e22c-5e08-85e1-65c5234f0b40" diff --git a/test/gpu/README.md b/test/gpu/README.md new file mode 100644 index 0000000..060efa3 --- /dev/null +++ b/test/gpu/README.md @@ -0,0 +1,12 @@ +# CUDA device tests + +`test/test_device.jl` runs in the default suite on the JLArrays reference backend. This +environment runs the same file on a CUDA device; it is skipped when `CUDA.functional()` is false. + +```bash +julia --project=test/gpu -e 'using Pkg; Pkg.develop(path = "."); Pkg.instantiate()' # once +julia --project=test/gpu test/gpu/runtests.jl +``` + +CUDA uses the first visible device; on a host with several, select one with the environment +variable `CUDA_VISIBLE_DEVICES`. The arrays of the tests are small (tens of elements). diff --git a/test/gpu/runtests.jl b/test/gpu/runtests.jl new file mode 100644 index 0000000..3802be7 --- /dev/null +++ b/test/gpu/runtests.jl @@ -0,0 +1,17 @@ +# The device tests of the package on a CUDA device. CUDA is a dependency of +# this environment only; see README.md in this directory. + +using CUDA: CUDA, CuArray +using OceanOptics +using Test + +if CUDA.functional() + CUDA.allowscalar(false) + const DEVICE_ARRAY = CuArray + @info "OceanOptics device tests on $(CUDA.name(CUDA.device()))" + @testset "OceanOptics.jl on CUDA" begin + include(joinpath(@__DIR__, "..", "test_device.jl")) + end +else + @info "CUDA is not functional on this host; the CUDA device tests are skipped" +end diff --git a/test/runtests.jl b/test/runtests.jl index 10163f7..530a620 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -4,6 +4,7 @@ using ForwardDiff @testset "OceanOptics.jl" begin include("test_iop.jl") + include("test_spectral_table.jl") include("test_pure_water.jl") include("test_refractive_index.jl") include("test_cdom.jl") @@ -20,5 +21,14 @@ using ForwardDiff include("test_layer_optics.jl") include("test_absorbed_light.jl") include("test_column.jl") + include("test_solver_contract.jl") + include("test_parameters.jl") include("test_ad.jl") + include("static_helpers.jl") + include("test_inference.jl") + include("test_float32.jl") + include("test_device.jl") + include("test_aqua.jl") + include("test_explicit_imports.jl") + include("test_jet.jl") end diff --git a/test/static_helpers.jl b/test/static_helpers.jl new file mode 100644 index 0000000..9343bd5 --- /dev/null +++ b/test/static_helpers.jl @@ -0,0 +1,22 @@ +# Fixtures shared by the JET, inference and Float32 tests. + +iop_constituents(::Type{FT}) where {FT} = + (PureWater{FT}(), + PureWater{FT}(absorption_model = PopeFry1997(), scattering_model = Morel1974()), + CDOM{FT}(), Phytoplankton{FT}(Chl = FT(0.5)), + Phytoplankton{FT}(Chl = FT(0.5), pigments = ProspectPigments(carotenoid_ratio = FT(0.3))), + Phytoplankton{FT}(Chl = FT(0.5), pigments = Bidigare1990Pigments(chl_a = FT(0.5), psc = FT(0.3))), + NonAlgalParticles{FT}(), NonAlgalParticles{FT, FellMineral}()) + +scalar_phases(::Type{FT}) where {FT} = + (FournierForandPhase{FT}(backscatter_fraction = FT(0.018)), + HenyeyGreensteinPhase{FT}(g = FT(0.7)), RayleighWaterPhase{FT}(), PetzoldPhase{FT}()) + +# Water, CDOM and phytoplankton with a pigment partition, chlorophyll +# fluorescence and water Raman, 0–5 m. +function inelastic_layer(::Type{FT}) where {FT} + phyto = Phytoplankton{FT}(Chl = FT(0.5), pigments = ProspectPigments(carotenoid_ratio = FT(0.3))) + fluo = chlorophyll_fluorescence(phyto; quantum_yield = FT(0.02), carotenoid_transfer = FT(0.5)) + return OceanLayer(FT(0), FT(5), AbstractOceanConstituent{FT}[PureWater{FT}(), CDOM{FT}(), phyto]; + inelastic = AbstractOceanInelasticProcess{FT}[fluo, WaterRaman{FT}()]) +end diff --git a/test/test_ad.jl b/test/test_ad.jl index 43b8a7a..f3c9e6a 100644 --- a/test/test_ad.jl +++ b/test/test_ad.jl @@ -1,6 +1,6 @@ using ForwardDiff -@testset "Forward-mode AD transparency (DESIGN §12.5)" begin +@testset "Forward-mode automatic differentiation" begin @testset "CDOM ∂a/∂λ" begin cdom = CDOM{Float64}(a_ref = 0.03, λ_ref = 440.0, slope = 0.014) @@ -51,17 +51,366 @@ using ForwardDiff end end - @testset "CDOM ∂a/∂slope (parametric gradient)" begin - # Gradient of the summed CDOM absorption w.r.t. the spectral slope. - # `CDOM` itself requires `FT<:AbstractFloat`, so we differentiate - # through the analytic formula directly rather than instantiating - # the struct with a `Dual` type parameter. Integration window kept - # above `λ_ref` so increasing `S` unambiguously shrinks the sum - # (a mixed integration window straddling `λ_ref` can flip the sign). - a_ref, λ_ref = 0.03, 440.0 - f(S) = sum(a_ref * exp(-S * (λ - λ_ref)) - for λ in (500.0, 600.0, 700.0)) - d = ForwardDiff.derivative(f, 0.014) - @test isfinite(d) && d < 0 + @testset "CDOM ∂a/∂slope and ∂a/∂a_ref match the closed forms" begin + # a = a_ref exp(−S (λ − λ_ref)) ⇒ ∂a/∂S = −(λ − λ_ref) a and ∂a/∂a_ref = a / a_ref. + a_ref, λ_ref, S = 0.03, 440.0, 0.014 + for λ in (412.5, 500.0, 600.0, 700.0) + a = absorption(CDOM{Float64}(; a_ref, λ_ref, slope = S), λ) + @test ForwardDiff.derivative(x -> absorption(CDOM(; a_ref, λ_ref, slope = x), λ), S) ≈ + -(λ - λ_ref) * a rtol = 1e-12 + @test ForwardDiff.derivative(x -> absorption(CDOM(; a_ref = x, λ_ref, slope = S), λ), a_ref) ≈ + a / a_ref rtol = 1e-12 + end + end + + @testset "Absorbed light ∂/∂E₀" begin + λ = collect(400.0:50.0:700.0) + o = layer_optics(OceanLayer(0.0, 3.0, AbstractOceanConstituent{Float64}[PureWater{Float64}(), + CDOM{Float64}()]), + λ; ℓ_max = 2) + E₀ = [1.0, 0.9, 0.8, 0.6, 0.5, 0.3, 0.2] + τ = absorption_optical_depth(o) + # A[c, k] = τ_c[k] E₀[k]: the Jacobian of Σ_c A[c, ·] is diag(τ). + J = ForwardDiff.jacobian(E -> vec(sum(absorbed_power(o, E); dims = 1)), E₀) + @test J ≈ [i == j ? τ[i] : 0.0 for i in eachindex(τ), j in eachindex(τ)] rtol = 1e-13 + # Photon units and absorbed PAR are linear in the irradiance, so the + # derivative along a scaling x·E₀ is the value at E₀. + @test ForwardDiff.derivative(x -> sum(absorbed_photons(o, x .* E₀)), 1.3) ≈ + sum(absorbed_photons(o, E₀)) rtol = 1e-13 + @test ForwardDiff.derivative(x -> absorbed_par(o, x .* E₀), 0.7) ≈ absorbed_par(o, E₀) rtol = 1e-13 + end + + # ------------------------------------------------------------------------- + # Derivatives with respect to model parameters + # ------------------------------------------------------------------------- + # A model built with a dual parameter has the dual element type. The + # reference is a central difference of the same call with plain `Float64` + # parameters, step h = 1e-5·|x|: truncation ~h²f‴/6 and round-off ~ε/h give + # 1e-8 or better relative to the derivative for every case below (the + # largest observed is 6e-9). Stated tolerance: rtol = 1e-6, and atol = 1e-12 + # where the derivative is exactly zero. + central(f, x; h = 1e-5 * abs(x)) = (f(x + h) .- f(x - h)) ./ (2h) + agree(ad, fd; rtol = 1e-6, atol = 1e-12) = all(isapprox.(ad, fd; rtol, atol)) + check(f, x; atol = 1e-12) = agree(ForwardDiff.derivative(f, x), central(f, x); atol) + λs = (412.5, 443.7, 551.3, 672.1) + one_dual(x) = ForwardDiff.Dual(x, one(x)) + D = typeof(one_dual(0.5)) + + @testset "Constructors take the element type of their parameters" begin + @test Phytoplankton(Chl = 1) isa Phytoplankton{Float64} + @test CDOM(a_ref = 0.5f0) isa CDOM{Float64} + @test (@inferred Phytoplankton(Chl = one_dual(0.5))) isa Phytoplankton{D} + @test (@inferred CDOM(slope = one_dual(0.014))) isa CDOM{D} + @test (@inferred PureWater(temperature = one_dual(20.0))) isa PureWater{D} + @test (@inferred NonAlgalParticles(a_ref = one_dual(0.05))) isa NonAlgalParticles{D} + @test (@inferred FournierForandPhase(backscatter_fraction = one_dual(0.018))) isa + FournierForandPhase{D} + @test (@inferred CDOM{D}(a_ref = one_dual(0.03))) isa CDOM{D} + end + + @testset "Phytoplankton ∂/∂Chl" begin + for λ in λs + @test check(x -> absorption(Phytoplankton(Chl = x), λ), 0.5) + @test check(x -> scattering(Phytoplankton(Chl = x), λ), 0.5) + @test check(x -> backscattering(Phytoplankton(Chl = x), λ), 0.5) + # b_p = 0.30 Chl^0.62 (550/λ) ⇒ ∂b_p/∂Chl = 0.62 b_p / Chl + @test ForwardDiff.derivative(x -> scattering(Phytoplankton(Chl = x), λ), 0.5) ≈ + 0.62 * 0.30 * 0.5^(0.62 - 1) * 550 / λ rtol = 1e-12 + # Bricaud a_p = A Chl^E is not linear in Chl: E = Chl ∂a/∂Chl / a lies in (0, 1). + E = 0.5 * ForwardDiff.derivative(x -> absorption(Phytoplankton(Chl = x), λ), 0.5) / + absorption(Phytoplankton(Chl = 0.5), λ) + @test 0.5 < E < 1 + end + pig = ProspectPigments(carotenoid_ratio = 0.3) + @test check(x -> collect(absorption_by_part(Phytoplankton(Chl = x, pigments = pig), 443.7)), 0.5) + @test check(x -> backscattering(Phytoplankton(Chl = 0.5, B = x), 551.3), 0.01) + @test check(x -> scattering(Phytoplankton{typeof(x)}( + Chl = 0.5, scattering_model = GordonMorel1983(b_ref = x)), 551.3), 0.30) + p = Phytoplankton(Chl = one_dual(0.5)) + @test (@inferred absorption(p, 443.7)) isa D + @test (@inferred scattering(p, 443.7)) isa D + @test (@inferred backscattering(p, 443.7)) isa D + end + + @testset "Non-algal particles ∂/∂(a_ref, slope, b_ref, γ, B, c_ref, ω)" begin + for λ in λs + @test check(x -> absorption(NonAlgalParticles(a_ref = x), λ), 0.05) + @test check(x -> absorption(NonAlgalParticles(slope = x), λ), 0.011) + @test check(x -> scattering(NonAlgalParticles(b_ref = x), λ), 0.45) + @test check(x -> scattering(NonAlgalParticles(spectral_exponent = x), λ), 1.0) + @test check(x -> backscattering(NonAlgalParticles(B = x), λ), 0.02) + @test check(x -> absorption(NonAlgalParticles{typeof(x), FellMineral}(c_ref = x), λ), 0.40) + @test check(x -> scattering(NonAlgalParticles{typeof(x), FellMineral}(ω_nap = x), λ), 0.90) + # Fell: a = (1 − ω) c_ref (440/λ) ⇒ ∂a/∂ω = −c_ref (440/λ) + @test ForwardDiff.derivative( + x -> absorption(NonAlgalParticles{typeof(x), FellMineral}(ω_nap = x), λ), 0.90) ≈ + -0.40 * 440 / λ rtol = 1e-12 + end + @test (@inferred absorption(NonAlgalParticles(a_ref = one_dual(0.05)), 443.7)) isa D + end + + @testset "Pure water ∂/∂(T, S, δ) and refractive index ∂n/∂(T, S)" begin + # Absorption: a(T) = a(T_ref) + Ψ_T (T − T_ref) above 550 nm, no dependence below. + for λ in (650.0, 720.0, 1250.0) + @test check(x -> absorption(PureWater(temperature = x), λ), 20.0) + @test ForwardDiff.derivative(x -> absorption(PureWater(temperature = x), λ), 20.0) ≈ + absorption(PureWater{Float64}(temperature = 23.0), λ) - + absorption(PureWater{Float64}(temperature = 22.0), λ) rtol = 1e-9 + end + @test ForwardDiff.derivative(x -> absorption(PureWater(temperature = x), 443.7), 20.0) == 0 + @test ForwardDiff.derivative(x -> absorption(PureWater(salinity = x), 650.0), 35.0) == 0 + for λ in λs + @test check(x -> scattering(PureWater(temperature = x), λ), 20.0) + @test check(x -> scattering(PureWater(salinity = x), λ), 35.0) + @test check(x -> scattering(PureWater(depolarization = x), λ), 0.039) + @test check(x -> refractive_index(QuanFry1995(temperature = x, salinity = 35.0), λ), 20.0) + # Quan & Fry (1995): ∂n/∂S = n₁ + n₂T + n₃T² + n₆/λ + @test ForwardDiff.derivative( + x -> refractive_index(QuanFry1995(temperature = 20.0, salinity = x), λ), 30.0) ≈ + 1.779e-4 - 1.05e-6 * 20 + 1.6e-8 * 20^2 + 0.01155 / λ rtol = 1e-12 + end + # Salinity raises the scattering of seawater, warming lowers it at 20 °C. + @test ForwardDiff.derivative(x -> scattering(PureWater(salinity = x), 500.0), 35.0) > 0 + w = PureWater(temperature = one_dual(20.0)) + @test (@inferred absorption(w, 650.0)) isa D + @test (@inferred scattering(w, 500.0)) isa D + @test (@inferred refractive_index(QuanFry1995(temperature = one_dual(20.0), salinity = 35.0), + 500.0)) isa D + end + + @testset "Phase-function parameters" begin + ff(x) = FournierForandPhase(backscatter_fraction = x) + for B in (0.005, 0.018, 0.05) + # The constructor inverts B ↦ (n, μ_j); the closed-form B of the result returns it. + @test ForwardDiff.derivative(x -> backscatter_fraction(ff(x)), B) ≈ 1 rtol = 1e-10 + for μ in (-0.9, -0.5, 0.3, 0.9, 0.999) + @test check(x -> phase_function_value(ff(x), μ), B) + end + # Carried through the Legendre quadrature; β₀ = 1 for every B. + dβ = ForwardDiff.derivative(x -> phase_function_moments(ff(x), 16), B) + @test agree(dβ, central(x -> phase_function_moments(ff(x), 16), B); atol = 1e-7) + @test abs(dβ[1]) < 1e-7 + @test all(<(0), dβ[2:end]) # more backscatter, less forward peak + end + # The value of a dual-parameter model is that of the plain model. + @test ForwardDiff.value(ff(one_dual(0.018)).μ_j) ≈ ff(0.018).μ_j rtol = 1e-13 + @test ForwardDiff.value.(phase_function_moments(ff(one_dual(0.018)), 16)) ≈ + phase_function_moments(ff(0.018), 16) rtol = 1e-10 + @test (@inferred phase_function_moments(ff(one_dual(0.018)), 8)) isa Vector{D} + # Henyey–Greenstein: β_ℓ = (2ℓ+1) g^ℓ ⇒ ∂β_ℓ/∂g = (2ℓ+1) ℓ g^(ℓ−1) + g = 0.8 + @test ForwardDiff.derivative(x -> phase_function_moments(HenyeyGreensteinPhase(g = x), 6), g) ≈ + [(2ℓ + 1) * ℓ * g^(ℓ - 1) for ℓ in 0:6] rtol = 1e-12 + @test check(x -> backscatter_fraction(HenyeyGreensteinPhase(g = x)), g) + # Rayleigh water: β₂ = (1 − ρ)/(2 + ρ) ⇒ ∂β₂/∂ρ = −3/(2 + ρ)² + ρ = 0.039 + @test ForwardDiff.derivative( + x -> phase_function_moments(RayleighWaterPhase(depolarization = x), 2)[3], ρ) ≈ + -3 / (2 + ρ)^2 rtol = 1e-12 + end + + # A mixed layer: water, CDOM, phytoplankton and non-algal particles, all at + # the element type that the parameters promote to. + function mixed_layer(; Chl = 0.5, a_cdom = 0.03, S_cdom = 0.014, a_nap = 0.05, T = 20.0, + S = 35.0, B = 0.01, Δz = 5.0) + FT = promote_type(map(typeof, (Chl, a_cdom, S_cdom, a_nap, T, S, B, Δz))...) + return OceanLayer(0.0, Δz, AbstractOceanConstituent{FT}[ + PureWater{FT}(temperature = T, salinity = S), + CDOM{FT}(a_ref = a_cdom, slope = S_cdom), + Phytoplankton{FT}(Chl = Chl, B = B), + NonAlgalParticles{FT}(a_ref = a_nap)]) + end + λ_layer = [412.5, 443.7, 551.3, 672.1, 720.0] + optics(; kw...) = layer_optics(mixed_layer(; kw...), λ_layer; ℓ_max = 16) + defaults = (Chl = 0.5, a_cdom = 0.03, S_cdom = 0.014, a_nap = 0.05, T = 20.0, S = 35.0, + B = 0.01, Δz = 5.0) + + @testset "layer_optics: ∂(τ_a, τ, ω̄)/∂$name" for name in keys(defaults) + x₀ = defaults[name] + at(x) = optics(; name => x) + @test check(x -> absorption_optical_depth(at(x)), x₀) + @test check(x -> optical_depth(at(x)), x₀) + # ω̄ and B are ratios of order 0.1–1 that some parameters leave unchanged (Δz); the + # central difference of a constant is round-off, ε/h ≈ 1e-11, hence atol = 1e-10. + @test check(x -> single_scattering_albedo(at(x)), x₀; atol = 1e-10) + @test check(x -> backscatter_fraction(at(x)), x₀; atol = 1e-10) + # The values are those of the plain layer. + o_dual, o = at(one_dual(x₀)), at(x₀) + @test ForwardDiff.value.(optical_depth(o_dual)) ≈ optical_depth(o) rtol = 1e-13 + @test ForwardDiff.value.(single_scattering_albedo(o_dual)) ≈ single_scattering_albedo(o) rtol = 1e-13 + end + + @testset "layer_optics: which optical depths respond to which parameter" begin + dτa(name) = ForwardDiff.derivative(x -> absorption_optical_depth(optics(; name => x)), defaults[name]) + dτs(name) = ForwardDiff.derivative(x -> scattering_optical_depth(optics(; name => x)), defaults[name]) + @test all(>(0), dτa(:Chl)[1:4]) && all(>(0), dτs(:Chl)) + @test all(>(0), dτa(:a_cdom)) && all(==(0), dτs(:a_cdom)) + @test dτa(:a_cdom) ≈ [5.0 * exp(-0.014 * (λ - 440)) for λ in λ_layer] rtol = 1e-12 + @test all(==(0), dτa(:S)) && all(>(0), dτs(:S)) + @test all(==(0), dτa(:B)) && all(==(0), dτs(:B)) + @test dτa(:T)[1:2] == [0, 0] && dτa(:T)[5] > 0 # Röttgers correction from 550 nm + # Component optical depths: only the phytoplankton component depends on Chl. + o = optics(Chl = one_dual(0.5)) + for c in o.absorbers + sensitive = any(!iszero, ForwardDiff.partials.(c.τ, 1)) + @test sensitive == (c.label == "Phytoplankton") + end + end + + @testset "layer_optics: Greek coefficients ∂β_ℓ/∂B (Fournier-Forand)" begin + β(x, iλ) = greek_expansion(optics(B = x), iλ).β + for iλ in (1, 3) + dβ = ForwardDiff.derivative(x -> β(x, iλ), 0.01) + @test agree(dβ, central(x -> β(x, iλ), 0.01); atol = 1e-7) + @test maximum(abs, dβ) > 10 # a silent zero derivative fails here + end + # Phase parameters that are plain: the expansion has zero partials. + o = optics(Chl = one_dual(0.5)) + @test all(c -> all(g -> all(iszero, ForwardDiff.partials.(g.β, 1)), c.greek), o.scatterers) + # Polarized: the Rayleigh matrix of water follows its depolarization ratio, + # α₂ = 3 (1 − ρ)/(1 + ρ/2) ⇒ ∂α₂/∂ρ = −4.5/(1 + ρ/2)². + dα = ForwardDiff.derivative(0.039) do ρ + FT = typeof(ρ) + layer = OceanLayer(0.0, 1.0, AbstractOceanConstituent{FT}[PureWater{FT}(depolarization = ρ)]) + greek_expansion(layer_optics(layer, λ_layer; ℓ_max = 4, polarized = true), 1).α[3] + end + @test dα ≈ -4.5 / (1 + 0.039 / 2)^2 rtol = 1e-12 + end + + @testset "layer_optics: type stability with dual parameters" begin + layer = mixed_layer(Chl = one_dual(0.5)) + @test layer isa OceanLayer{D} + o = @inferred layer_optics(layer, λ_layer; ℓ_max = 8) + @test o isa OceanLayerOptics{D} + @test (@inferred absorption_optical_depth(o)) isa Vector{D} + @test (@inferred optical_depth(o)) isa Vector{D} + @test (@inferred single_scattering_albedo(o)) isa Vector{D} + @test (@inferred greek_expansion(o, 2)) isa GreekCoefficients{D} + # A plain layer evaluated at a dual element type: wavelength derivatives. + plain = mixed_layer() + @test (@inferred layer_optics(D, plain, λ_layer; ℓ_max = 8)) isa OceanLayerOptics{D} + τ₁(x) = absorption_optical_depth(layer_optics(typeof(x), plain, [x, 551.3]; ℓ_max = 2))[1] + @test check(τ₁, 437.3) + end + + @testset "column_optics with dual parameters" begin + function column(; Chl = 0.5, T = 20.0) + top, deep = mixed_layer(; Chl, T, Δz = 5.0), mixed_layer(; Chl = 0.1 * one(Chl), T) + lower = OceanLayer(5.0, 20.0, deep.constituents) + return column_optics(OceanColumn([top, lower]), λ_layer[1:4]; # Quan–Fry: 400–700 nm + refractive_index = QuanFry1995(temperature = T, salinity = 35.0), + bottom = LambertianBottom(0.1), ℓ_max = 8) + end + @test check(x -> optical_depth(column(Chl = x).layers[1]), 0.5) + @test all(iszero, ForwardDiff.derivative(x -> optical_depth(column(Chl = x).layers[2]), 0.5)) + @test check(x -> column(T = x).refractive_index, 20.0) + @test check(x -> absorption_optical_depth(column(T = x).layers[2]), 20.0) + col = column(Chl = one_dual(0.5)) + @test col isa OceanColumnOptics{D} + @test all(iszero, ForwardDiff.partials.(bottom_albedo(col), 1)) + end + + @testset "Tabulated coefficients and IOP carry dual numbers" begin + λ_tab, a_tab = [400.0, 500.0, 600.0], [0.10, 0.20, 0.40] + @test ForwardDiff.derivative(x -> absorption(TabulatedAbsorber(λ_tab, x .* a_tab), 500.0), 1.0) ≈ 0.20 + b(x) = TabulatedScatterer(λ_tab .* one(x), x .* a_tab, HenyeyGreensteinPhase(g = 0.8 * one(x))) + @test ForwardDiff.derivative(x -> backscattering(b(x), 600.0), 1.0) ≈ + 0.40 * backscatter_fraction(HenyeyGreensteinPhase(g = 0.8)) rtol = 1e-12 + # ω = b/(a + b) ⇒ ∂ω/∂a = −b/(a + b)² + @test ForwardDiff.derivative(x -> single_scattering_albedo(IOP(x, 0.3, 0.01) + IOP(0.1, 0.2, 0.01)), + 0.1) ≈ -0.5 / 0.7^2 rtol = 1e-12 + @test IOP(1, 2, 0.5) isa IOP{Float64} + end + + @testset "What is rejected for dual numbers" begin + x = one_dual(0.5) + # A model of fixed floating-point type cannot store a dual parameter. + @test_throws MethodError Phytoplankton{Float64}(Chl = x) + @test_throws MethodError CDOM{Float64}(a_ref = x) + @test_throws MethodError FournierForandPhase{Float64}(backscatter_fraction = one_dual(0.018)) + # Measured phase tables have no parameter and exist in floating point only. + @test_throws "has no parameter to differentiate" PetzoldPhase{D}() + @test_throws ArgumentError PetzoldPhase{D}() + # Inelastic processes are floating point only. + @test_throws TypeError WaterRaman{D}() + @test_throws MethodError chlorophyll_fluorescence(Phytoplankton(Chl = x); quantum_yield = 0.02) + # A backscatter fraction outside the Mobley et al. (2002) family, also as a dual. + @test_throws "outside the range" FournierForandPhase(backscatter_fraction = one_dual(0.7)) + end + @testset "Range checks accept dual numbers at their bounds" begin + # ForwardDiff 1.x orders duals by value, then partials: Dual(35, 1) > 35. + nS(S) = refractive_index(QuanFry1995(temperature = 20, salinity = S), 500) + # n is linear in S (Quan & Fry 1995), so the backward difference is exact. + @test ForwardDiff.derivative(nS, 35.0) ≈ nS(35.0) - nS(34.0) rtol = 1e-9 + nT(T) = refractive_index(QuanFry1995(temperature = T, salinity = 10), 500) + # n is quadratic in T: the three-point backward difference is exact. + @test ForwardDiff.derivative(nT, 30.0) ≈ (3nT(30.0) - 4nT(29.0) + nT(28.0)) / 2 rtol = 1e-8 + nλ(λ) = refractive_index(QuanFry1995(temperature = 20, salinity = 35), λ) + @test ForwardDiff.derivative(nλ, 700.0) ≈ (3nλ(700.0) - 4nλ(699.99) + nλ(699.98)) / 0.02 rtol = 1e-6 + # Fell mineral b = ω c_ref (λ_ref/λ): ∂b/∂ω = c_ref λ_ref/λ, also at ω = 1. + bω(ω) = scattering(NonAlgalParticles{typeof(ω), FellMineral}(ω_nap = ω), 500.0) + @test ForwardDiff.derivative(bω, 1.0) ≈ 0.40 * 440 / 500 rtol = 1e-14 + # A slope at the edge of the advisory range does not warn. + aS(S) = absorption(CDOM(slope = S), 500.0) + d = @test_logs ForwardDiff.derivative(aS, 0.030) + @test d ≈ -60 * 0.03 * exp(-0.030 * 60) rtol = 1e-14 + # A wavelength at the last node of an absorption table. + w = PureWater(absorption_model = PopeFry1997()) + @test isfinite(ForwardDiff.derivative(x -> absorption(w, x), 727.5)) + end + + @testset "Zhang-Hu scattering: ∂b/∂S at S = 0 is the one-sided derivative" begin + b(S) = scattering(PureWater(temperature = 20.0, salinity = S), 500.0) + d0 = ForwardDiff.derivative(b, 0.0) + # b(S) − b(0) = d S + a S^1.5 + O(S²): D(h) = (b(h) − b(0))/h = d + a√h + O(h), and + # 2D(h/4) − D(h) cancels the √h term. + D(h) = (b(h) - b(0.0)) / h + @test isfinite(d0) && d0 > 0 + @test d0 ≈ 2D(2.5e-5) - D(1e-4) rtol = 1e-4 + @test d0 ≈ ForwardDiff.derivative(b, 1e-10) rtol = 1e-4 + end + + @testset "Fournier-Forand: nested derivatives with respect to B" begin + μj(B) = FournierForandPhase(backscatter_fraction = B).μ_j + d1(B) = ForwardDiff.derivative(μj, B) + d2(B) = ForwardDiff.derivative(d1, B) + h = 1e-5 + # Richardson-extrapolated central difference of a derivative g, error O(h⁴). + rich(g, B) = (4 * (g(B + h / 2) - g(B - h / 2)) / h - (g(B + h) - g(B - h)) / 2h) / 3 + for B in (0.005, 0.02, 0.05) + @test d2(B) ≈ rich(d1, B) rtol = 1e-8 + @test ForwardDiff.derivative(d2, B) ≈ rich(d2, B) rtol = 1e-8 + @test ForwardDiff.hessian(x -> μj(x[1]), [B])[1] ≈ d2(B) rtol = 1e-12 + # The family relation B(n(μ_j), μ_j) = B holds to second order: its second + # derivative along B vanishes. + Bback(x) = backscatter_fraction(FournierForandPhase(backscatter_fraction = x)) + @test abs(ForwardDiff.derivative(y -> ForwardDiff.derivative(Bback, y), B)) < 1e-8 + end + β2(B) = phase_function_moments(FournierForandPhase(backscatter_fraction = B), 4)[3] + dβ2(B) = ForwardDiff.derivative(β2, B) + for B in (0.01, 0.02) + d = ForwardDiff.derivative(dβ2, B) + @test isfinite(d) + @test d ≈ rich(dβ2, B) rtol = 1e-6 + end + # Second derivatives in n and μ_j directly. + for (f, x0) in ((x -> phase_function_moments(FournierForandPhase(n = x, μ_j = 3.5), 4)[3], 1.1), + (x -> phase_function_moments(FournierForandPhase(n = 1.1, μ_j = x), 4)[3], 3.5)) + df(x) = ForwardDiff.derivative(f, x) + @test ForwardDiff.derivative(df, x0) ≈ rich(df, x0) rtol = 1e-6 + end + end + + @testset "Phytoplankton without an element type follows a dual scattering model" begin + # b_p = b_ref Chl^0.62 (550/λ): ∂b_p/∂b_ref = Chl^0.62 · 550/λ. + bp(x) = scattering(Phytoplankton(Chl = 0.5, scattering_model = GordonMorel1983(b_ref = x)), 500.0) + @test ForwardDiff.derivative(bp, 0.3) ≈ 0.5^0.62 * 550 / 500 rtol = 1e-14 + τ(x) = optical_depth(layer_optics(OceanLayer(0.0, 2.0, + [PureWater{typeof(x)}(), Phytoplankton(Chl = 0.5, scattering_model = GordonMorel1983(b_ref = x))]), + [500.0]))[1] + @test ForwardDiff.derivative(τ, 0.3) ≈ 2 * 0.5^0.62 * 550 / 500 rtol = 1e-12 + x = ForwardDiff.Dual(0.3, 1.0) + @test_throws "cannot hold" Phytoplankton{Float32}(Chl = 0.5, scattering_model = GordonMorel1983(b_ref = x)) + @test Phytoplankton{Float32}(Chl = 0.5).scattering_model isa GordonMorel1983{Float64} end end diff --git a/test/test_aqua.jl b/test/test_aqua.jl new file mode 100644 index 0000000..f12ce89 --- /dev/null +++ b/test/test_aqua.jl @@ -0,0 +1,7 @@ +using Aqua + +@testset "Aqua" begin + Aqua.test_all(OceanOptics) + # Not part of `test_all`; `Base.Docs.undocumented_names` exists from Julia 1.11. + VERSION ≥ v"1.11" && Aqua.test_undocumented_names(OceanOptics) +end diff --git a/test/test_cdom.jl b/test/test_cdom.jl index 92cfeb1..6fa34a6 100644 --- a/test/test_cdom.jl +++ b/test/test_cdom.jl @@ -7,6 +7,13 @@ # Exponential decay: a(λ+1/S) = a(λ)/e @test absorption(cdom, 440.0 + 1/0.014) ≈ 0.03 / ℯ rtol=1e-10 + # Defaults: slope 0.014 1/nm (Bricaud, Morel & Prieur 1981; Fell 1997, Eq. 5.4) + # anchored at 440 nm, so a(540)/a(440) = exp(−1.4) = 0.24660. + d = CDOM{Float64}() + @test d.slope == 0.014 && d.λ_ref == 440.0 + @test absorption(d, 540.0) / absorption(d, 440.0) ≈ exp(-1.4) rtol = 1e-12 + @test absorption(d, 540.0) / absorption(d, 440.0) ≈ 0.24660 rtol = 1e-4 + # Monotonic decay into the red @test absorption(cdom, 500.0) < absorption(cdom, 440.0) @test absorption(cdom, 400.0) > absorption(cdom, 440.0) diff --git a/test/test_column.jl b/test/test_column.jl index 7a34420..b2c692e 100644 --- a/test/test_column.jl +++ b/test/test_column.jl @@ -56,7 +56,7 @@ depth = -1.0) end - @testset "fell_column matches DESIGN §4.5 grid" begin + @testset "fell_column matches the layer grid of Fell (1997)" begin cdom = CDOM{Float64}(a_ref = 0.03) col = fell_column(AbstractOceanConstituent{Float64}[cdom]; depth = 60.0) diff --git a/test/test_device.jl b/test/test_device.jl new file mode 100644 index 0000000..4ab7cca --- /dev/null +++ b/test/test_device.jl @@ -0,0 +1,227 @@ +# Device tests: result structs moved with `Adapt.adapt`, their validation and +# derived quantities on device arrays, and the array methods of the +# closed-form models. +# +# The array type under test is `DEVICE_ARRAY`. An including script may set +# it (test/gpu/runtests.jl sets `CuArray`); otherwise the reference backend +# JLArrays is used, with scalar indexing disallowed. JLArrays ≥ 0.5 compiles +# every broadcast through the GPU compiler; earlier versions run kernels as +# plain host code and accept what a real device rejects. + +using Adapt: adapt + +if !@isdefined(DEVICE_ARRAY) + using JLArrays: JLArrays, JLArray + JLArrays.allowscalar(false) + const DEVICE_ARRAY = JLArray + @testset "reference backend" begin + @test pkgversion(JLArrays) ≥ v"0.5" + end +end + +# Two layers of water, CDOM, phytoplankton and non-algal particles with +# chlorophyll fluorescence and water Raman, polarized, Lambertian bottom. +function device_test_column(::Type{FT}) where {FT} + phyto = Phytoplankton{FT}(Chl = FT(0.5)) + fluo = chlorophyll_fluorescence(phyto; quantum_yield = FT(0.02)) + cs = AbstractOceanConstituent{FT}[PureWater{FT}(), CDOM{FT}(), phyto, NonAlgalParticles{FT}()] + layers = [OceanLayer(FT(0), FT(4), cs; inelastic = AbstractOceanInelasticProcess{FT}[fluo, WaterRaman{FT}()]), + OceanLayer(FT(4), FT(15), cs)] + return column_optics(FT, OceanColumn(layers), collect(FT, 400:20:700); + refractive_index = QuanFry1995(temperature = FT(20), salinity = FT(35)), + bottom = LambertianBottom(FT(0.1)), ℓ_max = 16, polarized = true, + scalar_phase_approximation = :depolarizing) +end + +# A layer whose scattering component has two expansions selected by +# `phase_index`, and an absorber that vanishes at one wavelength. +function device_test_indexed_layer(::Type{FT}) where {FT} + g1 = GreekCoefficients(FT[1, 0.3, 0.1]) + g2 = GreekCoefficients(FT[1, 1.5, 0.6]) + s = ScatteringComponent("two phases", FT[0.2, 0.0, 0.4, 0.1], [g1, g2], FT[0.4, 0.1], :scalar; + phase_index = [1, 2, 2, 1]) + r = ScatteringComponent("Rayleigh", FT[0.05, 0.0, 0.02, 0.01], [GreekCoefficients(FT[1, 0, 0.5])], + FT[0.5], :scalar) + a = AbsorptionComponent("absorber", :total, FT[0.3, 0.0, 0.1, 0.2]) + return OceanLayerOptics{FT}(FT[400, 500, 600, 700], 0, 2, [a], [s, r], InelasticComponent{FT}[], 3, false) +end + +@testset "Device arrays ($DEVICE_ARRAY, $FT)" for FT in (Float32, Float64) + Dev = DEVICE_ARRAY + col = device_test_column(FT) + dev = adapt(Dev, col) + + @testset "scalar indexing is disallowed" begin + @test_throws "calar indexing" dev.refractive_index[1] + end + + @testset "adapt: arrays move, the element type and host metadata stay" begin + @test dev isa OceanColumnOptics{FT, <:LambertianBottom{FT}} + @test dev.refractive_index isa Dev{FT, 1} + @test dev.bottom.albedo isa Dev{FT, 1} + for (l, lh) in zip(dev.layers, col.layers) + @test l isa OceanLayerOptics{FT} + @test l.λ isa Dev{FT, 1} + @test (l.depth_top, l.depth_bottom, l.n_moments, l.polarized) === + (lh.depth_top, lh.depth_bottom, lh.n_moments, lh.polarized) + @test all(c -> c.τ isa Dev{FT, 1}, l.absorbers) + @test [(c.label, c.part) for c in l.absorbers] == [(c.label, c.part) for c in lh.absorbers] + for (c, ch) in zip(l.scatterers, lh.scatterers) + @test c.τ isa Dev{FT, 1} && c.backscatter_fraction isa Dev{FT, 1} + @test c.phase_index isa Dev{Int, 1} + @test all(g -> g isa GreekCoefficients{FT, <:Dev} && g.β isa Dev{FT, 1} && + g.α isa Dev{FT, 1}, c.greek) + @test (c.label, c.polarization) == (ch.label, ch.polarization) + @test c.phase_id == ch.phase_id # content keys of the host copies + end + # Inelastic components are host data: the same objects. + @test l.inelastic === lh.inelastic + @test all(c -> c.efficiency isa Vector{FT} && c.excitation isa Vector{Int}, l.inelastic) + end + @test length(dev.layers[1].inelastic) == 2 && isempty(dev.layers[2].inelastic) + # The excitation link of the adapted layer is read on the host, from host data. + k = findfirst(c -> !isempty(c.excitation), col.layers[1].inelastic) + @test dev.layers[1].inelastic[k].excitation == col.layers[1].inelastic[k].excitation + end + + @testset "adapt: shared expansions stay shared, keys are kept" begin + g_host = col.layers[1].scatterers[1].greek[1] + @test g_host === col.layers[2].scatterers[1].greek[1] # shared by column_optics + @test dev.layers[1].scatterers[1].greek[1] === dev.layers[2].scatterers[1].greek[1] + @test dev.layers[1].scatterers[1].greek[1].β === dev.layers[2].scatterers[1].greek[1].β + distinct(c) = length(unique(objectid, [g for l in c.layers for s in l.scatterers for g in s.greek])) + @test distinct(dev) == distinct(col) + @test Array(dev.layers[2].scatterers[1].greek[1].β) == g_host.β + end + + @testset "adapt: an adaptor that changes the element type is refused" begin + Other = FT === Float32 ? Float64 : Float32 + for x in (col, col.layers[1], col.layers[1].scatterers[1], col.layers[1].absorbers[1], + col.layers[1].scatterers[1].greek[1], col.bottom, + SpectralTable(FT[400, 500], FT[1, 2])) + @test_throws "changes the element type from $FT to $Other" adapt(Dev{Other}, x) + @test_throws "changes the element type" adapt(Array{Other}, x) + end + end + + # A struct captured by a broadcast is rebuilt by the backend's kernel adaptor, + # which must not run reductions. The structs without host metadata qualify; + # components carry a label and stay containers. + @testset "result structs pass into a device broadcast" begin + xs = Dev(FT[1, 2, 3]) + g = dev.layers[1].scatterers[1].greek[1] + @test Array(broadcast((gg, x) -> length(gg.β) * x, Ref(g), xs)) == FT[17, 34, 51] + b = dev.bottom + @test Array(broadcast((bb, x) -> length(bb.albedo) * x, Ref(b), xs)) == FT[1, 2, 3] + end + + @testset "round trip and host no-op" begin + back = adapt(Array, dev) + @test typeof(back) === typeof(col) + @test back.refractive_index == col.refractive_index + @test back.bottom.albedo == col.bottom.albedo + for (l, lh) in zip(back.layers, col.layers) + @test l.λ == lh.λ + @test all(((c, ch),) -> c.τ == ch.τ, zip(l.absorbers, lh.absorbers)) + @test all(((c, ch),) -> c.τ == ch.τ && c.greek == ch.greek && c.phase_id == ch.phase_id && + c.backscatter_fraction == ch.backscatter_fraction, + zip(l.scatterers, lh.scatterers)) + @test all(((c, ch),) -> c.efficiency == ch.efficiency, zip(l.inelastic, lh.inelastic)) + end + same = adapt(Array, col) # host to host: the same arrays + @test same.layers[1].λ === col.layers[1].λ + @test same.layers[2].scatterers[1].greek[1].β === col.layers[2].scatterers[1].greek[1].β + @test same.refractive_index === col.refractive_index + end + + # The device runs the host's broadcasts; a device may contract a·b + c + # into one fused operation, which changes a sum by at most one rounding. + @testset "derived quantities on the device equal the host's" begin + rtol = 4 * eps(FT) + for (l, lh) in zip(dev.layers, col.layers), + f in (absorption_optical_depth, scattering_optical_depth, optical_depth, + single_scattering_albedo, backscatter_fraction) + y = f(l) + @test y isa Dev{FT, 1} + @test Array(y) ≈ f(lh) rtol = rtol + end + @test bottom_albedo(dev) isa Dev{FT, 1} + @test Array(bottom_albedo(dev)) == bottom_albedo(col) + black = adapt(Dev, column_optics(FT, uniform_column(AbstractOceanConstituent{FT}[PureWater{FT}()]; + n_layers = 1, depth = FT(5)), FT[450, 550]; + refractive_index = FixedRefractiveIndex(FT(1.34)), + bottom = BlackBottom(), ℓ_max = 4)) + @test black isa OceanColumnOptics{FT, BlackBottom} + @test bottom_albedo(black) isa Dev{FT, 1} && Array(bottom_albedo(black)) == zeros(FT, 2) + + # phase_index gather, zero optical depth (ϖ = 0, B = 0 there) + lh = device_test_indexed_layer(FT) + l = adapt(Dev, lh) + @test l.scatterers[1].phase_index isa Dev{Int, 1} + @test Array(single_scattering_albedo(l)) ≈ FT[0.25 / 0.55, 0, 0.42 / 0.52, 0.11 / 0.31] rtol = rtol + @test Array(backscatter_fraction(l)) ≈ + FT[(0.2 * 0.4 + 0.05 * 0.5) / 0.25, 0, (0.4 * 0.1 + 0.02 * 0.5) / 0.42, + (0.1 * 0.4 + 0.01 * 0.5) / 0.11] rtol = rtol + @test Array(backscatter_fraction(l)) ≈ backscatter_fraction(lh) rtol = rtol + @test Array(single_scattering_albedo(l))[2] === zero(FT) + end + + @testset "construction and validation on device arrays" begin + @test AbsorptionComponent("w", :total, Dev(FT[0.1, 0.2])).τ isa Dev{FT, 1} + @test LambertianBottom(Dev(FT[0.1, 0.3])).albedo isa Dev{FT, 1} + g = GreekCoefficients(Dev(FT[1, 0.3, 0.1])) + @test g isa GreekCoefficients{FT, <:Dev} + @test depolarized(g).α isa Dev{FT, 1} && Array(depolarized(g).α) == zeros(FT, 3) + @test Array(resize_moments(g, 4).β) == FT[1, 0.3, 0.1, 0, 0] + @test phase_id(g) == phase_id(GreekCoefficients(FT[1, 0.3, 0.1])) + @test_throws "|β_1| = 4.0 > 2ℓ+1 = 3" GreekCoefficients(Dev(FT[1, 4])) + @test_throws "β₀ = 0.5" GreekCoefficients(Dev(FT[0.5, 0.1])) + @test_throws "γ_1 = 0.2 must be zero" GreekCoefficients(Dev(FT[1, 0.3, 0.1]); α = Dev(FT[0, 0, 0.1]), + γ = Dev(FT[0, 0.2, 0.1]), δ = Dev(FT[0, 0, 0.1]), ϵ = Dev(FT[0, 0, 0.1]), ζ = Dev(FT[0, 0, 0.1])) + @test_throws "finite and non-negative" AbsorptionComponent("w", :total, Dev(FT[0.1, -0.2])) + @test_throws "albedo must lie in [0, 1]" LambertianBottom(Dev(FT[0.1, 1.3])) + lh = device_test_indexed_layer(FT) + l = adapt(Dev, lh) + @test_throws "strictly increasing or strictly decreasing" OceanLayerOptics{FT}( + Dev(FT[400, 600, 500, 700]), 0, 2, l.absorbers, l.scatterers, l.inelastic, 3, false) + @test_throws "phase_index refers to missing expansions" ScatteringComponent( + "two phases", l.scatterers[1].τ, l.scatterers[1].greek, l.scatterers[1].backscatter_fraction, + :scalar; phase_index = Dev([1, 3, 2, 1])) + end + + # A table moved to the device is interpolated there in one broadcast; the + # range check uses the limits stored as numbers and throws on the host. + @testset "SpectralTable on the device" begin + host = SpectralTable(FT[400, 410, 430, 500], FT[1, 3, 2, 9]) + tbl = adapt(Dev, host) + @test tbl isa SpectralTable{FT, <:Dev{FT, 1}} + @test (tbl.lo, tbl.hi) === (host.lo, host.hi) + @test adapt(Array, host).λ === host.λ + λh = FT[400, 405, 410, 425, 430, 465, 500] + y = linterp(tbl, Dev(λh)) + @test y isa Dev{FT, 1} + @test Array(y) ≈ FT[1, 2, 3, 2.25, 2, 5.5, 9] rtol = 4 * eps(FT) + @test Array(y) ≈ linterp(host, λh) rtol = 4 * eps(FT) + @test_throws "outside the tabulated range 400.0–500.0 nm" linterp(tbl, Dev(FT[405, 501])) + @test_throws DomainError linterp(tbl, Dev(FT[399, 405])) + end + + # Models without tables are plain bits and their array methods are one + # `map`. The device's `exp` and `^` differ from the host's by a few ulp. + @testset "array methods of closed-form models" begin + λh = collect(FT, 400:12.5:700) + λd = Dev(λh) + index = QuanFry1995(temperature = FT(20), salinity = FT(35)) + for (f, c) in ((absorption, CDOM{FT}()), (absorption, NonAlgalParticles{FT}()), + (scattering, NonAlgalParticles{FT}()), (backscattering, NonAlgalParticles{FT}()), + (absorption, NonAlgalParticles{FT, FellMineral}()), + (scattering, NonAlgalParticles{FT, FellMineral}()), + (refractive_index, index), (refractive_index, FixedRefractiveIndex(FT(1.34)))) + @test isbits(c) + y = f(c, λd) + @test y isa Dev{FT, 1} + @test Array(y) ≈ f(c, λh) rtol = 32 * eps(FT) + @test f(c, λh) == [f(c, x) for x in λh] + end + end +end diff --git a/test/test_explicit_imports.jl b/test/test_explicit_imports.jl new file mode 100644 index 0000000..ff1ff0a --- /dev/null +++ b/test/test_explicit_imports.jl @@ -0,0 +1,10 @@ +using ExplicitImports + +@testset "ExplicitImports" begin + # `Base.Fix1`, `Base.require_one_based_indexing` and Adapt's extension + # point `Adapt.adapt_structure` are documented API, declared `public` + # from Julia 1.11 on; Julia 1.10 has no such declaration to check. + ExplicitImports.test_explicit_imports(OceanOptics; + all_qualified_accesses_are_public = (; ignore = (:Fix1, :require_one_based_indexing, + :adapt_structure))) +end diff --git a/test/test_float32.jl b/test/test_float32.jl new file mode 100644 index 0000000..3c2a62d --- /dev/null +++ b/test/test_float32.jl @@ -0,0 +1,117 @@ +@testset "Float32" begin + FT = Float32; λ = 550f0 + @test absorption(CDOM{FT}(), λ) isa FT + for nap in (NonAlgalParticles{FT}(), NonAlgalParticles{FT, FellMineral}()), + f in (absorption, scattering, backscattering) + @test f(nap, λ) isa FT + end + @test refractive_index(QuanFry1995(temperature = 20f0, salinity = 35f0), λ) isa FT + for pf in scalar_phases(FT) + @test greek_expansion(pf, 16) isa GreekCoefficients{FT} + @test backscatter_fraction(pf) isa FT + end + @test phase_function_value(PetzoldPhase{FT}(), 0.3f0) isa FT + + layer = inelastic_layer(FT); λg = collect(FT, 350:10:750) + o = layer_optics(layer, λg; ℓ_max = 8) # element type of the layer + @test o isa OceanLayerOptics{FT} + @test eltype(o.λ) === FT && all(a -> eltype(a.τ) === FT, o.absorbers) && + all(s -> eltype(s.τ) === FT, o.scatterers) + @test layer_optics(Float64, layer, λg; ℓ_max = 8) isa OceanLayerOptics{Float64} + # The element type is the first positional argument; there is no keyword for it. + @test_throws MethodError layer_optics(layer, λg; ℓ_max = 8, FT = Float64) + column = uniform_column(layer.constituents; n_layers = 2, depth = FT(10)) + col = column_optics(column, λg; refractive_index = FixedRefractiveIndex(FT(1.34)), + bottom = LambertianBottom(0.1), ℓ_max = 8) + @test typeof(col) === OceanColumnOptics{FT, LambertianBottom{FT, Vector{FT}}, Vector{FT}, Vector{Int}} + @test col isa OceanColumnOptics{FT, <:LambertianBottom{FT}} + E₀ = ones(FT, length(λg)) + @test absorbed_power(o, E₀) isa Matrix{FT} + @test excitation_optical_depth(o, 2) isa Vector{FT} + @test inelastic_emission(o, 2, E₀, FT[500, 520]) isa Vector{FT} + + @test absorbed_par(o, E₀) isa Vector{FT} + @test absorbed_photons(o, E₀) isa Matrix{FT} +end + +# Functions that read a data table or evaluate a formula with Float64 +# constants compute on the host in Float64 and round the result once. With +# parameters and arguments that are exact in both precisions the Float32 +# value is therefore the correctly rounded Float64 value (`===`); where a +# Float32 parameter differs from its Float64 default the two models differ by +# that rounding and the comparison carries a tolerance in units of +# eps(Float32). +@testset "Float32 against Float64" begin + FT = Float32; ϵ = eps(FT) + λs = collect(FT, 352:7:748) + rounded(f, c, c64, xs) = all(x -> f(c, x) === FT(f(c64, Float64(x))), xs) + + # The depolarization 0.039 is not exact in Float32 and enters the Zhang-Hu + # magnitude, so the Float64 twin takes the Float32 model's stored value. + water = PureWater{FT}() + water64 = PureWater{Float64}(depolarization = Float64(water.depolarization)) + @test (water.temperature, water.salinity) == (water64.temperature, water64.salinity) + @test all(x -> isapprox(scattering(water, x), scattering(PureWater{Float64}(), Float64(x)); rtol = 2ϵ), λs) + @test absorption(water, 550f0) isa FT && scattering(water, 550f0) isa FT + @test rounded(absorption, water, water64, λs) + @test rounded(scattering, water, water64, λs) + @test rounded(backscattering, water, water64, λs) + + phyto, phyto64 = Phytoplankton{FT}(Chl = 0.5f0), Phytoplankton{Float64}(Chl = 0.5) + @test absorption(phyto, 550f0) isa FT && scattering(phyto, 550f0) isa FT + @test rounded(absorption, phyto, phyto64, λs) + @test rounded(scattering, phyto, phyto64, λs) + + # The same (n, μ_j), exact in both precisions. + ff = FournierForandPhase{FT}(backscatter_fraction = 0.018f0) + ff64 = FournierForandPhase{Float64}(Float64(ff.n), Float64(ff.μ_j)) + μs = collect(FT, -0.95:0.1:0.95) + @test phase_function_value(ff, 0.3f0) isa FT + @test rounded(phase_function_value, ff, ff64, μs) + + # Default parameters: 2.7e-4 and 0.17 are not exact in Float32, which + # changes the Float32 model by up to eps/2 in each. + raman, raman64 = WaterRaman{FT}(), WaterRaman{Float64}() + λem = FT[505, 515, 520, 525, 535] + @test emission(raman, 440f0, 520f0) isa FT + @test all(x -> isapprox(emission(raman, 440f0, x), emission(raman64, 440.0, Float64(x)); rtol = 2ϵ), λem) + @test raman_peak_wavelength(raman, 440f0) === FT(raman_peak_wavelength(raman64, 440.0)) + + # A wider argument widens the result; the model's precision is the floor. + @test absorption(water, 550.0) === absorption(water64, 550.0) + @test scattering(phyto, 550.0) isa Float64 + @test phase_function_value(ff, 0.3) isa Float64 + @test phase_function_value(RayleighWaterPhase{FT}(), 0.3) isa Float64 + @test phase_function_value(TabulatedGreekPhase(FT[1, 0.3]), 0.3) isa Float64 + @test phase_function_value(PetzoldPhase{FT}(), 0.3) isa Float64 + @test phase_function_value(RayleighWaterPhase{FT}(), FT(0.3)) isa FT + @test phase_function_value(TabulatedGreekPhase(FT[1, 0.3]), FT(0.3)) isa FT + @test phase_function_value(PetzoldPhase{FT}(), FT(0.3)) isa FT + @test emission(raman, 440.0, 520.0) isa Float64 + + # A dual-number argument passes through a Float32 model; the derivative + # is compared with a central difference in Float64 (step 1e-3 nm or + # 1e-5 in μ, truncation and round-off below 1e-7 relative). + index = QuanFry1995(temperature = 20f0, salinity = 35f0) + dn = ForwardDiff.derivative(x -> refractive_index(index, x), 550.0) + @test dn ≈ (refractive_index(index, 550.001) - refractive_index(index, 549.999)) / 0.002 rtol = 1e-6 + rayleigh = RayleighWaterPhase{FT}() + dp = ForwardDiff.derivative(x -> phase_function_value(rayleigh, x), 0.3) + @test dp ≈ (phase_function_value(rayleigh, 0.30001) - phase_function_value(rayleigh, 0.29999)) / 0.00002 rtol = 1e-6 + + # Layer results: optical depths are rounded per component from Float64 + # coefficients; the sums over components and the trapezoidal sum of + # absorbed_par run in Float32 (41 wavelengths, positive terms). + layer, layer64 = inelastic_layer(FT), inelastic_layer(Float64) + λg = collect(FT, 350:10:750) + o, o64 = layer_optics(layer, λg; ℓ_max = 8), layer_optics(layer64, Float64.(λg); ℓ_max = 8) + for f in (absorption_optical_depth, scattering_optical_depth, optical_depth, single_scattering_albedo) + @test f(o) isa Vector{FT} + @test f(o) ≈ f(o64) rtol = 4ϵ + end + E₀ = ones(FT, length(λg)) + par, par64 = absorbed_par(o, E₀), absorbed_par(o64, ones(length(λg))) + @test par isa Vector{FT} + @test count(>(0), par64) ≥ 3 # the other parts absorb nothing in 400–700 nm + @test all(((x, y),) -> y == 0 ? x == 0 : isapprox(x, y; rtol = 8ϵ), zip(par, par64)) +end diff --git a/test/test_fluorescence.jl b/test/test_fluorescence.jl index c17fd5f..011359a 100644 --- a/test/test_fluorescence.jl +++ b/test/test_fluorescence.jl @@ -1,3 +1,5 @@ +using QuadGK + @testset "Fluorescence processes" begin @testset "IsotropicFluorescence with a CDOM absorber" begin @@ -108,8 +110,27 @@ @test η[:phycoerythrin_peb] == 1 && η[:unassigned] == 0 a = absorption_by_part(pb, 470.0) @test excitation_absorption(f, 470.0) ≈ 0.02(a[1] + a[2] + a[3] + 0.8a[4] + a[6] + a[7]) rtol = 1e-12 - @test_throws ArgumentError chlorophyll_fluorescence(pb; quantum_yield = 0.02, - transfer = (photosynthetic_carotenoids = 0.8,)) + + # Defaults: carotenoid_transfer reaches the photosynthetic carotenoids only; + # photoprotective carotenoids dissipate (η = 0) unless photoprotective_transfer says otherwise. + fd = chlorophyll_fluorescence(pb; quantum_yield = 0.02, carotenoid_transfer = 0.7) + ηd = Dict(x.part => x.efficiency for x in excitation_pathways(fd)) + @test ηd[:photosynthetic_carotenoids] == 0.7 && ηd[:photoprotective_carotenoids] == 0 + for λ in (360.0, 440.0, 470.0) + a = absorption_by_part(pb, λ) + @test a[5] > 0 + @test excitation_absorption(fd, λ) ≈ 0.02(a[1] + a[2] + a[3] + 0.7a[4] + a[6] + a[7]) rtol = 1e-12 + end + fp = chlorophyll_fluorescence(pb; quantum_yield = 0.02, carotenoid_transfer = 0.7, + photoprotective_transfer = 0.25) + a = absorption_by_part(pb, 440.0) + @test excitation_absorption(fp, 440.0) - excitation_absorption(fd, 440.0) ≈ 0.02 * 0.25a[5] rtol = 1e-12 + # carotenoid_transfer is required while a photosynthetic carotenoid has no η ... + @test_throws ArgumentError chlorophyll_fluorescence(pb; quantum_yield = 0.02) + # ... and not when `transfer` gives it (photoprotective carotenoids default to 0). + ft = chlorophyll_fluorescence(pb; quantum_yield = 0.02, + transfer = (photosynthetic_carotenoids = 0.8,)) + @test Dict(x.part => x.efficiency for x in excitation_pathways(ft))[:photoprotective_carotenoids] == 0 @test_throws ArgumentError chlorophyll_fluorescence(pb; quantum_yield = 0.02, carotenoid_transfer = 0.5, transfer = (fucoxanthin = 1.0,)) @@ -131,14 +152,53 @@ @test_throws UndefKeywordError CDOMFluorescence(cdom; emission = em) end + # Excitation below the 400 nm start of the pigment tables: the shares at 400 nm + # apply, so a partition whose parts all transfer with η = 1 excites exactly like + # the unpartitioned phytoplankton (reference: the total absorption itself). + @testset "UV excitation with a pigment partition" begin + plain = Phytoplankton(Chl = 0.5) + whole = chlorophyll_fluorescence(plain; quantum_yield = 0.02, excitation_range = (350.0, 700.0)) + for pig in (ProspectPigments(carotenoid_ratio = 0.3), + Bidigare1990Pigments(chl_a = 0.5, chl_c = 0.1, psc = 0.3, ppc = 0.15)) + phyto = Phytoplankton(Chl = 0.5, pigments = pig) + f = chlorophyll_fluorescence(phyto; quantum_yield = 0.02, carotenoid_transfer = 1.0, + photoprotective_transfer = 1.0, + excitation_range = (350.0, 700.0)) + # Continuous across 400 nm (a_p changes by < 0.1 % per 0.001 nm). + @test excitation_absorption(f, 399.999) ≈ excitation_absorption(f, 400.0) rtol = 1e-4 + @test excitation_absorption(f, 399.0) ≈ 0.02 * absorption(plain, 399.0) rtol = 1e-12 + @test excitation_absorption(f, 399.0) > 0.9 * excitation_absorption(f, 400.0) + I, _ = quadgk(x -> excitation_absorption(f, x), 350.0, 400.0, 700.0; rtol = 1e-8) + I0, _ = quadgk(x -> excitation_absorption(whole, x), 350.0, 400.0, 700.0; rtol = 1e-8) + @test I ≈ I0 rtol = 1e-7 + Iref, _ = quadgk(x -> 0.02 * absorption(plain, x), 350.0, 400.0, 700.0; rtol = 1e-8) + @test I ≈ Iref rtol = 1e-7 + end + # Strict rule: no excitation outside the table, so the 350–700 nm integral is + # that of the total absorption over 400–700 nm only. + strict = Phytoplankton(Chl = 0.5, pigments = ProspectPigments(carotenoid_ratio = 0.3, + outside = UnassignedOutsideTable())) + fs = chlorophyll_fluorescence(strict; quantum_yield = 0.02, carotenoid_transfer = 1.0, + excitation_range = (350.0, 700.0)) + @test excitation_absorption(fs, 399.999) == 0 + Is, _ = quadgk(x -> excitation_absorption(fs, x), 350.0, 400.0, 700.0; rtol = 1e-8) + Ivis, _ = quadgk(x -> 0.02 * absorption(plain, x), 400.0, 700.0; rtol = 1e-8) + @test Is ≈ Ivis rtol = 1e-7 + end + @testset "Photon and energy kernels" begin phyto = Phytoplankton(Chl = 1.0) sif = chlorophyll_fluorescence(phyto; quantum_yield = 0.02) λ′, λ = 440.0, 685.0 # Quantum yield is part of the excitation coefficient, applied once. @test excitation_absorption(sif, λ′) ≈ quantum_yield(sif) * absorption(phyto, λ′) - # Energy kernel = photon kernel × λ'/λ (ratio of photon energies). - @test radiance_source_kernel(sif, λ′, λ) ≈ inelastic_coefficient(sif, λ′, λ) * λ′ / λ + # Fluorescence converts photons: the energy kernel is φ a f λ'/λ, written out + # from its parts (φ = 0.02, Fluspect emission density at 685 nm). + @test conversion_units(sif) === PhotonConversion() + @test radiance_source_kernel(sif, λ′, λ) ≈ + 0.02 * absorption(phyto, λ′) * redistribution(chloroplast_emission(), λ′, λ) * 440 / 685 + @test inelastic_coefficient(sif, λ′, λ) ≈ + 0.02 * absorption(phyto, λ′) * redistribution(chloroplast_emission(), λ′, λ) # Photon budget: emission integrates to the excitation coefficient. em = 600.0:0.25:900.0 @test sum(inelastic_coefficient(sif, λ′, x) for x in em) * step(em) ≈ diff --git a/test/test_greek.jl b/test/test_greek.jl index dc6da6c..2aae20a 100644 --- a/test/test_greek.jl +++ b/test/test_greek.jl @@ -117,4 +117,17 @@ @test greek_expansion(rw, 2, 650.0; polarized = true).γ[3] < greek_expansion(rw, 2, 450.0; polarized = true).γ[3] end + + @testset "hash agrees with ==" begin + g1 = GreekCoefficients([1.0, 0.3, 0.1]) + g2 = GreekCoefficients([1.0, 0.3, 0.1]) + g3 = GreekCoefficients([1.0, 0.3, 0.2]) + @test g1 == g2 && g1 !== g2 && hash(g1) == hash(g2) + @test length(unique([g1, g2, g3])) == 2 + @test Dict(g1 => 1)[g2] == 1 + # `==` compares values across element types, and so does `hash`. + h = GreekCoefficients(Float32[1, 0.5, 0.25]) + @test h == GreekCoefficients([1.0, 0.5, 0.25]) && hash(h) == hash(GreekCoefficients([1.0, 0.5, 0.25])) + @test phase_id(h) != phase_id(GreekCoefficients([1.0, 0.5, 0.25])) + end end diff --git a/test/test_inference.jl b/test/test_inference.jl new file mode 100644 index 0000000..153f28f --- /dev/null +++ b/test/test_inference.jl @@ -0,0 +1,47 @@ +@testset "Inference ($FT)" for FT in (Float64, Float32) + λ = FT(550) + for c in iop_constituents(FT) + @test (@inferred absorption(c, λ)) isa AbstractFloat + @test (@inferred scattering(c, λ)) isa AbstractFloat + @test (@inferred backscattering(c, λ)) isa AbstractFloat + @test (@inferred absorption_by_part(c, λ)) isa Tuple + end + bidigare = Bidigare1990Pigments(chl_a = FT(0.5), chl_b = FT(0.05), psc = FT(0.3)) + @test (@inferred pigment_fractions(bidigare, λ)) isa NTuple{8, FT} + for pf in scalar_phases(FT) + @test (@inferred greek_expansion(pf, 16)) isa GreekCoefficients{FT} + @test (@inferred backscatter_fraction(pf)) isa FT + end + @test (@inferred greek_expansion(RayleighWaterPhase{FT}(), 16; polarized = true)) isa GreekCoefficients{FT} + @test (@inferred refractive_index(FixedRefractiveIndex(FT(1.34)), λ)) isa FT + @test (@inferred phase_id(greek_expansion(RayleighWaterPhase{FT}(), 4))) isa UInt64 + + @testset "layer and column optics" begin + layer = inelastic_layer(FT) + λg = collect(FT, 350:10:750) + o = @inferred layer_optics(FT, layer, λg; ℓ_max = 8) + @test typeof(o) === OceanLayerOptics{FT, Vector{FT}, Vector{Int}} + @test (@inferred layer_optics(layer, λg; ℓ_max = 8)) isa OceanLayerOptics{FT} + @test (@inferred layer_optics(FT, layer, λg; ℓ_max = 8, polarized = true, + scalar_phase_approximation = :depolarizing)) isa OceanLayerOptics{FT} + column = uniform_column(layer.constituents; n_layers = 2, depth = FT(10)) + index = FixedRefractiveIndex(FT(1.34)) + @test (@inferred column_optics(FT, column, λg; refractive_index = index, + bottom = BlackBottom(), ℓ_max = 8)) isa + OceanColumnOptics{FT, BlackBottom, Vector{FT}, Vector{Int}} + @test (@inferred column_optics(FT, column, λg; refractive_index = index, + bottom = LambertianBottom(FT(0.1)), ℓ_max = 8)) isa + OceanColumnOptics{FT, LambertianBottom{FT, Vector{FT}}, Vector{FT}, Vector{Int}} + + E₀ = ones(FT, length(λg)) + @test (@inferred absorbed_power(o, E₀)) isa Matrix{FT} + @test (@inferred absorbed_photons(o, E₀)) isa Matrix + @test (@inferred absorbed_par(o, E₀)) isa Vector + λ_em = collect(FT, 660:10:740) + for j in eachindex(o.inelastic) # fluorescence, water Raman + @test (@inferred excitation_optical_depth(o, j)) isa Vector{FT} + @test (@inferred inelastic_emission(o, j, E₀, λ_em)) isa Vector{FT} + end + @test all(c -> isconcretetype(typeof(c)), o.inelastic) + end +end diff --git a/test/test_iop.jl b/test/test_iop.jl index e114538..e62e3b1 100644 --- a/test/test_iop.jl +++ b/test/test_iop.jl @@ -42,3 +42,30 @@ promoted = IOP(0.1, 0.05f0, 1//10) @test promoted.a isa Float64 # promoted to Float64 since 0.1 is Float64 end + +@testset "Integer and rational element types" begin + # Arrays of integers or rationals become floating-point IOPs, as scalars do. + iop = IOP([1, 2], [3, 4], [0, 1]) + @test iop isa IOP{Float64} && iop.a == [1.0, 2.0] && iop.bb == [0.0, 1.0] + @test IOP([1//2], [1//4], [0//1]) isa IOP{Float64} + @test IOP(1, 2, 0) isa IOP{Float64} + # Models and optics are not built in integer or rational arithmetic. + for T in (Int, Rational{Int}) + @test_throws "floating-point type" CDOM{T}() + @test_throws "floating-point type" PureWater{T}() + @test_throws "floating-point type" Phytoplankton{T}(Chl = 1) + @test_throws "floating-point type" NonAlgalParticles{T}() + @test_throws "floating-point type" NonAlgalParticles{T, FellMineral}() + @test_throws "floating-point type" GordonMorel1983{T}() + @test_throws "floating-point type" HenyeyGreensteinPhase{T}() + @test_throws "floating-point type" RayleighWaterPhase{T}() + @test_throws "floating-point type" FournierForandPhase{T}(backscatter_fraction = 0.01) + end + layer = OceanLayer(0.0, 1.0, [PureWater(), CDOM()]) + @test_throws "floating-point type" layer_optics(Int, layer, [500.0]) + @test_throws "floating-point type" layer_optics(Rational{Int}, layer, [500.0]) + col = OceanColumn([layer]) + @test_throws "floating-point type" column_optics(Rational{Int}, col, [500.0]; + refractive_index = FixedRefractiveIndex(1.34), + bottom = BlackBottom()) +end diff --git a/test/test_jet.jl b/test/test_jet.jl new file mode 100644 index 0000000..5867f0b --- /dev/null +++ b/test/test_jet.jl @@ -0,0 +1,32 @@ +using JET + +@testset "JET" begin + tm = (OceanOptics,) + @testset "package" begin + JET.test_package(OceanOptics; target_modules = tm) + end + @testset "scalar IOPs: no runtime dispatch, no possible error ($FT)" for FT in (Float64, Float32) + for c in iop_constituents(FT), f in (absorption, scattering, backscattering, absorption_by_part) + JET.test_opt(f, (typeof(c), FT); target_modules = tm) + JET.test_call(f, (typeof(c), FT); target_modules = tm) + end + JET.test_opt(refractive_index, (QuanFry1995{FT}, FT); target_modules = tm) + end + @testset "expansions ($FT)" for FT in (Float64, Float32) + for pf in scalar_phases(FT) + JET.test_opt(greek_expansion, (typeof(pf), Int); target_modules = tm) + JET.test_call(greek_expansion, (typeof(pf), Int); target_modules = tm) + end + end + # Layer assembly iterates an abstractly typed constituent vector (dynamic dispatch by + # design), so only possible errors are tested, not optimization. + @testset "layer assembly: no possible error ($FT)" for FT in (Float64, Float32) + L = typeof(inelastic_layer(FT)) + for approximation in (Nothing, Symbol) + JET.test_call(OceanOptics._layer_optics, + (L, Vector{FT}, Int, Bool, approximation, Type{FT}, + typeof(OceanOptics._expansion_cache(FT))); + target_modules = tm) + end + end +end diff --git a/test/test_layer_optics.jl b/test/test_layer_optics.jl index 10ba52d..48bf9f2 100644 --- a/test/test_layer_optics.jl +++ b/test/test_layer_optics.jl @@ -5,6 +5,16 @@ cdom = CDOM{Float64}(a_ref = 0.05) λ = [412.5, 443.0, 490.0, 555.0, 670.0] + @testset "PureWater at most once per layer" begin + twice = OceanLayer(0.0, 1.0, AbstractOceanConstituent{Float64}[water, cdom, PureWater{Float64}()]) + err = try layer_optics(twice, λ; ℓ_max = 4) catch e; e end + @test err isa ArgumentError && occursin("PureWater 2 times", err.msg) + # Other constituents may repeat: two CDOM pools add. + one_ = layer_optics(OceanLayer(0.0, 1.0, AbstractOceanConstituent{Float64}[water, cdom]), λ; ℓ_max = 4) + two = layer_optics(OceanLayer(0.0, 1.0, AbstractOceanConstituent{Float64}[water, cdom, cdom]), λ; ℓ_max = 4) + @test absorption_optical_depth(two) .- absorption_optical_depth(one_) ≈ absorption(cdom, λ) rtol = 1e-12 + end + @testset "Components and mixed quantities" begin layer = OceanLayer(2.0, 7.0, AbstractOceanConstituent{Float64}[water, cdom, phyto]) o = layer_optics(layer, λ; ℓ_max = 32) @@ -85,7 +95,7 @@ # vSmartMOM-style wavenumber grid, evaluated at λ = 1e7/ν. ν = collect(range(1e7 / 670, 1e7 / 412.5; length = 7)) @test n_wavelengths(layer_optics(layer, 1e7 ./ ν; ℓ_max = 8)) == 7 - o32 = layer_optics(layer, λ; ℓ_max = 8, FT = Float32) + o32 = layer_optics(Float32, layer, λ; ℓ_max = 8) @test o32 isa OceanLayerOptics{Float32} @test optical_depth(o32) ≈ Float32.(optical_depth(o)) rtol = 1e-5 # Outside a constituent's tabulated range: an error, never an extrapolation. @@ -117,7 +127,11 @@ @test greek_expansion(cf, 1) === cf.greek[1] && greek_expansion(cf, 2000) === cf.greek[2] @test cf.phase_index[findfirst(>(550.0), λf)] == 2 @test t < 10 - @test_throws ArgumentError WavelengthDependentPhase(λ2, pf.phases; lookup = :linear) + @test_throws "lookup must be :exact or :nearest, got :linear" WavelengthDependentPhase( + λ2, pf.phases; lookup = :linear) + @test pn isa WavelengthDependentPhase{Float64, <:Any, NearestLookup} + @test WavelengthDependentPhase(λ2, pf.phases; lookup = NearestLookup()) isa + WavelengthDependentPhase{Float64, <:Any, NearestLookup} end @testset "Total absorption cannot be double counted" begin diff --git a/test/test_nap.jl b/test/test_nap.jl index 6d8367e..6e4152e 100644 --- a/test/test_nap.jl +++ b/test/test_nap.jl @@ -30,6 +30,18 @@ @test attenuation(nap, 880.0) ≈ 0.20 rtol=1e-12 end + @testset "FellMineral defaults are those of Fell (1997)" begin + # Fell (1997) §5.1.4, p. 120: ω₀ = 0.95 (Eq. 5.11) and a backscatter + # probability b_b,AS = 0.036; c ∝ 440/λ (Eq. 5.10). + nap = NonAlgalParticles{Float64, FellMineral}(c_ref = 0.40) + @test nap.ω_nap == 0.95 + @test absorption(nap, 440.0) ≈ 0.05 * 0.40 rtol = 1e-12 + @test scattering(nap, 440.0) ≈ 0.95 * 0.40 rtol = 1e-12 + @test backscatter_fraction(scattering_phase(nap)) ≈ 0.036 rtol = 1e-8 + @test backscattering(nap, 440.0) ≈ 0.95 * 0.036 * 0.40 rtol = 1e-8 + @test backscattering(nap, 880.0) ≈ 0.95 * 0.036 * 0.20 rtol = 1e-8 + end + @testset "Construction validation" begin @test_throws ArgumentError NonAlgalParticles{Float64, FellMineral}(ω_nap = 1.1) @test_throws ArgumentError NonAlgalParticles{Float64, FellMineral}(c_ref = -1.0) diff --git a/test/test_parameters.jl b/test/test_parameters.jl new file mode 100644 index 0000000..f7043b2 --- /dev/null +++ b/test/test_parameters.jl @@ -0,0 +1,177 @@ +using QuadGK + +# Every exposed physical parameter is set to a non-default value and the result is +# compared with the closed form in that parameter: a parameter that is stored but not +# used fails here. +@testset "Exposed parameters reach the results" begin + + @testset "PureWater" begin + w = PureWater{Float64}() + @test (w.temperature, w.salinity, w.depolarization) == (20.0, 35.0, 0.039) + # temperature: a(T) = a(22 °C) + Ψ_T (T − 22); Ψ_T(740 nm) ≈ 0.016 1/(m K) (Röttgers 2014) + a22 = absorption(PureWater{Float64}(temperature = 22.0), 740.0) + a32 = absorption(PureWater{Float64}(temperature = 32.0), 740.0) + @test (a32 - a22) / 10 ≈ 0.016 atol = 1e-3 + @test absorption(PureWater{Float64}(temperature = 12.0), 740.0) - a22 ≈ -(a32 - a22) rtol = 1e-10 + # salinity: seawater scatters 30 % more than fresh water (Zhang, Hu & He 2009) + @test scattering(w, 500.0) / scattering(PureWater{Float64}(salinity = 0.0), 500.0) ≈ 1.30 atol = 0.005 + @test scattering(PureWater{Float64}(temperature = 0.0), 500.0) != scattering(w, 500.0) + # depolarization: magnitude and phase matrix + w0 = PureWater{Float64}(depolarization = 0.0) + @test scattering(w, 500.0) / scattering(w0, 500.0) ≈ + (6 + 6 * 0.039) / (6 - 7 * 0.039) * (2.039 / 1.039) / 2 rtol = 1e-12 + @test phase_function_moments(scattering_phase(w0), 2)[3] == 0.5 + # model choice by type + @test scattering(PureWater{Float64}(scattering_model = Morel1974()), 550.0) ≈ 0.00193 rtol = 1e-12 + @test absorption(PureWater{Float64}(absorption_model = SmithBaker1981()), 500.0) ≈ 0.0257 rtol = 1e-6 + end + + @testset "RayleighWaterPhase" begin + for ρ in (0.0, 0.039, 0.09, 0.2906) + @test phase_function_moments(RayleighWaterPhase{Float64}(depolarization = ρ), 2)[3] ≈ + (1 - ρ) / (2 + ρ) rtol = 1e-14 + end + end + + @testset "Phytoplankton and GordonMorel1983" begin + ref = Phytoplankton(Chl = 2.0) + sc(; kw...) = Phytoplankton(Chl = 2.0, scattering_model = GordonMorel1983(; kw...)) + @test scattering(sc(b_ref = 0.45), 500.0) ≈ 1.5 * scattering(ref, 500.0) rtol = 1e-12 + @test scattering(sc(chl_exponent = 1.0), 500.0) ≈ scattering(ref, 500.0) * 2^0.38 rtol = 1e-12 + @test scattering(sc(λ_ref = 500.0), 500.0) ≈ 0.30 * 2^0.62 rtol = 1e-12 + @test scattering(sc(spectral_exponent = 2.0), 440.0) ≈ 0.30 * 2^0.62 * (550 / 440)^2 rtol = 1e-12 + @test scattering(sc(spectral_exponent = 0.0), 440.0) ≈ 0.30 * 2^0.62 rtol = 1e-12 + @test backscattering(Phytoplankton(Chl = 2.0, B = 0.02), 500.0) ≈ 0.02 * scattering(ref, 500.0) rtol = 1e-6 + @test backscattering(ref, 500.0) ≈ 0.01 * scattering(ref, 500.0) rtol = 1e-6 + # Float32 model, double-precision parameters: same law + @test scattering(Phytoplankton{Float32}(Chl = 2, scattering_model = GordonMorel1983(b_ref = 0.45)), 500f0) ≈ + Float32(0.45 * 2^0.62 * 1.1) rtol = 1f-6 + end + + @testset "CDOM" begin + c = CDOM{Float64}(a_ref = 0.2, λ_ref = 400.0, slope = 0.018) + @test absorption(c, 400.0) == 0.2 + @test absorption(c, 450.0) ≈ 0.2 * exp(-0.018 * 50) rtol = 1e-13 + d = CDOM{Float64}() + @test (d.a_ref, d.λ_ref, d.slope) == (0.03, 440.0, 0.014) # slope: Fell (1997) Eq. 5.4 + @test absorption(d, 500.0) ≈ 0.03 * exp(-0.014 * 60) rtol = 1e-13 + end + + @testset "NonAlgalParticles" begin + n = NonAlgalParticles{Float64}(a_ref = 0.1, b_ref = 0.6, λ_ref = 500.0, slope = 0.009, B = 0.03, + spectral_exponent = 0.5) + @test absorption(n, 550.0) ≈ 0.1 * exp(-0.009 * 50) rtol = 1e-13 + @test scattering(n, 600.0) ≈ 0.6 * sqrt(500 / 600) rtol = 1e-13 + @test backscattering(n, 600.0) ≈ 0.03 * scattering(n, 600.0) rtol = 1e-6 + d = NonAlgalParticles{Float64}() + @test scattering(d, 550.0) ≈ 0.45 * 443 / 550 rtol = 1e-13 + @test absorption(d, 500.0) ≈ 0.05 * exp(-0.011 * 57) rtol = 1e-13 + f = NonAlgalParticles{Float64, FellMineral}(c_ref = 1.0, ω_nap = 0.8, λ_ref = 500.0, B = 0.05, + spectral_exponent = 2.0) + @test absorption(f, 600.0) ≈ 0.2 * (500 / 600)^2 rtol = 1e-13 + @test scattering(f, 600.0) ≈ 0.8 * (500 / 600)^2 rtol = 1e-13 + @test backscattering(f, 600.0) ≈ 0.05 * scattering(f, 600.0) rtol = 1e-6 + # Defaults of Fell (1997) Eqs. 5.10–5.11: c ∝ 440/λ, ω₀ = 0.95, b_b/b = 0.036 + g = NonAlgalParticles{Float64, FellMineral}() + @test absorption(g, 550.0) ≈ 0.05 * 0.40 * 440 / 550 rtol = 1e-12 + @test backscattering(g, 440.0) ≈ 0.95 * 0.036 * 0.40 rtol = 1e-6 + end + + @testset "Phase functions" begin + @test phase_function_moments(HenyeyGreensteinPhase{Float64}(g = 0.6), 2) ≈ [1, 3 * 0.6, 5 * 0.36] + @test HenyeyGreensteinPhase{Float64}().g == 0.85 + a = FournierForandPhase{Float64}(1.10, 3.5835) + b = FournierForandPhase{Float64}(1.15, 3.5835) + c = FournierForandPhase{Float64}(1.10, 4.0) + @test backscatter_fraction(a) ≈ 0.0183 atol = 1e-4 # Mobley et al. (2002) + @test backscatter_fraction(b) > backscatter_fraction(a) + @test backscatter_fraction(c) > backscatter_fraction(a) + # Mobley, Sundman & Boss (2002) family: n = 1.01 + 0.1542 (μ − 3) + ff = FournierForandPhase{Float64}(backscatter_fraction = 0.05) + @test ff.n ≈ 1.01 + 0.1542 * (ff.μ_j - 3) rtol = 1e-12 + end + + @testset "Refractive index" begin + @test refractive_index(FixedRefractiveIndex(1.36), 500.0) == 1.36 + q(T, S) = refractive_index(QuanFry1995(temperature = T, salinity = S), 589.3) + @test q(20.0, 35.0) - q(20.0, 0.0) ≈ 35 * 1.83e-4 rtol = 0.01 # dn/dS (Quan & Fry 1995) + @test q(30.0, 35.0) < q(10.0, 35.0) + end + + @testset "WaterRaman" begin + r = WaterRaman{Float64}(shift_cm_inv = 3000.0, σ_cm_inv = 40.0, cross_section_ref = 5e-4, + cross_section_λ_ref = 500.0, cross_section_n = 4.0, + linear_depolarization = 0.3, excitation_range = (300.0, 600.0), + conversion = PhotonConversion()) + @test raman_peak_wavelength(r, 440.0) ≈ 1e7 / (1e7 / 440 - 3000) rtol = 1e-14 + λp = raman_peak_wavelength(r, 440.0) + @test emission(r, 440.0, λp) ≈ 1e7 / λp^2 / (40 * sqrt(2π)) rtol = 1e-12 + @test excitation_absorption(r, 500.0) == 5e-4 + @test excitation_absorption(r, 400.0) ≈ 5e-4 * 1.25^4 rtol = 1e-13 + @test phase_function_moments(raman_phase(r), 2)[3] ≈ 0.7 / (2 * 1.6) rtol = 1e-14 + @test excitation_range(r) == (300.0, 600.0) + @test radiance_source_kernel(r, 440.0, λp) ≈ inelastic_coefficient(r, 440.0, λp) * 440 / λp + e = WaterRaman{Float64}(shift_cm_inv = 3000.0, σ_cm_inv = 40.0, cross_section_ref = 5e-4, + cross_section_λ_ref = 500.0, cross_section_n = 4.0) + @test radiance_source_kernel(e, 440.0, λp) ≈ inelastic_coefficient(r, 440.0, λp) + # Shared band defaults of the redistribution type and the process + d = WaterRaman{Float64}(); s = WavenumberShiftEmission{Float64}() + @test (d.shift_cm_inv, d.σ_cm_inv) == (s.shift_cm_inv, s.σ_cm_inv) == (3400.0, 85.0) + @test redistribution(WavenumberShiftEmission{Float64}(shift_cm_inv = 3000.0, σ_cm_inv = 40.0), 440.0, λp) == + emission(r, 440.0, λp) + end + + @testset "Emission bands" begin + g = GaussianEmission{Float64}(center_nm = 700.0, σ_nm = 5.0) + @test redistribution(g, 440.0, 700.0) ≈ 1 / (5 * sqrt(2π)) rtol = 1e-14 + @test redistribution(g, 440.0, 705.0) ≈ exp(-0.5) / (5 * sqrt(2π)) rtol = 1e-14 + d = GaussianEmission{Float64}() + @test (d.center_nm, d.σ_nm) == (685.0, 10.6) # Fell (1997) §2.2.9 + end + + @testset "Fluorescence and absorbed light" begin + phyto = Phytoplankton(Chl = 1.0, pigments = ProspectPigments(carotenoid_ratio = 0.3)) + mk(; φ = 0.02, car = 0.5, range = (400.0, 700.0)) = + chlorophyll_fluorescence(phyto; quantum_yield = φ, carotenoid_transfer = car, excitation_range = range) + f = mk() + @test excitation_range(chlorophyll_fluorescence(phyto; quantum_yield = 0.02, carotenoid_transfer = 0.5)) == + (400.0, 700.0) + @test excitation_absorption(mk(φ = 0.05), 450.0) ≈ 2.5 * excitation_absorption(f, 450.0) rtol = 1e-12 + a_chl, a_car, _ = absorption_by_part(phyto, 450.0) + @test excitation_absorption(mk(car = 1.0), 450.0) - excitation_absorption(mk(car = 0.0), 450.0) ≈ + 0.02 * a_car rtol = 1e-10 + @test absorption_part(Phytoplankton(Chl = 1.0, pigments = ProspectPigments(carotenoid_ratio = 0.6)), + :carotenoids, 450.0) > a_car + λ = collect(350.0:5.0:750.0) + layer(p) = layer_optics(OceanLayer(0.0, 2.0, AbstractOceanConstituent{Float64}[PureWater{Float64}(), phyto]; + inelastic = AbstractOceanInelasticProcess{Float64}[p]), λ; ℓ_max = 2) + E = ones(length(λ)); λ_em = collect(650.0:2.0:800.0) + P_par = inelastic_emission(layer(f), 1, E, λ_em) + P_uv = inelastic_emission(layer(mk(range = (350.0, 700.0))), 1, E, λ_em) + P_set = inelastic_emission(layer(f), 1, E, λ_em; range = (350.0, 700.0)) + @test all(P_uv .> P_par) && P_set ≈ P_uv + o = layer(f) + # absorbed_par: range limits (water row; unit irradiance) + par(r) = absorbed_par(o, E; range = r)[1] + @test par((400, 700)) == absorbed_par(o, E)[1] + @test par((400, 600)) + par((600, 700)) ≈ par((400, 700)) rtol = 1e-12 + @test par((350, 700)) > par((400, 700)) + # round-off allowance for negative irradiance + noisy = copy(E); noisy[end] = -1e-6 + @test_throws ArgumentError absorbed_power(o, noisy) + @test absorbed_power(o, noisy; roundoff_rtol = 1e-5)[:, 1:end-1] == absorbed_power(o, E)[:, 1:end-1] + @test all(absorbed_power(o, noisy; roundoff_rtol = 1e-5)[:, end] .== 0) + @test absorbed_par(o, noisy; roundoff_rtol = 1e-5) ≈ absorbed_par(o, E) rtol = 1e-6 + @test absorbed_photons(o, noisy; roundoff_rtol = 1e-5)[1, 1] == absorbed_photons(o, E)[1, 1] + @test inelastic_emission(o, 1, noisy, λ_em; roundoff_rtol = 1e-5) == P_par + tiny = copy(E); tiny[end] = -1e-12 + @test_throws ArgumentError absorbed_power(o, tiny; roundoff_rtol = 0) + @test_throws ArgumentError absorbed_power(o, E; roundoff_rtol = -1) + # CDOM fluorescence: yield and window + cdom = CDOM{Float64}() + cf(φ, r) = CDOMFluorescence(cdom; emission = GaussianEmission{Float64}(center_nm = 430.0, σ_nm = 20.0), + quantum_yield = φ, excitation_range = r) + @test excitation_absorption(cf(0.02, (300.0, 400.0)), 350.0) ≈ 0.02 * absorption(cdom, 350.0) + @test excitation_range(cf(0.02, (310.0, 390.0))) == (310.0, 390.0) + end +end diff --git a/test/test_phase.jl b/test/test_phase.jl index 40d9211..704662b 100644 --- a/test/test_phase.jl +++ b/test/test_phase.jl @@ -16,6 +16,15 @@ numeric_backscatter(pf) = # The generic θ quadrature reproduces the closed form. @test numeric_moments(pf0, 8) ≈ β atol = 1e-12 + # Scalar phase function and moments with depolarization: β₂ = Δ/2, + # Δ = (1 − ρ)/(1 + ρ/2), so p(μ) = 1 + (Δ/4)(3μ² − 1). At ρ = 0.039 and + # μ = 0.3, Δ = 0.961/1.0195 and p = 1 − 0.1825·Δ = 0.827972. + pfρ = RayleighWaterPhase{Float64}(depolarization = 0.039) + @test phase_function_moments(pfρ, 4) ≈ [1, 0, 0.5 * 0.961 / 1.0195, 0, 0] rtol = 1e-14 + @test phase_function_value(pfρ, 0.3) ≈ 1 - 0.1825 * 0.961 / 1.0195 rtol = 1e-14 + @test phase_function_value(pfρ, 0.3) ≈ 0.827972 rtol = 1e-6 + @test numeric_moments(pfρ, 4) ≈ phase_function_moments(pfρ, 4) atol = 1e-12 + for ρ in (0.0, 0.039, 0.09) pf = RayleighWaterPhase{Float64}(depolarization = ρ) dpl_p = (1 - ρ) / (1 + ρ / 2) @@ -56,6 +65,14 @@ numeric_backscatter(pf) = @test pf.n ≈ 1.10 atol = 1e-3 @test pf.μ_j ≈ 3.5835 atol = 1e-3 @test backscatter_fraction(FournierForandPhase{Float64}(n = 1.10, μ_j = 3.5835)) ≈ 0.0183 atol = 5e-5 + # Away from that point the parameters still lie on the family line of + # Mobley, Sundman & Boss (2002), n = 1.01 + 0.1542 (μ − 3). + for B in (0.002, 0.005, 0.03, 0.05) + q = FournierForandPhase{Float64}(backscatter_fraction = B) + @test q.n ≈ 1.01 + 0.1542 * (q.μ_j - 3) rtol = 1e-12 + end + @test FournierForandPhase{Float64}(backscatter_fraction = 0.005).μ_j < + FournierForandPhase{Float64}(backscatter_fraction = 0.03).μ_j # Exact normalization, checked by an independent adaptive integration # in θ (the forward peak is p ~ θ^(2|ν|-2)), no renormalization involved. diff --git a/test/test_phytoplankton.jl b/test/test_phytoplankton.jl index 8e5661f..66e0f45 100644 --- a/test/test_phytoplankton.jl +++ b/test/test_phytoplankton.jl @@ -1,7 +1,9 @@ @testset "Phytoplankton" begin - @testset "Morel & Maritorena (2001) scattering" begin - # b_p(λ) = 0.30 · Chl^0.62 · (550/λ) + @testset "Gordon & Morel (1983) particulate scattering" begin + # b_p(λ) = 0.30 · Chl^0.62 · (550/λ), Gordon & Morel (1983) as cited by + # Fell (1997), Eq. 5.5. Morel & Maritorena (2001), Eq. 14, would give + # 0.416 at Chl = 1 and 550 nm. p = Phytoplankton{Float64, Bricaud1998}(Chl = 1.0) @test scattering(p, 550.0) ≈ 0.30 rtol=1e-12 @test scattering(p, 440.0) ≈ 0.30 * 550/440 rtol=1e-12 @@ -15,24 +17,46 @@ @test backscattering(p, 550.0) ≈ scattering(p, 550.0) * bf end - @testset "Bricaud (1998 + UV-extended) absorption" begin - # a_φ(λ, Chl=1) = A(λ)·1^{1-E(λ)} = A(λ) exactly; tabulated A(440) is - # around 0.0394 m²/mg (Bricaud 1998 + Morrison-Nelson + Vasilkov update). - p = Phytoplankton{Float64, Bricaud1998}(Chl = 1.0) - @test 0.02 < absorption(p, 440.0) < 0.08 - - # Red chlorophyll peak (676 nm) stronger than the green minimum (600 nm) - @test absorption(p, 676.0) > absorption(p, 600.0) + @testset "Bricaud et al. (1998) particulate absorption a_p = A·Chl^E" begin + # Reference: the coefficients of HydroLight's AEmidUVabs.txt, whose header + # reads "ap(wave) = A(wave)*[chl]^E(wave)": A(440) = 0.0520, E(440) = 0.6350 + # (Bricaud et al. 1998: a_p(440) = 0.052 Chl^0.635) and A(676) = 0.0203, + # E(676) = 0.8223. The specific-absorption form A·Chl^(1−E) differs from + # these by a factor 2.6 (440 nm) and 9.6 (676 nm) at Chl = 0.03. + for Chl in (0.03, 0.1, 1.0, 10.0) + p = Phytoplankton{Float64, Bricaud1998}(; Chl) + @test absorption(p, 440.0) ≈ 0.0520 * Chl^0.6350 rtol = 1e-12 + @test absorption(p, 676.0) ≈ 0.0203 * Chl^0.8223 rtol = 1e-12 + end + # The same numbers written out (four significant figures). + @test absorption(Phytoplankton(Chl = 0.1), 440.0) ≈ 0.01205 rtol = 5e-4 + @test absorption(Phytoplankton(Chl = 10.0), 676.0) ≈ 0.1348 rtol = 5e-4 + # The blue-to-red ratio falls with chlorophyll (0.0520/0.0203·Chl^(0.6350−0.8223)). + ratio(Chl) = (p = Phytoplankton(; Chl); absorption(p, 440.0) / absorption(p, 676.0)) + @test ratio(0.03) ≈ 4.94 rtol = 2e-3 + @test ratio(10.0) ≈ 1.66 rtol = 3e-3 - # a_φ ∝ Chl^{1-E} with E < 1 ⇒ quadrupling Chl gives less than 4× - p2 = Phytoplankton{Float64, Bricaud1998}(Chl = 4.0) - @test absorption(p2, 440.0) > absorption(p, 440.0) - @test absorption(p2, 440.0) < 4 * absorption(p, 440.0) + # No chlorophyll, no particulate absorption: zero at every tabulated + # wavelength, also where E > 1 (698–700 nm). + p0 = Phytoplankton(Chl = 0.0) + @test all(iszero, absorption(p0, collect(300.0:2.0:1000.0))) + @test absorption(Phytoplankton{Float32}(Chl = 0), 700f0) === 0f0 end - @testset "Gordon (1992) absorption is a reserved stub" begin - p = Phytoplankton{Float64, Gordon1992}(Chl = 1.0) - @test_throws ErrorException absorption(p, 440.0) + @testset "Gordon & Morel (1983) scattering: published values and parameters" begin + # Fell (1997) Eq. 5.5: b_P(550) = 0.30 Chl^0.62. Values worked by hand: + # 10^0.62 = 4.16869, 10^-0.62 = 0.239883. + @test scattering(Phytoplankton(Chl = 10.0), 550.0) ≈ 1.25061 rtol = 1e-5 + @test scattering(Phytoplankton(Chl = 0.1), 550.0) ≈ 0.0719650 rtol = 1e-5 + @test scattering(Phytoplankton(Chl = 0.1), 440.0) ≈ 0.0719650 * 1.25 rtol = 1e-5 + gm = Phytoplankton(Chl = 1.0).scattering_model + @test gm === GordonMorel1983() && (gm.b_ref, gm.chl_exponent, gm.λ_ref, gm.spectral_exponent) == (0.30, 0.62, 550.0, 1.0) + # Morel & Maritorena (2001), Eq. 14 magnitude at 550 nm, as a non-default model. + mm = Phytoplankton(Chl = 10.0, scattering_model = GordonMorel1983(b_ref = 0.416, chl_exponent = 0.766)) + @test scattering(mm, 550.0) ≈ 0.416 * 10^0.766 rtol = 1e-12 + @test_throws ArgumentError GordonMorel1983(b_ref = -0.1) + @test_throws ArgumentError GordonMorel1983(λ_ref = 0.0) + @test !isdefined(OceanOptics, :Gordon1992) end @testset "Construction sanity" begin diff --git a/test/test_pigments.jl b/test/test_pigments.jl index 9e372b1..ef0922d 100644 --- a/test/test_pigments.jl +++ b/test/test_pigments.jl @@ -28,9 +28,27 @@ f = pigment_fractions(pig, 480.0) @test f[2] / f[1] ≈ 0.3kca / kab rtol = 1e-12 @test f[3] == 0 - # No carotenoid absorption beyond 557 nm; UV outside the table is unassigned. + # No carotenoid absorption beyond 557 nm. @test absorption_part(phyto, :carotenoids, 600.0) == 0 - @test absorption_part(phyto, :unassigned, 350.0) == absorption(phyto, 350.0) + # Outside the table (400–800 nm) the shares of the nearest tabulated + # wavelength apply by default: nothing is dropped in the UV. + @test pig.outside === HoldEdgeShares() + @test pigment_fractions(pig, 350.0) == pigment_fractions(pig, 400.0) + @test pigment_fractions(pig, 399.999) == pigment_fractions(pig, 400.0) + @test pigment_fractions(pig, 900.0) == pigment_fractions(pig, 800.0) + @test absorption_part(phyto, :unassigned, 350.0) == 0 + @test sum(absorption_by_part(phyto, 350.0)) ≈ absorption(phyto, 350.0) rtol = 1e-14 + # The 400 nm shares are those of the PROSPECT-D table: Kab(400) : r·Kca(400). + k400 = (OceanOptics.linterp(OceanOptics._PROSPECT_KAB, 400.0), + 0.3 * OceanOptics.linterp(OceanOptics._PROSPECT_KCA, 400.0)) + @test collect(pigment_fractions(pig, 350.0)[1:2]) ≈ collect(k400 ./ sum(k400)) rtol = 1e-14 + # Strict rule: all absorption outside the table is unassigned. + strict = ProspectPigments(carotenoid_ratio = 0.3, outside = UnassignedOutsideTable()) + @test pigment_fractions(strict, 399.999) == (0.0, 0.0, 1.0) + @test pigment_fractions(strict, 800.001) == (0.0, 0.0, 1.0) + @test pigment_fractions(strict, 450.0) == pigment_fractions(pig, 450.0) + pstrict = Phytoplankton(Chl = 0.5, pigments = strict) + @test absorption_part(pstrict, :unassigned, 350.0) == absorption(pstrict, 350.0) @test pigment_fractions(ProspectPigments(carotenoid_ratio = 0.0), 450.0) == (1.0, 0.0, 0.0) @test_throws ArgumentError ProspectPigments(carotenoid_ratio = -0.1) @test_throws ArgumentError absorption_part(phyto, :total, 450.0) @@ -40,7 +58,8 @@ pig = Bidigare1990Pigments(chl_a = 0.5, chl_b = 0.05, chl_c = 0.1, psc = 0.3, ppc = 0.15) phyto = Phytoplankton(Chl = 0.5, pigments = pig) @test length(absorption_parts(phyto)) == 8 && last(absorption_parts(phyto)) == :unassigned - @test pigment_class(pig, :photoprotective_carotenoids) == :carotenoid + @test pigment_class(pig, :photoprotective_carotenoids) == :photoprotective_carotenoid + @test pigment_class(pig, :photosynthetic_carotenoids) == :carotenoid @test pigment_class(pig, :phycoerythrin_peb) == :phycobilin @test pigment_class(pig, :chlorophyll_c) == :chlorophyll for λ in (380.0, 440.0, 470.0, 550.0, 676.0, 740.0) @@ -57,7 +76,15 @@ pigment_fractions(pig, 470.0)) # Red band: chlorophyll a only; beyond it and outside the table: unassigned. @test pigment_fractions(Bidigare1990Pigments(chl_a = 1.0, psc = 1.0), 676.0)[1] == 1 - @test last(pigment_fractions(pig, 740.0)) == 1 && last(pigment_fractions(pig, 390.0)) == 1 + # Beyond the red band all spectra vanish (unassigned under both rules); below + # the table the 400 nm shares apply by default, or all is unassigned (strict). + @test last(pigment_fractions(pig, 740.0)) == 1 && last(pigment_fractions(pig, 760.0)) == 1 + @test pigment_fractions(pig, 390.0) == pigment_fractions(pig, 400.0) + @test last(pigment_fractions(pig, 390.0)) == 0 + strictb = Bidigare1990Pigments(chl_a = 0.5, chl_b = 0.05, chl_c = 0.1, psc = 0.3, ppc = 0.15, + outside = UnassignedOutsideTable()) + @test last(pigment_fractions(strictb, 390.0)) == 1 + @test pigment_fractions(strictb, 470.0) == pigment_fractions(pig, 470.0) @test_throws ArgumentError Bidigare1990Pigments(chl_a = 0.0) @test_throws ArgumentError Bidigare1990Pigments(chl_a = 1.0, ppc = -0.1) @test_throws UndefKeywordError Bidigare1990Pigments(psc = 1.0) @@ -76,6 +103,8 @@ @test absorption_by_part(p32, 450.0f0) isa NTuple{3, typeof(absorption(p32, 450.0f0))} b32 = Phytoplankton{Float32, Bricaud1998}(Chl = 0.5, pigments = Bidigare1990Pigments(chl_a = 0.5, ppc = 0.1)) @test b32.pigments isa Bidigare1990Pigments{Float32} + s32 = Phytoplankton{Float32, Bricaud1998}(Chl = 0.5, pigments = ProspectPigments(carotenoid_ratio = 0.3, outside = UnassignedOutsideTable())) + @test s32.pigments isa ProspectPigments{Float32, UnassignedOutsideTable} end @testset "AD through a partition" begin diff --git a/test/test_pure_water.jl b/test/test_pure_water.jl index 3ef2be7..8de1c3e 100644 --- a/test/test_pure_water.jl +++ b/test/test_pure_water.jl @@ -14,7 +14,11 @@ @testset "Smith-Baker (1981) absorption" begin w = PureWater{Float64}(absorption_model = SmithBaker1981()) - @test absorption(w, 500.0) > 0.0 + # Smith & Baker (1981), Table 1: a_w = 0.0171, 0.0257 and 0.650 1/m at + # 400, 500 and 700 nm. + @test absorption(w, 400.0) ≈ 0.0171 rtol = 1e-12 + @test absorption(w, 500.0) ≈ 0.0257 rtol = 1e-12 + @test absorption(w, 700.0) ≈ 0.650 rtol = 1e-12 @test absorption(w, 500.0) < absorption(w, 200.0) # UV is very absorbing # No temperature correction: Smith & Baker give no reference temperature. @test absorption(w, 700.0) == absorption(PureWater{Float64}(absorption_model = SmithBaker1981(), @@ -41,8 +45,32 @@ @test absorption(cold, 720.0) < absorption(ref, 720.0) # water absorbs more when warm end + @testset "Kou et al. (1993) absorption against published values" begin + kou = PureWater{Float64}(absorption_model = Kou1993(), temperature = 22.0) + # Kou, Labrie & Chylek (1993) as printed in the omlc.org table kou93b (22 °C). + @test absorption(kou, 667.0) == 0.4663 + @test absorption(kou, 740.0) == 2.768 + @test absorption(kou, 750.0) == 2.8484 + # Independent file: the IOCCG (2018) recommended table, whose 730–750 nm values + # are from Kou et al. (Loisel et al. 2023, Sect. 2.3), printed to three figures. + for (λ, a) in ((730.0, 1.97), (735.0, 2.51), (740.0, 2.78), (745.0, 2.83), (750.0, 2.85)) + @test absorption(kou, λ) ≈ a rtol = 1e-2 + end + @test_throws DomainError absorption(kou, 660.0) + end + @testset "Morel (1974) scattering" begin w = PureWater{Float64}(scattering_model = Morel1974()) + # Pure-sea-water scattering quoted by Mobley et al. (1993), Problem 7, from + # Smith & Baker (1981): b_w(417) = 0.0063, b_w(486) = 0.0032 1/m (two digits). + # The power law lies 1.3 % and 2.9 % above them; tolerances are those offsets + # plus half a unit of the last printed digit. + @test scattering(w, 417.0) ≈ 0.0063 rtol = 0.022 + @test scattering(w, 486.0) ≈ 0.0032 rtol = 0.045 + # The law is a seawater fit: salinity, temperature and depolarization do not enter. + fresh = PureWater{Float64}(scattering_model = Morel1974(), salinity = 0.0, temperature = 5.0, + depolarization = 0.09) + @test scattering(fresh, 500.0) == scattering(w, 500.0) # Reference: b(λ) = 0.00193 · (550/λ)^4.32, salinity-independent @test scattering(w, 550.0) ≈ 0.00193 rtol=1e-6 @test scattering(w, 500.0) ≈ 0.00193 * (550/500)^4.32 rtol=1e-6 @@ -68,6 +96,14 @@ temperature = 20.0, salinity = 38.4) @test scattering(w_morel, 546.0) ≈ 0.001791 rtol=1e-3 + # A second temperature and wavelength, from a line-by-line transcription of + # `betasw_ZHH2009.m` made for the physics audit (independent of this port): + # b(443 nm, 5 °C, 35 PSU). 18, 20 and 30 °C alone do not fix the + # temperature polynomials of the compressibility. + w_cold = PureWater{Float64}(scattering_model = ZhangHu2009(), + temperature = 5.0, salinity = 35.0) + @test scattering(w_cold, 443.0) ≈ 4.421043e-3 rtol = 1e-6 + # Temperature sensitivity: scattering decreases with warming near 20 °C w_warm = PureWater{Float64}(scattering_model = ZhangHu2009(), temperature = 30.0, salinity = 35.0) @@ -78,6 +114,36 @@ @test scattering(w, 400.0) / scattering(w, 700.0) > (700/400)^4.0 end + @testset "Depolarization enters the Zhang-Hu magnitude" begin + # b ∝ [(6 + 6δ)/(6 − 7δ)]·[(2 + δ)/(1 + δ)] (Zhang, Hu & He 2009): closed-form + # ratio between δ = 0.09 (Morel 1974) and δ = 0.039, +9.3 %. + w39 = PureWater{Float64}() + w09 = PureWater{Float64}(depolarization = 0.09) + f(δ) = (6 + 6δ) / (6 - 7δ) * (2 + δ) / (1 + δ) + for λ in (400.0, 500.0, 650.0) + @test scattering(w09, λ) / scattering(w39, λ) ≈ f(0.09) / f(0.039) rtol = 1e-12 + end + @test f(0.09) / f(0.039) ≈ 1.0932 atol = 1e-4 + @test scattering(w09, 500.0) ≈ 2.785e-3 rtol = 1e-3 + @test scattering_phase(w09).depolarization == 0.09 + @test_throws ArgumentError PureWater{Float64}(depolarization = 1.0) + @test_throws ArgumentError PureWater{Float64}(depolarization = -0.01) + end + + @testset "Default depolarization ratio" begin + # δ = 0.039 (Farinato & Rowell 1976), the value Zhang, Hu & He (2009) + # adopt. The phase matrix of the default water then has the Rayleigh + # moments β₂ = Δ/2, α₂ = 3Δ with Δ = (1 − δ)/(1 + δ/2) = 0.961/1.0195 + # (Hansen & Travis 1974); δ = 0.09 would give β₂ = 0.4354. + w = PureWater{Float64}() + @test w.depolarization == 0.039 + @test RayleighWaterPhase{Float64}().depolarization == 0.039 + g = greek_expansion(scattering_phase(w), 2; polarized = true) + @test g.β[3] ≈ 0.5 * 0.961 / 1.0195 rtol = 1e-14 + @test g.β[3] ≈ 0.471309 rtol = 1e-6 + @test g.α[3] ≈ 3 * 0.961 / 1.0195 rtol = 1e-14 + end + @testset "Backscatter: molecular is exactly b/2" begin w = PureWater{Float64}() for λ in (400.0, 500.0, 600.0, 700.0) @@ -95,6 +161,11 @@ k = PureWater{Float64}(temperature = 32.0, absorption_model = Kou1993()) k₀ = PureWater{Float64}(temperature = 22.0, absorption_model = Kou1993()) @test 0.012 < (absorption(k, 740.0) - absorption(k₀, 740.0)) / 10 < 0.02 + # Röttgers et al. (2014), Media 1 (data of their Fig. 5): Ψ_T(740 nm) = + # 0.0161 1/(m K). The 10 K difference divides out the table value a(22 °C). + @test (absorption(k, 740.0) - absorption(k₀, 740.0)) / 10 ≈ 0.0161 rtol = 1e-9 + ioccg(T) = absorption(PureWater{Float64}(temperature = T), 740.0) + @test (ioccg(12.0) - ioccg(22.0)) / -10 ≈ 0.0161 rtol = 1e-9 # Ψ_T changes sign: slightly negative at 700 nm. @test absorption(w₃₂, 700.0) < absorption(w₂₂, 700.0) end diff --git a/test/test_raman.jl b/test/test_raman.jl index 2e3a51e..30f1167 100644 --- a/test/test_raman.jl +++ b/test/test_raman.jl @@ -50,9 +50,100 @@ using QuadGK @test λ_grid[i] ≈ λ_peak atol = 0.05 end - @testset "is_isotropic: false for Cabannes-depolarized Raman" begin + # b_R is an energy conversion coefficient (Mobley et al. 1993, Problem 7 and + # Eqs. A3–A4): the energy kernel integrates over emission wavelength to b_R(λ′). + # The reference b_R is written out here, not taken from the package. + @testset "Energy convention: ∫ K_E dλ = b_R(λ′)" begin + ram = WaterRaman{Float64}() + @test conversion_units(ram) === EnergyConversion() + @test ram isa WaterRaman{Float64, EnergyConversion} + for λ′ in (350.0, 417.0, 488.0, 600.0) + b_R = 2.7e-4 * (488.0 / λ′)^5.5 + λp = 1e7 / (1e7 / λ′ - 3400.0) + IE, _ = quadgk(λ -> radiance_source_kernel(ram, λ′, λ), 0.8λp, λp, 1.25λp; rtol = 1e-10) + @test IE ≈ b_R rtol = 1e-8 + # Photon kernel = energy kernel × λ/λ′: more photons leave than b_R counts, + # by the mean of λ/λ′ over the band (≈ λ_peak/λ′). + IN, _ = quadgk(λ -> inelastic_coefficient(ram, λ′, λ), 0.8λp, λp, 1.25λp; rtol = 1e-10) + @test IN > b_R + @test IN / b_R ≈ λp / λ′ rtol = 2e-3 + @test inelastic_coefficient(ram, λ′, λp) ≈ radiance_source_kernel(ram, λ′, λp) * λp / λ′ + end + end + + @testset "Photon convention: ∫ K_N dλ = b_R(λ′)" begin + ram = WaterRaman{Float64}(conversion = PhotonConversion()) + @test conversion_units(ram) === PhotonConversion() + # The energy form of the photon convention integrates to λ′/λ_peak of b_R, the + # ratio for Δν = 3400 cm⁻¹ (0.858 = 417/486 at 417 nm excitation). + for (λ′, low) in ((350.0, 0.881), (417.0, 0.858), (488.0, 0.834), (600.0, 0.796)) + b_R = 2.7e-4 * (488.0 / λ′)^5.5 + λp = 1e7 / (1e7 / λ′ - 3400.0) + IN, _ = quadgk(λ -> inelastic_coefficient(ram, λ′, λ), 0.8λp, λp, 1.25λp; rtol = 1e-10) + IE, _ = quadgk(λ -> radiance_source_kernel(ram, λ′, λ), 0.8λp, λp, 1.25λp; rtol = 1e-10) + @test IN ≈ b_R rtol = 1e-8 + @test IE / b_R ≈ low atol = 1e-3 + end + end + + # Mobley et al. (1993), Problem 7: b_R = b_w(417) = 0.0063 1/m, all light Raman + # scattered at 417 nm appears at 486 nm; the band-integrated source of radiance is + # b_R E₀ / (4π), with no photon-energy ratio. + @testset "Mobley et al. (1993) Problem 7 source" begin + ram = WaterRaman{Float64}(cross_section_ref = 0.0063, cross_section_λ_ref = 417.0, + linear_depolarization = 0.17, excitation_range = (410.0, 424.0)) + @test raman_peak_wavelength(ram, 417.0) ≈ 486.0 atol = 0.2 + Δz = 2.0 + layer = OceanLayer(0.0, Δz, AbstractOceanConstituent{Float64}[PureWater{Float64}()]; + inelastic = AbstractOceanInelasticProcess{Float64}[ram]) + λ = collect(410.0:1.0:424.0) + o = layer_optics(layer, λ; ℓ_max = 2) + # A line of unit irradiance (1 W m⁻²) at 417 nm: triangle of base 2 nm, height 1. + E₀ = [x == 417.0 ? 1.0 : 0.0 for x in λ] + λ_em = collect(460.0:0.02:515.0) + P = inelastic_emission(o, 1, E₀, λ_em) # W m⁻² nm⁻¹, all directions + source = sum(P) * 0.02 / (4π * Δz) # W m⁻³ sr⁻¹ + @test source ≈ 0.0063 * 1.0 / (4π) rtol = 1e-6 + # The photon convention is 417/486 = 14.2 % lower for the same coefficient. + ramN = WaterRaman{Float64}(cross_section_ref = 0.0063, cross_section_λ_ref = 417.0, + excitation_range = (410.0, 424.0), conversion = PhotonConversion()) + oN = layer_optics(OceanLayer(0.0, Δz, AbstractOceanConstituent{Float64}[PureWater{Float64}()]; + inelastic = AbstractOceanInelasticProcess{Float64}[ramN]), λ; ℓ_max = 2) + PN = inelastic_emission(oN, 1, E₀, λ_em) + @test sum(PN) / sum(P) ≈ 417 / 486 rtol = 1e-3 + end + + # Mobley et al. (1993) Eq. 9 with ρ = 0.17, typed here from the paper: + # p_R = (3/16π) (1+3ρ)/(1+2ρ) [1 + (1−ρ)/(1+3ρ) cos²Θ]. + @testset "Raman phase function and matrix" begin ram = WaterRaman{Float64}() @test !is_isotropic(ram) + @test ram.linear_depolarization == 0.17 + ρ = 0.17 + ρ_n = natural_depolarization(ram) + @test ρ_n ≈ 2ρ / (1 + ρ) rtol = 1e-14 + @test ρ_n ≈ 0.2906 atol = 5e-5 + pf = raman_phase(ram) + @test pf isa RayleighWaterPhase{Float64} && pf.depolarization == ρ_n + mobley(μ) = 3 / (16π) * (1 + 3ρ) / (1 + 2ρ) * (1 + (1 - ρ) / (1 + 3ρ) * μ^2) + for μ in (-1.0, -0.4, 0.0, 0.3, 0.8, 1.0) + @test phase_function_value(pf, μ) / (4π) ≈ mobley(μ) rtol = 1e-13 + end + I, _ = quadgk(mobley, -1, 1) + @test 2π * I ≈ 1 rtol = 1e-12 + # β₂ of RayleighWaterPhase for ρ_n equals (1−ρ)/(2(1+2ρ)) = 0.3097. + β = phase_function_moments(pf, 4) + @test β[3] ≈ (1 - ρ) / (2 * (1 + 2ρ)) rtol = 1e-14 + @test β[3] ≈ 0.3097 atol = 5e-5 + @test β[1] == 1 && β[2] == 0 && β[4] == 0 && β[5] == 0 + # Phase matrix: Rayleigh matrix with depolarization ρ_n (Hansen & Travis 1974). + g = greek_expansion(pf, 2; polarized = true) + Δ = (1 - ρ_n) / (1 + ρ_n / 2) + @test g.β[3] ≈ Δ / 2 && g.α[3] ≈ 3Δ && g.γ[3] ≈ sqrt(1.5) * Δ + @test g.δ[2] ≈ 1.5 * Δ * (1 - 2ρ_n) / (1 - ρ_n) + # A different ρ changes the phase function (the stored value is the one used). + @test phase_function_moments(raman_phase(WaterRaman{Float64}(linear_depolarization = 0.0)), 2)[3] == 0.5 + @test phase_function_moments(raman_phase(WaterRaman{Float32}()), 2)[3] isa Float32 end @testset "excitation_range + constructor validation" begin @@ -61,7 +152,7 @@ using QuadGK @test_throws ArgumentError WaterRaman{Float64}(σ_cm_inv = 0.0) @test_throws ArgumentError WaterRaman{Float64}(cross_section_ref = -1e-4) - @test_throws ArgumentError WaterRaman{Float64}(depolarization = 1.0) + @test_throws ArgumentError WaterRaman{Float64}(linear_depolarization = 0.8) @test_throws ArgumentError WaterRaman{Float64}(excitation_range = (700.0, 400.0)) end diff --git a/test/test_redistribution.jl b/test/test_redistribution.jl index 3461f45..26f913b 100644 --- a/test/test_redistribution.jl +++ b/test/test_redistribution.jl @@ -27,10 +27,9 @@ using QuadGK @test_throws ArgumentError GaussianEmission{Float64}(center_nm = -1.0, σ_nm = 1.0) end - @testset "WavenumberShiftEmission: Raman peak at 440 nm → ≈ 491 nm" begin - # 3400 cm⁻¹ Stokes shift moves ν' = 10⁷/440 ≈ 22727 cm⁻¹ to ν ≈ 19327 cm⁻¹, - # which is λ ≈ 517 nm. Wait — redo: shift for water Raman is 3400 cm⁻¹; - # at λ'=440 we expect emission peak λ = 10⁷/(22727 - 3400) = 10⁷/19327 ≈ 517.4 nm. + @testset "WavenumberShiftEmission: Raman peak at 440 nm → 517.4 nm" begin + # The 3400 cm⁻¹ Stokes shift moves ν' = 10⁷/440 ≈ 22727 cm⁻¹ to ν ≈ 19327 cm⁻¹, + # so the emission peaks at λ = 10⁷/19327 ≈ 517.4 nm. r = WavenumberShiftEmission{Float64}(shift_cm_inv = 3400.0, σ_cm_inv = 85.0) λ_prime = 440.0 diff --git a/test/test_refractive_index.jl b/test/test_refractive_index.jl index 9d56452..b93b8e5 100644 --- a/test/test_refractive_index.jl +++ b/test/test_refractive_index.jl @@ -9,6 +9,14 @@ @test refractive_index(qs, 400.0) > refractive_index(qs, 700.0) @test refractive_index(qs, [450.0, 550.0]) == [refractive_index(qs, 450.0), refractive_index(qs, 550.0)] + # Quan & Fry (1995), Eq. 4, evaluated term by term with the published + # coefficients at a point where every term contributes (10 °C, 30 PSU, 450 nm). + T, S, λ = 10.0, 30.0, 450.0 + n_ref = 1.31405 + (1.779e-4 - 1.05e-6 * T + 1.6e-8 * T^2) * S - 2.02e-6 * T^2 + + (15.868 + 0.01155 * S - 0.00423 * T) / λ - 4382 / λ^2 + 1.1455e6 / λ^3 + @test refractive_index(QuanFry1995(temperature = T, salinity = S), λ) ≈ n_ref rtol = 1e-14 + @test n_ref ≈ 1.3458 atol = 1e-4 + # Fitted domain only, unless extrapolation is chosen explicitly. @test_throws DomainError refractive_index(qs, 350.0) @test_throws DomainError refractive_index(qs, 865.0) diff --git a/test/test_solver_contract.jl b/test/test_solver_contract.jl new file mode 100644 index 0000000..06c046a --- /dev/null +++ b/test/test_solver_contract.jl @@ -0,0 +1,188 @@ +# What a radiative-transfer solver relies on when it consumes the layer and +# column optics: expansion keys, wavelength matching, irradiance round-off, +# bottoms, the interface index and the layout of scalar expansions. + +struct UnknownTestBottom <: AbstractOceanBottom end + +@testset "Solver contract" begin + @testset "phase_id: content key of an expansion" begin + # Published FNV-1a 64-bit test vectors (Fowler, Noll & Vo reference suite). + @test OceanOptics._fnv1a(OceanOptics._FNV_OFFSET, "") == 0xcbf29ce484222325 + @test OceanOptics._fnv1a(OceanOptics._FNV_OFFSET, "a") == 0xaf63dc4c8601ec8c + @test OceanOptics._fnv1a(OceanOptics._FNV_OFFSET, "foobar") == 0x85944171f73967e8 + + # Keys computed outside Julia (Python `struct.pack`, byte-wise FNV-1a) over + # the type name, then length and little-endian values of α, β, γ, δ, ϵ, ζ: + # fixed numbers, so the key cannot depend on the session or Julia version. + g = GreekCoefficients([1.0, 0.0, 0.5]) + @test phase_id(g) == 0x5be608ecb86bcfb4 + @test phase_id(GreekCoefficients(Float32[1, 0, 0.5])) == 0x10904bc3da6e3ce3 + @test phase_id(depolarized(g)) == 0xdc568201c219d257 + + # Equal content in distinct arrays ⇒ equal key; −0.0 == 0.0. + @test phase_id(GreekCoefficients([1.0, 0.0, 0.5])) == phase_id(g) + @test phase_id(GreekCoefficients([1.0, -0.0, 0.5])) == phase_id(g) + # Any difference in a coefficient, ℓ_max, element type or polarization ⇒ another key. + others = (GreekCoefficients([1.0, 0.0, 0.5 + 1e-15]), GreekCoefficients([1.0, 0.0, 0.5, 0.0]), + GreekCoefficients(Float32[1, 0, 0.5]), depolarized(g)) + @test allunique([phase_id(g); [phase_id(x) for x in others]]) + + λ = [450.0, 550.0, 650.0] + pf = HenyeyGreensteinPhase{Float64}(g = 0.8) + layer(pf, FT = Float64) = OceanLayer(FT(0), FT(1), + AbstractOceanConstituent{FT}[TabulatedScatterer(FT.(λ), FT[0.3, 0.2, 0.1], pf)]) + sc(o) = only(o.scatterers) + o16 = layer_optics(layer(pf), λ; ℓ_max = 16) + @test sc(o16).phase_id == [phase_id(only(sc(o16).greek))] + @test sc(o16).phase_id == sc(layer_optics(layer(HenyeyGreensteinPhase{Float64}(g = 0.8)), λ; ℓ_max = 16)).phase_id + @test sc(o16).phase_id != sc(layer_optics(layer(pf), λ; ℓ_max = 32)).phase_id + @test sc(o16).phase_id != sc(layer_optics(layer(pf), λ; ℓ_max = 16, polarized = true, + scalar_phase_approximation = :depolarizing)).phase_id + pf32 = HenyeyGreensteinPhase{Float32}(g = 0.8f0) + @test sc(o16).phase_id != sc(layer_optics(layer(pf32, Float32), Float32.(λ); ℓ_max = 16)).phase_id + + # Equal-valued tables held in different arrays share the key. + β = [1.0, 1.5, 1.25, 0.875] # (2ℓ+1) gˡ, g = 1/2 + tab() = sc(layer_optics(layer(TabulatedGreekPhase(copy(β))), λ; ℓ_max = 3)).phase_id + @test tab() == tab() == [phase_id(GreekCoefficients(β))] + + # A wavelength-dependent phase function: one key per distinct expansion. + wd = WavelengthDependentPhase([450.0, 650.0], + [HenyeyGreensteinPhase{Float64}(g = x) for x in (0.8, 0.9)]; + lookup = :nearest) + c = sc(layer_optics(layer(wd), λ; ℓ_max = 16)) + @test length(c.phase_id) == 2 && allunique(c.phase_id) + @test c.phase_id[1] == only(sc(o16).phase_id) # the g = 0.8 entry + @test [phase_id(c, k) for k in eachindex(λ)] == [phase_id(greek_expansion(c, k)) for k in eachindex(λ)] + @test phase_id(c, 1) != phase_id(c, 3) + end + + @testset "Tabulated constituents: wavelength match and interpolation" begin + λ_tab = [350.0, 412.0, 443.0, 475.0, 550.0, 670.0, 865.0] + a_tab = [0.07, 0.05, 0.04, 0.03, 0.06, 0.44, 4.6] + a = TabulatedAbsorber(λ_tab, a_tab) + # Single-precision wavelengths obtained from single-precision wavenumbers. + λ32 = 1f7 ./ (1f7 ./ Float32.(λ_tab)) + @test any(Float64.(λ32) .!= λ_tab) # the round trip is not exact + @test absorption(a, λ32) == a_tab + @test absorption(a, Float64.(λ32)) == a_tab + @test absorption(a, 1e7 ./ (1e7 ./ λ_tab)) == a_tab + o = layer_optics(OceanLayer(0.0, 2.0, AbstractOceanConstituent{Float64}[a]), λ32; ℓ_max = 2) + @test only(o.absorbers).τ ≈ 2 .* a_tab rtol = 1e-15 + # The tolerance is 1e-6 relative: 2e-6 away is another wavelength. + @test absorption(a, 550.0 * (1 + 0.9e-6)) == 0.06 + @test_throws "match tolerance 1.0e-6 relative" absorption(a, 550.0 * (1 + 2e-6)) + @test_throws "is not a tabulated wavelength" absorption(a, 500.0) + @test_throws "neighbouring wavelengths must differ" TabulatedAbsorber( + [550.0, 550.0 * (1 + 1e-6)], [0.1, 0.1]) + + lin = TabulatedAbsorber(λ_tab, a_tab; lookup = :linear) + @test absorption(lin, λ_tab) == a_tab + @test absorption(lin, 512.5) ≈ (0.03 + 0.06) / 2 rtol = 1e-14 # midpoint of 475 and 550 + @test absorption(lin, 400.0) ≈ 0.07 + (0.05 - 0.07) * 50 / 62 rtol = 1e-14 + @test_throws DomainError absorption(lin, 340.0) + @test_throws DomainError absorption(lin, 900.0) + @test_throws "lookup must be :exact or :linear, got :nearest" TabulatedAbsorber( + λ_tab, a_tab; lookup = :nearest) + # The lookup is a type: names and lookup objects select the same one. + @test a isa TabulatedAbsorber{Float64, ExactLookup} + @test lin isa TabulatedAbsorber{Float64, LinearLookup} + @test TabulatedAbsorber(λ_tab, a_tab; lookup = LinearLookup()) isa TabulatedAbsorber{Float64, LinearLookup} + @test (@inferred absorption(lin, 512.5)) isa Float64 + # Slope of the segment 400–500 nm of a table (1, 2): 0.01 per nm. + ramp = TabulatedAbsorber([400.0, 500.0], [1.0, 2.0]; lookup = :linear) + @test ForwardDiff.derivative(x -> absorption(ramp, x), 450.0) ≈ 0.01 rtol = 1e-14 + # A 1 cm⁻¹ wavenumber grid inside the table runs through layer_optics. + λν = 1e7 ./ (14_300.0:1.0:14_310.0) # 698.8–699.3 nm, decreasing + τ = only(layer_optics(OceanLayer(0.0, 1.0, AbstractOceanConstituent{Float64}[lin]), λν; + ℓ_max = 2).absorbers).τ + @test τ ≈ [0.44 + (4.6 - 0.44) * (x - 670) / (865 - 670) for x in λν] rtol = 1e-13 + + pf = RayleighWaterPhase{Float64}() + s = TabulatedScatterer([400.0, 500.0], [0.02, 0.01], pf; lookup = :linear) + @test scattering(s, 425.0) ≈ 0.0175 rtol = 1e-14 + @test backscattering(s, 425.0) ≈ 0.0175 / 2 rtol = 1e-12 # Rayleigh: B = 1/2 + @test_throws "is not a tabulated wavelength" scattering( + TabulatedScatterer([400.0, 500.0], [0.02, 0.01], pf), 425.0) + @test_throws "lookup must be :exact or :linear, got :cubic" TabulatedScatterer( + [400.0, 500.0], [0.02, 0.01], pf; lookup = :cubic) + # Interpolated values have the type the query and the table promote to, + # on the matching and on the interpolating branch. + s32 = TabulatedScatterer(Float32[400, 500], Float32[0.02, 0.01], + RayleighWaterPhase{Float32}(); lookup = :linear) + @test scattering(s32, 425.0) isa Float64 && scattering(s32, 400.0) isa Float64 + @test scattering(s32, 425f0) isa Float32 && scattering(s32, 400f0) isa Float32 + end + + @testset "Irradiance with round-off negatives" begin + λ = collect(400.0:50.0:700.0) + o = layer_optics(OceanLayer(0.0, 3.0, AbstractOceanConstituent{Float64}[PureWater{Float64}(), CDOM{Float64}()]; + inelastic = AbstractOceanInelasticProcess{Float64}[WaterRaman{Float64}()]), + λ; ℓ_max = 2) + E₀ = [1.0, 0.8, 0.5, 0.2, 1e-9, 0.0, 0.0] + noisy = E₀ .+ [0, 0, 0, 0, 0, -1e-14, -1e-9] # down to −1e-9 of the peak + @test absorbed_power(o, noisy) == absorbed_power(o, E₀) + @test absorbed_photons(o, noisy) == absorbed_photons(o, E₀) + @test absorbed_par(o, noisy) == absorbed_par(o, E₀) + @test inelastic_emission(o, 1, noisy, [520.0, 560.0]; range = (400, 700)) == + inelastic_emission(o, 1, E₀, [520.0, 560.0]; range = (400, 700)) + @test all(≥(0), absorbed_power(o, noisy)) + # √eps(Float64) ≈ 1.5e-8 of the peak is the limit. + @test absorbed_power(o, E₀ .+ [0, 0, 0, 0, 0, 0, -1e-8]) == absorbed_power(o, E₀) + for bad in (-2e-8, -1e-3, -1.0) + @test_throws "below the round-off allowance" absorbed_power(o, E₀ .+ [0, 0, 0, 0, 0, 0, bad]) + @test_throws "below the round-off allowance" absorbed_par(o, E₀ .+ [0, 0, 0, 0, 0, 0, bad]) + @test_throws "below the round-off allowance" inelastic_emission( + o, 1, E₀ .+ [0, 0, 0, 0, 0, 0, bad], [520.0]; range = (400, 700)) + end + # The allowance scales with the field: the same −1e-9 is not round-off of a 1e-6 peak. + @test_throws "below the round-off allowance" absorbed_power(o, 1e-6 .* E₀ .+ [0, 0, 0, 0, 0, 0, -1e-9]) + @test_throws "must be finite" absorbed_power(o, [NaN; E₀[2:end]]) + # Single precision: √eps(Float32) ≈ 3.5e-4. + @test absorbed_power(o, Float32.(E₀) .+ Float32[0, 0, 0, 0, 0, 0, -1f-4]) == absorbed_power(o, Float32.(E₀)) + @test_throws "below the round-off allowance" absorbed_power( + o, Float32.(E₀) .+ Float32[0, 0, 0, 0, 0, 0, -1f-3]) + end + + @testset "Bottoms and interface index" begin + column = uniform_column(AbstractOceanConstituent{Float64}[PureWater{Float64}()]; n_layers = 2, depth = 10.0) + col = column_optics(column, [450.0, 550.0]; refractive_index = FixedRefractiveIndex(1.34), + bottom = UnknownTestBottom(), ℓ_max = 2) + @test col.bottom === UnknownTestBottom() + @test_throws ArgumentError bottom_albedo(col) + @test_throws "UnknownTestBottom has no Lambertian albedo" bottom_albedo(col) + + @test refractive_index(FixedRefractiveIndex(1.0), 550.0) == 1.0 # index-matched interface + @test FixedRefractiveIndex(1) isa FixedRefractiveIndex{Float64} + for n in (0.9, 1 - 1e-12, 0.0, -1.34, Inf, NaN) + @test_throws ArgumentError FixedRefractiveIndex(n) + end + @test_throws "n_water / n_air" FixedRefractiveIndex(1 / 1.34) + # A column built directly applies the same rule. + @test OceanColumnOptics(col.layers, [1.0, 1.34], BlackBottom()) isa OceanColumnOptics + @test_throws "n_water / n_air" OceanColumnOptics(col.layers, [1.34, 1 / 1.34], BlackBottom()) + @test_throws "n_water / n_air" OceanColumnOptics(col.layers, [1.34, NaN], BlackBottom()) + end + + @testset "Composite pure-water absorption names its range" begin + w = PureWater{Float64}() # IOCCG2018: 350–2500 nm + @test absorption(w, 350.0) > 0 && absorption(w, 2500.0) > 0 + for λ in (349.9, 2500.1) + err = try absorption(w, λ) catch e; e end + @test err isa DomainError && err.val == λ + @test occursin("350.0–2500.0 nm", sprint(showerror, err)) + end + end + + @testset "zero_padded: six equal-length coefficient vectors" begin + g = GreekCoefficients([1.0, 0.3, 0.5]) + p = zero_padded(g) + @test p.β == [1.0, 0.3, 0.5] && is_polarized(p) + @test p.α == p.γ == p.δ == p.ϵ == p.ζ == [0.0, 0.0, 0.0] + @test all(length(getfield(p, f)) == 3 for f in fieldnames(GreekCoefficients)) + @test zero_padded(GreekCoefficients(Float32[1, 0.3])) isa GreekCoefficients{Float32} + full = greek_expansion(RayleighWaterPhase{Float64}(), 4; polarized = true) + @test zero_padded(full) === full # already polarized: unchanged + @test any(!iszero, full.γ) + end +end diff --git a/test/test_spectral_table.jl b/test/test_spectral_table.jl new file mode 100644 index 0000000..850e1df --- /dev/null +++ b/test/test_spectral_table.jl @@ -0,0 +1,66 @@ +# `SpectralTable` and `linterp` against values worked out by hand on a table +# with unequal spacing: λ = (400, 410, 430, 500), y = (1, 3, 2, 9). +@testset "SpectralTable" begin + tbl = SpectralTable([400.0, 410.0, 430.0, 500.0], [1.0, 3.0, 2.0, 9.0]) + @test tbl isa SpectralTable{Float64, Vector{Float64}} + @test (tbl.lo, tbl.hi, length(tbl)) === (400.0, 500.0, 4) + + @testset "values" begin + @test [linterp(tbl, x) for x in tbl.λ] == tbl.y # knots are exact + @test linterp(tbl, 405.0) == 2.0 # 1 + 5 · (3 − 1)/10 + @test linterp(tbl, 425.0) ≈ 2.25 rtol = 4eps() # 3 − 15/20 + @test linterp(tbl, 465.0) ≈ 5.5 rtol = 4eps() # 2 + 35 · 7/70 + @test linterp(tbl, [405.0, 425.0, 500.0]) ≈ [2.0, 2.25, 9.0] rtol = 4eps() + @test linterp(tbl, Float64[]) == Float64[] + @test @inferred(linterp(tbl, 405.0)) isa Float64 + @test @inferred(linterp(tbl, 405.0f0)) isa Float64 # the table's precision is the floor + end + + @testset "never beyond the data" begin + @test_throws DomainError linterp(tbl, 399.999) + @test_throws DomainError linterp(tbl, 500.001) + @test_throws DomainError linterp(tbl, NaN) + @test_throws "outside the tabulated range 400.0–500.0 nm" linterp(tbl, [405.0, 501.0]) + @test_throws "outside the tabulated range 400.0–500.0 nm" linterp(tbl, [399.0, 405.0]) + end + + # Slope of the segment. At an interior knot the interpolant has a kink: + # the derivative is the slope of one of the two segments that meet there. + @testset "derivative" begin + d(x) = ForwardDiff.derivative(z -> linterp(tbl, z), x) + @test d(405.0) ≈ 0.2 rtol = 4eps() + @test d(420.0) ≈ -0.05 rtol = 4eps() + @test d(499.0) ≈ 0.1 rtol = 4eps() + @test d(400.0) ≈ 0.2 rtol = 4eps() + @test any(s -> isapprox(d(410.0), s; rtol = 4eps()), (0.2, -0.05)) + @test any(s -> isapprox(d(430.0), s; rtol = 4eps()), (-0.05, 0.1)) + end + + @testset "construction" begin + t32 = SpectralTable(Float32[400, 500], Float32[1, 2]) + @test t32 isa SpectralTable{Float32, Vector{Float32}} + @test linterp(t32, 450.0f0) === 1.5f0 + @test SpectralTable(400:50:500, [1, 2, 4]) isa SpectralTable{Float64, Vector{Float64}} + @test linterp(SpectralTable(400:50:500, [1, 2, 4]), 475) == 3.0 + @test_throws DimensionMismatch SpectralTable([400.0, 500.0], [1.0]) + @test_throws "at least two points" SpectralTable([400.0], [1.0]) + @test_throws "strictly increasing" SpectralTable([400.0, 500.0, 450.0], [1.0, 2.0, 3.0]) + @test_throws "strictly increasing" SpectralTable([400.0, 450.0, 450.0], [1.0, 2.0, 3.0]) + @test_throws "finite" SpectralTable([400.0, Inf], [1.0, 2.0]) + end + + # The shipped tables are what the models interpolate: a mid-point of two + # neighbouring rows of the Pope & Fry (1997) file is their mean. + @testset "shipped table" begin + pf = OceanOptics._POPE_FRY_1997_TABLE + i = findfirst(==(550.0), pf.λ) + @test i !== nothing + @test linterp(pf, (pf.λ[i] + pf.λ[i+1]) / 2) ≈ (pf.y[i] + pf.y[i+1]) / 2 rtol = 4eps() + end + + @testset "values must be finite" begin + @test_throws "values must be finite" SpectralTable([400.0, 500.0], [NaN, 1.0]) + @test_throws "values must be finite" SpectralTable([400.0, 500.0], [1.0, Inf]) + @test_throws "wavelengths must be finite" SpectralTable([400.0, Inf], [1.0, 2.0]) + end +end