diff --git a/.buildkite/pipeline.yml b/.buildkite/pipeline.yml index adba1049d..470ef775b 100644 --- a/.buildkite/pipeline.yml +++ b/.buildkite/pipeline.yml @@ -100,6 +100,7 @@ steps: - "kelp" - "data_assimilation" - "oae_experiment" + - "dissolving_particles" depends_on: "init-gpu" agents: hostname: "$BUILDKITE_AGENT_META_DATA_HOSTNAME" diff --git a/Project.toml b/Project.toml index 58d9828f6..a0a3e0fcb 100644 --- a/Project.toml +++ b/Project.toml @@ -1,6 +1,6 @@ name = "OceanBioME" uuid = "a49af516-9db8-4be4-be45-1dad61c5a376" -version = "0.21.1" +version = "0.21.2" authors = ["Jago Strong-Wright and contributors"] [deps] diff --git a/docs/make.jl b/docs/make.jl index 657b8b15b..93426ad54 100644 --- a/docs/make.jl +++ b/docs/make.jl @@ -25,7 +25,8 @@ examples = [ "Baroclinic instability" => "eady", "Model with particles (kelp) interacting with the biogeochemistry" => "kelp", "Data assimilation" => "data_assimilation", - "Ocean alkalinity enhancement" => "oae_experiment" + "Ocean alkalinity enhancement" => "oae_experiment", + "Sinking and dissolving particles" => "dissolving_particles" ] example_pages = [ title => "generated/$(filename).md" for (title, filename) in examples ] @@ -83,6 +84,7 @@ sediments_pages = [ individuals_pages = [ "Overview" => "model_components/individuals/index.md", "Sugar Kelp (Broch and Slagstad 2012 ++)" => "model_components/individuals/slatissima.md", + "Dissolving particles" => "model_components/individuals/dissolving_particles.md", ] component_pages = [ diff --git a/docs/prepare_examples.jl b/docs/prepare_examples.jl index a1dfd3e9d..3d7aded9e 100644 --- a/docs/prepare_examples.jl +++ b/docs/prepare_examples.jl @@ -10,7 +10,8 @@ const EXAMPLES = [ "eady", "kelp", "data_assimilation", - "oae_experiment" + "oae_experiment", + "dissolving_particles" ] for example_name in EXAMPLES diff --git a/docs/src/appendix/library.md b/docs/src/appendix/library.md index 72050ffc0..0804b2531 100644 --- a/docs/src/appendix/library.md +++ b/docs/src/appendix/library.md @@ -96,6 +96,12 @@ Modules = [OceanBioME.Models.PISCESModel.Nitrogen] Modules = [OceanBioME.Models.SugarKelpModel] ``` +### Dissolving particles + +```@autodocs +Modules = [OceanBioME.Models.DissolvingParticlesModel] +``` + ### Carbon Chemistry ```@autodocs diff --git a/docs/src/model_components/individuals/dissolving_particles.md b/docs/src/model_components/individuals/dissolving_particles.md new file mode 100644 index 000000000..1360cfbdb --- /dev/null +++ b/docs/src/model_components/individuals/dissolving_particles.md @@ -0,0 +1,126 @@ +# [Dissolving particles](@id dissolving-particles) + +Dissolving particles are active particles which sink, dissolve, and release material into tracer fields. +They were written for mineral-based ocean alkalinity enhancement (OAE), where particles of a mineral such as +lime (Ca(OH)₂), calcite (CaCO₃), or olivine (Mg₂SiO₄) increase the alkalinity as they dissolve, and for +the secondary mineral precipitates which can form in response to OAE. + +Each particle tracks its radius, ``r`` (m), which sets how fast it dissolves and sinks. +An example of particles sinking and dissolving in two-dimensional turbulence is given in the +[examples](@ref dissolving-particles-example). + +The particle biogeochemistry is set up with [`DissolvingMineral`](@ref): +```@example dissolving_particles +using OceanBioME, Oceananigans + +mineral = DissolvingMineral() +``` +which can be put into `BiogeochemicalParticles`, or the particles can be created directly with +[`DissolvingParticles`](@ref): +```@example dissolving_particles +grid = RectilinearGrid(size = (1, 1, 1), extent = (1, 1, 1)) + +particles = DissolvingParticles(10; grid) +``` + +The particles can then be added to any biogeochemical model which has the tracers they release, +for example a carbonate system without any biology: +```@example dissolving_particles +biogeochemistry = NutrientsPlanktonDetritus(grid; inorganic_carbon = CarbonateSystem(), particles) +``` + +## Model equations + +The radius of each particle shrinks at the dissolution rate, ``k`` (m/s): + +```math +\frac{dr}{dt} = -k, +``` + +so the volume of each particle, ``V = 4\pi r^3/3``, decreases at ``4\pi r^2 k``. +When the dissolution is controlled by reactions on the particle surface ``k`` is a constant +(the default), and when it is limited by diffusion away from the particle surface ``k \propto 1/r``. + +As the particles dissolve they release each tracer at: + +```math +\frac{dX}{dt} = \frac{4\pi r^2 k \theta_X}{V_m}, +``` + +where ``\theta_X`` is the number of moles of tracer ``X`` released per mole of mineral (`released_tracers`), and +``V_m`` is the molar volume of the mineral (`molar_mass / density`). +For example, calcium hydroxide releases two moles of alkalinity per mole (`released_tracers = (; Alk = 2)`), +and calcium carbonate releases two moles of alkalinity and one mole of dissolved inorganic carbon +(`released_tracers = (; Alk = 2, DIC = 1)`). + +The released tracers go into the grid cell nearest to the particle, and each particle can represent many real +particles by setting its `scalefactors`. + +### Sinking + +When the particles are moved by `LagrangianAdvection` (the default) they move with the water, and also +move vertically relative to it at `sinking_speed`, which is positive upwards, so it is negative for sinking +particles. By default it is given by Stokes' law ([`StokesSinking`](@ref)): + +```math +w = \frac{2(\rho - \rho_p)gr^2}{9\mu}, +``` + +where ``\rho_p`` is the density of the particle, ``\rho`` the density of the water, ``g`` the gravitational acceleration, +and ``\mu`` the dynamic viscosity of the water. This is only valid for small particles, with a Reynolds number +``2r|w|\rho/\mu`` less than about one. + +The `sinking_speed` of each particle is stored in the particle field of the same name, which is updated every +time step. Particles which reach the bottom of the domain bounce off it, so they stay within one time step's +sinking of the bottom and continue to dissolve into the bottom grid cells. + +### Dependence on particle and model fields + +`dissolution_rate` and `sinking_speed` can be numbers, or functions called as +`f(mineral, particle_fields, tracer_fields)`, where `particle_fields` is a `NamedTuple` of the particle's +`r` and `sinking_speed`, and `tracer_fields` is a `NamedTuple` of the model fields listed in `required_fields` +(tracers, velocities, or auxiliary fields) at the particle position. +For example, a dissolution rate which increases with temperature: +```@example dissolving_particles +warm_dissolution(mineral, particle_fields, tracer_fields) = 1e-8 * (1 + 0.05 * (tracer_fields.T - 20)) + +mineral = DissolvingMineral(required_fields = (:T, ), dissolution_rate = warm_dissolution) +``` + +The `water_density` and `dynamic_viscosity` of [`StokesSinking`](@ref) can be functions called in the same way, +for example for particles which sink faster as the water warms and becomes less viscous: +```@example dissolving_particles +viscosity(mineral, particle_fields, tracer_fields) = 1.8e-3 / (1 + 0.03 * tracer_fields.T) + +stokes = StokesSinking(particle_density = 2211, dynamic_viscosity = viscosity) + +mineral = DissolvingMineral(required_fields = (:T, ), sinking_speed = stokes) +``` + +### Parameter variable names + +| Symbol | Variable name | Units | +|-------------|--------------------|------------------------| +| ``\rho_p`` | `density` | kg / m³ | +| - | `molar_mass` | kg / mol | +| ``\theta_X`` | `released_tracers` | mol / mol | +| ``k`` | `dissolution_rate` | m / s | +| ``w`` | `sinking_speed` | m / s | +| - | `required_fields` | - | + +The default `density`, `molar_mass`, and `released_tracers` are for calcium hydroxide. +The default dissolution rate is only illustrative (a 100 μm particle dissolves in about 3 hours). + +## Model conservations + +The total of each released tracer, in the water and in the particles, is conserved. The amount of tracer ``X`` in each particle is: + +```math +X_\text{particle} = \frac{4\pi r^3 \theta_X}{3V_m}. +``` + +Because the particle radius and the tracers are stepped forward differently, this is conserved up to a first +order time stepping error. When the particles fully dissolve slightly too much tracer is released, about +``0.5k\Delta t / r_0`` of the total with the default `RungeKutta3` time stepper (or ``3k\Delta t / r_0`` with +`QuasiAdamsBashforth2`), so the time step should be much shorter than the time it takes the particles to +dissolve, ``r_0/k``. diff --git a/docs/src/model_components/individuals/index.md b/docs/src/model_components/individuals/index.md index 2b59427db..f483bc521 100644 --- a/docs/src/model_components/individuals/index.md +++ b/docs/src/model_components/individuals/index.md @@ -1,6 +1,6 @@ # [Individuals](@id individuals) -The effects of individuals can be modelled in OceanBioME. We have implemented this through custom dynamics in the [Lagrangian Particle tracking feature of Oceananigans](https://clima.github.io/OceananigansDocumentation/stable/model_setup/lagrangian_particles/). We have extended these functionalities to make it easier to implement "active" particles which interact with the tracers. We have then implemented a model of [sugar kelp](@ref sugar-kelp) which can be followed as an example of using this functionality. +The effects of individuals can be modelled in OceanBioME. We have implemented this through custom dynamics in the [Lagrangian Particle tracking feature of Oceananigans](https://clima.github.io/OceananigansDocumentation/stable/model_setup/lagrangian_particles/). We have extended these functionalities to make it easier to implement "active" particles which interact with the tracers. We have then implemented a model of [sugar kelp](@ref sugar-kelp) which can be followed as an example of using this functionality, and [dissolving particles](@ref dissolving-particles) which sink and release tracers as they dissolve (e.g. for ocean alkalinity enhancement). To setup particles first create a particle biogeochemistry, e.g.: diff --git a/examples/dissolving_particles.jl b/examples/dissolving_particles.jl new file mode 100644 index 000000000..2b8424cae --- /dev/null +++ b/examples/dissolving_particles.jl @@ -0,0 +1,354 @@ +# # [Sinking and dissolving particles in two-dimensional turbulence](@id dissolving-particles-example) +# +# In this example we release mineral particles at the surface of a two-dimensional turbulent flow, +# as might be done for ocean alkalinity enhancement. The particles sink and dissolve, releasing +# alkalinity into the water. +# +# We first release hydrated lime (calcium hydroxide) with the default parameters, where large particles +# sink out of the eddies before they dissolve while small particles dissolve near the surface. +# We then release calcite, with a dissolution rate which depends on the calcite saturation of the water, +# across a front between strongly undersaturated water and water which is close to saturation. + +# ## Install dependencies +# First we check we have the dependencies installed +# ```julia +# using Pkg +# pkg"add OceanBioME, Oceananigans, CairoMakie, JLD2" +# ``` + +# ## Model setup +using OceanBioME, Oceananigans, Oceananigans.Units +using CairoMakie, JLD2, Printf, Random + +using OceanBioME.Models.CarbonChemistryModel: calcium_carbonate_saturation + +Random.seed!(1234) +nothing #hide + +# We use a two-dimensional domain which is 64 m wide and deep, and periodic in x +grid = RectilinearGrid(size = (128, 128), x = (0, 64), z = (-64, 0), + topology = (Periodic, Flat, Bounded)) + +# ## Hydrated lime +# [`DissolvingParticles`](@ref) are spheres whose radius shrinks at a `dissolution_rate`, and which +# sink at a `sinking_speed`. By default the radius shrinks at a constant rate and the particles sink +# according to Stokes' law, so they slow down as they dissolve. Both can instead be functions of the +# particle properties and the model fields at the particle, see [`DissolvingMineral`](@ref). +# The default mineral is calcium hydroxide, which releases two moles of alkalinity per mole dissolved. +n = 1000 + +particles = DissolvingParticles(n; grid) + +# The particles start with zero radius, so they do nothing until we release them. +# +# We couple the particles to a carbonate system without any biology, which has the alkalinity (`Alk`) +# tracer that the particles release, and dissolved inorganic carbon (`DIC`) +biogeochemistry = NutrientsPlanktonDetritus(grid; inorganic_carbon = CarbonateSystem(), particles) + +model = NonhydrostaticModel(grid; biogeochemistry, advection = WENO(order = 5)) + +# ## Spin up +# We start from random velocities and let the turbulence develop for 30 minutes +Alk₀ = 2300 # mmol/m³ + +uᵢ(x, z) = 0.02 * randn() # m/s + +set!(model, u = uᵢ, w = uᵢ, DIC = 2000, Alk = Alk₀) + +simulation = Simulation(model, Δt = 1, stop_time = 30minutes) + +conjure_time_step_wizard!(simulation, cfl = 0.5, max_Δt = 10) + +progress(sim) = @printf("Iteration: %04d, time: %s, Δt: %s, wall time: %s\n", + iteration(sim), prettytime(sim), prettytime(sim.Δt), prettytime(sim.run_wall_time)) + +add_callback!(simulation, progress, TimeInterval(30minutes)) + +run!(simulation) + +# ## Release +# Now we release the particles in a 16 m wide patch at the surface, with radii between 20 and 80 μm. +# +# Each computational particle stands for many real particles, the number of which is set by the +# `scalefactors`. Here we release 1 kg of lime per metre in the (flat) y direction. +r₀ = 20e-6 .+ 60e-6 * rand(n) +x₀ = 24 .+ 16 * rand(n) +z₀ = - rand(n) + +mineral = particles.biogeochemistry + +scalefactor = 1 / (mineral.density * 4π / 3 * sum(r₀.^3)) # 1 kg / total particle mass + +set!(particles, r = r₀, x = x₀, z = z₀, scalefactors = scalefactor) + +release_time = time(simulation) + +# ## Diagnosing the pH +# The pH is not a model variable, so we diagnose it from the carbonate chemistry with a `KernelFunctionOperation`, +# which is computed in every cell when it is saved. The model has no temperature or salinity, so we choose +# constant values of 10 °C and 35. +carbon_chemistry = CarbonChemistry() + +@inline total_scale_pH(i, j, k, grid, carbon_chemistry, DIC, Alk, T, S) = + @inbounds carbon_chemistry(; DIC = DIC[i, j, k], Alk = Alk[i, j, k], T, S, output = Val(:pHᵗ)) + +(; DIC, Alk) = model.tracers + +pH = KernelFunctionOperation{Center, Center, Center}(total_scale_pH, grid, carbon_chemistry, DIC, Alk, 10.0, 35.0) + +# We save the alkalinity, its horizontal average and integral, the pH, and the particle positions and radii +filename = "dissolving_particles" + +outputs = (; Alk, pH, mean_Alk = Average(Alk, dims = 1), total_Alk = Integral(Alk)) + +simulation.output_writers[:alkalinity] = JLD2Writer(model, outputs; + filename = "$filename.jld2", + schedule = TimeInterval(1minute), + overwrite_files = true) + +simulation.output_writers[:particles] = JLD2Writer(model, (; particles); + filename = "$(filename)_particles.jld2", + schedule = TimeInterval(1minute), + overwrite_files = true) + +# and run for long enough that the largest particles dissolve +simulation.stop_time = 3hours + +run!(simulation) + +# ## Results +# First we load the alkalinity, pH, and particle output +Alk = FieldTimeSeries("$filename.jld2", "Alk") +pH = FieldTimeSeries("$filename.jld2", "pH") +mean_Alk = FieldTimeSeries("$filename.jld2", "mean_Alk") +total_Alk = FieldTimeSeries("$filename.jld2", "total_Alk") + +times = Alk.times + +function particle_output(filename) + file = jldopen(filename) + states = [file["timeseries/particles/$iteration"] for iteration in keys(file["timeseries/t"])] + close(file) + + return (stack(getproperty.(states, name)) for name in (:x, :z, :r)) +end + +x, z, r = particle_output("$(filename)_particles.jld2") +nothing #hide + +# and animate the particles sinking and dissolving through the turbulence, with each particle drawn +# at its current size (magnified), alongside the pH +frame = Observable(1) + +Alkₙ = @lift Alk[$frame] - Alk₀ +pHₙ = @lift pH[$frame] +positions = @lift Point2f.(x[:, $frame], z[:, $frame]) +sizes = @lift 2e5 * r[:, $frame] +title = @lift prettytime(times[$frame] - release_time) * " after release" + +fig = Figure(size = (1300, 650), fontsize = 20) + +Label(fig[0, 1:4], title) + +ax = Axis(fig[1, 1], title = "Alkalinity increase and particles", xlabel = "x (m)", ylabel = "z (m)", aspect = DataAspect()) + +hm = heatmap!(ax, Alkₙ, colormap = Reverse(:deep), colorrange = (0, 80)) +scatter!(ax, positions, markersize = sizes, color = :white) + +Colorbar(fig[1, 2], hm, label = "mmol/m³") + +ax = Axis(fig[1, 3], title = "pH and particles", xlabel = "x (m)", aspect = DataAspect()) + +hm = heatmap!(ax, pHₙ, colormap = :viridis, colorrange = (8.27, 8.4)) +scatter!(ax, positions, markersize = sizes, color = :white) + +Colorbar(fig[1, 4], hm) + +record(fig, "$filename.mp4", eachindex(times), framerate = 12) do i + frame[] = i +end +nothing #hide + +# ![](dissolving_particles.mp4) + +# To see how the turbulence changes where the particles dissolve, we compare the depth at which each +# particle finished dissolving with the depth it would reach in still water. A particle sinking at +# the Stokes' law speed, ``w ∝ r²``, while its radius shrinks at a constant rate ``k``, sinks +# ``|w(r₀)| r₀ / 3k`` before it has dissolved. +dissolution_depth = [-z[p, findfirst(iszero, r[p, :])] for p in 1:n] + +k = mineral.dissolution_rate + +still_water_depth(r) = - mineral.sinking_speed(mineral, (; r), nothing) * r / 3k +nothing #hide + +# We also check that the alkalinity lost from the particles is gained by the water +θ = mineral.released_tracers.Alk # mol Alk / mol mineral + +mineral_concentration = 1000 * mineral.density / mineral.molar_mass # mmol / m³ + +particle_alkalinity = scalefactor * θ * mineral_concentration * 4π / 3 * vec(sum(r.^3, dims = 1)) +dissolved_alkalinity = interior(total_Alk, 1, 1, 1, :) .- total_Alk[1, 1, 1, 1] +nothing #hide + +# and plot these along with the particle radii and the horizontally averaged alkalinity increase +hours_after_release = (times .- release_time) / hour + +fig = Figure(size = (1200, 900), fontsize = 20) + +ax = Axis(fig[1, 1], xlabel = "Initial radius (μm)", ylabel = "Depth (m)", title = "Depth when fully dissolved", + yreversed = true, limits = (nothing, (0, 64))) + +scatter!(ax, 1e6 * r₀, dissolution_depth, color = (:black, 0.3), label = "Turbulence") +lines!(ax, 20:80, still_water_depth.(1e-6 * (20:80)), color = :red, linewidth = 3, label = "Still water") +axislegend(ax, position = :lb) + +ax = Axis(fig[1, 3], xlabel = "Time (hours)", ylabel = "Radius (μm)", title = "Particle radius") + +for p in 1:10:n + lines!(ax, hours_after_release, 1e6 * r[p, :], color = r₀[p], colormap = :viridis, colorrange = (20e-6, 80e-6)) +end + +ax = Axis(fig[2, 1], xlabel = "Time (hours)", ylabel = "z (m)", title = "Horizontally averaged alkalinity increase") + +hm = heatmap!(ax, hours_after_release, znodes(mean_Alk), interior(mean_Alk, 1, 1, :, :)' .- Alk₀, colormap = Reverse(:deep)) +Colorbar(fig[2, 2], hm, label = "mmol/m³") + +ax = Axis(fig[2, 3], xlabel = "Time (hours)", ylabel = "Fraction of alkalinity", title = "Alkalinity budget") + +lines!(ax, hours_after_release, particle_alkalinity / particle_alkalinity[1], linewidth = 3, label = "In particles") +lines!(ax, hours_after_release, dissolved_alkalinity / particle_alkalinity[1], linewidth = 3, label = "Dissolved") +lines!(ax, hours_after_release, (particle_alkalinity .+ dissolved_alkalinity) / particle_alkalinity[1], + linewidth = 3, linestyle = :dash, color = :black, label = "Total") +axislegend(ax, position = :rc) + +fig + +# ## Calcite with saturation dependent dissolution +# Calcite only dissolves in water which is undersaturated, and as it dissolves it raises the saturation +# state of the water around it. The calcite saturation state, `Ω`, is computed from the dissolved inorganic +# carbon and alkalinity by `CarbonChemistry`, at the same constant temperature and salinity as the pH. +@inline calcite_saturation(carbon_chemistry, DIC, Alk) = + calcium_carbonate_saturation(carbon_chemistry; DIC, Alk, T = 10.0, S = 35.0) + +# The `dissolution_rate` of a [`DissolvingMineral`](@ref) can be any function of the mineral, the +# particle's fields, and the `required_fields` of the model at the particle. Here the radius shrinks +# at a rate proportional to the undersaturation, `1 - Ω`. +struct SaturationLimitedDissolution{C, FT} + carbon_chemistry :: C + maximum_rate :: FT # m/s +end + +@inline function (dissolution::SaturationLimitedDissolution)(mineral, particle_fields, tracer_fields) + Ω = calcite_saturation(dissolution.carbon_chemistry, tracer_fields.DIC, tracer_fields.Alk) + + return dissolution.maximum_rate * max(0, 1 - Ω) +end + +calcite = DissolvingMineral(density = 2710, + molar_mass = 100.09e-3, + released_tracers = (; DIC = 1, Alk = 2), + dissolution_rate = SaturationLimitedDissolution(carbon_chemistry, 4e-8), + required_fields = (:DIC, :Alk)) + +# We put the calcite particles into a new model, which starts from the turbulence at the end of the last simulation +calcite_particles = DissolvingParticles(n; grid, biogeochemistry = calcite) + +biogeochemistry = NutrientsPlanktonDetritus(grid; inorganic_carbon = CarbonateSystem(), particles = calcite_particles) + +calcite_model = NonhydrostaticModel(grid; biogeochemistry, advection = WENO(order = 5)) + +# and split the domain down the middle. The left half has more dissolved inorganic carbon and is strongly +# undersaturated, while the right half is close to saturation. +DICᵢ(x, z) = ifelse(x < 32, 2400, 2310) # mmol/m³ + +set!(calcite_model, u = model.velocities.u, w = model.velocities.w, DIC = DICᵢ, Alk = Alk₀) + +(calcite_saturation(carbon_chemistry, 2400.0, 2300.0), calcite_saturation(carbon_chemistry, 2310.0, 2300.0)) + +# The particles are released with the same sizes and positions as the lime, which straddle the front +scalefactor = 1 / (calcite.density * 4π / 3 * sum(r₀.^3)) # 1 kg / total particle mass + +set!(calcite_particles, r = r₀, x = x₀, z = z₀, scalefactors = scalefactor) + +# This time we diagnose the saturation state with a `KernelFunctionOperation` +@inline calcite_saturation(i, j, k, grid, carbon_chemistry, DIC, Alk) = + @inbounds calcite_saturation(carbon_chemistry, DIC[i, j, k], Alk[i, j, k]) + +(; DIC, Alk) = calcite_model.tracers + +Ω = KernelFunctionOperation{Center, Center, Center}(calcite_saturation, grid, carbon_chemistry, DIC, Alk) + +simulation = Simulation(calcite_model, Δt = 1, stop_time = 2.5hours) + +conjure_time_step_wizard!(simulation, cfl = 0.5, max_Δt = 10) + +add_callback!(simulation, progress, TimeInterval(30minutes)) + +filename = "dissolving_calcite" + +simulation.output_writers[:saturation] = JLD2Writer(calcite_model, (; Ω); + filename = "$filename.jld2", + schedule = TimeInterval(1minute), + overwrite_files = true) + +simulation.output_writers[:particles] = JLD2Writer(calcite_model, (; particles = calcite_particles); + filename = "$(filename)_particles.jld2", + schedule = TimeInterval(1minute), + overwrite_files = true) + +run!(simulation) + +# We animate the particles sinking through the saturation state, where undersaturated water is blue and +# supersaturated water is red +Ω = FieldTimeSeries("$filename.jld2", "Ω") + +times = Ω.times + +x, z, r = particle_output("$(filename)_particles.jld2") + +frame = Observable(1) + +Ωₙ = @lift Ω[$frame] +positions = @lift Point2f.(x[:, $frame], z[:, $frame]) +sizes = @lift 2e5 * r[:, $frame] +title = @lift "Calcite saturation and particles, " * prettytime(times[$frame]) * " after release" + +fig = Figure(size = (700, 600), fontsize = 20) + +ax = Axis(fig[1, 1]; title, xlabel = "x (m)", ylabel = "z (m)", aspect = DataAspect()) + +hm = heatmap!(ax, Ωₙ, colormap = :balance, colorrange = (0.5, 1.5)) +scatter!(ax, positions, markersize = sizes, color = :black) + +Colorbar(fig[1, 2], hm, label = "Ω") + +record(fig, "$filename.mp4", eachindex(times), framerate = 12) do i + frame[] = i +end +nothing #hide + +# ![](dissolving_calcite.mp4) + +# The particles released into the undersaturated water dissolve as they sink, while those released +# close to saturation dissolve much more slowly, and the largest reach the bottom. We can see this in the +# radius of each particle, and in the fraction of the calcite released on each side of the front which is left. +undersaturated = x₀ .< 32 + +remaining(released) = vec(sum(r[released, :].^3, dims = 1)) / sum(r₀[released].^3) + +fig = Figure(size = (1200, 500), fontsize = 20) + +ax = Axis(fig[1, 1], xlabel = "Time (hours)", ylabel = "Radius (μm)", title = "Particle radius") + +for p in 1:10:n + lines!(ax, times / hour, 1e6 * r[p, :], color = ifelse(undersaturated[p], :dodgerblue, :firebrick)) +end + +ax = Axis(fig[1, 2], xlabel = "Time (hours)", ylabel = "Fraction of calcite remaining", title = "Calcite remaining") + +lines!(ax, times / hour, remaining(undersaturated), linewidth = 3, color = :dodgerblue, label = "Released undersaturated") +lines!(ax, times / hour, remaining(.!undersaturated), linewidth = 3, color = :firebrick, label = "Released near saturation") +axislegend(ax, position = :lb) + +fig diff --git a/src/Models/Individuals/DissolvingParticles/DissolvingParticles.jl b/src/Models/Individuals/DissolvingParticles/DissolvingParticles.jl new file mode 100644 index 000000000..382704253 --- /dev/null +++ b/src/Models/Individuals/DissolvingParticles/DissolvingParticles.jl @@ -0,0 +1,284 @@ +""" +Active particles which sink, dissolve, and release material into tracer fields, for example mineral +particles added to the ocean for ocean alkalinity enhancement, or dissolving secondary mineral precipitate. + +Prognostic properties +===================== +* Radius: r (m) + +Diagnostic properties +===================== +* Vertical velocity relative to the water: sinking_speed (m/s, positive upwards) + +Tracer dependencies +=================== +Those listed in `required_fields`, by default none + +Coupled tracers +=============== +Those listed in `released_tracers`, by default alkalinity: Alk (mmol/m³) +""" + +module DissolvingParticlesModel + +export DissolvingMineral, DissolvingParticles, StokesSinking + +using Oceananigans: Biogeochemistry, defaults, fields +using Oceananigans.Architectures: architecture +using Oceananigans.Models: LagrangianParticleTracking +using Oceananigans.Utils: KernelParameters, launch! + +using OceanBioME: Particles +using OceanBioME.Particles: BiogeochemicalParticles, extract_tracer_values, required_tracers + +using KernelAbstractions: @kernel, @index + +""" + StokesSinking(FT = Float64; + particle_density, + water_density = 1025, + dynamic_viscosity = 1.08e-3, + gravitational_acceleration = defaults.gravitational_acceleration) + +Stokes' law for the vertical velocity (m/s, positive upwards) of a sphere of radius `r` (m) relative to the water, + + w = 2 (ρ - ρₚ) g r² / 9μ, + +valid at small particle Reynolds number, `2 r |w| ρ / μ`. It is called as +`stokes(mineral, particle_fields, tracer_fields)` and reads the radius from `particle_fields.r`. + +Keyword Arguments +================= + +- `particle_density`: density of the particle, `ρₚ` (kg/m³). +- `water_density`: density of the water, `ρ` (kg/m³), a number or a function called as + `water_density(mineral, particle_fields, tracer_fields)`. Default: 1025. +- `dynamic_viscosity`: dynamic viscosity of the water, `μ` (kg/m/s), a number or a function called as + `dynamic_viscosity(mineral, particle_fields, tracer_fields)`. Default: 1.08e-3. +- `gravitational_acceleration`: `g` (m/s²). Default: `Oceananigans.defaults.gravitational_acceleration`. + +Example +======= + +```jldoctest +julia> using OceanBioME + +julia> stokes = StokesSinking(particle_density = 2710) +StokesSinking{Float64, Float64, Float64}(2710.0, 1025.0, 0.00108, 9.80665) +``` +""" +struct StokesSinking{WD, DV, FT} + particle_density :: FT + water_density :: WD + dynamic_viscosity :: DV + gravitational_acceleration :: FT +end + +function StokesSinking(FT = Float64; + particle_density, + water_density = 1025, + dynamic_viscosity = 1.08e-3, + gravitational_acceleration = defaults.gravitational_acceleration) + + water_density = maybe_convert(FT, water_density) + dynamic_viscosity = maybe_convert(FT, dynamic_viscosity) + + return StokesSinking(convert(FT, particle_density), water_density, dynamic_viscosity, + convert(FT, gravitational_acceleration)) +end + +@inline function (stokes::StokesSinking)(mineral, particle_fields, tracer_fields) + r = particle_fields.r + ρₚ = stokes.particle_density + ρ = evaluate(stokes.water_density, mineral, particle_fields, tracer_fields) + μ = evaluate(stokes.dynamic_viscosity, mineral, particle_fields, tracer_fields) + g = stokes.gravitational_acceleration + + return 2 * (ρ - ρₚ) * g * r^2 / (9 * μ) +end + +""" + DissolvingMineral(FT = Float64; + density = 2211, + molar_mass = 74.093e-3, + released_tracers = (; Alk = 2), + dissolution_rate = 1e-8, + sinking_speed = StokesSinking(FT; particle_density = density), + required_fields = ()) + +Spherical mineral particles of radius `r` (m) which dissolve, release tracers, and sink. + +The radius shrinks at the dissolution rate `k` (m/s), + + dr/dt = -k, + +so each particle releases `4π r² k θ ρₚ / M` of each tracer (mol/s, converted to mmol/s), +where `θ` is the moles of tracer released per mole of mineral, `ρₚ` the `density`, +and `M` the `molar_mass`. + +`dissolution_rate` and `sinking_speed` are numbers or functions called as +`f(mineral, particle_fields, tracer_fields)`, where `particle_fields` is a `NamedTuple` of the particle's +`r` and `sinking_speed`, and `tracer_fields` is a `NamedTuple` of the `required_fields` at the particle position. + +Keyword Arguments +================= + +- `density`: density of the mineral (kg/m³). Default: 2211. +- `molar_mass`: molar mass of the mineral (kg/mol). Default: 74.093e-3. +- `released_tracers`: `NamedTuple` of the moles of each tracer released per mole of mineral dissolved. + Default: `(; Alk = 2)`. + +The default `density`, `molar_mass`, and `released_tracers` are for calcium hydroxide, Ca(OH)₂. +- `dissolution_rate`: speed that the radius shrinks (m/s). Default: 1e-8. +- `sinking_speed`: vertical velocity of the particles relative to the water (m/s, positive upwards). + Default: `StokesSinking(FT; particle_density = density)`. +- `required_fields`: names of the model fields (tracers, velocities, or auxiliary fields) passed to + `dissolution_rate` and `sinking_speed`. Default: `()`. + +Example +======= + +```jldoctest +julia> using OceanBioME + +julia> calcite = DissolvingMineral(density = 2710, molar_mass = 100.09e-3, released_tracers = (; Alk = 2, DIC = 1)) +DissolvingMineral{Float64} biogeochemistry tracking particle `r`adius +├── density: 2710.0 kg/m³ +├── molar mass: 0.10009 kg/mol +├── released tracers: (Alk = 2.0, DIC = 1.0) mol/mol +├── dissolution rate: 1.0e-8 m/s +├── sinking speed: StokesSinking{Float64, Float64, Float64}(2710.0, 1025.0, 0.00108, 9.80665) m/s +└── required fields: () +``` +""" +struct DissolvingMineral{FT, R, D, W, F} + density :: FT + molar_mass :: FT + released_tracers :: R + dissolution_rate :: D + sinking_speed :: W + + DissolvingMineral(density::FT, molar_mass::FT, released_tracers::R, dissolution_rate::D, sinking_speed::W, + required_fields::Tuple) where {FT, R, D, W} = + new{FT, R, D, W, required_fields}(density, molar_mass, released_tracers, dissolution_rate, sinking_speed) +end + +function DissolvingMineral(FT = Float64; + density = 2211, + molar_mass = 74.093e-3, + released_tracers = (; Alk = 2), + dissolution_rate = 1e-8, + sinking_speed = StokesSinking(FT; particle_density = density), + required_fields = ()) + + released_tracers = map(θ -> convert(FT, θ), released_tracers) + dissolution_rate = maybe_convert(FT, dissolution_rate) + sinking_speed = maybe_convert(FT, sinking_speed) + + return DissolvingMineral(convert(FT, density), convert(FT, molar_mass), released_tracers, + dissolution_rate, sinking_speed, required_fields) +end + +maybe_convert(FT, value::Number) = convert(FT, value) +maybe_convert(FT, func) = func + +@inline evaluate(value::Number, args...) = value +@inline evaluate(func, args...) = func(args...) + +""" + DissolvingParticles(n; + grid, + mineral_parameters = NamedTuple(), + biogeochemistry = DissolvingMineral(eltype(grid); mineral_parameters...), + kwargs...) + +Return `n` `BiogeochemicalParticles` on `grid` with `DissolvingMineral` `biogeochemistry`. +`mineral_parameters` are keyword arguments for `DissolvingMineral`, and `kwargs` are passed to +`BiogeochemicalParticles`. +""" +DissolvingParticles(n; + grid, + mineral_parameters = NamedTuple(), + biogeochemistry = DissolvingMineral(eltype(grid); mineral_parameters...), + kwargs...) = + BiogeochemicalParticles(n; grid, biogeochemistry, kwargs...) + +@inline Particles.required_particle_fields(::DissolvingMineral) = (:r, :sinking_speed) +@inline Particles.required_tracers(::DissolvingMineral{<:Any, <:Any, <:Any, <:Any, F}) where F = F +@inline Particles.coupled_tracers(mineral::DissolvingMineral) = keys(mineral.released_tracers) + +@inline function dissolution_rate(mineral, r, w, field_values...) + particle_fields = (; r, sinking_speed = w) + tracer_fields = NamedTuple{required_tracers(mineral)}(field_values) + + return evaluate(mineral.dissolution_rate, mineral, particle_fields, tracer_fields) * (r > 0) +end + +@inline (mineral::DissolvingMineral)(::Val{:r}, t, r, w, field_values...) = + - dissolution_rate(mineral, r, w, field_values...) + +@inline (mineral::DissolvingMineral)(::Val{:sinking_speed}, t, r, w, field_values...) = zero(r) + +@inline dissolution(mineral, r::FT, w, field_values...) where FT = + convert(FT, 4π) * r^2 * dissolution_rate(mineral, r, w, field_values...) # m³ / s + +@inline function (mineral::DissolvingMineral{FT})(::Val{tracer}, t, r, w, field_values...) where {FT, tracer} + mineral_concentration = convert(FT, 1000) * mineral.density / mineral.molar_mass # mmol / m³ + θ = mineral.released_tracers[tracer] # mol tracer / mol mineral + dissolution_rate = dissolution(mineral, r, w, field_values...) # m³ / s + + return θ * dissolution_rate * mineral_concentration # mmol / s +end + +@inline sinking_speed(mineral, particle_fields, tracer_fields) = + evaluate(mineral.sinking_speed, mineral, particle_fields, tracer_fields) * (particle_fields.r > 0) + +const DissolvingBiogeochemicalParticles = BiogeochemicalParticles{<:Any, <:DissolvingMineral} + +@inline LagrangianParticleTracking.particle_w_velocity(particles::DissolvingBiogeochemicalParticles, n, w) = + @inbounds w + particles.fields.sinking_speed[n] + +function Particles.update_particle_state!(particles::DissolvingBiogeochemicalParticles, model, Δt) + r = particles.fields.r + r .= max.(r, 0) + + return nothing +end + +Biogeochemistry.update_biogeochemical_state!(model, particles::DissolvingBiogeochemicalParticles) = + update_sinking_speed!(particles, model) + +function update_sinking_speed!(particles, model) + grid = model.grid + + launch!(architecture(grid), grid, KernelParameters(1:length(particles)), + _update_sinking_speed!, particles, grid, fields(model)) + + return nothing +end + +@kernel function _update_sinking_speed!(particles, grid, fields) + n = @index(Global) + + mineral = particles.biogeochemistry + + particle_fields = map(field -> @inbounds(field[n]), particles.fields) + + tracer_values = extract_tracer_values(nothing, particles.field_interpolation, particles, grid, fields, n) + tracer_fields = NamedTuple{required_tracers(mineral)}(tracer_values) + + @inbounds particles.fields.sinking_speed[n] = sinking_speed(mineral, particle_fields, tracer_fields) +end + +Base.summary(::DissolvingMineral{FT}) where FT = "DissolvingMineral{$FT} biogeochemistry" + +Base.show(io::IO, mineral::DissolvingMineral) = + print(io, summary(mineral), " tracking particle `r`adius", "\n", + "├── density: ", mineral.density, " kg/m³", "\n", + "├── molar mass: ", mineral.molar_mass, " kg/mol", "\n", + "├── released tracers: ", mineral.released_tracers, " mol/mol", "\n", + "├── dissolution rate: ", mineral.dissolution_rate, " m/s", "\n", + "├── sinking speed: ", mineral.sinking_speed, " m/s", "\n", + "└── required fields: ", required_tracers(mineral)) + +end # module diff --git a/src/Models/Models.jl b/src/Models/Models.jl index 029e83401..28ad34f4a 100644 --- a/src/Models/Models.jl +++ b/src/Models/Models.jl @@ -15,6 +15,8 @@ export Oxygen export SugarKelp, SugarKelpParticles, GiantKelp +export DissolvingMineral, DissolvingParticles, StokesSinking + export CarbonChemistry export GasExchange, @@ -32,12 +34,14 @@ include("seawater_density.jl") include("CarbonChemistry/CarbonChemistry.jl") # NPD's ExplicitCalciumCarbonate uses CarbonChemistry, so load it first include("AdvectedPopulations/NutrientsPlanktonDetritus/NutrientsPlanktonDetritus.jl") include("Individuals/SugarKelp/SugarKelp.jl") +include("Individuals/DissolvingParticles/DissolvingParticles.jl") include("GasExchange/GasExchange.jl") include("AdvectedPopulations/PISCES/PISCES.jl") using .SedimentModels using .NutrientsPlanktonDetritusModels using .SugarKelpModel +using .DissolvingParticlesModel using .PISCESModel using .CarbonChemistryModel using .GasExchangeModel diff --git a/src/OceanBioME.jl b/src/OceanBioME.jl index 794e49c99..e9daafe87 100644 --- a/src/OceanBioME.jl +++ b/src/OceanBioME.jl @@ -26,6 +26,8 @@ export DepthDependantSinkingSpeed, PrescribedLatitude, ModelLatitude, PISCESMode # Macroalgae models export BiogeochemicalParticles, SugarKelp, SugarKelpParticles +export DissolvingMineral, DissolvingParticles, StokesSinking + # Box model export BoxModel, BoxModelGrid, SpeedyOutput, load_output @@ -188,6 +190,7 @@ function update_biogeochemical_state!(bgc::CompleteBiogeochemistry, model) update_biogeochemical_state!(model, bgc.light_attenuation) update_biogeochemical_state!(model, bgc.underlying_biogeochemistry) update_biogeochemical_state!(model, bgc.sediment) + update_biogeochemical_state!(model, bgc.particles) end update_biogeochemical_state!(model, modifiers::Tuple) = [update_biogeochemical_state!(model, modifier) for modifier in modifiers] diff --git a/src/Particles/Particles.jl b/src/Particles/Particles.jl index db243e429..e1f01e35e 100644 --- a/src/Particles/Particles.jl +++ b/src/Particles/Particles.jl @@ -188,9 +188,7 @@ function Base.show(io::IO, particles::BiogeochemicalParticles) end # User may want to overload this to not output parameters over and over again -function fetch_output(particles::BiogeochemicalParticles, model) - names = propertynames(particles.fields) - return NamedTuple{names}([getproperty(particles.fields, name) for name in names]) -end +fetch_output(particles::BiogeochemicalParticles, model) = + (; x = particles.x, y = particles.y, z = particles.z, particles.fields...) end #module diff --git a/test/runtests.jl b/test/runtests.jl index 11ede21e9..89df59d75 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -5,6 +5,7 @@ include("test_utils.jl") include("test_construction_in_functions.jl") include("test_light.jl") include("test_particles.jl") +include("test_dissolving_particles.jl") include("test_sugar_kelp.jl") include("test_external_plankton_interface.jl") include("test_NutrientsPlanktonDetritus.jl") diff --git a/test/test_dissolving_particles.jl b/test/test_dissolving_particles.jl new file mode 100644 index 000000000..d1668746f --- /dev/null +++ b/test/test_dissolving_particles.jl @@ -0,0 +1,137 @@ +include("dependencies_for_runtests.jl") + +using Oceananigans.Architectures: on_architecture + +# total tracer in a grid made of 1 m³ cells (mmol) +total_tracer(tracer) = sum(on_architecture(CPU(), interior(tracer))) + +particle_radii(particles) = on_architecture(CPU(), particles.fields.r) + +function dissolving_particle_model(grid, particles; kwargs...) + biogeochemistry = NutrientsPlanktonDetritus(grid; inorganic_carbon = CarbonateSystem(), particles) + + model = NonhydrostaticModel(grid; biogeochemistry, advection = nothing, kwargs...) + + set!(model, DIC = 2000, Alk = 2300) + + return model +end + +@testset "Dissolving particle dissolution" begin + grid = RectilinearGrid(architecture; size = (1, 1, 1), extent = (1, 1, 1)) + + k = 1e-6 # m/s + r₀ = 1e-4 # m + Δt = 0.1 # so the particle dissolves in 1000 timesteps + scalefactor = 1e6 + + particles = DissolvingParticles(1; grid, + advection = nothing, + scalefactors = [scalefactor], + mineral_parameters = (; dissolution_rate = k, + released_tracers = (; Alk = 2, DIC = 1))) + + set!(particles, r = r₀, x = 0.5, y = 0.5, z = -0.5) + + model = dissolving_particle_model(grid, particles) + + mineral = particles.biogeochemistry + initial_mineral = scalefactor * 4/3 * π * r₀^3 * mineral.density / mineral.molar_mass * 1000 # mmol + + # the radius shrinks at the dissolution rate + for _ in 1:500 + time_step!(model, Δt) + end + + @test particle_radii(particles)[1] ≈ r₀ - 500 * k * Δt + + # and stops at zero rather than overshooting + for _ in 1:600 + time_step!(model, Δt) + end + + @test particle_radii(particles)[1] == 0 + + # all of the mineral is released, in the right ratio, up to the timestepping error + released_Alk = total_tracer(model.tracers.Alk) - 2300 + released_DIC = total_tracer(model.tracers.DIC) - 2000 + + @test isapprox(released_Alk, 2 * initial_mineral; rtol = 10 * k * Δt / r₀) + @test released_Alk ≈ 2 * released_DIC + + # and nothing more is released once it has dissolved + time_step!(model, Δt) + + @test total_tracer(model.tracers.Alk) - 2300 == released_Alk +end + +@testset "Dissolving particle sinking" begin + grid = RectilinearGrid(architecture; size = (1, 1, 10), extent = (2, 2, 10)) + + w = 0.01 # m/s + + particles = DissolvingParticles(2; grid, mineral_parameters = (; sinking_speed = -w, dissolution_rate = 0)) + + # the second particle has already dissolved so shouldn't sink + set!(particles, r = [1e-4, 0], x = 1, y = 1, z = -1) + + model = dissolving_particle_model(grid, particles) + + for _ in 1:10 + time_step!(model, 10) + end + + z = on_architecture(CPU(), particles.z) + + @test z[1] ≈ -1 - 10 * 10 * w + @test z[2] ≈ -1 + + @test on_architecture(CPU(), particles.fields.sinking_speed) ≈ [-w, 0] + + stokes = StokesSinking(; particle_density = 2025, water_density = 1025, + dynamic_viscosity = 1e-3, gravitational_acceleration = 9) + + @test stokes(nothing, (; r = 1e-4), NamedTuple()) ≈ - 2 * 1000 * 9 * 1e-8 / (9 * 1e-3) +end + +@testset "Dissolving particles depending on model fields" begin + grid = RectilinearGrid(architecture; size = (1, 1, 10), extent = (2, 2, 10)) + + r₀ = 1e-4 # m + Δt = 1 + + particles = DissolvingParticles(1; grid, mineral_parameters = (; required_fields = (:T, ), + dissolution_rate = (mineral, particle_fields, tracer_fields) -> 1e-9 * tracer_fields.T, + sinking_speed = (mineral, particle_fields, tracer_fields) -> - 1e-3 * tracer_fields.T)) + + set!(particles, r = r₀, x = 1, y = 1, z = -1) + + model = dissolving_particle_model(grid, particles; tracers = :T) + + set!(model, T = 10) + + time_step!(model, Δt) + + @test particle_radii(particles)[1] ≈ r₀ - 1e-8 * Δt + @test on_architecture(CPU(), particles.z)[1] ≈ -1 - 1e-2 * Δt + + stokes = StokesSinking(; particle_density = 2025, + water_density = (mineral, particle_fields, tracer_fields) -> 1000 + tracer_fields.T, + dynamic_viscosity = (mineral, particle_fields, tracer_fields) -> 1e-4 * tracer_fields.T) + + particles = DissolvingParticles(1; grid, mineral_parameters = (; required_fields = (:T, ), + dissolution_rate = 0, + sinking_speed = stokes)) + + set!(particles, r = r₀, x = 1, y = 1, z = -1) + + model = dissolving_particle_model(grid, particles; tracers = :T) + + set!(model, T = 10) + + time_step!(model, Δt) + + w = StokesSinking(; particle_density = 2025, water_density = 1010, dynamic_viscosity = 1e-3)(nothing, (; r = r₀), nothing) + + @test on_architecture(CPU(), particles.z)[1] ≈ -1 + w * Δt +end