licenses
sequencelengths
1
3
version
stringclasses
677 values
tree_hash
stringlengths
40
40
path
stringclasses
1 value
type
stringclasses
2 values
size
stringlengths
2
8
text
stringlengths
25
67.1M
package_name
stringlengths
2
41
repo
stringlengths
33
86
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
11111
using JustRelax, JustRelax.JustRelax2D, JustRelax.DataIO const backend_JR = CPUBackend using ParallelStencil, ParallelStencil.FiniteDifferences2D @init_parallel_stencil(Threads, Float64, 2) #or (CUDA, Float64, 2) or (AMDGPU, Float64, 2) using Printf, LinearAlgebra, GeoParams, GLMakie, SpecialFunctions # function to compute strain rate (compulsory) @inline function custom_εII(a::CustomRheology, TauII; args...) η = custom_viscosity(a; args...) return TauII / η * 0.5 end # function to compute deviatoric stress (compulsory) @inline function custom_τII(a::CustomRheology, EpsII; args...) η = custom_viscosity(a; args...) return 2.0 * η * EpsII end # helper function (optional) @inline function custom_viscosity(a::CustomRheology; P=0.0, T=273.0, depth=0.0, kwargs...) (; η0, Ea, Va, T0, R, cutoff) = a.args η = η0 * exp((Ea + P * Va) / (R * T) - Ea / (R * T0)) correction = (depth ≤ 660e3) + (2740e3 ≥ depth > 660e3) * 1e1 + (depth > 2700e3) * 1e-1 η = clamp(η * correction, cutoff...) end # HELPER FUNCTIONS --------------------------------------------------------------- import ParallelStencil.INDICES const idx_j = INDICES[2] macro all_j(A) esc(:($A[$idx_j])) end @parallel function init_P!(P, ρg, z) @all(P) = @all(ρg)*abs(@all_j(z)) return nothing end # Half-space-cooling model @parallel_indices (i, j) function init_T!(T, z, κ, Tm, Tp, Tmin, Tmax) yr = 3600*24*365.25 dTdz = (Tm-Tp)/2890e3 zᵢ = abs(z[j]) Tᵢ = Tp + dTdz*(zᵢ) time = 100e6 * yr Ths = Tmin + (Tm -Tmin) * erf((zᵢ)*0.5/(κ*time)^0.5) T[i, j] = min(Tᵢ, Ths) return end function circular_perturbation!(T, δT, xc, yc, r, xvi) @parallel_indices (i, j) function _circular_perturbation!(T, δT, xc, yc, r, x, y) @inbounds if (((x[i] - xc))^2 + ((y[j] - yc))^2) ≤ r^2 T[i, j] *= δT / 100 + 1 end return nothing end @parallel _circular_perturbation!(T, δT, xc, yc, r, xvi...) end function random_perturbation!(T, δT, xbox, ybox, xvi) @parallel_indices (i, j) function _random_perturbation!(T, δT, xbox, ybox, x, y) @inbounds if (xbox[1] ≤ x[i] ≤ xbox[2]) && (abs(ybox[1]) ≤ abs(y[j]) ≤ abs(ybox[2])) δTi = δT * (rand() - 0.5) # random perturbation within ±δT [%] T[i, j] *= δTi / 100 + 1 end return nothing end @parallel (@idx size(T)) _random_perturbation!(T, δT, xbox, ybox, xvi...) end # -------------------------------------------------------------------------------- # BEGIN MAIN SCRIPT # -------------------------------------------------------------------------------- function thermal_convection2D(; ar=8, ny=16, nx=ny*8, figdir="figs2D", thermal_perturbation = :circular) # initialize MPI # Physical domain ------------------------------------ ly = 2890e3 lx = ly * ar origin = 0.0, -ly # origin coordinates ni = nx, ny # number of cells li = lx, ly # domain length in x- and y- di = @. li / ni # grid step in x- and -y grid = Geometry(ni, li; origin = origin) (; xci, xvi) = grid # nodes at the center and vertices of the cells # ---------------------------------------------------- # create rheology struct v_args = (; η0=5e20, Ea=200e3, Va=2.6e-6, T0=1.6e3, R=8.3145, cutoff=(1e16, 1e25)) creep = CustomRheology(custom_εII, custom_τII, v_args) # Physical properties using GeoParams ---------------- η_reg = 1e16 G0 = 70e9 # shear modulus cohesion = 30e6 friction = asind(0.01) pl = DruckerPrager_regularised(; C = cohesion, ϕ=friction, η_vp=η_reg, Ψ=0.0) # non-regularized plasticity el = SetConstantElasticity(; G=G0, ν=0.5) # elastic spring β = inv(get_Kb(el)) rheology = SetMaterialParams(; Name = "Mantle", Phase = 1, Density = PT_Density(; ρ0=3.1e3, β=β, T0=0.0, α = 1.5e-5), HeatCapacity = ConstantHeatCapacity(; Cp=1.2e3), Conductivity = ConstantConductivity(; k=3.0), CompositeRheology = CompositeRheology((creep, el, )), Elasticity = el, Gravity = ConstantGravity(; g=9.81), ) rheology_plastic = SetMaterialParams(; Name = "Mantle", Phase = 1, Density = PT_Density(; ρ0=3.5e3, β=β, T0=0.0, α = 1.5e-5), HeatCapacity = ConstantHeatCapacity(; Cp=1.2e3), Conductivity = ConstantConductivity(; k=3.0), CompositeRheology = CompositeRheology((creep, el, pl)), Elasticity = el, Gravity = ConstantGravity(; g=9.81), ) # heat diffusivity κ = (rheology.Conductivity[1].k / (rheology.HeatCapacity[1].Cp * rheology.Density[1].ρ0)).val dt = dt_diff = 0.5 * min(di...)^2 / κ / 2.01 # diffusive CFL timestep limiter # ---------------------------------------------------- # TEMPERATURE PROFILE -------------------------------- thermal = ThermalArrays(backend_JR, ni) thermal_bc = TemperatureBoundaryConditions(; no_flux = (left = true, right = true, top = false, bot = false), ) # initialize thermal profile - Half space cooling adiabat = 0.3 # adiabatic gradient Tp = 1900 Tm = Tp + adiabat * 2890 Tmin, Tmax = 300.0, 3.5e3 @parallel init_T!(thermal.T, xvi[2], κ, Tm, Tp, Tmin, Tmax) thermal_bcs!(thermal, thermal_bc) # Temperature anomaly if thermal_perturbation == :random δT = 5.0 # thermal perturbation (in %) random_perturbation!(thermal.T, δT, (lx*1/8, lx*7/8), (-2000e3, -2600e3), xvi) elseif thermal_perturbation == :circular δT = 10.0 # thermal perturbation (in %) xc, yc = 0.5*lx, -0.75*ly # center of the thermal anomaly r = 150e3 # radius of perturbation circular_perturbation!(thermal.T, δT, xc, yc, r, xvi) end @views thermal.T[:, 1] .= Tmax @views thermal.T[:, end] .= Tmin temperature2center!(thermal) # ---------------------------------------------------- # STOKES --------------------------------------------- # Allocate arrays needed for every Stokes problem stokes = StokesArrays(backend_JR, ni) pt_stokes = PTStokesCoeffs(li, di; ϵ=1e-7, CFL = 0.9 / √2.1) args = (; T = thermal.Tc, P = stokes.P, dt=Inf) # Buoyancy forces ρg = @zeros(ni...), @zeros(ni...) for _ in 1:2 compute_ρg!(ρg[2], rheology, (T=thermal.Tc, P=stokes.P)) @parallel init_P!(stokes.P, ρg[2], xci[2]) end # Rheology depth = PTArray(backend_JR)([y for x in xci[1], y in xci[2]]) args = (; T = thermal.Tc, P = stokes.P, depth = depth, dt = dt, ΔTc = thermal.ΔTc) viscosity_cutoff = 1e18, 1e23 compute_viscosity!(stokes, args, rheology, viscosity_cutoff) # Boundary conditions flow_bcs = VelocityBoundaryConditions(; free_slip = (left = true, right=true, top=true, bot=true), ) flow_bcs!(stokes, flow_bcs) # apply boundary conditions update_halo!(@velocity(stokes)...) # ---------------------------------------------------- # IO ------------------------------------------------- # if it does not exist, make folder where figures are stored take(figdir) # ---------------------------------------------------- # Plot initial T and η profiles fig0 = let Yv = [y for x in xvi[1], y in xvi[2]][:] Y = [y for x in xci[1], y in xci[2]][:] fig = Figure(size = (1200, 900)) ax1 = Axis(fig[1,1], aspect = 2/3, title = "T") ax2 = Axis(fig[1,2], aspect = 2/3, title = "log10(η)") lines!(ax1, Array(thermal.T[2:end-1,:][:]), Yv./1e3) lines!(ax2, Array(log10.(stokes.viscosity.η[:])), Y./1e3) ylims!(ax1, -2890, 0) ylims!(ax2, -2890, 0) hideydecorations!(ax2) save(joinpath(figdir, "initial_profile.png"), fig) fig end # Time loop t, it = 0.0, 0 local iters while (t / (1e6 * 3600 * 24 * 365.25)) < 4.5e3 # Stokes solver ---------------- args = (; T = thermal.Tc, P = stokes.P, depth = depth, dt=dt, ΔTc = thermal.ΔTc) iters = solve!( stokes, pt_stokes, di, flow_bcs, ρg, rheology, args, dt, igg; kwargs = ( viscosity_cutoff = viscosity_cutoff, iterMax = 10e3, nout = 1e2, verbose = true ), ); dt = compute_dt(stokes, di, dt_diff, igg) # ------------------------------ # Thermal solver --------------- args_T = (; P=stokes.P) solve!( thermal, thermal_bc, stokes, rheology, args_T, di, dt ) # ------------------------------ it += 1 t += dt println("\n") println("Time step number $it") println(" time = $(t/(1e6 * 3600 * 24 *365.25)) Myrs, dt = $(dt/(1e6 * 3600 * 24 *365.25)) Myrs") println("\n") # Plotting --------------------- if it == 1 || rem(it, 10) == 0 fig = Figure(size = (1000, 1000), title = "t = $t") ax1 = Axis(fig[1,1], aspect = DataAspect(), title = "T [K] (t=$(t/(1e6 * 3600 * 24 *365.25)) Myrs)") ax2 = Axis(fig[2,1], aspect = DataAspect(), title = "Vy [m/s]") ax3 = Axis(fig[3,1], aspect = DataAspect(), title = "τII [MPa]") ax4 = Axis(fig[4,1], aspect = DataAspect(), title = "log10(η)") h1 = heatmap!(ax1, xvi[1].*1e-3, xvi[2].*1e-3, Array(thermal.T) , colormap=:batlow) h2 = heatmap!(ax2, xci[1].*1e-3, xvi[2].*1e-3, Array(stokes.V.Vy[2:end-1,:]) , colormap=:batlow) h3 = heatmap!(ax3, xci[1].*1e-3, xci[2].*1e-3, Array(stokes.τ.II.*1e-6) , colormap=:batlow) h4 = heatmap!(ax4, xci[1].*1e-3, xci[2].*1e-3, Array(log10.(stokes.viscosity.η_vep)) , colormap=:batlow) hidexdecorations!(ax1) hidexdecorations!(ax2) hidexdecorations!(ax3) Colorbar(fig[1,2], h1, height=100) Colorbar(fig[2,2], h2, height=100) Colorbar(fig[3,2], h3, height=100) Colorbar(fig[4,2], h4, height=100) save( joinpath(figdir, "$(it).png"), fig) fig end # ------------------------------ end return (ni=ni, xci=xci, li=li, di=di), thermal end function run() figdir = "figs2D_test" ar = 2 # aspect ratio n = 128 nx = n*ar - 2 ny = n - 2 thermal_convection2D(; figdir=figdir, ar=ar,nx=nx, ny=ny); end run()
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
11706
using JustRelax, JustRelax.JustRelax2D, JustRelax.DataIO import JustRelax.@cell const backend = CPUBackend using ParallelStencil @init_parallel_stencil(Threads, Float64, 2) #or (CUDA, Float64, 2) or (AMDGPU, Float64, 2) using GeoParams, GLMakie, SpecialFunctions # function to compute strain rate (compulsory) @inline function custom_εII(a::CustomRheology, TauII; args...) η = custom_viscosity(a; args...) return TauII / η * 0.5 end # function to compute deviatoric stress (compulsory) @inline function custom_τII(a::CustomRheology, EpsII; args...) η = custom_viscosity(a; args...) return 2.0 * η * EpsII end # helper function (optional) @inline function custom_viscosity(a::CustomRheology; P=0.0, T=273.0, depth=0.0, kwargs...) (; η0, Ea, Va, T0, R, cutoff) = a.args η = η0 * exp((Ea + P * Va) / (R * T) - Ea / (R * T0)) correction = (depth ≤ 660e3) + (2740e3 ≥ depth > 660e3) * 1e1 + (depth > 2700e3) * 1e-1 η = clamp(η * correction, cutoff...) end # HELPER FUNCTIONS --------------------------------------------------------------- import ParallelStencil.INDICES const idx_j = INDICES[2] macro all_j(A) esc(:($A[$idx_j])) end @parallel function init_P!(P, ρg, z) @all(P) = @all(ρg) * abs(@all_j(z)) return nothing end # Half-space-cooling model @parallel_indices (i, j) function init_T!(T, z, κ, Tm, Tp, Tmin, Tmax) yr = 3600*24*365.25 dTdz = (Tm-Tp)/2890e3 zᵢ = abs(z[j]) Tᵢ = Tp + dTdz*(zᵢ) time = 100e6 * yr Ths = Tmin + (Tm -Tmin) * erf((zᵢ)*0.5/(κ*time)^0.5) T[i, j] = min(Tᵢ, Ths) return end function circular_perturbation!(T, δT, xc, yc, r, xvi) @parallel_indices (i, j) function _circular_perturbation!(T, δT, xc, yc, r, x, y) @inbounds if (((x[i] - xc))^2 + ((y[j] - yc))^2) ≤ r^2 T[i, j] *= δT / 100 + 1 end return nothing end @parallel _circular_perturbation!(T, δT, xc, yc, r, xvi...) end function random_perturbation!(T, δT, xbox, ybox, xvi) @parallel_indices (i, j) function _random_perturbation!(T, δT, xbox, ybox, x, y) @inbounds if (xbox[1] ≤ x[i] ≤ xbox[2]) && (abs(ybox[1]) ≤ abs(y[j]) ≤ abs(ybox[2])) δTi = δT * (rand() - 0.5) # random perturbation within ±δT [%] T[i, j] *= δTi / 100 + 1 end return nothing end @parallel (@idx size(T)) _random_perturbation!(T, δT, xbox, ybox, xvi...) end # -------------------------------------------------------------------------------- # BEGIN MAIN SCRIPT # -------------------------------------------------------------------------------- function thermal_convection2D(igg; ar=8, ny=16, nx=ny*8, figdir="figs2D", thermal_perturbation = :circular) # Physical domain ------------------------------------ ly = 2890e3 lx = ly * ar origin = 0.0, -ly # origin coordinates ni = nx, ny # number of cells li = lx, ly # domain length in x- and y- di = @. li / (nx_g(), ny_g()) # grid step in x- and -y grid = Geometry(ni, li; origin = origin) (; xci, xvi) = grid # nodes at the center and vertices of the cells # ---------------------------------------------------- # Weno model ----------------------------------------- weno = WENO5(ni = ni .+ 1, method = Val(2)) # ni.+1 for Temp # ---------------------------------------------------- # create rheology struct v_args = (; η0=5e20, Ea=200e3, Va=2.6e-6, T0=1.6e3, R=8.3145, cutoff=(1e16, 1e25)) creep = CustomRheology(custom_εII, custom_τII, v_args) # Physical properties using GeoParams ---------------- η_reg = 1e16 G0 = 70e9 # shear modulus cohesion = 30e6 friction = asind(0.01) pl = DruckerPrager_regularised(; C = cohesion, ϕ=friction, η_vp=η_reg, Ψ=0.0) # non-regularized plasticity el = SetConstantElasticity(; G=G0, ν=0.5) # elastic spring β = inv(get_Kb(el)) rheology = SetMaterialParams(; Name = "Mantle", Phase = 1, Density = PT_Density(; ρ0=3.1e3, β=β, T0=0.0, α = 1.5e-5), HeatCapacity = ConstantHeatCapacity(; Cp=1.2e3), Conductivity = ConstantConductivity(; k=3.0), CompositeRheology = CompositeRheology((creep, el, )), Elasticity = el, Gravity = ConstantGravity(; g=9.81), ) rheology_plastic = SetMaterialParams(; Name = "Mantle", Phase = 1, Density = PT_Density(; ρ0=3.5e3, β=β, T0=0.0, α = 1.5e-5), HeatCapacity = ConstantHeatCapacity(; Cp=1.2e3), Conductivity = ConstantConductivity(; k=3.0), CompositeRheology = CompositeRheology((creep, el, pl)), Elasticity = el, Gravity = ConstantGravity(; g=9.81), ) # heat diffusivity κ = (rheology.Conductivity[1].k / (rheology.HeatCapacity[1].Cp * rheology.Density[1].ρ0)).val dt = dt_diff = 0.5 * min(di...)^2 / κ / 2.01 # diffusive CFL timestep limiter # ---------------------------------------------------- # TEMPERATURE PROFILE -------------------------------- thermal = ThermalArrays(backend, ni) thermal_bc = TemperatureBoundaryConditions(; no_flux = (left = true, right = true, top = false, bot = false), ) # initialize thermal profile - Half space cooling adiabat = 0.3 # adiabatic gradient Tp = 1900 Tm = Tp + adiabat * 2890 Tmin, Tmax = 300.0, 3.5e3 @parallel init_T!(thermal.T, xvi[2], κ, Tm, Tp, Tmin, Tmax) thermal_bcs!(thermal, thermal_bc) # Temperature anomaly if thermal_perturbation == :random δT = 5.0 # thermal perturbation (in %) random_perturbation!(thermal.T, δT, (lx*1/8, lx*7/8), (-2000e3, -2600e3), xvi) elseif thermal_perturbation == :circular δT = 10.0 # thermal perturbation (in %) xc, yc = 0.5*lx, -0.75*ly # center of the thermal anomaly r = 150e3 # radius of perturbation circular_perturbation!(thermal.T, δT, xc, yc, r, xvi) end @views thermal.T[:, 1] .= Tmax @views thermal.T[:, end] .= Tmin update_halo!(thermal.T) temperature2center!(thermal) # ---------------------------------------------------- # STOKES --------------------------------------------- # Allocate arrays needed for every Stokes problem stokes = StokesArrays(backend, ni) pt_stokes = PTStokesCoeffs(li, di; ϵ=1e-4, CFL = 0.8 / √2.1) # Buoyancy forces args = (; T = thermal.Tc, P = stokes.P, dt = Inf) ρg = @zeros(ni...), @zeros(ni...) for _ in 1:1 compute_ρg!(ρg[2], rheology, args) @parallel init_P!(stokes.P, ρg[2], xci[2]) end # Rheology viscosity_cutoff = (1e16, 1e24) compute_viscosity!(stokes, args, rheology, viscosity_cutoff) # PT coefficients for thermal diffusion pt_thermal = PTThermalCoeffs( backend, rheology, args, dt, ni, di, li; ϵ=1e-5, CFL=1e-3 / √2.1 ) # Boundary conditions flow_bcs = VelocityBoundaryConditions(; free_slip = (left = true , right = true , top = true , bot = true), ) flow_bcs!(stokes, flow_bcs) # apply boundary conditions update_halo!(@velocity(stokes)...) # ---------------------------------------------------- # IO ------------------------------------------------- # if it does not exist, make folder where figures are stored take(figdir) # ---------------------------------------------------- # WENO arrays T_WENO = @zeros(ni.+1) Vx_v = @zeros(ni.+1...) Vy_v = @zeros(ni.+1...) # Time loop t, it = 0.0, 0 local iters igg.me == 0 && println("Starting model") while (t / (1e6 * 3600 * 24 * 365.25)) < 4.5e3 # Update buoyancy and viscosity - args = (; T = thermal.Tc, P = stokes.P, dt=Inf) compute_ρg!(ρg[end], rheology, (T=thermal.Tc, P=stokes.P)) compute_viscosity!( stokes, args, rheology, viscosity_cutoff ) # ------------------------------ igg.me == 0 && println("Starting stokes solver...") iters = solve!( stokes, pt_stokes, di, flow_bcs, ρg, rheology, args, dt, igg; kwargs = (; iterMax = 150e3, nout = 1e3, viscosity_cutoff = viscosity_cutoff ) ); dt = compute_dt(stokes, di, dt_diff, igg) println("Rank $(igg.me) ...stokes solver finished") # ------------------------------ # Thermal solver --------------- igg.me == 0 && println("Starting thermal solver...") heatdiffusion_PT!( thermal, pt_thermal, thermal_bc, rheology, args, dt, di; kwargs = ( igg = igg, iterMax = 10e3, nout = 1e2, verbose = true ), ) igg.me == 0 && println("...thermal solver finished") # Weno advection T_WENO .= @views thermal.T[2:end-1, :] velocity2vertex!(Vx_v, Vy_v, @velocity(stokes)...) WENO_advection!(T_WENO, (Vx_v, Vy_v), weno, di, dt) @views thermal.T[2:end-1, :] .= T_WENO # ------------------------------ it += 1 t += dt println("\n") println("Time step number $it") println(" time = $(t/(1e6 * 3600 * 24 *365.25)) Myrs, dt = $(dt/(1e6 * 3600 * 24 *365.25)) Myrs") println("\n") # Plotting --------------------- if it == 1 || rem(it, 10) == 0 fig = Figure(size = (1000, 1000), title = "t = $t") ax1 = Axis(fig[1,1], aspect = ar, title = "T [K] (t=$(t/(1e6 * 3600 * 24 *365.25)) Myrs)") ax2 = Axis(fig[2,1], aspect = ar, title = "Vy [m/s]") ax3 = Axis(fig[3,1], aspect = ar, title = "τII [MPa]") ax4 = Axis(fig[4,1], aspect = ar, title = "log10(η)") h1 = heatmap!(ax1, xvi[1].*1e-3, xvi[2].*1e-3, Array(thermal.T) , colormap=:batlow) h2 = heatmap!(ax2, xci[1].*1e-3, xvi[2].*1e-3, Array(stokes.V.Vy[2:end-1,:]) , colormap=:batlow) h3 = heatmap!(ax3, xci[1].*1e-3, xci[2].*1e-3, Array(stokes.τ.II.*1e-6) , colormap=:batlow) h4 = heatmap!(ax4, xci[1].*1e-3, xci[2].*1e-3, Array(log10.(η_vep)) , colormap=:batlow) hidexdecorations!(ax1) hidexdecorations!(ax2) hidexdecorations!(ax3) Colorbar(fig[1,2], h1, height=100) Colorbar(fig[2,2], h2, height=100) Colorbar(fig[3,2], h3, height=100) Colorbar(fig[4,2], h4, height=100) save( joinpath(figdir, "$(it).png"), fig) fig end # ------------------------------ end finalize_global_grid() return nothing end figdir = "figs2D_test_weno" ar = 8 # aspect ratio n = 32 nx = n*ar - 2 ny = n - 2 thermal_perturbation = :circular igg = if !(JustRelax.MPI.Initialized()) # initialize (or not) MPI grid IGG(init_global_grid(nx, ny, 1; init_MPI= true, select_device=false)...) else igg end thermal_convection2D(igg; figdir=figdir, ar=ar,nx=nx, ny=ny, thermal_perturbation=thermal_perturbation);
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
11785
using JustRelax, JustRelax.JustRelax3D, JustRelax.DataIO import JustRelax.@cell const backend_JR = CPUBackend using ParallelStencil @init_parallel_stencil(Threads, Float64, 3) #or (CUDA, Float64, 3) or (AMDGPU, Float64, 3) using Printf, LinearAlgebra, GeoParams, GLMakie, SpecialFunctions # function to compute strain rate (compulsory) @inline function custom_εII(a::CustomRheology, TauII; args...) η = custom_viscosity(a; args...) return TauII / η * 0.5 end # function to compute deviatoric stress (compulsory) @inline function custom_τII(a::CustomRheology, EpsII; args...) η = custom_viscosity(a; args...) return 2.0 * η * EpsII end # helper function (optional) @inline function custom_viscosity(a::CustomRheology; P=0.0, T=273.0, depth=0.0, kwargs...) (; η0, Ea, Va, T0, R, cutoff) = a.args η = η0 * exp((Ea + P * Va) / (R * T) - Ea / (R * T0)) correction = (depth ≤ 660e3) + (2740e3 ≥ depth > 660e3) * 1e1 + (depth > 2700e3) * 1e-1 η = clamp(η * correction, cutoff...) end # HELPER FUNCTIONS --------------------------------------------------------------- const idx_k = ParallelStencil.INDICES[3] macro all_k(A) esc(:($A[$idx_k])) end @parallel function init_P!(P, ρg, z) @all(P) = @all(ρg)*abs(@all_k(z)) return nothing end # Half-space-cooling model @parallel_indices (i, j, k) function init_T!(T, z, κ, Tm, Tp, Tmin, Tmax) yr = 3600*24*365.25 dTdz = (Tm-Tp)/2890e3 zᵢ = abs(z[k]) Tᵢ = Tp + dTdz*(zᵢ) time = 100e6 * yr Ths = Tmin + (Tm -Tmin) * erf((zᵢ)*0.5/(κ*time)^0.5) T[i, j, k] = min(Tᵢ, Ths) return end function elliptical_perturbation!(T, δT, xc, yc, zc, r, xvi) @parallel_indices (i, j, k) function _elliptical_perturbation!(T, δT, xc, yc, zc, r, x, y, z) @inbounds if ((x[i]-xc )^2 + (y[j] - yc)^2 + (z[k] - zc))^2 ≤ r^2 T[i, j, k] *= δT/100 + 1 end return nothing end @parallel _elliptical_perturbation!(T, δT, xc, yc, zc, r, xvi...) end function random_perturbation!(T, δT, xbox, ybox, zbox, xvi) @parallel_indices (i, j, k) function _random_perturbation!(T, δT, xbox, ybox, zbox, x, y, z) inbox = (xbox[1] ≤ x[i] ≤ xbox[2]) && (ybox[1] ≤ y[j] ≤ ybox[2]) && (abs(zbox[1]) ≤ abs(z[k]) ≤ abs(zbox[2])) @inbounds if inbox δTi = δT * (rand() - 0.5) # random perturbation within ±δT [%] T[i, j, k] *= δTi / 100 + 1 end return nothing end @parallel (@idx size(T)) _random_perturbation!(T, δT, xbox, ybox, zbox, xvi...) end Rayleigh_number(ρ, α, ΔT, κ, η0) = ρ * 9.81 * α * ΔT * 2890e3^3 * inv(κ * η0) function thermal_convection3D(; ar=8, nz=16, nx=ny*8, ny=nx, figdir="figs3D", thermal_perturbation = :random) # initialize MPI igg = IGG(init_global_grid(nx, ny, nz; init_MPI = JustRelax.MPI.Initialized() ? false : true)...) # Physical domain ------------------------------------ lz = 2890e3 lx = ly = lz * ar origin = 0.0, 0.0, -lz # origin coordinates ni = nx, ny, nz # number of cells li = lx, ly, lz # domain length in x- and y- di = @. li / (nx_g(), ny_g(), nz_g()) # grid step in x- and -y grid = Geometry(ni, li; origin = origin) (; xci, xvi) = grid # nodes at the center and vertices of the cells # ---------------------------------------------------- # create rheology struct v_args = (; η0=5e20, Ea=200e3, Va=2.6e-6, T0=1.6e3, R=8.3145, cutoff=(1e16, 1e25)) creep = CustomRheology(custom_εII, custom_τII, v_args) # Physical properties using GeoParams ---------------- η_reg = 1e18 G0 = 70e9 # shear modulus cohesion = 30e6 friction = asind(0.01) pl = DruckerPrager_regularised(; C = cohesion, ϕ=friction, η_vp=η_reg, Ψ=0.0) # non-regularized plasticity el = SetConstantElasticity(; G=G0, ν=0.5) # elastic spring β = inv(get_Kb(el)) # Define rheolgy struct rheology = SetMaterialParams(; Name = "Mantle", Phase = 1, Density = PT_Density(; ρ0=3.1e3, β=β, T0=0.0, α = 1.5e-5), HeatCapacity = ConstantHeatCapacity(; Cp=1.2e3), Conductivity = ConstantConductivity(; k=3.0), CompositeRheology = CompositeRheology((creep, el, )), Elasticity = el, Gravity = ConstantGravity(; g=9.81), ) rheology_depth = SetMaterialParams(; Name = "Mantle", Phase = 1, Density = PT_Density(; ρ0=3.5e3, β=β, T0=0.0, α = 1.5e-5), HeatCapacity = ConstantHeatCapacity(; Cp=1.2e3), Conductivity = ConstantConductivity(; k=3.0), CompositeRheology = CompositeRheology((creep, el, pl)), Elasticity = el, Gravity = ConstantGravity(; g=9.81), ) # heat diffusivity κ = (rheology.Conductivity[1].k / (rheology.HeatCapacity[1].Cp * rheology.Density[1].ρ0)).val dt = dt_diff = min(di...)^2 / κ / 3.01 # diffusive CFL timestep limiter # ---------------------------------------------------- # TEMPERATURE PROFILE -------------------------------- thermal = ThermalArrays(backend, ni) thermal_bc = TemperatureBoundaryConditions(; no_flux = (left = true, right = true, top = false, bot = false, front=true, back=true), ) # initialize thermal profile - Half space cooling adiabat = 0.3 # adiabatic gradient Tp = 1900 Tm = Tp + adiabat * 2890 Tmin, Tmax = 300.0, 3.5e3 # thermal.T .= 1600.0 @parallel init_T!(thermal.T, xvi[3], κ, Tm, Tp, Tmin, Tmax) thermal_bcs!(thermal, thermal_bc) # Elliptical temperature anomaly if thermal_perturbation == :random δT = 5.0 # thermal perturbation (in %) random_perturbation!(thermal.T, δT, (lx*1/8, lx*7/8), (ly*1/8, ly*7/8), (-2000e3, -2600e3), xvi) elseif thermal_perturbation == :circular δT = 15.0 # thermal perturbation (in %) xc, yc, zc = 0.5*lx, 0.5*ly, -0.75*lz # origin of thermal anomaly r = 150e3 # radius of perturbation elliptical_perturbation!(thermal.T, δT, xc, yc, zc, r, xvi) end @views thermal.T[:, :, 1] .= Tmax @views thermal.T[:, :, end] .= Tmin temperature2center!(thermal) # ---------------------------------------------------- # STOKES --------------------------------------------- # Allocate arrays needed for every Stokes problem stokes = StokesArrays(backend, ni) pt_stokes = PTStokesCoeffs(li, di; ϵ=1e-4, CFL = 1.0 / √3.1) # Buoyancy forces ρg = @zeros(ni...), @zeros(ni...), @zeros(ni...) for _ in 1:2 compute_ρg!(ρg[3], rheology, (T=thermal.Tc, P=stokes.P)) @parallel init_P!(stokes.P, ρg[3], xci[3]) end # Rheology args = (; T = thermal.Tc, P = stokes.P, depth = depth, dt = Inf) compute_viscosity!(stokes, args, rheology, (1e18, 1e24)) # Boundary conditions flow_bcs = VelocityBoundaryConditions(; free_slip = (left=true , right=true , top=true , bot=true , front=true , back=true ), no_slip = (left=false, right=false, top=false, bot=false, front=false, back=false), ) flow_bcs!(stokes, flow_bcs) # apply boundary conditions update_halo!(@velocity(stokes)...) # ---------------------------------------------------- # IO ------------------------------------------------- # if it does not exist, make folder where figures are stored !isdir(figdir) && mkpath(figdir) # creata Paraview .vtu file for time series collections data_series = VTKDataSeries(joinpath(figdir, "full_simulation"), xci) # ---------------------------------------------------- # Plot initial T and η profiles fig0 = let Zv = [z for x in xvi[1], y in xvi[2], z in xvi[3]][:] Z = [z for x in xci[1], y in xci[2], z in xci[3]][:] fig = Figure(size = (1200, 900)) ax1 = Axis(fig[1,1], aspect = 2/3, title = "T") ax2 = Axis(fig[1,2], aspect = 2/3, title = "log10(η)") scatter!(ax1, Array(thermal.T[:]), Zv./1e3) scatter!(ax2, Array(log10.(stokes.viscosity.η[:])), Z./1e3 ) ylims!(ax1, minimum(xvi[3])./1e3, 0) ylims!(ax2, minimum(xvi[3])./1e3, 0) hideydecorations!(ax2) save(joinpath(figdir, "initial_profile.png"), fig) fig end # Time loop t, it = 0.0, 0 local iters while (t / (1e6 * 3600 * 24 * 365.25)) < 4.5e3 # Update arguments needed to compute several physical properties # e.g. density, viscosity, etc - args = (; T=thermal.Tc, P=stokes.P, depth=depth, dt=Inf) # Stokes solver ---------------- solve!( stokes, pt_stokes, di, flow_bcs, ρg, rheology, args, Inf, igg; kwargs = (; iterMax=150e3, nout=2e3, ) ); println("starting non linear iterations") dt = compute_dt(stokes, di, dt_diff, igg) # ------------------------------ # Thermal solver --------------- solve!( thermal, thermal_bc, stokes, rheology, args, di, dt ) # ------------------------------ it += 1 t += dt println("\n") println("Time step number $it") println(" time = $(t/(1e6 * 3600 * 24 *365.25)) Myrs, dt = $(dt/(1e6 * 3600 * 24 *365.25)) Myrs") println("\n") # Plotting --------------------- if it == 1 || rem(it, 5) == 0 slice_j = Int(ny ÷ 2) fig = Figure(size = (1000, 1000), title = "t = $t") ax1 = Axis(fig[1,1], aspect = ar, title = "T [K] (t=$(t/(1e6 * 3600 * 24 *365.25)) Myrs)") ax2 = Axis(fig[2,1], aspect = ar, title = "Vz [m/s]") ax3 = Axis(fig[3,1], aspect = ar, title = "τII [MPa]") ax4 = Axis(fig[4,1], aspect = ar, title = "log10(η)") h1 = heatmap!(ax1, xvi[1].*1e-3, xvi[3].*1e-3, Array(thermal.T[:,slice_j,:]) , colormap=:batlow) h2 = heatmap!(ax2, xci[1].*1e-3, xvi[3].*1e-3, Array(stokes.V.Vz[:,slice_j,:]) , colormap=:batlow) h3 = heatmap!(ax3, xci[1].*1e-3, xci[3].*1e-3, Array(stokes.τ.II[:,slice_j,:].*1e-6) , colormap=:batlow) h4 = heatmap!(ax4, xci[1].*1e-3, xci[3].*1e-3, Array(log10.(stokes.viscosity.η_vep[:,slice_j,:])) , colormap=:batlow) hidexdecorations!(ax1) hidexdecorations!(ax2) hidexdecorations!(ax3) Colorbar(fig[1,2], h1) Colorbar(fig[2,2], h2) Colorbar(fig[3,2], h3) Colorbar(fig[4,2], h4) fig save(joinpath(figdir, "$(it).png"), fig) # save vtk time series data_c = (; Temperature = Array(thermal.Tc), TauII = Array(stokes.τ.II), Density=Array(ρg[3]./9.81)) JustRelax.DataIO.append!(data_series, data_c, it, t) end # ------------------------------ end return (ni=ni, xci=xci, li=li, di=di), thermal end figdir = "figs3D_test" ar = 3 # aspect ratio n = 32 nx = n*ar - 2 ny = nx nz = n - 2 thermal_convection3D(; figdir=figdir, ar=ar,nx=nx, ny=ny, nz=nz);
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
14105
using JustRelax, JustRelax.JustRelax2D, JustRelax.DataIO import JustRelax.@cell const backend_JR = CPUBackend using ParallelStencil, ParallelStencil.FiniteDifferences2D @init_parallel_stencil(Threads, Float64, 2) #or (CUDA, Float64, 2) or (AMDGPU, Float64, 2) using JustPIC, JustPIC._2D # Threads is the default backend, # to run on a CUDA GPU load CUDA.jl (i.e. "using CUDA") at the beginning of the script, # and to run on an AMD GPU load AMDGPU.jl (i.e. "using AMDGPU") at the beginning of the script. const backend = CPUBackend # Options: CPUBackend, CUDABackend, AMDGPUBackend # Load script dependencies using GeoParams, GLMakie # Load file with all the rheology configurations include("Layered_rheology.jl") ## SET OF HELPER FUNCTIONS PARTICULAR FOR THIS SCRIPT -------------------------------- function copyinn_x!(A, B) @parallel function f_x(A, B) @all(A) = @inn_x(B) return nothing end @parallel f_x(A, B) end import ParallelStencil.INDICES const idx_j = INDICES[2] macro all_j(A) esc(:($A[$idx_j])) end # Initial pressure profile - not accurate @parallel function init_P!(P, ρg, z) @all(P) = abs(@all(ρg) * @all_j(z)) * <(@all_j(z), 0.0) return nothing end # Initial thermal profile @parallel_indices (i, j) function init_T!(T, y, thick_air) depth = -y[j] - thick_air # (depth - 15e3) because we have 15km of sticky air if depth < 0e0 T[i + 1, j] = 273e0 elseif 0e0 ≤ (depth) < 35e3 dTdZ = (923-273)/35e3 offset = 273e0 T[i + 1, j] = (depth) * dTdZ + offset elseif 110e3 > (depth) ≥ 35e3 dTdZ = (1492-923)/75e3 offset = 923 T[i + 1, j] = (depth - 35e3) * dTdZ + offset elseif (depth) ≥ 110e3 dTdZ = (1837 - 1492)/590e3 offset = 1492e0 T[i + 1, j] = (depth - 110e3) * dTdZ + offset end return nothing end # Thermal rectangular perturbation function rectangular_perturbation!(T, xc, yc, r, xvi, thick_air) @parallel_indices (i, j) function _rectangular_perturbation!(T, xc, yc, r, x, y) @inbounds if ((x[i]-xc)^2 ≤ r^2) && ((y[j] - yc - thick_air)^2 ≤ r^2) depth = -y[j] - thick_air dTdZ = (2047 - 2017) / 50e3 offset = 2017 T[i + 1, j] = (depth - 585e3) * dTdZ + offset end return nothing end ni = length.(xvi) @parallel (@idx ni) _rectangular_perturbation!(T, xc, yc, r, xvi...) return nothing end ## END OF HELPER FUNCTION ------------------------------------------------------------ ## BEGIN OF MAIN SCRIPT -------------------------------------------------------------- function main2D(igg; ar=8, ny=16, nx=ny*8, figdir="figs2D", do_vtk =false) # Physical domain ------------------------------------ thick_air = 0 # thickness of sticky air layer ly = 700e3 + thick_air # domain length in y lx = ly * ar # domain length in x ni = nx, ny # number of cells li = lx, ly # domain length in x- and y- di = @. li / ni # grid step in x- and -y origin = 0.0, -ly # origin coordinates (15km f sticky air layer) grid = Geometry(ni, li; origin = origin) (; xci, xvi) = grid # nodes at the center and vertices of the cells # ---------------------------------------------------- # Physical properties using GeoParams ---------------- rheology = init_rheologies(; is_plastic = true) κ = (4 / (rheology[4].HeatCapacity[1].Cp * rheology[4].Density[1].ρ0)) dt = dt_diff = 0.5 * min(di...)^2 / κ / 2.01 # diffusive CFL timestep limiter # ---------------------------------------------------- # Initialize particles ------------------------------- nxcell, max_xcell, min_xcell = 25, 30, 12 particles = init_particles( backend, nxcell, max_xcell, min_xcell, xvi... ) subgrid_arrays = SubgridDiffusionCellArrays(particles) # velocity grids grid_vx, grid_vy = velocity_grids(xci, xvi, di) # temperature pT, pPhases = init_cell_arrays(particles, Val(2)) particle_args = (pT, pPhases) # Elliptical temperature anomaly xc_anomaly = lx/2 # origin of thermal anomaly yc_anomaly = -610e3 # origin of thermal anomaly r_anomaly = 25e3 # radius of perturbation phase_ratios = PhaseRatio(backend_JR, ni, length(rheology)) init_phases!(pPhases, particles, lx, yc_anomaly, r_anomaly, thick_air) phase_ratios_center!(phase_ratios, particles, grid, pPhases) # ---------------------------------------------------- # STOKES --------------------------------------------- # Allocate arrays needed for every Stokes problem stokes = StokesArrays(backend_JR, ni) pt_stokes = PTStokesCoeffs(li, di; ϵ=1e-4, CFL = 0.75 / √2.1) # ---------------------------------------------------- # TEMPERATURE PROFILE -------------------------------- thermal = ThermalArrays(backend_JR, ni) thermal_bc = TemperatureBoundaryConditions(; no_flux = (left = true, right = true, top = false, bot = false), ) # initialize thermal profile - Half space cooling @parallel (@idx ni .+ 1) init_T!(thermal.T, xvi[2], thick_air) thermal_bcs!(thermal, thermal_bc) Tbot = thermal.T[1, 1] rectangular_perturbation!(thermal.T, xc_anomaly, yc_anomaly, r_anomaly, xvi, thick_air) temperature2center!(thermal) # ---------------------------------------------------- # Buoyancy forces args = (; T = thermal.Tc, P = stokes.P, dt = Inf) ρg = @zeros(ni...), @zeros(ni...) for _ in 1:1 compute_ρg!(ρg[2], phase_ratios, rheology, args) @parallel init_P!(stokes.P, ρg[2], xci[2]) end # Rheology viscosity_cutoff = (1e16, 1e24) compute_viscosity!(stokes, phase_ratios, args, rheology, viscosity_cutoff) (; η, η_vep) = stokes.viscosity # PT coefficients for thermal diffusion pt_thermal = PTThermalCoeffs( backend_JR, rheology, phase_ratios, args, dt, ni, di, li; ϵ=1e-5, CFL= 1e-2 / √2.1 ) # Boundary conditions flow_bcs = VelocityBoundaryConditions(; free_slip = (left = true, right=true, top=true, bot=true), ) flow_bcs!(stokes, flow_bcs) # apply boundary conditions update_halo!(@velocity(stokes)...) # IO ----- ------------------------------------------- # if it does not exist, make folder where figures are stored if do_vtk vtk_dir = joinpath(figdir,"vtk") take(vtk_dir) end take(figdir) # ---------------------------------------------------- # Plot initial T and η profiles let Yv = [y for x in xvi[1], y in xvi[2]][:] Y = [y for x in xci[1], y in xci[2]][:] fig = Figure(size = (1200, 900)) ax1 = Axis(fig[1,1], aspect = 2/3, title = "T") ax2 = Axis(fig[1,2], aspect = 2/3, title = "log10(η)") scatter!(ax1, Array(thermal.T[2:end-1,:][:]), Yv./1e3) scatter!(ax2, Array(log10.(stokes.viscosity.η[:])), Y./1e3) ylims!(ax1, minimum(xvi[2])./1e3, 0) ylims!(ax2, minimum(xvi[2])./1e3, 0) hideydecorations!(ax2) save(joinpath(figdir, "initial_profile.png"), fig) fig end T_buffer = @zeros(ni.+1) Told_buffer = similar(T_buffer) dt₀ = similar(stokes.P) for (dst, src) in zip((T_buffer, Told_buffer), (thermal.T, thermal.Told)) copyinn_x!(dst, src) end grid2particle!(pT, xvi, T_buffer, particles) local Vx_v, Vy_v if do_vtk Vx_v = @zeros(ni.+1...) Vy_v = @zeros(ni.+1...) end # Time loop t, it = 0.0, 0 while (t/(1e6 * 3600 * 24 *365.25)) < 5 # run only for 5 Myrs # interpolate fields from particle to grid vertices particle2grid!(T_buffer, pT, xvi, particles) @views T_buffer[:, end] .= 273.0 @views T_buffer[:, 1] .= Tbot @views thermal.T[2:end-1, :] .= T_buffer temperature2center!(thermal) # Update buoyancy and viscosity - args = (; T = thermal.Tc, P = stokes.P, dt=Inf) compute_ρg!(ρg[end], phase_ratios, rheology, (T=thermal.Tc, P=stokes.P)) compute_viscosity!( stokes, phase_ratios, args, rheology, viscosity_cutoff ) # ------------------------------ # Stokes solver ---------------- solve!( stokes, pt_stokes, di, flow_bcs, ρg, phase_ratios, rheology, args, Inf, igg; kwargs = (; iterMax = 150e3, nout = 1e3, viscosity_cutoff = viscosity_cutoff ) ) tensor_invariant!(stokes.ε) dt = compute_dt(stokes, di, dt_diff) # ------------------------------ # Thermal solver --------------- heatdiffusion_PT!( thermal, pt_thermal, thermal_bc, rheology, args, dt, di; kwargs = ( igg = igg, phase = phase_ratios, iterMax = 10e3, nout = 1e2, verbose = true ), ) for (dst, src) in zip((T_buffer, Told_buffer), (thermal.T, thermal.Told)) copyinn_x!(dst, src) end subgrid_characteristic_time!( subgrid_arrays, particles, dt₀, phase_ratios, rheology, thermal, stokes, xci, di ) centroid2particle!(subgrid_arrays.dt₀, xci, dt₀, particles) subgrid_diffusion!( pT, T_buffer, thermal.ΔT[2:end-1, :], subgrid_arrays, particles, xvi, di, dt ) # ------------------------------ # Advection -------------------- # advect particles in space advection!(particles, RungeKutta2(), @velocity(stokes), (grid_vx, grid_vy), dt) # advect particles in memory move_particles!(particles, xvi, particle_args) # check if we need to inject particles inject_particles_phase!(particles, pPhases, (pT, ), (T_buffer,), xvi) # update phase ratios phase_ratios_center!(phase_ratios, particles, grid, pPhases) @show it += 1 t += dt # Data I/O and plotting --------------------- if it == 1 || rem(it, 1) == 0 checkpointing_hdf5(figdir, stokes, thermal.T, t, dt) if do_vtk JustRelax.velocity2vertex!(Vx_v, Vy_v, @velocity(stokes)...) data_v = (; T = Array(thermal.T[2:end-1, :]), τxy = Array(stokes.τ.xy), εxy = Array(stokes.ε.xy), Vx = Array(Vx_v), Vy = Array(Vy_v), ) data_c = (; P = Array(stokes.P), τxx = Array(stokes.τ.xx), τyy = Array(stokes.τ.yy), εxx = Array(stokes.ε.xx), εyy = Array(stokes.ε.yy), η = Array(stokes.viscosity.η_vep), ) velocity_v = ( Array(Vx_v), Array(Vy_v), ) save_vtk( joinpath(vtk_dir, "vtk_" * lpad("$it", 6, "0")), xvi, xci, data_v, data_c, velocity_v ) end # Make particles plottable p = particles.coords ppx, ppy = p pxv = ppx.data[:]./1e3 pyv = ppy.data[:]./1e3 clr = pPhases.data[:] clr = pT.data[:] idxv = particles.index.data[:]; # Make Makie figure fig = Figure(size = (900, 900), title = "t = $t") ax1 = Axis(fig[1,1], aspect = ar, title = "T [K] (t=$(t/(1e6 * 3600 * 24 *365.25)) Myrs)") ax2 = Axis(fig[2,1], aspect = ar, title = "Vy [m/s]") ax3 = Axis(fig[1,3], aspect = ar, title = "log10(εII)") ax4 = Axis(fig[2,3], aspect = ar, title = "log10(η)") # Plot temperature h1 = heatmap!(ax1, xvi[1].*1e-3, xvi[2].*1e-3, Array(thermal.T[2:end-1,:]) , colormap=:batlow) # Plot particles phase h2 = scatter!(ax2, Array(pxv[idxv]), Array(pyv[idxv]), color=Array(clr[idxv])) # Plot 2nd invariant of strain rate h3 = heatmap!(ax3, xci[1].*1e-3, xci[2].*1e-3, Array(log10.(stokes.ε.II)) , colormap=:batlow) # Plot effective viscosity h4 = heatmap!(ax4, xci[1].*1e-3, xci[2].*1e-3, Array(log10.(stokes.viscosity.η_vep)) , colormap=:batlow) hidexdecorations!(ax1) hidexdecorations!(ax2) hidexdecorations!(ax3) Colorbar(fig[1,2], h1) Colorbar(fig[2,2], h2) Colorbar(fig[1,4], h3) Colorbar(fig[2,4], h4) linkaxes!(ax1, ax2, ax3, ax4) save(joinpath(figdir, "$(it).png"), fig) fig end # ------------------------------ end return nothing end ## END OF MAIN SCRIPT ---------------------------------------------------------------- # (Path)/folder where output data and figures are stored figdir = "Plume2D" do_vtk = false # set to true to generate VTK files for ParaView ar = 1 # aspect ratio n = 128 nx = n*ar - 2 ny = n - 2 igg = if !(JustRelax.MPI.Initialized()) # initialize (or not) MPI grid IGG(init_global_grid(nx, ny, 1; init_MPI= true)...) else igg end # run main script main2D(igg; figdir = figdir, ar = ar, nx = nx, ny = ny, do_vtk = do_vtk);
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
6548
# from "Fingerprinting secondary mantle plumes", Cloetingh et al. 2022 function init_rheologies(; is_plastic = true) # Dislocation and Diffusion creep disl_upper_crust = DislocationCreep(A=5.07e-18, n=2.3, E=154e3, V=6e-6, r=0.0, R=8.3145) disl_lower_crust = DislocationCreep(A=2.08e-23, n=3.2, E=238e3, V=6e-6, r=0.0, R=8.3145) disl_lithospheric_mantle = DislocationCreep(A=2.51e-17, n=3.5, E=530e3, V=6e-6, r=0.0, R=8.3145) disl_sublithospheric_mantle = DislocationCreep(A=2.51e-17, n=3.5, E=530e3, V=6e-6, r=0.0, R=8.3145) diff_lithospheric_mantle = DiffusionCreep(A=2.51e-17, n=1.0, E=530e3, V=6e-6, p=0, r=0.0, R=8.3145) diff_sublithospheric_mantle = DiffusionCreep(A=2.51e-17, n=1.0, E=530e3, V=6e-6, p=0, r=0.0, R=8.3145) # Elasticity el_upper_crust = SetConstantElasticity(; G=25e9, ν=0.5) el_lower_crust = SetConstantElasticity(; G=25e9, ν=0.5) el_lithospheric_mantle = SetConstantElasticity(; G=67e9, ν=0.5) el_sublithospheric_mantle = SetConstantElasticity(; G=67e9, ν=0.5) β_upper_crust = inv(get_Kb(el_upper_crust)) β_lower_crust = inv(get_Kb(el_lower_crust)) β_lithospheric_mantle = inv(get_Kb(el_lithospheric_mantle)) β_sublithospheric_mantle = inv(get_Kb(el_sublithospheric_mantle)) # Physical properties using GeoParams ---------------- η_reg = 1e16 cohesion = 3e6 friction = asind(0.2) pl_crust = if is_plastic DruckerPrager_regularised(; C = cohesion, ϕ=friction, η_vp=η_reg, Ψ=0.0) # non-regularized plasticity else DruckerPrager_regularised(; C = Inf, ϕ=friction, η_vp=η_reg, Ψ=0.0) # non-regularized plasticity end friction = asind(0.3) pl = if is_plastic DruckerPrager_regularised(; C = cohesion, ϕ=friction, η_vp=η_reg, Ψ=0.0) # non-regularized plasticity else DruckerPrager_regularised(; C = Inf, ϕ=friction, η_vp=η_reg, Ψ=0.0) # non-regularized plasticity end pl_wz = if is_plastic DruckerPrager_regularised(; C = 2e6, ϕ=2.0, η_vp=η_reg, Ψ=0.0) # non-regularized plasticity else DruckerPrager_regularised(; C = Inf, ϕ=friction, η_vp=η_reg, Ψ=0.0) # non-regularized plasticity end # crust K_crust = TP_Conductivity(; a = 0.64, b = 807e0, c = 0.77, d = 0.00004*1e-6, ) K_mantle = TP_Conductivity(; a = 0.73, b = 1293e0, c = 0.77, d = 0.00004*1e-6, ) # Define rheolgy struct rheology = ( # Name = "UpperCrust", SetMaterialParams(; Phase = 1, Density = PT_Density(; ρ0=2.75e3, β=β_upper_crust, T0=0.0, α = 3.5e-5), HeatCapacity = ConstantHeatCapacity(; Cp=7.5e2), Conductivity = K_crust, CompositeRheology = CompositeRheology((disl_upper_crust, el_upper_crust, pl_crust)), Elasticity = el_upper_crust, RadioactiveHeat = ConstantRadioactiveHeat(0.0), Gravity = ConstantGravity(; g=9.81), ), # Name = "LowerCrust", SetMaterialParams(; Phase = 2, Density = PT_Density(; ρ0=3e3, β=β_lower_crust, T0=0.0, α = 3.5e-5), HeatCapacity = ConstantHeatCapacity(; Cp=7.5e2), Conductivity = K_crust, RadioactiveHeat = ConstantRadioactiveHeat(0.0), CompositeRheology = CompositeRheology((disl_lower_crust, el_lower_crust, pl_crust)), Elasticity = el_lower_crust, ), # Name = "LithosphericMantle", SetMaterialParams(; Phase = 3, Density = PT_Density(; ρ0=3.3e3, β=β_lithospheric_mantle, T0=0.0, α = 3e-5), HeatCapacity = ConstantHeatCapacity(; Cp=1.25e3), Conductivity = K_mantle, RadioactiveHeat = ConstantRadioactiveHeat(0.0), CompositeRheology = CompositeRheology((disl_lithospheric_mantle, diff_lithospheric_mantle, el_lithospheric_mantle, pl)), Elasticity = el_lithospheric_mantle, ), SetMaterialParams(; Phase = 4, Density = PT_Density(; ρ0=3.3e3-50, β=β_sublithospheric_mantle, T0=0.0, α = 3e-5), HeatCapacity = ConstantHeatCapacity(; Cp=1.25e3), Conductivity = K_mantle, RadioactiveHeat = ConstantRadioactiveHeat(0.0), CompositeRheology = CompositeRheology((disl_sublithospheric_mantle, diff_sublithospheric_mantle, el_sublithospheric_mantle)), Elasticity = el_sublithospheric_mantle, ), # Name = "StickyAir", SetMaterialParams(; Phase = 5, Density = ConstantDensity(; ρ=1e3), # water density HeatCapacity = ConstantHeatCapacity(; Cp=3e3), RadioactiveHeat = ConstantRadioactiveHeat(0.0), Conductivity = ConstantConductivity(; k=1.0), CompositeRheology = CompositeRheology((LinearViscous(; η=1e19),)), ), ) end function init_phases!(phases, particles, Lx, d, r, thick_air) ni = size(phases) @parallel_indices (i, j) function init_phases!(phases, px, py, index, r, Lx) @inbounds for ip in JustRelax.cellaxes(phases) # quick escape JustRelax.@cell(index[ip, i, j]) == 0 && continue x = JustRelax.@cell px[ip, i, j] depth = -(JustRelax.@cell py[ip, i, j]) - thick_air if 0e0 ≤ depth ≤ 21e3 JustRelax.@cell phases[ip, i, j] = 1.0 elseif 35e3 ≥ depth > 21e3 JustRelax.@cell phases[ip, i, j] = 2.0 elseif 90e3 ≥ depth > 35e3 JustRelax.@cell phases[ip, i, j] = 3.0 elseif depth > 90e3 JustRelax.@cell phases[ip, i, j] = 3.0 elseif depth < 0e0 JustRelax.@cell phases[ip, i, j] = 5.0 end # plume - rectangular if ((x - Lx * 0.5)^2 ≤ r^2) && (((JustRelax.@cell py[ip, i, j]) - d - thick_air)^2 ≤ r^2) JustRelax.@cell phases[ip, i, j] = 4.0 end end return nothing end @parallel (@idx ni) init_phases!(phases, particles.coords..., particles.index, r, Lx) end
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
15838
using JustRelax, JustRelax.JustRelax2D, JustRelax.DataIO import JustRelax.@cell const backend_JR = CPUBackend using ParallelStencil @init_parallel_stencil(Threads, Float64, 2) #or (CUDA, Float64, 2) or (AMDGPU, Float64, 2) using JustPIC, JustPIC._2D # Threads is the default backend, # to run on a CUDA GPU load CUDA.jl (i.e. "using CUDA") at the beginning of the script, # and to run on an AMD GPU load AMDGPU.jl (i.e. "using AMDGPU") at the beginning of the script. const backend = CPUBackend # Options: CPUBackend, CUDABackend, AMDGPUBackend # Load script dependencies using GeoParams, GLMakie # Load file with all the rheology configurations include("Layered_rheology.jl") ## SET OF HELPER FUNCTIONS PARTICULAR FOR THIS SCRIPT -------------------------------- function copyinn_x!(A, B) @parallel function f_x(A, B) @all(A) = @inn_x(B) return nothing end @parallel f_x(A, B) end import ParallelStencil.INDICES const idx_j = INDICES[2] macro all_j(A) esc(:($A[$idx_j])) end # Initial pressure profile - not accurate @parallel function init_P!(P, ρg, z) @all(P) = abs(@all(ρg) * @all_j(z)) * <(@all_j(z), 0.0) return nothing end # Initial thermal profile @parallel_indices (i, j) function init_T!(T, y, thick_air, CharDim) depth = -y[j] - thick_air # (depth - 15e3) because we have 15km of sticky air if depth < nondimensionalize(0e0km, CharDim) T[i + 1, j] = nondimensionalize(273e0K, CharDim) elseif nondimensionalize(0e0km, CharDim) ≤ (depth) < nondimensionalize(35km, CharDim) dTdZ = nondimensionalize((923-273)/35 * K/km, CharDim) offset = nondimensionalize(273e0K, CharDim) T[i + 1, j] = (depth) * dTdZ + offset elseif nondimensionalize(110km, CharDim) > (depth) ≥ nondimensionalize(35km, CharDim) dTdZ = nondimensionalize((1492-923)/75 * K/km, CharDim) offset = nondimensionalize(923K, CharDim) T[i + 1, j] = (depth - nondimensionalize(35km, CharDim)) * dTdZ + offset elseif (depth) ≥ nondimensionalize(110km, CharDim) dTdZ = nondimensionalize((1837 - 1492)/590 * K/km, CharDim) offset = nondimensionalize(1492e0K, CharDim) T[i + 1, j] = (depth - nondimensionalize(110km, CharDim)) * dTdZ + offset end return nothing end # Thermal rectangular perturbation function rectangular_perturbation!(T, xc, yc, r, xvi, thick_air, CharDim) @parallel_indices (i, j) function _rectangular_perturbation!(T, xc, yc, r, CharDim, x, y) @inbounds if ((x[i]-xc)^2 ≤ r^2) && ((y[j] - yc - thick_air)^2 ≤ r^2) depth = -y[j] - thick_air dTdZ = nondimensionalize((2047 - 2017)K / 50km, CharDim) offset = nondimensionalize(2017e0K, CharDim) T[i + 1, j] = (depth - nondimensionalize(585km, CharDim)) * dTdZ + offset end return nothing end ni = length.(xvi) @parallel (@idx ni) _rectangular_perturbation!(T, xc, yc, r, CharDim, xvi...) return nothing end ## END OF HELPER FUNCTION ------------------------------------------------------------ ## BEGIN OF MAIN SCRIPT -------------------------------------------------------------- function main2D(igg; ar=8, ny=16, nx=ny*8, figdir="figs2D", do_vtk =false) thickness = 700 * km η0 = 1e20 CharDim = GEO_units(; length = thickness, viscosity = η0, temperature = 1e3K ) # Physical domain ------------------------------------ thick_air = nondimensionalize(0e0km, CharDim) # thickness of sticky air layer ly = nondimensionalize(thickness, CharDim) + thick_air # domain length in y lx = ly * ar # domain length in x ni = nx, ny # number of cells li = lx, ly # domain length in x- and y- di = @. li / ni # grid step in x- and -y origin = 0.0, -ly # origin coordinates (15km f sticky air layer) grid = Geometry(ni, li; origin = origin) (; xci, xvi) = grid # nodes at the center and vertices of the cells # ---------------------------------------------------- # Physical properties using GeoParams ---------------- rheology = init_rheologies(CharDim; is_plastic = true) κ = (4 / (rheology[4].HeatCapacity[1].Cp * rheology[4].Density[1].ρ0)) dt = dt_diff = 0.5 * min(di...)^2 / κ / 2.01 # diffusive CFL timestep limiter # ---------------------------------------------------- # Initialize particles ------------------------------- nxcell, max_xcell, min_xcell = 25, 30, 8 particles = init_particles( backend, nxcell, max_xcell, min_xcell, xvi..., di..., ni... ) subgrid_arrays = SubgridDiffusionCellArrays(particles) # velocity grids grid_vx, grid_vy = velocity_grids(xci, xvi, di) # temperature pT, pPhases = init_cell_arrays(particles, Val(2)) particle_args = (pT, pPhases) # Elliptical temperature anomaly xc_anomaly = lx/2 # origin of thermal anomaly yc_anomaly = nondimensionalize(-610km, CharDim) # origin of thermal anomaly r_anomaly = nondimensionalize(25km, CharDim) # radius of perturbation phase_ratios = PhaseRatio(backend_JR, ni, length(rheology)) init_phases!(pPhases, particles, lx, yc_anomaly, r_anomaly, thick_air, CharDim) phase_ratios_center!(phase_ratios, particles, grid, pPhases) # ---------------------------------------------------- # STOKES --------------------------------------------- # Allocate arrays needed for every Stokes problem stokes = StokesArrays(backend_JR, ni) pt_stokes = PTStokesCoeffs(li, di; ϵ=1e-7, CFL = 0.9 / √2.1) # ---------------------------------------------------- # TEMPERATURE PROFILE -------------------------------- thermal = ThermalArrays(backend_JR, ni) thermal_bc = TemperatureBoundaryConditions(; no_flux = (left = true, right = true, top = false, bot = false), ) # initialize thermal profile - Half space cooling @parallel (@idx ni .+ 1) init_T!(thermal.T, xvi[2], thick_air, CharDim) thermal_bcs!(thermal, thermal_bc) Tbot = thermal.T[1, 1] Ttop = thermal.T[1, end] rectangular_perturbation!(thermal.T, xc_anomaly, yc_anomaly, r_anomaly, xvi, thick_air, CharDim) temperature2center!(thermal) # ---------------------------------------------------- args = (; T = thermal.Tc, P = stokes.P, dt=Inf) # Buoyancy forces ρg = @zeros(ni...), @zeros(ni...) for _ in 1:1 compute_ρg!(ρg[2], phase_ratios, rheology, args) @parallel init_P!(stokes.P, ρg[2], xci[2]) end # Rheology viscosity_cutoff = nondimensionalize((1e16Pa*s, 1e24Pa*s), CharDim) compute_viscosity!(stokes, phase_ratios, args, rheology, viscosity_cutoff) # PT coefficients for thermal diffusion pt_thermal = PTThermalCoeffs( backend_JR, rheology, phase_ratios, args, dt, ni, di, li; ϵ=1e-6, CFL= 1e-3 / √2.1 ) # Boundary conditions flow_bcs = VelocityBoundaryConditions(; free_slip = (left = true, right=true, top=true, bot=true), ) flow_bcs!(stokes, flow_bcs) # apply boundary conditions update_halo!(@velocity(stokes)...) # IO ------------------------------------------------ # if it does not exist, make folder where figures are stored if do_vtk vtk_dir = joinpath(figdir, "vtk") take(vtk_dir) end take(figdir) # ---------------------------------------------------- # Plot initial T and η profiles let Yv = [y for x in xvi[1], y in xvi[2]][:] Y = [y for x in xci[1], y in xci[2]][:] fig = Figure(size = (1200, 900)) ax1 = Axis(fig[1,1], aspect = 2/3, title = "T") ax2 = Axis(fig[1,2], aspect = 2/3, title = "log10(η)") scatter!(ax1, Array(thermal.T[2:end-1,:][:]), Yv) scatter!(ax2, Array(log10.(stokes.viscosity.η[:])), Y) ylims!(ax1, minimum(xvi[2]), 0) ylims!(ax2, minimum(xvi[2]), 0) hideydecorations!(ax2) save(joinpath(figdir, "initial_profile.png"), fig) fig end T_buffer = @zeros(ni.+1) Told_buffer = similar(T_buffer) dt₀ = similar(stokes.P) for (dst, src) in zip((T_buffer, Told_buffer), (thermal.T, thermal.Told)) copyinn_x!(dst, src) end grid2particle!(pT, xvi, T_buffer, particles) local Vx_v, Vy_v if do_vtk Vx_v = @zeros(ni.+1...) Vy_v = @zeros(ni.+1...) end # Time loop t, it = 0.0, 0 while t < nondimensionalize(5e6yr, CharDim) # run only for 5 Myrs # interpolate fields from particle to grid vertices particle2grid!(T_buffer, pT, xvi, particles) @views thermal.T[2:end-1, :] .= T_buffer @views thermal.T[:, end] .= Ttop @views thermal.T[:, 1] .= Tbot thermal_bcs!(thermal, thermal_bc) temperature2center!(thermal) # Update buoyancy and viscosity - args = (; T = thermal.Tc, P = stokes.P, dt=Inf) compute_ρg!(ρg[end], phase_ratios, rheology, (T=thermal.Tc, P=stokes.P)) compute_viscosity!( stokes, phase_ratios, args, rheology, viscosity_cutoff ) # ------------------------------ # Stokes solver ---------------- solve!( stokes, pt_stokes, di, flow_bcs, ρg, phase_ratios, rheology, args, Inf, igg; kwargs = (; iterMax = 150e3, nout = 1e3, viscosity_cutoff = viscosity_cutoff ) ) tensor_invariant!(stokes.ε) dt = compute_dt(stokes, di, dt_diff) # ------------------------------ # Thermal solver --------------- heatdiffusion_PT!( thermal, pt_thermal, thermal_bc, rheology, args, dt, di; kwargs = ( igg = igg, phase = phase_ratios, iterMax = 10e3, nout = 1e2, verbose = true ), ) for (dst, src) in zip((T_buffer, Told_buffer), (thermal.T, thermal.Told)) copyinn_x!(dst, src) end subgrid_characteristic_time!( subgrid_arrays, particles, dt₀, phase_ratios, rheology, thermal, stokes, xci, di ) centroid2particle!(subgrid_arrays.dt₀, xci, dt₀, particles) subgrid_diffusion!( pT, T_buffer, thermal.ΔT[2:end-1, :], subgrid_arrays, particles, xvi, di, dt ) # ------------------------------ # Advection -------------------- # advect particles in space advection!(particles, RungeKutta2(), @velocity(stokes), (grid_vx, grid_vy), dt) # advect particles in memory move_particles!(particles, xvi, particle_args) # check if we need to inject particles inject_particles_phase!(particles, pPhases, (pT, ), (T_buffer,), xvi) # update phase ratios phase_ratios_center!(phase_ratios, particles, grid, pPhases) @show it += 1 t += dt # Data I/O and plotting --------------------- if it == 1 || rem(it, 25) == 0 checkpointing_hdf5(figdir, stokes, thermal.T, t, dt) if do_vtk velocity2vertex!(Vx_v, Vy_v, @velocity(stokes)...) data_v = (; T = Array(ustrip.(dimensionalize(thermal.T[2:(end - 1), :], C, CharDim))), τxy = Array(ustrip.(dimensionalize(stokes.τ.xy, s^-1, CharDim))), εxy = Array(ustrip.(dimensionalize(stokes.ε.xy, s^-1, CharDim))), Vx = Array(ustrip.(dimensionalize(Vx_v,cm/yr,CharDim))), Vy = Array(ustrip.(dimensionalize(Vy_v, cm/yr, CharDim))), ) data_c = (; P = Array(ustrip.(dimensionalize(stokes.P,MPa,CharDim))), τxx = Array(ustrip.(dimensionalize(stokes.τ.xx, MPa,CharDim))), τyy = Array(ustrip.(dimensionalize(stokes.τ.yy,MPa,CharDim))), τII = Array(ustrip.(dimensionalize(stokes.τ.II, MPa, CharDim))), εxx = Array(ustrip.(dimensionalize(stokes.ε.xx, s^-1,CharDim))), εyy = Array(ustrip.(dimensionalize(stokes.ε.yy, s^-1,CharDim))), εII = Array(ustrip.(dimensionalize(stokes.ε.II, s^-1,CharDim))), η = Array(ustrip.(dimensionalize(stokes.viscosity.η_vep,Pa*s,CharDim))), ) velocity_v = ( Array(ustrip.(dimensionalize(Vx_v,cm/yr,CharDim))), Array(ustrip.(dimensionalize(Vy_v, cm/yr, CharDim))), ) save_vtk( joinpath(vtk_dir, "vtk_" * lpad("$it", 6, "0")), xvi, xci, data_v, data_c, velocity_v ) end # Make particles plottable p = particles.coords ppx, ppy = p pxv = ppx.data[:] pyv = ppy.data[:] clr = pPhases.data[:] idxv = particles.index.data[:]; # Make Makie figure t_dim = Float16(dimensionalize(t, yr, CharDim).val / 1e3) fig = Figure(size = (900, 900), title = "t = $t_dim [kyr]") ax1 = Axis(fig[1,1], aspect = ar, title = "T [K] ; t=$t_dim [kyrs]") ax2 = Axis(fig[2,1], aspect = ar, title = "phase") # ax2 = Axis(fig[2,1], aspect = ar, title = "Vy [m/s]") ax3 = Axis(fig[1,3], aspect = ar, title = "log10(εII)") ax4 = Axis(fig[2,3], aspect = ar, title = "log10(η)") # Plot temperature h1 = heatmap!(ax1, xvi[1], xvi[2], Array(ustrip.(dimensionalize(thermal.T[2:(end - 1), :], C, CharDim))) , colormap=:batlow) # Plot particles phase h2 = scatter!(ax2, Array(pxv[idxv]), Array(pyv[idxv]), color=Array(clr[idxv]), colormap=:grayC) # Plot 2nd invariant of strain rate h3 = heatmap!(ax3, xci[1], xci[2], Array(log10.(ustrip.(dimensionalize(stokes.ε.II, s^-1,CharDim)))) , colormap=:batlow) # Plot effective viscosity h4 = heatmap!(ax4, xci[1], xci[2], Array(log10.(ustrip.(dimensionalize(stokes.viscosity.η_vep,Pa*s,CharDim)))) , colormap=:batlow) hidexdecorations!(ax1) hidexdecorations!(ax2) hidexdecorations!(ax3) Colorbar(fig[1,2], h1) Colorbar(fig[2,2], h2) Colorbar(fig[1,4], h3) Colorbar(fig[2,4], h4) linkaxes!(ax1, ax2, ax3, ax4) save(joinpath(figdir, "$(it).png"), fig) fig end # ------------------------------ end return nothing end ## END OF MAIN SCRIPT ---------------------------------------------------------------- # (Path)/folder where output data and figures are stored figdir = "Plume2D" do_vtk = false # set to true to generate VTK files for ParaView ar = 1 # aspect ratio n = 64 nx = n*ar - 2 ny = n - 2 igg = if !(JustRelax.MPI.Initialized()) # initialize (or not) MPI grid IGG(init_global_grid(nx, ny, 1; init_MPI= true)...) else igg end # run main script main2D(igg; figdir = figdir, ar = ar, nx = nx, ny = ny, do_vtk = do_vtk);
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
8089
# from "Fingerprinting secondary mantle plumes", Cloetingh et al. 2022 function init_rheologies(CharDim; is_plastic = true) # Dislocation and Diffusion creep disl_upper_crust = DislocationCreep( A=5.07e-18Pa^(-23//10) / s, # units are Pa^(-n) / s n=2.3NoUnits, E=154e3J/mol, V=6e-6m^3/mol, r=0.0NoUnits, R=8.3145J/mol/K ) disl_lower_crust = DislocationCreep( A=2.08e-23Pa^(-32//10) / s, # units are Pa^(-n) / s n=3.2NoUnits, E=238e3J/mol, V=6e-6m^3/mol, r=0.0NoUnits, R=8.3145J/mol/K, ) disl_lithospheric_mantle = DislocationCreep( A=2.51e-17Pa^(-35//10) / s, # units are Pa^(-n) / s n=3.5NoUnits, E=530e3J/mol, V=6e-6m^3/mol, r=0.0NoUnits, R=8.3145J/mol/K ) disl_sublithospheric_mantle = DislocationCreep( A=2.51e-17Pa^(-35//10) / s, # units are Pa^(-n) / s n=3.5NoUnits, E=530e3J/mol, V=6e-6m^3/mol, r=0.0NoUnits, R=8.3145J/mol/K ) diff_lithospheric_mantle = DiffusionCreep( A=2.51e-17Pa^(-1) / s, # units are Pa^(-n - r) / s * m^(-p) n=1.0NoUnits, E=530e3J/mol, V=6e-6m^3/mol, r=0.0NoUnits, p=0.0NoUnits, R=8.3145J/mol/K ) diff_sublithospheric_mantle = DiffusionCreep( A=2.51e-17Pa^(-1) / s, # units are Pa^(-n - r) / s * m^(-p) n=1.0NoUnits, E=530e3J/mol, V=6e-6m^3/mol, r=0.0NoUnits, p=0.0NoUnits, R=8.3145J/mol/K ) # Elasticity el_upper_crust = SetConstantElasticity(; G=25e9Pa, ν=0.5) el_lower_crust = SetConstantElasticity(; G=25e9Pa, ν=0.5) el_lithospheric_mantle = SetConstantElasticity(; G=67e9Pa, ν=0.5) el_sublithospheric_mantle = SetConstantElasticity(; G=67e9Pa, ν=0.5) β_upper_crust = inv(get_Kb(el_upper_crust)) β_lower_crust = inv(get_Kb(el_lower_crust)) β_lithospheric_mantle = inv(get_Kb(el_lithospheric_mantle)) β_sublithospheric_mantle = inv(get_Kb(el_sublithospheric_mantle)) # Physical properties using GeoParams ---------------- η_reg = 1e16 * Pa * s cohesion = 3e6 * Pa friction = asind(0.2) pl_crust = if is_plastic DruckerPrager_regularised(; C = cohesion, ϕ=friction, η_vp=η_reg, Ψ=0.0) # non-regularized plasticity else DruckerPrager_regularised(; C = Inf, ϕ=friction, η_vp=η_reg, Ψ=0.0) # non-regularized plasticity end friction = asind(0.3) pl = if is_plastic DruckerPrager_regularised(; C = cohesion, ϕ=friction, η_vp=η_reg, Ψ=0.0) # non-regularized plasticity else DruckerPrager_regularised(; C = Inf, ϕ=friction, η_vp=η_reg, Ψ=0.0) # non-regularized plasticity end K_crust = TP_Conductivity(; a = 0.64Watt / K / m , b = 807e00Watt / m , c = 0.77K, d = 0.00004/ MPa, ) K_mantle = TP_Conductivity(; a = 0.73Watt / K / m , b = 1293e00Watt / m , c = 0.77K, d = 0.00004/ MPa, ) g = 9.81m/s^2 # Define rheolgy struct rheology = ( # Name = "UpperCrust", SetMaterialParams(; Phase = 1, Density = PT_Density(; ρ0=2.75e3kg / m^3, β=β_upper_crust, T0=0e0C, α = 3.5e-5/ K), HeatCapacity = ConstantHeatCapacity(; Cp=7.5e2J / kg / K), Conductivity = K_crust, CompositeRheology = CompositeRheology((disl_upper_crust, el_upper_crust, pl_crust)), Elasticity = el_upper_crust, RadioactiveHeat = ConstantRadioactiveHeat(0.0), Gravity = ConstantGravity(; g=g), CharDim = CharDim, ), # Name = "LowerCrust", SetMaterialParams(; Phase = 2, Density = PT_Density(; ρ0=3e3kg / m^3, β=β_upper_crust, T0=0e0C, α = 3.5e-5/ K), HeatCapacity = ConstantHeatCapacity(; Cp=7.5e2J / kg / K), Conductivity = K_crust, RadioactiveHeat = ConstantRadioactiveHeat(0.0), CompositeRheology = CompositeRheology((disl_lower_crust, el_lower_crust, pl_crust)), Gravity = ConstantGravity(; g=g), Elasticity = el_lower_crust, CharDim = CharDim, ), # Name = "LithosphericMantle", SetMaterialParams(; Phase = 3, Density = PT_Density(; ρ0=3.3e3kg / m^3, β=β_upper_crust, T0=0e0C, α = 3.5e-5/ K), HeatCapacity = ConstantHeatCapacity(; Cp=1.25e3J / kg / K), Conductivity = K_mantle, RadioactiveHeat = ConstantRadioactiveHeat(0.0), CompositeRheology = CompositeRheology((disl_lithospheric_mantle, diff_lithospheric_mantle, el_lithospheric_mantle, pl)), Gravity = ConstantGravity(; g=g), Elasticity = el_lithospheric_mantle, CharDim = CharDim, ), SetMaterialParams(; Phase = 4, Density = PT_Density(; ρ0=(3.3e3-50)kg / m^3, β=β_upper_crust, T0=0e0C, α = 3.5e-5/ K), HeatCapacity = ConstantHeatCapacity(; Cp=1.25e3J / kg / K), Conductivity = K_mantle, RadioactiveHeat = ConstantRadioactiveHeat(0.0), CompositeRheology = CompositeRheology((disl_sublithospheric_mantle, diff_sublithospheric_mantle, el_sublithospheric_mantle)), Gravity = ConstantGravity(; g=g), Elasticity = el_sublithospheric_mantle, CharDim = CharDim, ), # Name = "StickyAir", SetMaterialParams(; Phase = 5, Density = ConstantDensity(; ρ=1e3kg / m^3), # water density HeatCapacity = ConstantHeatCapacity(; Cp=3e3J / kg / K), RadioactiveHeat = ConstantRadioactiveHeat(0.0), Conductivity = ConstantConductivity(; k=1.0Watt / m / K), Gravity = ConstantGravity(; g=g), CompositeRheology = CompositeRheology((LinearViscous(; η=1e19Pa*s),)), CharDim = CharDim, ), ) end function init_phases!(phases, particles, Lx, d, r, thick_air, CharDim) ni = size(phases) @parallel_indices (i, j) function init_phases!(phases, px, py, index, r, Lx, CharDim) @inbounds for ip in JustRelax.cellaxes(phases) # quick escape JustRelax.@cell(index[ip, i, j]) == 0 && continue x = JustRelax.@cell px[ip, i, j] depth = -(JustRelax.@cell py[ip, i, j]) - nondimensionalize(thick_air * km, CharDim) if nondimensionalize(0e0km, CharDim) ≤ depth ≤ nondimensionalize(21km, CharDim) JustRelax.@cell phases[ip, i, j] = 1.0 elseif nondimensionalize(35km, CharDim) ≥ depth > nondimensionalize(21km, CharDim) JustRelax.@cell phases[ip, i, j] = 2.0 elseif nondimensionalize(90km, CharDim) ≥ depth > nondimensionalize(35km, CharDim) JustRelax.@cell phases[ip, i, j] = 3.0 elseif depth > nondimensionalize(90km, CharDim) JustRelax.@cell phases[ip, i, j] = 3.0 elseif depth < nondimensionalize(0e0km, CharDim) JustRelax.@cell phases[ip, i, j] = 5.0 end # plume - rectangular if ((x - Lx * 0.5)^2 ≤ r^2) && (((JustRelax.@cell py[ip, i, j]) - d - nondimensionalize(thick_air * km, CharDim))^2 ≤ r^2) JustRelax.@cell phases[ip, i, j] = 4.0 end end return nothing end @parallel (@idx ni) init_phases!(phases, particles.coords..., particles.index, r, Lx, CharDim) end
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
13268
using JustRelax, JustRelax.JustRelax3D, JustRelax.DataIO import JustRelax.@cell const backend_JR = CPUBackend using ParallelStencil @init_parallel_stencil(Threads, Float64, 3) using JustPIC, JustPIC._3D # Threads is the default backend, # to run on a CUDA GPU load CUDA.jl (i.e. "using CUDA") at the beginning of the script, # and to run on an AMD GPU load AMDGPU.jl (i.e. "using AMDGPU") at the beginning of the script. const backend = CPUBackend # Options: CPUBackend, CUDABackend, AMDGPUBackend # Load script dependencies using Printf, GeoParams, GLMakie, GeoParams # Load file with all the rheology configurations include("Layered_rheology.jl") ## SET OF HELPER FUNCTIONS PARTICULAR FOR THIS SCRIPT -------------------------------- import ParallelStencil.INDICES const idx_k = INDICES[3] macro all_k(A) esc(:($A[$idx_k])) end # Initial pressure profile - not accurate @parallel function init_P!(P, ρg, z) @all(P) = abs(@all(ρg) * @all_k(z)) * <(@all_k(z), 0.0) return nothing end # Initial thermal profile @parallel_indices (I...) function init_T!(T, z) depth = -z[I[3]] if depth < 0e0 T[I...] = 273.0 elseif 0e0 ≤ (depth) < 35e3 dTdZ = (923-273)/35e3 offset = 273e0 T[I...] = (depth) * dTdZ + offset elseif 110e3 > (depth) ≥ 35e3 dTdZ = (1492-923)/75e3 offset = 923 T[I...] = (depth - 35e3) * dTdZ + offset elseif (depth) ≥ 110e3 dTdZ = (1837 - 1492)/590e3 offset = 1492e0 T[I...] = (depth - 110e3) * dTdZ + offset end return nothing end # Thermal rectangular perturbation function rectangular_perturbation!(T, xc, yc, zc, r, xvi) @parallel_indices (i, j, k) function _rectangular_perturbation!(T, xc, yc, zc, r, x, y, z) @inbounds if (abs(x[i]-xc) ≤ r) && (abs(y[j] - yc) ≤ r) && (abs(z[k] - zc) ≤ r) depth = abs(z[k]) dTdZ = (2047 - 2017) / 50e3 offset = 2017 T[i, j, k] = (depth - 585e3) * dTdZ + offset end return nothing end @parallel _rectangular_perturbation!(T, xc, yc, zc, r, xvi...) end ## END OF HELPER FUNCTION ------------------------------------------------------------ ## BEGIN OF MAIN SCRIPT -------------------------------------------------------------- function main3D(igg; ar=1, nx=16, ny=16, nz=16, figdir="figs3D", do_vtk =false) # Physical domain ------------------------------------ lz = 700e3 # domain length in z lx = ly = lz * ar # domain length in x and y ni = nx, ny, nz # number of cells li = lx, ly, lz # domain length di = @. li / ni # grid steps origin = 0.0, 0.0, -lz # origin coordinates (15km of sticky air layer) grid = Geometry(ni, li; origin = origin) (; xci, xvi) = grid # nodes at the center and vertices of the cells # ---------------------------------------------------- # Physical properties using GeoParams ---------------- rheology = init_rheologies(; is_plastic = true) κ = (10 / (rheology[1].HeatCapacity[1].Cp * rheology[1].Density[1].ρ0)) dt = dt_diff = 0.5 * min(di...)^3 / κ / 3.01 # diffusive CFL timestep limiter # ---------------------------------------------------- # Initialize particles ------------------------------- nxcell, max_xcell, min_xcell = 25, 35, 8 particles = init_particles( backend, nxcell, max_xcell, min_xcell, xvi..., di..., ni... ) subgrid_arrays = SubgridDiffusionCellArrays(particles) # velocity grids grid_vx, grid_vy, grid_vz = velocity_grids(xci, xvi, di) # temperature pT, pPhases = init_cell_arrays(particles, Val(2)) particle_args = (pT, pPhases) # Elliptical temperature anomaly xc_anomaly = lx/2 # origin of thermal anomaly yc_anomaly = ly/2 # origin of thermal anomaly zc_anomaly = -610e3 # origin of thermal anomaly r_anomaly = 50e3 # radius of perturbation init_phases!(pPhases, particles, lx, ly; d=abs(zc_anomaly), r=r_anomaly) phase_ratios = PhaseRatio(backend_JR, ni, length(rheology)) @parallel (@idx ni) phase_ratios_center!(phase_ratios.center, particles.coords, xci, di, pPhases) # ---------------------------------------------------- # STOKES --------------------------------------------- # Allocate arrays needed for every Stokes problem stokes = StokesArrays(backend_JR, ni) pt_stokes = PTStokesCoeffs(li, di; ϵ=1e-4, CFL = 0.5 / √3.1) # ---------------------------------------------------- # TEMPERATURE PROFILE -------------------------------- thermal = ThermalArrays(backend_JR, ni) thermal_bc = TemperatureBoundaryConditions(; no_flux = (left = true , right = true , top = false, bot = false, front = true , back = true), ) # initialize thermal profile - Half space cooling @parallel init_T!(thermal.T, xvi[3]) rectangular_perturbation!(thermal.T, xc_anomaly, yc_anomaly, zc_anomaly, r_anomaly, xvi) thermal_bcs!(thermal, thermal_bc) temperature2center!(thermal) # ---------------------------------------------------- # Buoyancy forces ρg = ntuple(_ -> @zeros(ni...), Val(3)) compute_ρg!(ρg[end], phase_ratios, rheology, (T=thermal.Tc, P=stokes.P)) @parallel init_P!(stokes.P, ρg[end], xci[end]) # Rheology viscosity_cutoff = (1e18, 1e24) compute_viscosity!(stokes, phase_ratios, args, rheology, viscosity_cutoff) # PT coefficients for thermal diffusion pt_thermal = PTThermalCoeffs( backend_JR, rheology, phase_ratios, args, dt, ni, di, li; ϵ=1e-5, CFL=1e-3 / √3 ) # Boundary conditions flow_bcs = VelocityBoundaryConditions(; free_slip = (left = true , right = true , top = true , bot = true , front = true , back = true ), no_slip = (left = false, right = false, top = false, bot = false, front = false, back = false), ) flow_bcs!(stokes, flow_bcs) # apply boundary conditions update_halo!(@velocity(stokes)...) # IO ------------------------------------------------- # if it does not exist, make folder where figures are stored if do_vtk vtk_dir = joinpath(figdir, "vtk") take(vtk_dir) end take(figdir) # ---------------------------------------------------- # Plot initial T and η profiles fig = let Zv = [z for x in xvi[1], y in xvi[2], z in xvi[3]][:] Z = [z for x in xci[1], y in xci[2], z in xci[3]][:] fig = Figure(size = (1200, 900)) ax1 = Axis(fig[1,1], aspect = 2/3, title = "T") ax2 = Axis(fig[1,2], aspect = 2/3, title = "log10(η)") lines!(ax1, Array(thermal.T[:]), Zv./1e3) lines!(ax2, Array(log10.(η[:])), Z./1e3) ylims!(ax1, minimum(xvi[3])./1e3, 0) ylims!(ax2, minimum(xvi[3])./1e3, 0) hideydecorations!(ax2) save(joinpath(figdir, "initial_profile.png"), fig) fig end grid2particle!(pT, xvi, thermal.T, particles) dt₀ = similar(stokes.P) local Vx_v, Vy_v, Vz_v if do_vtk Vx_v = @zeros(ni.+1...) Vy_v = @zeros(ni.+1...) Vz_v = @zeros(ni.+1...) end # Time loop t, it = 0.0, 0 while (t/(1e6 * 3600 * 24 *365.25)) < 5 # run only for 5 Myrs # interpolate fields from particle to grid vertices particle2grid!(thermal.T, pT, xvi, particles) temperature2center!(thermal) # Update buoyancy and viscosity - args = (; T = thermal.Tc, P = stokes.P, dt=Inf) compute_ρg!(ρg[end], phase_ratios, rheology, args) compute_viscosity!( stokes, phase_ratios, args, rheology, viscosity_cutoff ) # ------------------------------ # Stokes solver ---------------- solve!( stokes, pt_stokes, di, flow_bcs, ρg, phase_ratios, rheology, args, Inf, igg; kwargs =(; iterMax = 100e3, nout = 1e3, viscosity_cutoff = viscosity_cutoff ) ); tensor_invariant!(stokes.ε) dt = compute_dt(stokes, di, dt_diff) / 2 # ------------------------------ # Thermal solver --------------- heatdiffusion_PT!( thermal, pt_thermal, thermal_bc, rheology, args, dt, di; kawargs = (; igg = igg, phase = phase_ratios, iterMax = 10e3, nout = 1e2, verbose = true, ) ) subgrid_characteristic_time!( subgrid_arrays, particles, dt₀, phase_ratios, rheology, thermal, stokes, xci, di ) centroid2particle!(subgrid_arrays.dt₀, xci, dt₀, particles) subgrid_diffusion!( pT, thermal.T, thermal.ΔT, subgrid_arrays, particles, xvi, di, dt ) # ------------------------------ # Advection -------------------- # advect particles in space advection!(particles, RungeKutta2(), @velocity(stokes), (grid_vx, grid_vy, grid_vz), dt) # advect particles in memory move_particles!(particles, xvi, particle_args) # check if we need to inject particles inject_particles_phase!(particles, pPhases, (pT, ), (T_buffer,), xvi) # update phase ratios phase_ratios_center!(phase_ratios, particles, grid, pPhases) @show it += 1 t += dt # Data I/O and plotting --------------------- if it == 1 || rem(it, 1) == 0 checkpointing_hdf5(figdir, stokes, thermal.T, t, dt) if do_vtk velocity2vertex!(Vx_v, Vy_v, Vz_v, @velocity(stokes)...) data_v = (; T = Array(thermal.T), τxy = Array(stokes.τ.xy), εxy = Array(stokes.ε.xy), Vx = Array(Vx_v), Vy = Array(Vy_v), Vz = Array(Vz_v), ) data_c = (; Tc = Array(thermal.Tc), P = Array(stokes.P), τxx = Array(stokes.τ.xx), τyy = Array(stokes.τ.yy), εxx = Array(stokes.ε.xx), εyy = Array(stokes.ε.yy), η = Array(log10.(stokes.viscosity.η_vep)), ) velocity_v = ( Array(Vx_v), Array(Vy_v), Array(Vz_v), ) save_vtk( joinpath(vtk_dir, "vtk_" * lpad("$it", 6, "0")), xvi, xci, data_v, data_c, velocity_v ) end slice_j = ny >>> 1 # Make Makie figure fig = Figure(size = (1400, 1800), title = "t = $t") ax1 = Axis(fig[1,1], aspect = ar, title = "T [K] (t=$(t/(1e6 * 3600 * 24 *365.25)) Myrs)") ax2 = Axis(fig[2,1], aspect = ar, title = "τII [MPa]") ax3 = Axis(fig[1,3], aspect = ar, title = "log10(εII)") ax4 = Axis(fig[2,3], aspect = ar, title = "log10(η)") # Plot temperature h1 = heatmap!(ax1, xvi[1].*1e-3, xvi[3].*1e-3, Array(thermal.T[:, slice_j, :]) , colormap=:lajolla) # Plot particles phase h2 = heatmap!(ax2, xci[1].*1e-3, xci[3].*1e-3, Array(stokes.τ.II[:, slice_j, :].*1e-6) , colormap=:batlow) # Plot 2nd invariant of strain rate h3 = heatmap!(ax3, xci[1].*1e-3, xci[3].*1e-3, Array(log10.(stokes.ε.II[:, slice_j, :])) , colormap=:batlow) # Plot effective viscosity h4 = heatmap!(ax4, xci[1].*1e-3, xci[3].*1e-3, Array(log10.(η_vep[:, slice_j, :])) , colormap=:batlow) hideydecorations!(ax3) hideydecorations!(ax4) Colorbar(fig[1,2], h1) Colorbar(fig[2,2], h2) Colorbar(fig[1,4], h3) Colorbar(fig[2,4], h4) linkaxes!(ax1, ax2, ax3, ax4) save(joinpath(figdir, "$(it).png"), fig) fig end # ------------------------------ end return nothing end ## END OF MAIN SCRIPT ---------------------------------------------------------------- do_vtk = true # set to true to generate VTK files for ParaView ar = 1 # aspect ratio n = 32 nx = n ny = n nz = n igg = if !(JustRelax.MPI.Initialized()) # initialize (or not) MPI grid IGG(init_global_grid(nx, ny, nz; init_MPI= true)...) else igg end # (Path)/folder where output data and figures are stored figdir = "Plume3D_$n" # main3D(igg; figdir = figdir, ar = ar, nx = nx, ny = ny, nz = nz, do_vtk = do_vtk);
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
6920
# from "Fingerprinting secondary mantle plumes", Cloetingh et al. 2022 function init_rheologies(; is_plastic = true) # Dislocation and Diffusion creep disl_upper_crust = DislocationCreep(A=5.07e-18, n=2.3, E=154e3, V=6e-6, r=0.0, R=8.3145) disl_lower_crust = DislocationCreep(A=2.08e-23, n=3.2, E=238e3, V=6e-6, r=0.0, R=8.3145) disl_lithospheric_mantle = DislocationCreep(A=2.51e-17, n=3.5, E=530e3, V=6e-6, r=0.0, R=8.3145) disl_sublithospheric_mantle = DislocationCreep(A=2.51e-17, n=3.5, E=530e3, V=6e-6, r=0.0, R=8.3145) diff_lithospheric_mantle = DislocationCreep(A=2.51e-17, n=1.0, E=530e3, V=6e-6, r=0.0, R=8.3145) diff_sublithospheric_mantle = DislocationCreep(A=2.51e-17, n=1.0, E=530e3, V=6e-6, r=0.0, R=8.3145) # Elasticity el_upper_crust = SetConstantElasticity(; G=25e9, ν=0.5) el_lower_crust = SetConstantElasticity(; G=25e9, ν=0.5) el_lithospheric_mantle = SetConstantElasticity(; G=67e9, ν=0.5) el_sublithospheric_mantle = SetConstantElasticity(; G=67e9, ν=0.5) β_upper_crust = inv(get_Kb(el_upper_crust)) β_lower_crust = inv(get_Kb(el_lower_crust)) β_lithospheric_mantle = inv(get_Kb(el_lithospheric_mantle)) β_sublithospheric_mantle = inv(get_Kb(el_sublithospheric_mantle)) # Physical properties using GeoParams ---------------- η_reg = 1e16 cohesion = 3e6 friction = asind(0.2) pl_crust = if is_plastic DruckerPrager_regularised(; C = cohesion, ϕ=friction, η_vp=η_reg, Ψ=0.0) # non-regularized plasticity else DruckerPrager_regularised(; C = Inf, ϕ=friction, η_vp=η_reg, Ψ=0.0) # non-regularized plasticity end friction = asind(0.3) pl = if is_plastic DruckerPrager_regularised(; C = cohesion, ϕ=friction, η_vp=η_reg, Ψ=0.0) # non-regularized plasticity else DruckerPrager_regularised(; C = Inf, ϕ=friction, η_vp=η_reg, Ψ=0.0) # non-regularized plasticity end pl_wz = if is_plastic DruckerPrager_regularised(; C = 2e6, ϕ=2.0, η_vp=η_reg, Ψ=0.0) # non-regularized plasticity else DruckerPrager_regularised(; C = Inf, ϕ=friction, η_vp=η_reg, Ψ=0.0) # non-regularized plasticity end # crust K_crust = TP_Conductivity(; a = 0.64, b = 807e0, c = 0.77, d = 0.00004*1e-6, ) K_mantle = TP_Conductivity(; a = 0.73, b = 1293e0, c = 0.77, d = 0.00004*1e-6, ) # Define rheolgy struct rheology = ( # Name = "UpperCrust", SetMaterialParams(; Phase = 1, Density = PT_Density(; ρ0=2.75e3, β=β_upper_crust, T0=0.0, α = 3.5e-5), HeatCapacity = ConstantHeatCapacity(; Cp=7.5e2), Conductivity = K_crust, CompositeRheology = CompositeRheology((disl_upper_crust, el_upper_crust, pl_crust)), Elasticity = el_upper_crust, Gravity = ConstantGravity(; g=9.81), ), # Name = "LowerCrust", SetMaterialParams(; Phase = 2, Density = PT_Density(; ρ0=3e3, β=β_lower_crust, T0=0.0, α = 3.5e-5), HeatCapacity = ConstantHeatCapacity(; Cp=7.5e2), Conductivity = K_crust, CompositeRheology = CompositeRheology((disl_lower_crust, el_lower_crust, pl_crust)), Elasticity = el_lower_crust, ), # Name = "LithosphericMantle", SetMaterialParams(; Phase = 3, Density = PT_Density(; ρ0=3.3e3, β=β_lithospheric_mantle, T0=0.0, α = 3e-5), HeatCapacity = ConstantHeatCapacity(; Cp=1.25e3), Conductivity = K_mantle, CompositeRheology = CompositeRheology((disl_lithospheric_mantle, diff_lithospheric_mantle, el_lithospheric_mantle, pl)), Elasticity = el_lithospheric_mantle, ), # # Name = "SubLithosphericMantle", # SetMaterialParams(; # Phase = 4, # Density = PT_Density(; ρ0=3.3e3, β=β_sublithospheric_mantle, T0=0.0, α = 3e-5), # HeatCapacity = ConstantHeatCapacity(; Cp=1.25e3), # Conductivity = K_mantle, # RadioactiveHeat = ConstantRadioactiveHeat(0.0), # CompositeRheology = CompositeRheology((disl_sublithospheric_mantle, diff_sublithospheric_mantle, el_sublithospheric_mantle)), # Elasticity = el_sublithospheric_mantle, # ), # Name = "Plume", SetMaterialParams(; Phase = 4, Density = PT_Density(; ρ0=3.3e3-50, β=β_sublithospheric_mantle, T0=0.0, α = 3e-5), HeatCapacity = ConstantHeatCapacity(; Cp=1.25e3), Conductivity = K_mantle, CompositeRheology = CompositeRheology((disl_sublithospheric_mantle, diff_sublithospheric_mantle, el_sublithospheric_mantle)), Elasticity = el_sublithospheric_mantle, ), # Name = "StickyAir", SetMaterialParams(; Phase = 5, Density = ConstantDensity(; ρ=1e3), HeatCapacity = ConstantHeatCapacity(; Cp=1.25e3), Conductivity = ConstantConductivity(; k=15.0), CompositeRheology = CompositeRheology((LinearViscous(; η=1e21),)), ), ) end function init_phases!(phases, particles, Lx, Ly; d=650e3, r=50e3) ni = size(phases) @parallel_indices (I...) function init_phases!(phases, px, py, pz, index, r, Lx, Ly) @inbounds for ip in JustRelax.cellaxes(phases) # quick escape JustRelax.@cell(index[ip, I...]) == 0 && continue x = JustRelax.@cell px[ip, I...] y = JustRelax.@cell py[ip, I...] depth = -(JustRelax.@cell pz[ip, I...]) if 0e0 ≤ depth ≤ 21e3 JustRelax.@cell phases[ip, I...] = 1.0 elseif 35e3 ≥ depth > 21e3 JustRelax.@cell phases[ip, I...] = 2.0 elseif 90e3 ≥ depth > 35e3 JustRelax.@cell phases[ip, I...] = 3.0 elseif depth > 90e3 JustRelax.@cell phases[ip, I...] = 3.0 elseif 0e0 > depth JustRelax.@cell phases[ip, I...] = 5.0 end # plume - rectangular if ((x - Lx * 0.5)^2 ≤ r^2) && ((y - Ly * 0.5)^2 ≤ r^2) && ((depth - d)^2 ≤ r^2) JustRelax.@cell phases[ip, I...] = 4.0 end end return nothing end @parallel (@idx ni) init_phases!(phases, particles.coords..., particles.index, r, Lx, Ly) end
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
20261
# const isCUDA = false const isCUDA = true @static if isCUDA using CUDA end using JustRelax, JustRelax.JustRelax3D, JustRelax.DataIO import JustRelax.@cell const backend_JR = @static if isCUDA CUDABackend # Options: CPUBackend, CUDABackend, AMDGPUBackend else JustRelax.CPUBackend # Options: CPUBackend, CUDABackend, AMDGPUBackend end using ParallelStencil, ParallelStencil.FiniteDifferences3D @static if isCUDA @init_parallel_stencil(CUDA, Float64, 3) else @init_parallel_stencil(Threads, Float64, 3) end using JustPIC, JustPIC._3D # Threads is the default backend, # to run on a CUDA GPU load CUDA.jl (i.e. "using CUDA") at the beginning of the script, # and to run on an AMD GPU load AMDGPU.jl (i.e. "using AMDGPU") at the beginning of the script. const backend = @static if isCUDA CUDABackend # Options: CPUBackend, CUDABackend, AMDGPUBackend else JustPIC.CPUBackend # Options: CPUBackend, CUDABackend, AMDGPUBackend end using GeoParams, GLMakie, CellArrays ## SET OF HELPER FUNCTIONS PARTICULAR FOR THIS SCRIPT -------------------------------- import ParallelStencil.INDICES const idx_j = INDICES[3] macro all_j(A) return esc(:($A[$idx_j])) end @parallel function init_P!(P, ρg, z, sticky_air) @all(P) = @all(ρg) # @all(P) = abs(@all(ρg) * (@all_j(z) + sticky_air)) * <((@all_j(z) + sticky_air), 0.0) return nothing end function init_phases!(phases, particles, xc_anomaly, yc_anomaly, zc_anomaly, r_anomaly, sticky_air,top, bottom) ni = size(phases) @parallel_indices (I...) function init_phases!( phases, px, py, pz, index, xc_anomaly, yc_anomaly, zc_anomaly, r_anomaly, sticky_air, top, bottom ) @inbounds for ip in JustRelax.JustRelax.cellaxes(phases) # quick escape JustRelax.@cell(index[ip, I...]) == 0 && continue x = JustRelax.@cell px[ip, I...] y = JustRelax.@cell py[ip, I...] z = -(JustRelax.@cell pz[ip, I...]) - sticky_air if top ≤ z ≤ bottom @cell phases[ip, I...] = 1.0 # crust end # thermal anomaly - circular if ((x - xc_anomaly)^2 + (y - yc_anomaly)^2 + (z + zc_anomaly)^2 ≤ r_anomaly^2) JustRelax.@cell phases[ip, I...] = 2.0 end if z < top JustRelax.@cell phases[ip, I...] = 3.0 end end return nothing end @parallel (@idx ni) init_phases!( phases, particles.coords..., particles.index, xc_anomaly, yc_anomaly, zc_anomaly, r_anomaly, sticky_air, top, bottom, ) end # Initial thermal profile @parallel_indices (i, j, k) function init_T!(T, y, sticky_air, top, bottom, dTdz, offset) I = i, j, k depth = -y[k] - sticky_air if depth < top T[I...] = offset elseif top ≤ (depth) < bottom dTdZ = dTdz offset = offset T[I...] = (depth) * dTdZ + offset end return nothing end function circular_perturbation!(T, δT, xc_anomaly, yc_anomaly, zc_anomaly, r_anomaly, xvi, sticky_air) @parallel_indices (i, j, k) function _circular_perturbation!( T, δT, xc_anomaly, yc_anomaly, zc_anomaly, r_anomaly, x, y, z, sticky_air ) depth = -z[k] - sticky_air @inbounds if ((x[i] - xc_anomaly)^2 + (y[j] - yc_anomaly)^2 + (depth + zc_anomaly)^2 ≤ r_anomaly^2) T[i, j, k] = δT end return nothing end ni = size(T) @parallel (@idx ni) _circular_perturbation!( T, δT, xc_anomaly, yc_anomaly, zc_anomaly, r_anomaly, xvi..., sticky_air ) end function init_rheology(CharDim; is_compressible = false, steady_state=true) # plasticity setup do_DP = true # do_DP=false: Von Mises, do_DP=true: Drucker-Prager (friction angle) η_reg = 1.0e16Pa*s # regularisation "viscosity" for Drucker-Prager Coh = 10.0MPa # yield stress. If do_DP=true, τ_y stand for the cohesion: c*cos(ϕ) ϕ = 30.0 * do_DP # friction angle G0 = 6.0e11Pa # elastic shear modulus G_magma = 6.0e11Pa # elastic shear modulus perturbation # soft_C = LinearSoftening((ustrip(Coh)/2, ustrip(Coh)), (0e0, 1e-1)) # softening law soft_C = NonLinearSoftening(; ξ₀=ustrip(Coh), Δ=ustrip(Coh) / 2) # softening law pl = DruckerPrager_regularised(; C=Coh, ϕ=ϕ, η_vp=η_reg, Ψ=0.0, softening_C = soft_C) # plasticity if is_compressible == true el = SetConstantElasticity(; G=G0, ν=0.25) # elastic spring el_magma = SetConstantElasticity(; G=G_magma, ν=0.25)# elastic spring β_rock = 6.0e-11 β_magma = 6.0e-11 else el = SetConstantElasticity(; G=G0, ν=0.5) # elastic spring el_magma = SetConstantElasticity(; G=G_magma, ν=0.5) # elastic spring β_rock = inv(get_Kb(el)) β_magma = inv(get_Kb(el_magma)) end creep_rock = LinearViscous(; η=1e18 * Pa * s) creep_magma = LinearViscous(; η=1e18 * Pa * s) creep_air = LinearViscous(; η=1e18 * Pa * s) β_rock = 6.0e-11 β_magma = 6.0e-11 g = 9.81m/s^2 rheology = ( #Name="UpperCrust" SetMaterialParams(; Phase = 1, Density = PT_Density(; ρ0=2650kg / m^3, α=3e-5 / K, T0=0.0C, β=β_rock / Pa), HeatCapacity = ConstantHeatCapacity(; Cp=1050J / kg / K), Conductivity = ConstantConductivity(; k=3.0Watt / K / m), LatentHeat = ConstantLatentHeat(; Q_L=350e3J / kg), ShearHeat = ConstantShearheating(1.0NoUnits), CompositeRheology = CompositeRheology((creep_rock, el, pl)), # Melting = MeltingParam_Caricchi(), Gravity = ConstantGravity(; g=g), Elasticity = el, CharDim = CharDim, ), #Name="Magma" SetMaterialParams(; Phase = 2, Density = PT_Density(; ρ0=2650kg / m^3, T0=0.0C, β=β_magma / Pa), HeatCapacity = ConstantHeatCapacity(; Cp=1050J / kg / K), Conductivity = ConstantConductivity(; k=1.5Watt / K / m), LatentHeat = ConstantLatentHeat(; Q_L=350e3J / kg), ShearHeat = ConstantShearheating(0.0NoUnits), CompositeRheology = CompositeRheology((creep_magma, el_magma)), # Melting = MeltingParam_Caricchi(), Gravity = ConstantGravity(; g=g), Elasticity = el_magma, CharDim = CharDim, ), #Name="Sticky Air" SetMaterialParams(; Phase = 3, Density = ConstantDensity(ρ=1kg/m^3,), HeatCapacity = ConstantHeatCapacity(; Cp=1000J / kg / K), Conductivity = ConstantConductivity(; k=15Watt / K / m), LatentHeat = ConstantLatentHeat(; Q_L=0.0J / kg), ShearHeat = ConstantShearheating(0.0NoUnits), CompositeRheology = CompositeRheology((creep_air,)), Gravity = ConstantGravity(; g=g), CharDim = CharDim, ), ) end function main3D(igg; figdir = "output", nx = 64, ny = 64, nz = 64, do_vtk = false) # Characteristic lengths for non dimensionalization CharDim = GEO_units(;length=12.5km, viscosity=1e21, temperature = 1e3C) #-------JustRelax parameters------------------------------------------------------------- # Domain setup for JustRelax sticky_air = nondimensionalize(0km, CharDim) # thickness of the sticky air layer lz = nondimensionalize(12.5km,CharDim) + sticky_air # domain length in y-direction lx = ly = nondimensionalize(15.5km, CharDim) # domain length in x-direction li = lx, ly, lz # domain length in x- and y-direction ni = nx, ny, nz # number of grid points in x- and y-direction di = @. li / ni # grid step in x- and y-direction origin = nondimensionalize(0.0km,CharDim), nondimensionalize(0.0km,CharDim), -lz # origin coordinates of the domain grid = Geometry(ni, li; origin=origin) (; xci, xvi) = grid # nodes at the center and vertices of the cells εbg = nondimensionalize(0.0 / s, CharDim) # background strain rate #--------------------------------------------------------------------------------------- # Physical Parameters rheology = init_rheology(CharDim; is_compressible=true, steady_state=true) cutoff_visc = nondimensionalize((1e16Pa*s, 1e24Pa*s),CharDim) κ = (4 / (rheology[1].HeatCapacity[1].Cp * rheology[1].Density[1].ρ0)) dt = dt_diff = (0.5 * min(di...)^2 / κ / 2.01) # diffusive CFL timestep limiter # Initialize particles ------------------------------- nxcell = 20 max_xcell = 40 min_xcell = 15 particles = init_particles(backend, nxcell, max_xcell, min_xcell, xvi, di, ni); subgrid_arrays = SubgridDiffusionCellArrays(particles) # velocity grids grid_vxi = velocity_grids(xci, xvi, di) # temperature pT, pPhases = init_cell_arrays(particles, Val(2)) particle_args = (pT, pPhases) # Circular temperature anomaly-------------------------- x_anomaly = lx * 0.5 y_anomaly = ly * 0.5 z_anomaly = -lz * 0.5 # z_anomaly = nondimensionalize(-5km,CharDim) # origin of the small thermal anomaly r_anomaly = nondimensionalize(1.5km, CharDim) # radius of perturbation anomaly = nondimensionalize((750 + 273)K, CharDim) # thermal perturbation (in K) phase_ratios = PhaseRatio(backend_JR, ni, length(rheology)) init_phases!(pPhases, particles, x_anomaly, y_anomaly, z_anomaly, r_anomaly, sticky_air, nondimensionalize(0.0km,CharDim), nondimensionalize(20km,CharDim)) phase_ratios_center!(phase_ratios, particles, grid, pPhases) # Initialisation of thermal profile thermal = ThermalArrays(backend_JR, ni) # initialise thermal arrays and boundary conditions thermal_bc = TemperatureBoundaryConditions(; no_flux = (left = true, right = true, front = true, back = true, top = false, bot = false), ) @parallel (@idx ni .+ 1) init_T!( thermal.T, xvi[3], sticky_air, nondimensionalize(0e0km,CharDim), nondimensionalize(15km,CharDim), nondimensionalize((723 - 273)K,CharDim) / nondimensionalize(15km,CharDim), nondimensionalize(273K,CharDim) ) circular_perturbation!( thermal.T, anomaly, x_anomaly, y_anomaly, z_anomaly, r_anomaly, xvi, sticky_air ) thermal_bcs!(thermal, thermal_bc) temperature2center!(thermal) # STOKES --------------------------------------------- # Allocate arrays needed for every Stokes problem stokes = StokesArrays(backend_JR, ni) # initialise stokes arrays with the defined regime pt_stokes = PTStokesCoeffs(li, di; ϵ=1e-4, CFL=0.9 / √3.1) # ---------------------------------------------------- args = (; T=thermal.Tc, P=stokes.P, dt=dt, ΔTc=thermal.ΔTc) pt_thermal = PTThermalCoeffs( backend_JR, rheology, phase_ratios, args, dt, ni, di, li; ϵ=1e-5, CFL=0.8 / √3.1 ) flow_bcs = VelocityBoundaryConditions(; free_slip = (left=true, right=true, front=true, back=true, top=true, bot=true), no_slip = (left=false, right=false, front=false, back=false, top=false, bot=false), free_surface = true, ) flow_bcs!(stokes, flow_bcs) update_halo!(@velocity(stokes)...) # Buoyancy force & viscosity ρg = @zeros(ni...), @zeros(ni...), @zeros(ni...) # ρg[1] is the buoyancy force in the x direction, ρg[2] is the buoyancy force in the y direction for _ in 1:5 compute_ρg!(ρg[end], phase_ratios, rheology, (T=thermal.Tc, P=stokes.P)) @parallel init_P!(stokes.P, ρg[3], xci[3], sticky_air) end compute_viscosity!(stokes, phase_ratios, args, rheology, cutoff_visc) # Arguments for functions @copy thermal.Told thermal.T # IO ------------------------------------------------ # if it does not exist, make folder where figures are stored if do_vtk vtk_dir = joinpath(figdir, "vtk") take(vtk_dir) end take(figdir) # ---------------------------------------------------- # Plot initial T and η profiles let Zv = [z for _ in xvi[1], _ in xvi[2], z in xvi[3]][:] Z = [z for _ in xci[1], _ in xci[2], z in xci[3]][:] fig = Figure(; size=(1200, 900)) ax1 = Axis(fig[1, 1]; aspect=2 / 3, title="T") ax2 = Axis(fig[1, 2]; aspect=2 / 3, title="Pressure") scatter!( ax1, Array(ustrip.(dimensionalize(thermal.T[:], C, CharDim))), ustrip.(dimensionalize(Zv, km, CharDim)), ) scatter!( ax2, Array(ustrip.(dimensionalize(stokes.P[:], MPa, CharDim))), ustrip.(dimensionalize(Z, km, CharDim)), ) hideydecorations!(ax2) save(joinpath(figdir, "initial_profile.png"), fig) fig end # Time loop t, it = 0.0, 0 local Vx_v, Vy_v if do_vtk Vx_v = @zeros(ni .+ 1...) Vy_v = @zeros(ni .+ 1...) Vz_v = @zeros(ni .+ 1...) end dt₀ = similar(stokes.P) grid2particle!(pT, xvi, thermal.T, particles) @copy stokes.P0 stokes.P @copy thermal.Told thermal.T Tsurf, Tbot = extrema(thermal.T) while it < 25 # Update buoyancy and viscosity - args = (; T=thermal.Tc, P=stokes.P, dt=Inf) compute_ρg!(ρg[end], phase_ratios, rheology, (T=thermal.Tc, P=stokes.P)) compute_viscosity!(stokes, phase_ratios, args, rheology, cutoff_visc) # Stokes solver ----------------- solve!( stokes, pt_stokes, di, flow_bcs, ρg, phase_ratios, rheology, args, dt, igg; kwargs = (; iterMax = 150e3, free_surface = false, nout = 5e3, viscosity_cutoff = cutoff_visc, ) ) tensor_invariant!(stokes.ε) dt = compute_dt(stokes, di, dt_diff, igg) * 0.8 # -------------------------------- # Thermal solver --------------- heatdiffusion_PT!( thermal, pt_thermal, thermal_bc, rheology, args, dt, di; kwargs =(; igg = igg, phase = phase_ratios, iterMax = 150e3, nout = 1e3, verbose = true, ) ) # subgrid diffusion subgrid_characteristic_time!( subgrid_arrays, particles, dt₀, phase_ratios, rheology, thermal, stokes, xci, di ) centroid2particle!(subgrid_arrays.dt₀, xci, dt₀, particles) subgrid_diffusion!( pT, thermal.T, thermal.ΔT, subgrid_arrays, particles, xvi, di, dt ) # ------------------------------ # Advection -------------------- # advect particles in space advection!(particles, RungeKutta2(), @velocity(stokes), grid_vxi, dt) # advect particles in memory move_particles!(particles, xvi, particle_args) # check if we need to inject particles inject_particles_phase!(particles, pPhases, (pT, ), (thermal.T,), xvi) # update phase ratios phase_ratios_center!(phase_ratios, particles, grid, pPhases) particle2grid!(thermal.T, pT, xvi, particles) # @views thermal.T[:, :, end] .= Tsurf # @views thermal.T[:, :, 1] .= Tbot thermal_bcs!(thermal, thermal_bc) temperature2center!(thermal) # thermal.ΔT .= thermal.T .- thermal.Told # vertex2center!(thermal.ΔTc, thermal.ΔT) @show it += 1 t += dt # # # Plotting ------------------------------------------------------- if it == 1 || rem(it, 5) == 0 (; η) = stokes.viscosity # checkpointing(figdir, stokes, thermal.T, η, t) if igg.me == 0 if do_vtk velocity2vertex!(Vx_v, Vy_v, Vz_v, @velocity(stokes)...) data_v = (; T = Array(ustrip.(dimensionalize(thermal.T, C, CharDim))), τxy= Array(ustrip.(dimensionalize(stokes.τ.xy, s^-1, CharDim))), εxy= Array(ustrip.(dimensionalize(stokes.ε.xy, s^-1, CharDim))), ) data_c = (; P = Array(ustrip.(dimensionalize(stokes.P,MPa,CharDim))), τxx = Array(ustrip.(dimensionalize(stokes.τ.xx, MPa,CharDim))), τyy = Array(ustrip.(dimensionalize(stokes.τ.yy,MPa,CharDim))), τzz = Array(ustrip.(dimensionalize(stokes.τ.zz,MPa,CharDim))), τII = Array(ustrip.(dimensionalize(stokes.τ.II, MPa, CharDim))), εxx = Array(ustrip.(dimensionalize(stokes.ε.xx, s^-1,CharDim))), εyy = Array(ustrip.(dimensionalize(stokes.ε.yy, s^-1,CharDim))), εzz = Array(ustrip.(dimensionalize(stokes.ε.zz, s^-1,CharDim))), εII = Array(ustrip.(dimensionalize(stokes.ε.II, s^-1,CharDim))), η = Array(ustrip.(dimensionalize(stokes.viscosity.η,Pa*s,CharDim))), ) velocity_v = ( Array(ustrip.(dimensionalize(Vx_v,cm/yr,CharDim))), Array(ustrip.(dimensionalize(Vy_v, cm/yr, CharDim))), Array(ustrip.(dimensionalize(Vz_v, cm/yr, CharDim))), ) save_vtk( joinpath(vtk_dir, "vtk_" * lpad("$it", 6, "0")), xvi, xci, data_v, data_c, velocity_v ) end let Zv = [z for _ in 1:nx+1, _ in 1:ny+1, z in ustrip.(dimensionalize(xvi[3],km,CharDim))][:] Z = [z for _ in 1:nx , _ in 1:ny , z in ustrip.(dimensionalize(xci[3],km,CharDim))][:] fig = Figure(; size=(1200, 900)) ax1 = Axis(fig[1, 1]; aspect = 1, title="T") ax2 = Axis(fig[1, 2]; aspect = 1, title="Pressure") ax3 = Axis(fig[2, 1]; aspect = 1, title="τII") ax4 = Axis(fig[2, 2]; aspect = 1, title="Vz") ns = ny >>> 1 heatmap!(ax1, ustrip.(dimensionalize((Array(thermal.T)), C, CharDim))[:,ns,:] ) heatmap!(ax2, ustrip.(dimensionalize((Array(stokes.P)), MPa, CharDim))[:,ns,:] ) heatmap!(ax3, ustrip.(dimensionalize(Array(stokes.τ.II), MPa, CharDim))[:,ns,:]) heatmap!(ax4, ustrip.(dimensionalize(Array(stokes.V.Vz), m/s, CharDim))[:,ns,:]) hideydecorations!(ax2) save(joinpath(figdir, "pressure_profile_$it.png"), fig) fig end end end end # finalize_global_grid() return nothing end figdir = "Blob3D" do_vtk = true # set to true to generate VTK files for ParaView n = 64 nx = n ny = n nz = n igg = if !(JustRelax.MPI.Initialized()) # initialize (or not) MPI grid IGG(init_global_grid(nx, ny, nz; init_MPI=true)...) else igg end # run main script main3D(igg; figdir=figdir, nx=nx, ny=ny, nz=nz, do_vtk = do_vtk);
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
7087
# from "Fingerprinting secondary mantle plumes", Cloetingh et al. 2022 function init_rheologies(; is_plastic = true) # Dislocation and Diffusion creep disl_upper_crust = DislocationCreep(A=5.07e-18, n=2.3, E=154e3, V=6e-6, r=0.0, R=8.3145) disl_lower_crust = DislocationCreep(A=2.08e-23, n=3.2, E=238e3, V=6e-6, r=0.0, R=8.3145) disl_lithospheric_mantle = DislocationCreep(A=2.51e-17, n=3.5, E=530e3, V=6e-6, r=0.0, R=8.3145) disl_sublithospheric_mantle = DislocationCreep(A=2.51e-17, n=3.5, E=530e3, V=6e-6, r=0.0, R=8.3145) diff_lithospheric_mantle = DislocationCreep(A=2.51e-17, n=1.0, E=530e3, V=6e-6, r=0.0, R=8.3145) diff_sublithospheric_mantle = DislocationCreep(A=2.51e-17, n=1.0, E=530e3, V=6e-6, r=0.0, R=8.3145) # Elasticity el_upper_crust = SetConstantElasticity(; G=25e9, ν=0.5) el_lower_crust = SetConstantElasticity(; G=25e9, ν=0.5) el_lithospheric_mantle = SetConstantElasticity(; G=67e9, ν=0.5) el_sublithospheric_mantle = SetConstantElasticity(; G=67e9, ν=0.5) β_upper_crust = inv(get_Kb(el_upper_crust)) β_lower_crust = inv(get_Kb(el_lower_crust)) β_lithospheric_mantle = inv(get_Kb(el_lithospheric_mantle)) β_sublithospheric_mantle = inv(get_Kb(el_sublithospheric_mantle)) # Physical properties using GeoParams ---------------- η_reg = 1e16 cohesion = 3e6 friction = asind(0.2) pl_crust = if is_plastic DruckerPrager_regularised(; C = cohesion, ϕ=friction, η_vp=η_reg, Ψ=0.0) # non-regularized plasticity else DruckerPrager_regularised(; C = Inf, ϕ=friction, η_vp=η_reg, Ψ=0.0) # non-regularized plasticity end friction = asind(0.3) pl = if is_plastic DruckerPrager_regularised(; C = cohesion, ϕ=friction, η_vp=η_reg, Ψ=0.0) # non-regularized plasticity else DruckerPrager_regularised(; C = Inf, ϕ=friction, η_vp=η_reg, Ψ=0.0) # non-regularized plasticity end pl_wz = if is_plastic DruckerPrager_regularised(; C = 2e6, ϕ=2.0, η_vp=η_reg, Ψ=0.0) # non-regularized plasticity else DruckerPrager_regularised(; C = Inf, ϕ=friction, η_vp=η_reg, Ψ=0.0) # non-regularized plasticity end # crust K_crust = TP_Conductivity(; a = 0.64, b = 807e0, c = 0.77, d = 0.00004*1e-6, ) K_mantle = TP_Conductivity(; a = 0.73, b = 1293e0, c = 0.77, d = 0.00004*1e-6, ) # Define rheolgy struct rheology = ( # Name = "UpperCrust", SetMaterialParams(; Phase = 1, Density = PT_Density(; ρ0=2.75e3, β=β_upper_crust, T0=0.0, α = 3.5e-5), HeatCapacity = ConstantHeatCapacity(; Cp=7.5e2), Conductivity = K_crust, CompositeRheology = CompositeRheology((disl_upper_crust, el_upper_crust, pl_crust)), Elasticity = el_upper_crust, RadioactiveHeat = ConstantRadioactiveHeat(0.0), Gravity = ConstantGravity(; g=9.81), ), # Name = "LowerCrust", SetMaterialParams(; Phase = 2, Density = PT_Density(; ρ0=3e3, β=β_lower_crust, T0=0.0, α = 3.5e-5), HeatCapacity = ConstantHeatCapacity(; Cp=7.5e2), Conductivity = K_crust, RadioactiveHeat = ConstantRadioactiveHeat(0.0), CompositeRheology = CompositeRheology((disl_lower_crust, el_lower_crust, pl_crust)), Elasticity = el_lower_crust, ), # Name = "LithosphericMantle", SetMaterialParams(; Phase = 3, Density = PT_Density(; ρ0=3.3e3, β=β_lithospheric_mantle, T0=0.0, α = 3e-5), HeatCapacity = ConstantHeatCapacity(; Cp=1.25e3), Conductivity = K_mantle, RadioactiveHeat = ConstantRadioactiveHeat(0.0), CompositeRheology = CompositeRheology((disl_lithospheric_mantle, diff_lithospheric_mantle, el_lithospheric_mantle, pl)), Elasticity = el_lithospheric_mantle, ), # Name = "SubLithosphericMantle", # SetMaterialParams(; # Phase = 4, # Density = PT_Density(; ρ0=3.3e3, β=β_sublithospheric_mantle, T0=0.0, α = 3e-5), # HeatCapacity = ConstantHeatCapacity(; Cp=1.25e3), # Conductivity = K_mantle, # RadioactiveHeat = ConstantRadioactiveHeat(0.0), # CompositeRheology = CompositeRheology((disl_sublithospheric_mantle, diff_sublithospheric_mantle, el_sublithospheric_mantle)), # Elasticity = el_sublithospheric_mantle, # ), # Name = "Plume", SetMaterialParams(; Phase = 4, Density = PT_Density(; ρ0=3.3e3-50, β=β_sublithospheric_mantle, T0=0.0, α = 3e-5), HeatCapacity = ConstantHeatCapacity(; Cp=1.25e3), Conductivity = K_mantle, RadioactiveHeat = ConstantRadioactiveHeat(0.0), CompositeRheology = CompositeRheology((disl_sublithospheric_mantle, diff_sublithospheric_mantle, el_sublithospheric_mantle)), Elasticity = el_sublithospheric_mantle, ), # Name = "StickyAir", SetMaterialParams(; Phase = 5, Density = ConstantDensity(; ρ=1e3), HeatCapacity = ConstantHeatCapacity(; Cp=1.25e3), RadioactiveHeat = ConstantRadioactiveHeat(0.0), Conductivity = ConstantConductivity(; k=15.0), CompositeRheology = CompositeRheology((LinearViscous(; η=1e21),)), ), ) end function init_phases!(phases, particles, Lx; d=650e3, r=50e3) ni = size(phases) @parallel_indices (i, j) function init_phases!(phases, px, py, index, r, Lx) @inbounds for ip in JustRelax.cellaxes(phases) # quick escape JustRelax.@cell(index[ip, i, j]) == 0 && continue x = JustRelax.@cell px[ip, i, j] depth = -(JustRelax.@cell py[ip, i, j]) if 0e0 ≤ depth ≤ 21e3 @cell phases[ip, i, j] = 1.0 elseif 35e3 ≥ depth > 21e3 @cell phases[ip, i, j] = 2.0 elseif 90e3 ≥ depth > 35e3 @cell phases[ip, i, j] = 3.0 elseif depth > 90e3 @cell phases[ip, i, j] = 3.0 elseif depth < 0e0 @cell phases[ip, i, j] = 5.0 end # plume - rectangular if ((x - Lx * 0.5)^2 ≤ r^2) && ((depth - d)^2 ≤ r^2) JustRelax.@cell phases[ip, i, j] = 4.0 end end return nothing end @parallel (@idx ni) init_phases!(phases, particles.coords..., particles.index, r, Lx) end
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
10615
using JustRelax, JustRelax.JustRelax2D, JustRelax.DataIO import JustRelax.@cell const backend_JR = CPUBackend using ParallelStencil, ParallelStencil.FiniteDifferences2D @init_parallel_stencil(Threads, Float64, 2) #or (CUDA, Float64, 2) or (AMDGPU, Float64, 2) using JustPIC, JustPIC._2D # Threads is the default backend, # to run on a CUDA GPU load CUDA.jl (i.e. "using CUDA") at the beginning of the script, # and to run on an AMD GPU load AMDGPU.jl (i.e. "using AMDGPU") at the beginning of the script. const backend = CPUBackend # Options: CPUBackend, CUDABackend, AMDGPUBackend # Load script dependencies using Printf, LinearAlgebra, GeoParams, GLMakie, SpecialFunctions, CellArrays # Load file with all the rheology configurations include("Layered_rheology.jl") ## SET OF HELPER FUNCTIONS PARTICULAR FOR THIS SCRIPT -------------------------------- import ParallelStencil.INDICES const idx_j = INDICES[2] macro all_j(A) esc(:($A[$idx_j])) end # Initial pressure profile - not accurate @parallel function init_P!(P, ρg, z) @all(P) = abs(@all(ρg) * @all_j(z)) * <(@all_j(z), 0.0) return nothing end # Initial thermal profile @parallel_indices (i, j) function init_T!(T, z) depth = -z[j] # (depth - 15e3) because we have 15km of sticky air if depth < 0e0 T[i + 1, j] = 273e0 elseif 0e0 ≤ (depth) < 35e3 dTdZ = (923-273)/35e3 offset = 273e0 T[i + 1, j] = (depth) * dTdZ + offset elseif 110e3 > (depth) ≥ 35e3 dTdZ = (1492-923)/75e3 offset = 923 T[i + 1, j] = (depth - 35e3) * dTdZ + offset elseif (depth) ≥ 110e3 dTdZ = (1837 - 1492)/590e3 offset = 1492e0 T[i + 1, j] = (depth - 110e3) * dTdZ + offset end return nothing end # Thermal rectangular perturbation function rectangular_perturbation!(T, xc, yc, r, xvi) @parallel_indices (i, j) function _rectangular_perturbation!(T, xc, yc, r, x, y) @inbounds if ((x[i]-xc)^2 ≤ r^2) && ((y[j] - yc)^2 ≤ r^2) depth = abs(y[j]) dTdZ = (2047 - 2017) / 50e3 offset = 2017 T[i + 1, j] = (depth - 585e3) * dTdZ + offset end return nothing end ni = length.(xvi) @parallel (@idx ni) _rectangular_perturbation!(T, xc, yc, r, xvi...) return nothing end ## END OF HELPER FUNCTION ------------------------------------------------------------ ## BEGIN OF MAIN SCRIPT -------------------------------------------------------------- function main2D(igg; ar=8, ny=16, nx=ny*8, figdir="figs2D", do_vtk =false) # Physical domain ------------------------------------ ly = 700e3 # domain length in y lx = ly * ar # domain length in x ni = nx, ny # number of cells li = lx, ly # domain length in x- and y- di = @. li / ni # grid step in x- and -y origin = 0.0, -ly # origin coordinates (15km f sticky air layer) grid = Geometry(ni, li; origin = origin) (; xci, xvi) = grid # nodes at the center and vertices of the cells # ---------------------------------------------------- # Physical properties using GeoParams ---------------- rheology = init_rheologies(; is_plastic = true) κ = (10 / (rheology[1].HeatCapacity[1].Cp * rheology[1].Density[1].ρ0)) dt = dt_diff = 0.5 * min(di...)^2 / κ / 2.01 # diffusive CFL timestep limiter # ---------------------------------------------------- # Weno model ----------------------------------------- weno = WENO5(ni=(nx,ny).+1, method=Val{2}()) # ni.+1 for Temp # ---------------------------------------------------- # Initialize particles ------------------------------- nxcell, max_xcell, min_xcell = 20, 40, 1 particles = init_particles(backend, nxcell, max_xcell, min_xcell, xvi...); # velocity grids grid_vx, grid_vy = velocity_grids(xci, xvi, di) # temperature pT, pPhases = init_cell_arrays(particles, Val(3)) particle_args = (pT, pPhases) # Elliptical temperature anomaly xc_anomaly = lx/2 # origin of thermal anomaly yc_anomaly = -610e3 # origin of thermal anomaly r_anomaly = 25e3 # radius of perturbation init_phases!(pPhases, particles, lx; d=abs(yc_anomaly), r=r_anomaly) phase_ratios = PhaseRatio(backend_JR, ni, length(rheology)) phase_ratios_center!(phase_ratios, particles, grid, pPhases) # ---------------------------------------------------- # STOKES --------------------------------------------- # Allocate arrays needed for every Stokes problem stokes = StokesArrays(backend_JR, ni) pt_stokes = PTStokesCoeffs(li, di; ϵ=1e-4, CFL = 0.1 / √2.1) # ---------------------------------------------------- # TEMPERATURE PROFILE -------------------------------- thermal = ThermalArrays(backend_JR, ni) thermal_bc = TemperatureBoundaryConditions(; no_flux = (left = true, right = true, top = false, bot = false), ) # initialize thermal profile - Half space cooling @parallel (@idx ni .+ 1) init_T!(thermal.T, xvi[2]) thermal_bcs!(thermal, thermal_bc) rectangular_perturbation!(thermal.T, xc_anomaly, yc_anomaly, r_anomaly, xvi) temperature2center!(thermal) # ---------------------------------------------------- # Buoyancy forces ρg = @zeros(ni...), @zeros(ni...) for _ in 1:1 compute_ρg!(ρg[2], phase_ratios, rheology, (T=thermal.Tc, P=stokes.P)) @parallel init_P!(stokes.P, ρg[2], xci[2]) end args = (; T = thermal.Tc, P = stokes.P, dt = dt, ΔTc = thermal.ΔTc) # Rheology viscosity_cutoff = (1e16, 1e24) compute_viscosity!(stokes, phase_ratios, args, rheology, viscosity_cutoff) (; η, η_vep) = stokes.viscosity # PT coefficients for thermal diffusion pt_thermal = PTThermalCoeffs( backend_JR, rheology, phase_ratios, args, dt, ni, di, li; ϵ=1e-5, CFL=1e-3 / √2.1 ) # Boundary conditions flow_bcs = VelocityBoundaryConditions(; free_slip = (left = true, right=true, top=true, bot=true), ) flow_bcs!(stokes, flow_bcs) # apply boundary conditions update_halo!(@velocity(stokes)...) # IO ----- ------------------------------------------- # if it does not exist, make folder where figures are stored if do_vtk vtk_dir = joinpath(figdir,"vtk") take(vtk_dir) end take(figdir) # ---------------------------------------------------- # Plot initial T and η profiles let Yv = [y for x in xvi[1], y in xvi[2]][:] Y = [y for x in xci[1], y in xci[2]][:] fig = Figure(size = (1200, 900)) ax1 = Axis(fig[1,1], aspect = 2/3, title = "T") ax2 = Axis(fig[1,2], aspect = 2/3, title = "log10(η)") scatter!(ax1, Array(thermal.T[2:end-1,:][:]), Yv./1e3) scatter!(ax2, Array(log10.(stokes.viscosity.η[:])), Y./1e3) ylims!(ax1, minimum(xvi[2])./1e3, 0) ylims!(ax2, minimum(xvi[2])./1e3, 0) hideydecorations!(ax2) save(joinpath(figdir, "initial_profile.png"), fig) fig end # WENO arrays T_WENO = @zeros(ni.+1) Vx_v = @zeros(ni.+1...) Vy_v = @zeros(ni.+1...) # Time loop t, it = 0.0, 0 while (t/(1e6 * 3600 * 24 *365.25)) < 5 # run only for 5 Myrs # Update buoyancy and viscosity - args = (; T = thermal.Tc, P = stokes.P, dt=dt, ΔTc = thermal.ΔTc) compute_ρg!(ρg[end], phase_ratios, rheology, (T=thermal.Tc, P=stokes.P)) compute_viscosity!( stokes, phase_ratios, args, rheology, viscosity_cutoff ) # ------------------------------ # Stokes solver ---------------- iters = solve!( stokes, pt_stokes, di, flow_bcs, ρg, phase_ratios, rheology, args, Inf, igg; kwargs = (; iterMax = 150e3, nout = 1e3, viscosity_cutoff = viscosity_cutoff ) ) tensor_invariant!(stokes.ε) dt = compute_dt(stokes, di, dt_diff) # ------------------------------ # Weno advection heatdiffusion_PT!( thermal, pt_thermal, thermal_bc, rheology, args, dt, di; kwargs = ( igg = igg, phase = phase_ratios, iterMax = 10e3, nout = 1e2, verbose = true ), ) T_WENO .= thermal.T[2:end-1, :] velocity2vertex!(Vx_v, Vy_v, @velocity(stokes)...) WENO_advection!(T_WENO, (Vx_v, Vy_v), weno, di, dt) thermal.T[2:end-1, :] .= T_WENO # ------------------------------ # Advection -------------------- # advect particles in space advection!(particles, RungeKutta2(), @velocity(stokes), (grid_vx, grid_vy), dt) # advect particles in memory move_particles!(particles, xvi, particle_args) # check if we need to inject particles inject_particles_phase!(particles, pPhases, (pT, ), (T_WENO,), xvi) # update phase ratios phase_ratios_center!(phase_ratios, particles, grid, pPhases) @show it += 1 t += dt # Data I/O and plotting --------------------- if it == 1 || rem(it, 10) == 0 # Make Makie figure fig = Figure(size = (900, 900), title = "t = $t") ax1 = Axis(fig[1, 1]) h1 = heatmap!(ax1, xvi[1].*1e-3, xvi[2].*1e-3, Array(T_WENO) , colormap=:batlow) Colorbar(fig[1,2], h1) save(joinpath(figdir, "$(it).png"), fig) fig end # ------------------------------ end return iters end ## END OF MAIN SCRIPT ---------------------------------------------------------------- # (Path)/folder where output data and figures are stored figdir = "Weno2D" ar = 1 # aspect ratio n = 256 nx = n*ar - 2 ny = n - 2 igg = if !(JustRelax.MPI.Initialized()) # initialize (or not) MPI grid IGG(init_global_grid(nx, ny, 1; init_MPI= true)...) else igg end # run main script main2D(igg; figdir = figdir, ar = ar, nx = nx, ny = ny);
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
12462
# const isCUDA = false const isCUDA = true @static if isCUDA using CUDA end using JustRelax, JustRelax.JustRelax2D, JustRelax.DataIO import JustRelax.@cell const backend = @static if isCUDA CUDABackend # Options: CPUBackend, CUDABackend, AMDGPUBackend else JustRelax.CPUBackend # Options: CPUBackend, CUDABackend, AMDGPUBackend end using ParallelStencil, ParallelStencil.FiniteDifferences2D @static if isCUDA @init_parallel_stencil(CUDA, Float64, 2) else @init_parallel_stencil(Threads, Float64, 2) end using JustPIC, JustPIC._2D # Threads is the default backend, # to run on a CUDA GPU load CUDA.jl (i.e. "using CUDA") at the beginning of the script, # and to run on an AMD GPU load AMDGPU.jl (i.e. "using AMDGPU") at the beginning of the script. const backend_JP = @static if isCUDA CUDABackend # Options: CPUBackend, CUDABackend, AMDGPUBackend else JustPIC.CPUBackend # Options: CPUBackend, CUDABackend, AMDGPUBackend end # Load script dependencies using GeoParams, GLMakie, CellArrays # Load file with all the rheology configurations include("Subd2D_setup.jl") include("Subd2D_rheology.jl") ## SET OF HELPER FUNCTIONS PARTICULAR FOR THIS SCRIPT -------------------------------- import ParallelStencil.INDICES const idx_k = INDICES[2] macro all_k(A) esc(:($A[$idx_k])) end function copyinn_x!(A, B) @parallel function f_x(A, B) @all(A) = @inn_x(B) return nothing end @parallel f_x(A, B) end # Initial pressure profile - not accurate @parallel function init_P!(P, ρg, z) @all(P) = abs(@all(ρg) * @all_k(z)) * <(@all_k(z), 0.0) return nothing end ## END OF HELPER FUNCTION ------------------------------------------------------------ ## BEGIN OF MAIN SCRIPT -------------------------------------------------------------- function main(li, origin, phases_GMG, igg; nx=16, ny=16, figdir="figs2D", do_vtk =false) # Physical domain ------------------------------------ ni = nx, ny # number of cells di = @. li / ni # grid steps grid = Geometry(ni, li; origin = origin) (; xci, xvi) = grid # nodes at the center and vertices of the cells # ---------------------------------------------------- # Physical properties using GeoParams ---------------- rheology = init_rheology_linear() dt = 50e3 * 3600 * 24 * 365 # diffusive CFL timestep limiter # ---------------------------------------------------- # Initialize particles ------------------------------- nxcell = 40 max_xcell = 60 min_xcell = 20 particles = init_particles( backend_JP, nxcell, max_xcell, min_xcell, xvi, di, ni ) subgrid_arrays = SubgridDiffusionCellArrays(particles) # velocity grids grid_vxi = velocity_grids(xci, xvi, di) # material phase & temperature pPhases, pT = init_cell_arrays(particles, Val(2)) particle_args = (pT, pPhases) # Assign particles phases anomaly phases_device = PTArray(backend)(phases_GMG) phase_ratios = PhaseRatio(backend, ni, length(rheology)) init_phases!(pPhases, phases_device, particles, xvi) phase_ratios_center!(phase_ratios, particles, grid, pPhases) # ---------------------------------------------------- # STOKES --------------------------------------------- # Allocate arrays needed for every Stokes problem stokes = StokesArrays(backend, ni) pt_stokes = PTStokesCoeffs(li, di; ϵ=1e-4, Re=3π, r=1e0, CFL = 1 / √2.1) # Re=3π, r=0.7 # ---------------------------------------------------- # TEMPERATURE PROFILE -------------------------------- Ttop = 20 + 273 Tbot = maximum(T_GMG) thermal = ThermalArrays(backend, ni) @views thermal.T[2:end-1, :] .= PTArray(backend)(T_GMG) thermal_bc = TemperatureBoundaryConditions(; no_flux = (left = true, right = true, top = false, bot = false), ) thermal_bcs!(thermal, thermal_bc) @views thermal.T[:, end] .= Ttop @views thermal.T[:, 1] .= Tbot temperature2center!(thermal) # ---------------------------------------------------- # Buoyancy forces ρg = ntuple(_ -> @zeros(ni...), Val(2)) compute_ρg!(ρg[2], phase_ratios, rheology_augmented, (T=thermal.Tc, P=stokes.P)) stokes.P .= PTArray(backend)(reverse(cumsum(reverse((ρg[2]).* di[2], dims=2), dims=2), dims=2)) # Rheology args0 = (T=thermal.Tc, P=stokes.P, dt = Inf) viscosity_cutoff = (1e17, 1e24) compute_viscosity!(stokes, phase_ratios, args0, rheology, viscosity_cutoff) # PT coefficients for thermal diffusion pt_thermal = PTThermalCoeffs( backend, rheology_augmented, phase_ratios, args0, dt, ni, di, li; ϵ=1e-5, CFL=1e-3 / √3 ) # Boundary conditions flow_bcs = VelocityBoundaryConditions(; free_slip = (left = true , right = true , top = true , bot = true), free_surface = false, ) flow_bcs!(stokes, flow_bcs) # apply boundary conditions update_halo!(@velocity(stokes)...) # IO ------------------------------------------------- # if it does not exist, make folder where figures are stored if do_vtk vtk_dir = joinpath(figdir, "vtk") take(vtk_dir) end take(figdir) # ---------------------------------------------------- local Vx_v, Vy_v if do_vtk Vx_v = @zeros(ni.+1...) Vy_v = @zeros(ni.+1...) end # Smooth out thermal field --------------------------- for _ in 1:10 heatdiffusion_PT!( thermal, pt_thermal, thermal_bc, rheology_augmented, args0, 1e6 * 3600 * 24 * 365.25, di; kwargs = ( igg = igg, phase = phase_ratios, iterMax = 150e3, nout = 1e2, verbose = true, ) ) end T_buffer = @zeros(ni.+1) Told_buffer = similar(T_buffer) dt₀ = similar(stokes.P) for (dst, src) in zip((T_buffer, Told_buffer), (thermal.T, thermal.Told)) copyinn_x!(dst, src) end grid2particle!(pT, xvi, T_buffer, particles) # Time loop t, it = 0.0, 0 while it < 1000 # run only for 5 Myrs # interpolate fields from particle to grid vertices particle2grid!(T_buffer, pT, xvi, particles) @views T_buffer[:, end] .= Ttop @views T_buffer[:, 1] .= Tbot @views thermal.T[2:end-1, :] .= T_buffer thermal_bcs!(thermal, thermal_bc) temperature2center!(thermal) args = (; T = thermal.Tc, P = stokes.P, dt=Inf) # Stokes solver ---------------- t_stokes = @elapsed begin out = solve!( stokes, pt_stokes, di, flow_bcs, ρg, phase_ratios, rheology_augmented, args, dt, igg; kwargs = ( iterMax = 150e3, nout = 1e3, viscosity_cutoff = viscosity_cutoff, free_surface = false, viscosity_relaxation = 1e-2 ) ); end println("Stokes solver time ") println(" Total time: $t_stokes s") println(" Time/iteration: $(t_stokes / out.iter) s") tensor_invariant!(stokes.ε) dt = compute_dt(stokes, di) * 0.8 # ------------------------------ # Thermal solver --------------- heatdiffusion_PT!( thermal, pt_thermal, thermal_bc, rheology_augmented, args, dt, di; kwargs = ( igg = igg, phase = phase_ratios, iterMax = 50e3, nout = 1e2, verbose = true, ) ) subgrid_characteristic_time!( subgrid_arrays, particles, dt₀, phase_ratios, rheology_augmented, thermal, stokes, xci, di ) centroid2particle!(subgrid_arrays.dt₀, xci, dt₀, particles) subgrid_diffusion!( pT, thermal.T, thermal.ΔT, subgrid_arrays, particles, xvi, di, dt ) # ------------------------------ # Advection -------------------- # advect particles in space advection!(particles, RungeKutta2(), @velocity(stokes), grid_vxi, dt) # advect particles in memory move_particles!(particles, xvi, particle_args) # check if we need to inject particles inject_particles_phase!(particles, pPhases, (pT, ), (T_buffer, ), xvi) # update phase ratios phase_ratios_center!(phase_ratios, particles, grid, pPhases) @show it += 1 t += dt # Data I/O and plotting --------------------- if it == 1 || rem(it, 10) == 0 # checkpointing(figdir, stokes, thermal.T, η, t) (; η_vep, η) = stokes.viscosity if do_vtk velocity2vertex!(Vx_v, Vy_v, @velocity(stokes)...) data_v = (; T = Array(T_buffer), τII = Array(stokes.τ.II), εII = Array(stokes.ε.II), Vx = Array(Vx_v), Vy = Array(Vy_v), ) data_c = (; P = Array(stokes.P), η = Array(η_vep), ) velocity_v = ( Array(Vx_v), Array(Vy_v), ) save_vtk( joinpath(vtk_dir, "vtk_" * lpad("$it", 6, "0")), xvi, xci, data_v, data_c, velocity_v ) end # Make particles plottable p = particles.coords ppx, ppy = p pxv = ppx.data[:]./1e3 pyv = ppy.data[:]./1e3 clr = pPhases.data[:] # clr = pT.data[:] idxv = particles.index.data[:]; # Make Makie figure ar = 3 fig = Figure(size = (1200, 900), title = "t = $t") ax1 = Axis(fig[1,1], aspect = ar, title = "T [K] (t=$(t/(1e6 * 3600 * 24 *365.25)) Myrs)") ax2 = Axis(fig[2,1], aspect = ar, title = "Phase") ax3 = Axis(fig[1,3], aspect = ar, title = "log10(εII)") ax4 = Axis(fig[2,3], aspect = ar, title = "log10(η)") # Plot temperature h1 = heatmap!(ax1, xvi[1].*1e-3, xvi[2].*1e-3, Array(thermal.T[2:end-1,:]) , colormap=:batlow) # Plot particles phase h2 = scatter!(ax2, Array(pxv[idxv]), Array(pyv[idxv]), color=Array(clr[idxv]), markersize = 1) # Plot 2nd invariant of strain rate h3 = heatmap!(ax3, xci[1].*1e-3, xci[2].*1e-3, Array(log10.(stokes.ε.II)) , colormap=:batlow) # Plot effective viscosity h4 = heatmap!(ax4, xci[1].*1e-3, xci[2].*1e-3, Array(log10.(η_vep)) , colormap=:batlow) hidexdecorations!(ax1) hidexdecorations!(ax2) hidexdecorations!(ax3) Colorbar(fig[1,2], h1) Colorbar(fig[2,2], h2) Colorbar(fig[1,4], h3) Colorbar(fig[2,4], h4) linkaxes!(ax1, ax2, ax3, ax4) fig save(joinpath(figdir, "$(it).png"), fig) end # ------------------------------ end return nothing end ## END OF MAIN SCRIPT ---------------------------------------------------------------- do_vtk = true # set to true to generate VTK files for ParaView figdir = "Subduction2D" n = 128 nx, ny = 512, 256 li, origin, phases_GMG, T_GMG = GMG_subduction_2D(nx+1, ny+1) igg = if !(JustRelax.MPI.Initialized()) # initialize (or not) MPI grid IGG(init_global_grid(nx, ny, 1; init_MPI= true)...) else igg end main(li, origin, phases_GMG, igg; figdir = figdir, nx = nx, ny = ny, do_vtk = do_vtk);
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
4246
using GeoParams.Dislocation using GeoParams.Diffusion function init_rheology_nonNewtonian() #dislocation laws disl_wet_olivine = SetDislocationCreep(Dislocation.wet_olivine1_Hirth_2003) # diffusion laws diff_wet_olivine = SetDiffusionCreep(Diffusion.wet_olivine_Hirth_2003) lithosphere_rheology = CompositeRheology( (disl_wet_olivine, diff_wet_olivine)) init_rheologies(lithosphere_rheology) end function init_rheology_nonNewtonian_plastic() #dislocation laws disl_wet_olivine = SetDislocationCreep(Dislocation.wet_olivine1_Hirth_2003) # diffusion laws diff_wet_olivine = SetDiffusionCreep(Diffusion.wet_olivine_Hirth_2003) # plasticity ϕ_wet_olivine = asind(0.1) C_wet_olivine = 1e6 η_reg = 1e19 lithosphere_rheology = CompositeRheology( ( disl_wet_olivine, diff_wet_olivine, DruckerPrager_regularised(; C = C_wet_olivine, ϕ = ϕ_wet_olivine, η_vp=η_reg, Ψ=0.0) # non-regularized plasticity ) ) init_rheologies(lithosphere_rheology) end function init_rheology_linear() lithosphere_rheology = CompositeRheology( (LinearViscous(; η=1e20),)) init_rheologies(lithosphere_rheology) end function init_rheologies(lithosphere_rheology) # common physical properties α = 2.4e-5 # 1 / K Cp = 750 # J / kg K # Define rheolgy struct rheology = ( # Name = "Asthenoshpere", SetMaterialParams(; Phase = 1, Density = ConstantDensity(; ρ=3.2e3), HeatCapacity = ConstantHeatCapacity(; Cp = Cp), Conductivity = ConstantConductivity(; k = 2.5), CompositeRheology = CompositeRheology( (LinearViscous(; η=1e20),)), Gravity = ConstantGravity(; g=9.81), ), # Name = "Oceanic lithosphere", SetMaterialParams(; Phase = 2, Density = PT_Density(; ρ0=3.2e3, α = α, β = 0e0, T0 = 273+1474), HeatCapacity = ConstantHeatCapacity(; Cp = Cp), Conductivity = ConstantConductivity(; k = 2.5), CompositeRheology = lithosphere_rheology, ), # Name = "oceanic crust", SetMaterialParams(; Phase = 3, Density = ConstantDensity(; ρ=3.2e3), HeatCapacity = ConstantHeatCapacity(; Cp = Cp), Conductivity = ConstantConductivity(; k = 2.5), CompositeRheology = CompositeRheology( (LinearViscous(; η=1e20),)), ), # Name = "StickyAir", SetMaterialParams(; Phase = 4, Density = ConstantDensity(; ρ=100), # water density HeatCapacity = ConstantHeatCapacity(; Cp=3e3), Conductivity = ConstantConductivity(; k=1.0), CompositeRheology = CompositeRheology((LinearViscous(; η=1e19),)), ), ) end function init_phases!(phases, phase_grid, particles, xvi) ni = size(phases) @parallel (@idx ni) _init_phases!(phases, phase_grid, particles.coords, particles.index, xvi) end @parallel_indices (I...) function _init_phases!(phases, phase_grid, pcoords::NTuple{N, T}, index, xvi) where {N,T} ni = size(phases) for ip in JustRelax.cellaxes(phases) # quick escape @cell(index[ip, I...]) == 0 && continue pᵢ = ntuple(Val(N)) do i @cell pcoords[i][ip, I...] end d = Inf # distance to the nearest particle particle_phase = -1 for offi in 0:1, offj in 0:1 ii = I[1] + offi jj = I[2] + offj !(ii ≤ ni[1]) && continue !(jj ≤ ni[2]) && continue xvᵢ = ( xvi[1][ii], xvi[2][jj], ) d_ijk = √(sum((pᵢ[i] - xvᵢ[i])^2 for i in 1:N)) if d_ijk < d d = d_ijk particle_phase = phase_grid[ii, jj] end end @cell phases[ip, I...] = Float64(particle_phase) end return nothing end
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
2495
using GeophysicalModelGenerator function GMG_subduction_2D(nx, ny) model_depth = 660 # Our starting basis is the example above with ridge and overriding slab nx, nz = nx, ny Tbot = 1474.0 x = range(0, 3000, nx); air_thickness = 10.0 z = range(-model_depth, air_thickness, nz); Grid2D = CartData(xyz_grid(x,0,z)) Phases = zeros(Int64, nx, 1, nz); Temp = fill(Tbot, nx, 1, nz); Tlab = 1300 # lith = LithosphericPhases(Layers=[80], Phases=[1 0], Tlab=Tlab) # phases # 0: asthenosphere # 1: lithosphere # 2: subduction lithosphere # 3: oceanic crust # 4: air add_box!( Phases, Temp, Grid2D; xlim =(0, 3000), zlim =(-model_depth, 0.0), Origin = nothing, StrikeAngle=0, DipAngle=0, phase = LithosphericPhases(Layers=[], Phases=[0], Tlab=Tlab), T = HalfspaceCoolingTemp(Tsurface=20, Tmantle=Tbot, Age=50, Adiabat=0) ) # Add left oceanic plate add_box!( Phases, Temp, Grid2D; xlim =(100, 3000-100), zlim =(-model_depth, 0.0), Origin = nothing, StrikeAngle=0, DipAngle=0, phase = LithosphericPhases(Layers=[80], Phases=[1 0], Tlab=Tlab), T = HalfspaceCoolingTemp(Tsurface=20, Tmantle=Tbot, Age=50, Adiabat=0) ) # Add right oceanic plate crust add_box!( Phases, Temp, Grid2D; xlim =(3000-1430, 3000-200), zlim =(-model_depth, 0.0), Origin = nothing, StrikeAngle=0, DipAngle=0, phase = LithosphericPhases(Layers=[8 72], Phases=[2 1 0], Tlab=Tlab), T = HalfspaceCoolingTemp(Tsurface=20, Tmantle=Tbot, Age=50, Adiabat=0) ) # Add slab add_box!( Phases, Temp, Grid2D; xlim = (3000-1430, 3000-1430-250), zlim =(-80, 0.0), Origin = nothing, StrikeAngle=0, DipAngle=-30, phase = LithosphericPhases(Layers=[8 80], Phases=[2 1 0], Tlab=Tlab), T = HalfspaceCoolingTemp(Tsurface=20, Tmantle=Tbot, Age=50, Adiabat=0) ) surf = Grid2D.z.val .> 0.0 Temp[surf] .= 20.0 Phases[surf] .= 3 Grid2D = addfield(Grid2D,(;Phases, Temp)) li = (abs(last(x)-first(x)), abs(last(z)-first(z))).* 1e3 origin = (x[1], z[1]) .* 1e3 ph = Phases[:,1,:] .+ 1 T = Temp[:,1,:] return li, origin, ph, T end
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
8463
""" interp_Vx_on_Vy!(Vx_on_Vy, Vx) Interpolates the values of `Vx` onto the grid points of `Vy`. # Arguments - `Vx_on_Vy::AbstractArray`: `Vx` at `Vy` grid points. - `Vx::AbstractArray`: `Vx` at its staggered grid points. """ @parallel_indices (i, j) function interp_Vx_on_Vy!(Vx_on_Vy, Vx) Vx_on_Vy[i + 1, j] = 0.25 * (Vx[i, j] + Vx[i + 1, j] + Vx[i, j + 1] + Vx[i + 1, j + 1]) return nothing end @parallel_indices (i, j) function interp_Vx∂ρ∂x_on_Vy!(Vx_on_Vy, Vx, ρg, _dx) nx, ny = size(ρg) iW = clamp(i - 1, 1, nx) iE = clamp(i + 1, 1, nx) jS = clamp(j - 1, 1, ny) jN = clamp(j, 1, ny) # OPTION 1 ρg_L = 0.25 * (ρg[iW, jS] + ρg[i, jS] + ρg[iW, jN] + ρg[i, jN]) ρg_R = 0.25 * (ρg[iE, jS] + ρg[i, jS] + ρg[iE, jN] + ρg[i, jN]) Vx_on_Vy[i + 1, j] = (0.25 * (Vx[i, j] + Vx[i + 1, j] + Vx[i, j + 1] + Vx[i + 1, j + 1])) * (ρg_R - ρg_L) * _dx return nothing end # From cell vertices to cell center temperature2center!(thermal) = temperature2center!(backend(thermal), thermal) function temperature2center!(::CPUBackendTrait, thermal::JustRelax.ThermalArrays) return _temperature2center!(thermal) end function _temperature2center!(thermal::JustRelax.ThermalArrays) @parallel (@idx size(thermal.Tc)...) temperature2center_kernel!(thermal.Tc, thermal.T) return nothing end @parallel_indices (i, j) function temperature2center_kernel!( T_center::T, T_vertex::T ) where {T<:AbstractArray{_T,2} where {_T<:Real}} T_center[i, j] = ( T_vertex[i + 1, j] + T_vertex[i + 2, j] + T_vertex[i + 1, j + 1] + T_vertex[i + 2, j + 1] ) * 0.25 return nothing end @parallel_indices (i, j, k) function temperature2center_kernel!( T_center::T, T_vertex::T ) where {T<:AbstractArray{_T,3} where {_T<:Real}} @inline av_T() = _av(T_vertex, i, j, k) T_center[i, j, k] = av_T() return nothing end function vertex2center!(center, vertex) @parallel vertex2center_kernel!(center, vertex) return nothing end @parallel function vertex2center_kernel!(center, vertex) @all(center) = @av(vertex) return nothing end function center2vertex!(vertex, center) @parallel center2vertex_kernel!(vertex, center) return nothing end @parallel function center2vertex_kernel!(vertex, center) @inn(vertex) = @av(center) return nothing end function center2vertex!(vertex_yz, vertex_xz, vertex_xy, center_yz, center_xz, center_xy) @parallel center2vertex_kernel!( vertex_yz, vertex_xz, vertex_xy, center_yz, center_xz, center_xy ) return nothing end @parallel_indices (i, j, k) function center2vertex_kernel!( vertex_yz, vertex_xz, vertex_xy, center_yz, center_xz, center_xy ) i1, j1, k1 = (i, j, k) .+ 1 nx, ny, nz = size(center_yz) if i ≤ nx && 1 < j1 ≤ ny && 1 < k1 ≤ nz vertex_yz[i, j1, k1] = 0.25 * ( center_yz[i, j, k] + center_yz[i, j1, k] + center_yz[i, j, k1] + center_yz[i, j1, k1] ) end if 1 < i1 ≤ nx && j ≤ ny && 1 < k1 ≤ nz vertex_xz[i1, j, k1] = 0.25 * ( center_xz[i, j, k] + center_xz[i1, j, k] + center_xz[i, j, k1] + center_xz[i1, j, k1] ) end if 1 < i1 ≤ nx && 1 < j1 ≤ ny && k ≤ nz vertex_xy[i1, j1, k] = 0.25 * ( center_xy[i, j, k] + center_xy[i1, j, k] + center_xy[i, j1, k] + center_xy[i1, j1, k] ) end return nothing end # Velocity to cell vertices ## 2D function velocity2vertex!(Vx_v, Vy_v, Vx, Vy; ghost_nodes=true) ni = size(Vx_v) if !ghost_nodes @parallel (@idx ni) Vx2vertex_noghost!(Vx_v, Vx) @parallel (@idx ni) Vy2vertex_noghost!(Vy_v, Vy) else @parallel (@idx ni) Vx2vertex_LinP!(Vx_v, Vx) @parallel (@idx ni) Vy2vertex_LinP!(Vy_v, Vy) end end function velocity2vertex(Vx, Vy, nv_x, nv_y; ghost_nodes=true) Vx_v = @allocate(nv_x, nv_y) Vy_v = @allocate(nv_x, nv_y) if !ghost_nodes @parallel (@idx ni) Vx2vertex_noghost!(Vx_v, Vx) @parallel (@idx ni) Vy2vertex_noghost!(Vy_v, Vy) else @parallel (@idx ni) Vx2vertex_LinP!(Vx_v, Vx) @parallel (@idx ni) Vy2vertex_LinP!(Vy_v, Vy) end end @parallel_indices (i, j) function Vx2vertex_noghost!(V, Vx) if 1 < j < size(Vx, 2) V[i, j] = 0.5 * (Vx[i, j - 1] + Vx[i, j]) elseif j == 1 V[i, j] = Vx[i, j] elseif j == size(Vx, 2) V[i, j] = Vx[i, end] end return nothing end @parallel_indices (i, j) function Vy2vertex_noghost!(V, Vy) if 1 < i < size(Vy, 1) V[i, j] = 0.5 * (Vy[i - 1, j] + Vy[i, j]) elseif i == 1 V[i, j] = Vy[i, j] elseif i == size(Vy, 1) V[i, j] = Vy[end, j] end return nothing end @parallel_indices (i, j) function Vx2vertex_ghost!(V, Vx) @inline av(A) = _av_ya(A, i, j) V[i, j] = av(Vx) return nothing end @parallel_indices (i, j) function Vy2vertex_ghost!(V, Vy) @inline av(A) = _av_xa(A, i, j) V[i, j] = av(Vy) return nothing end @parallel_indices (i, j) function Vx2vertex_LinP!(V, Vx) @inline av(A, B) = (A + B) * 0.5 nx, ny = size(Vx) iSW, jSW = clamp(i - 1, 1, nx), clamp(j, 1, ny) iS, jS = clamp(i, 1, nx), clamp(j, 1, ny) iSE, jSE = clamp(i + 1, 1, nx), clamp(j, 1, ny) iNE, jNE = clamp(i + 1, 1, nx), clamp(j + 1, 1, ny) iN, jN = clamp(i, 1, nx), clamp(j + 1, 1, ny) iNW, jNW = clamp(i - 1, 1, nx), clamp(j + 1, 1, ny) V_SW = av(Vx[iSW, jSW], Vx[iS, jS]) V_SE = av(Vx[iS, jS], Vx[iSE, jSE]) V_NW = av(Vx[iNW, jNW], Vx[iN, jN]) V_NE = av(Vx[iN, jN], Vx[iNE, jNE]) V[i, j] = 0.25 * (V_SW + V_SE + V_NW + V_NE) return nothing end @parallel_indices (i, j) function Vy2vertex_LinP!(V, Vy) @inline av(A, B) = (A + B) * 0.5 nx, ny = size(Vy) iSW, jSW = clamp(i, 1, nx), clamp(j - 1, 1, ny) iW, jW = clamp(i, 1, nx), clamp(j, 1, ny) iSE, jSE = clamp(i, 1, nx), clamp(j + 1, 1, ny) iNE, jNE = clamp(i + 1, 1, nx), clamp(j - 1, 1, ny) iE, jE = clamp(i + 1, 1, nx), clamp(j, 1, ny) iNW, jNW = clamp(i + 1, 1, nx), clamp(j + 1, 1, ny) V_SW = av(Vy[iSW, jSW], Vy[iW, jW]) V_SE = av(Vy[iW, jW], Vy[iSE, jSE]) V_NW = av(Vy[iNW, jNW], Vy[iE, jE]) V_NE = av(Vy[iE, jE], Vy[iNE, jNE]) V[i, j] = 0.25 * (V_SW + V_SE + V_NW + V_NE) return nothing end ## 3D """ velocity2vertex(Vx, Vy, Vz) Interpolate the velocity field `Vx`, `Vy`, `Vz` from a staggered grid with ghost nodes onto the grid vertices. """ function velocity2vertex(Vx, Vy, Vz) # infer size of grid nx, ny, nz = size(Vx) nv_x, nv_y, nv_z = nx - 1, ny - 2, nz - 2 # allocate output arrays Vx_v = @zeros(nv_x, nv_y, nv_z) Vy_v = @zeros(nv_x, nv_y, nv_z) Vz_v = @zeros(nv_x, nv_y, nv_z) # interpolate to cell vertices @parallel (@idx nv_x nv_y nv_z) _velocity2vertex!(Vx_v, Vy_v, Vz_v, Vx, Vy, Vz) return Vx_v, Vy_v, Vz_v end """ velocity2vertex!(Vx_v, Vy_v, Vz_v, Vx, Vy, Vz) In-place interpolation of the velocity field `Vx`, `Vy`, `Vz` from a staggered grid with ghost nodes onto the pre-allocated `Vx_d`, `Vy_d`, `Vz_d` 3D arrays located at the grid vertices. """ function velocity2vertex!(Vx_v, Vy_v, Vz_v, Vx, Vy, Vz) # infer size of grid nx, ny, nz = size(Vx) n = max(nx, ny, nz) nv_x, nv_y, nv_z = nx - 1, ny - 2, nz - 2 # interpolate to cell vertices @parallel (@idx n, n, n) _velocity2vertex!(Vx_v, Vy_v, Vz_v, Vx, Vy, Vz) return nothing end @parallel_indices (i, j, k) function _velocity2vertex!(Vx_v, Vy_v, Vz_v, Vx, Vy, Vz) @inbounds begin if all((i, j, k) .≤ size(Vx)) Vx_v[i, j, k] = 0.25 * (Vx[i, j, k] + Vx[i, j + 1, k] + Vx[i, j, k + 1] + Vx[i, j + 1, k + 1]) end if all((i, j, k) .≤ size(Vy)) Vy_v[i, j, k] = 0.25 * (Vy[i, j, k] + Vy[i + 1, j, k] + Vy[i, j, k + 1] + Vy[i + 1, j, k + 1]) end if all((i, j, k) .≤ size(Vz)) Vz_v[i, j, k] = 0.25 * (Vz[i, j, k] + Vz[i, j + 1, k] + Vz[i + 1, j, k] + Vz[i + 1, j + 1, k]) end end return nothing end
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
1319
module JustRelax using Reexport @reexport using ImplicitGlobalGrid using LinearAlgebra using Printf using MPI using GeoParams using HDF5 using CellArrays using StaticArrays using Statistics function solve!() end abstract type AbstractBackend end struct CPUBackend <: AbstractBackend end struct AMDGPUBackend <: AbstractBackend end PTArray() = Array PTArray(::Type{CPUBackend}) = Array PTArray(::T) where {T} = error(ArgumentError("Unknown backend $T")) export PTArray, CPUBackend, CUDABackend, AMDGPUBackend include("types/stokes.jl") # export StokesArrays, PTStokesCoeffs include("types/heat_diffusion.jl") # export ThermalArrays, PTThermalCoeffs include("types/phases.jl") # export PhaseRatio include("boundaryconditions/types.jl") export TemperatureBoundaryConditions, DisplacementBoundaryConditions, VelocityBoundaryConditions include("types/traits.jl") export BackendTrait, CPUBackendTrait, NonCPUBackendTrait include("topology/Topology.jl") export IGG, lazy_grid, Geometry, velocity_grids, x_g, y_g, z_g include("phases/CellArrays.jl") export @cell, element, setelement!, cellnum, cellaxes, new_empty_cell, setindex! include("JustRelax_CPU.jl") include("IO/DataIO.jl") include("types/type_conversions.jl") export Array, copy end # module
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
1273
module JustRelax2D using ..JustRelax using StaticArrays using CellArrays using ParallelStencil, ParallelStencil.FiniteDifferences2D using ImplicitGlobalGrid using GeoParams, LinearAlgebra, Printf using Statistics using MPI import JustRelax: IGG, BackendTrait, CPUBackendTrait, backend, CPUBackend import JustRelax: PTStokesCoeffs import JustRelax: AbstractBoundaryConditions, TemperatureBoundaryConditions, AbstractFlowBoundaryConditions, DisplacementBoundaryConditions, VelocityBoundaryConditions @init_parallel_stencil(Threads, Float64, 2) include("common.jl") include("stokes/Stokes2D.jl") export solve! end module JustRelax3D using ..JustRelax using StaticArrays using CellArrays using ParallelStencil, ParallelStencil.FiniteDifferences3D using ImplicitGlobalGrid using GeoParams, LinearAlgebra, Printf using Statistics using MPI import JustRelax: IGG, BackendTrait, CPUBackendTrait, backend, CPUBackend import JustRelax: PTStokesCoeffs import JustRelax: AbstractBoundaryConditions, TemperatureBoundaryConditions, AbstractFlowBoundaryConditions, DisplacementBoundaryConditions, VelocityBoundaryConditions @init_parallel_stencil(Threads, Float64, 3) include("common.jl") include("stokes/Stokes3D.jl") export solve! end
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
5424
## 2D mini kernels const T2 = AbstractArray{T,2} where {T} # finite differences @inline _d_xa(A::T, i, j, _dx) where {T<:T2} = (-A[i, j] + A[i + 1, j]) * _dx @inline _d_ya(A::T, i, j, _dy) where {T<:T2} = (-A[i, j] + A[i, j + 1]) * _dy @inline _d_xi(A::T, i, j, _dx) where {T<:T2} = (-A[i, j + 1] + A[i + 1, j + 1]) * _dx @inline _d_yi(A::T, i, j, _dy) where {T<:T2} = (-A[i + 1, j] + A[i + 1, j + 1]) * _dy # averages @inline _av(A::T, i, j) where {T<:T2} = 0.25 * mysum(A, (i + 1):(i + 2), (j + 1):(j + 2)) @inline _av_a(A::T, i, j) where {T<:T2} = 0.25 * mysum(A, (i):(i + 1), (j):(j + 1)) @inline _av_xa(A::T, i, j) where {T<:T2} = (A[i, j] + A[i + 1, j]) * 0.5 @inline _av_ya(A::T, i, j) where {T<:T2} = (A[i, j] + A[i, j + 1]) * 0.5 @inline _av_xi(A::T, i, j) where {T<:T2} = (A[i, j + 1], A[i + 1, j + 1]) * 0.5 @inline _av_yi(A::T, i, j) where {T<:T2} = (A[i + 1, j], A[i + 1, j + 1]) * 0.5 # harmonic averages @inline function _harm(A::T, i, j) where {T<:T2} return eltype(A)(4) * mysum(inv, A, (i + 1):(i + 2), (j + 1):(j + 2)) end @inline function _harm_a(A::T, i, j) where {T<:T2} return eltype(A)(4) * mysum(inv, A, (i):(i + 1), (j):(j + 1)) end @inline function _harm_xa(A::T, i, j) where {T<:T2} return eltype(A)(2) * (inv(A[i + 1, j]) + inv(A[i, j])) end @inline function _harm_ya(A::T, i, j) where {T<:T2} return eltype(A)(2) * (inv(A[i, j + 1]) + inv(A[i, j])) end #others @inline function _gather(A::T, i, j) where {T<:T2} return A[i, j], A[i + 1, j], A[i, j + 1], A[i + 1, j + 1] end ## 3D mini kernels const T3 = AbstractArray{T,3} where {T} # finite differences @inline _d_xa(A::T, i, j, k, _dx) where {T<:T3} = (-A[i, j, k] + A[i + 1, j, k]) * _dx @inline _d_ya(A::T, i, j, k, _dy) where {T<:T3} = (-A[i, j, k] + A[i, j + 1, k]) * _dy @inline _d_za(A::T, i, j, k, _dz) where {T<:T3} = (-A[i, j, k] + A[i, j, k + 1]) * _dz @inline function _d_xi(A::T, i, j, k, _dx) where {T<:T3} return (-A[i, j + 1, k + 1] + A[i + 1, j + 1, k + 1]) * _dx end @inline function _d_yi(A::T, i, j, k, _dy) where {T<:T3} return (-A[i + 1, j, k + 1] + A[i + 1, j + 1, k + 1]) * _dy end @inline function _d_zi(A::T, i, j, k, _dz) where {T<:T3} return (-A[i + 1, j + 1, k] + A[i + 1, j + 1, k + 1]) * _dz end # averages @inline _av(A::T, i, j, k) where {T<:T3} = 0.125 * mysum(A, i:(i + 1), j:(j + 1), k:(k + 1)) @inline _av_x(A::T, i, j, k) where {T<:T3} = 0.5 * (A[i, j, k] + A[i + 1, j, k]) @inline _av_y(A::T, i, j, k) where {T<:T3} = 0.5 * (A[i, j, k] + A[i, j + 1, k]) @inline _av_z(A::T, i, j, k) where {T<:T3} = 0.5 * (A[i, j, k] + A[i, j, k + 1]) @inline _av_xy(A::T, i, j, k) where {T<:T3} = 0.25 * mysum(A, i:(i + 1), j:(j + 1), k:k) @inline _av_xz(A::T, i, j, k) where {T<:T3} = 0.25 * mysum(A, i:(i + 1), j:j, k:(k + 1)) @inline _av_yz(A::T, i, j, k) where {T<:T3} = 0.25 * mysum(A, i:i, j:(j + 1), k:(k + 1)) @inline _av_xyi(A::T, i, j, k) where {T<:T3} = 0.25 * mysum(A, (i - 1):i, (j - 1):j, k:k) @inline _av_xzi(A::T, i, j, k) where {T<:T3} = 0.25 * mysum(A, (i - 1):i, j:j, (k - 1):k) @inline _av_yzi(A::T, i, j, k) where {T<:T3} = 0.25 * mysum(A, i:i, (j - 1):j, (k - 1):k) # harmonic averages @inline function _harm_x(A::T, i, j, k) where {T<:T3} return eltype(A)(2) * inv(inv(A[i, j, k]) + inv(A[i + 1, j, k])) end @inline function _harm_y(A::T, i, j, k) where {T<:T3} return eltype(A)(2) * inv(inv(A[i, j, k]) + inv(A[i, j + 1, k])) end @inline function _harm_z(A::T, i, j, k) where {T<:T3} return eltype(A)(2) * inv(inv(A[i, j, k]) + inv(A[i, j, k + 1])) end @inline function _harm_xy(A::T, i, j, k) where {T<:T3} return eltype(A)(4) * inv(mysum(A, i:(i + 1), j:(j + 1), k:k)) end @inline function _harm_xz(A::T, i, j, k) where {T<:T3} return eltype(A)(4) * inv(mysum(A, i:(i + 1), j:j, k:(k + 1))) end @inline function _harm_yz(A::T, i, j, k) where {T<:T3} return eltype(A)(4) * inv(mysum(A, i:i, j:(j + 1), k:(k + 1))) end @inline function _harm_xyi(A::T, i, j, k) where {T<:T3} return eltype(A)(4) * inv(mysum(A, (i - 1):i, (j - 1):j, k:k)) end @inline function _harm_xzi(A::T, i, j, k) where {T<:T3} return eltype(A)(4) * inv(mysum(A, (i - 1):i, j:j, (k - 1):k)) end @inline function _harm_yzi(A::T, i, j, k) where {T<:T3} return eltype(A)(4) * inv(mysum(A, i:i, (j - 1):j, (k - 1):k)) end # others @inline function _gather_yz(A::T, i, j, k) where {T<:T3} return A[i, j, k], A[i, j + 1, k], A[i, j, k + 1], A[i, j + 1, k + 1] end @inline function _gather_xz(A::T, i, j, k) where {T<:T3} return A[i, j, k], A[i + 1, j, k], A[i, j, k + 1], A[i + 1, j, k + 1] end @inline function _gather_xy(A::T, i, j, k) where {T<:T3} return A[i, j, k], A[i + 1, j, k], A[i, j + 1, k], A[i + 1, j + 1, k] end @inline _current(A::T, i, j, k) where {T<:T3} = A[i, j, k] ## Because mysum(::generator) does not work inside CUDA kernels... @inline mysum(A, ranges::Vararg{T,N}) where {T,N} = mysum(identity, A, ranges...) @inline function mysum(f::F, A, ranges_i) where {F<:Function} s = 0.0 for i in ranges_i s += f(A[i]) end return s end @inline function mysum(f::F, A, ranges_i, ranges_j) where {F<:Function} s = 0.0 for i in ranges_i, j in ranges_j s += f(A[i, j]) end return s end @inline function mysum(f::F, A, ranges_i, ranges_j, ranges_k) where {F<:Function} s = 0.0 for i in ranges_i, j in ranges_j, k in ranges_k s += f(A[i, j, k]) end return s end
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
13243
# MACROS """ @idx(args...) Make a linear range from `1` to `args[i]`, with `i ∈ [1, ..., n]` """ macro idx(args...) return quote _idx($(esc.(args)...)) end end @inline _idx(args::NTuple{N,Int}) where {N} = ntuple(i -> 1:args[i], Val(N)) @inline _idx(args::Vararg{Int,N}) where {N} = ntuple(i -> 1:args[i], Val(N)) """ copy(B, A) convenience macro to copy data from the array `A` into array `B` """ macro copy(B, A) return quote multi_copyto!($(esc(B)), $(esc(A))) end end multi_copyto!(B::AbstractArray, A::AbstractArray) = copyto!(B, A) function detect_args_size(A::NTuple{N,AbstractArray{T,Dims}}) where {N,T,Dims} ntuple(Val(Dims)) do i Base.@_inline_meta s = ntuple(Val(N)) do j Base.@_inline_meta size(A[j], i) end maximum(s) end end @parallel_indices (I...) function multi_copy!( dst::NTuple{N,T}, src::NTuple{N,T} ) where {N,T} ntuple(Val(N)) do k Base.@_inline_meta if all(I .≤ size(dst[k])) @inbounds dst[k][I...] = src[k][I...] end end return nothing end Base.@propagate_inbounds @generated function unrolled_copy!( dst::NTuple{N,T}, src::NTuple{N,T}, I::Vararg{Int,NI} ) where {N,NI,T} quote Base.@_inline_meta Base.@nexprs $N n -> begin if all(tuple(I...) .≤ size(dst[n])) dst[n][I...] = src[n][I...] end end end end """ @add(I, args...) Add `I` to the scalars in `args` """ macro add(I, args...) quote Base.@_inline_meta v = (; $(esc.(args)...)) values(v) .+ $(esc(I)) end end macro tuple(A) return quote _tuple($(esc(A))) end end @inline _tuple(V::JustRelax.Velocity{<:AbstractArray{T,2}}) where {T} = V.Vx, V.Vy @inline _tuple(V::JustRelax.Velocity{<:AbstractArray{T,3}}) where {T} = V.Vx, V.Vy, V.Vz @inline _tuple(A::JustRelax.SymmetricTensor{<:AbstractArray{T,2}}) where {T} = A.xx, A.yy, A.xy_c @inline function _tuple(A::JustRelax.SymmetricTensor{<:AbstractArray{T,3}}) where {T} return A.xx, A.yy, A.zz, A.yz_c, A.xz_c, A.xy_c end """ @velocity(V) Unpacks the velocity arrays `V` from the StokesArrays `A`. """ macro velocity(A) return quote unpack_velocity(($(esc(A))).V) end end @inline unpack_velocity(V::JustRelax.Velocity{<:AbstractArray{T,2}}) where {T} = V.Vx, V.Vy @inline unpack_velocity(V::JustRelax.Velocity{<:AbstractArray{T,3}}) where {T} = V.Vx, V.Vy, V.Vz """ @displacement(U) Unpacks the displacement arrays `U` from the StokesArrays `A`. """ macro displacement(A) return quote unpack_displacement(($(esc(A))).U) end end @inline unpack_displacement(U::JustRelax.Displacement{<:AbstractArray{T,2}}) where {T} = U.Ux, U.Uy @inline unpack_displacement(U::JustRelax.Displacement{<:AbstractArray{T,3}}) where {T} = U.Ux, U.Uy, U.Uz """ @qT(V) Unpacks the flux arrays `qT_i` from the ThermalArrays `A`. """ macro qT(A) return quote unpack_qT(($(esc(A)))) end end @inline unpack_qT(A::JustRelax.ThermalArrays{<:AbstractArray{T,2}}) where {T} = A.qTx, A.qTy @inline unpack_qT(A::JustRelax.ThermalArrays{<:AbstractArray{T,3}}) where {T} = A.qTx, A.qTy, A.qTz """ @qT2(V) Unpacks the flux arrays `qT2_i` from the ThermalArrays `A`. """ macro qT2(A) return quote unpack_qT2(($(esc(A)))) end end @inline unpack_qT2(A::JustRelax.ThermalArrays{<:AbstractArray{T,2}}) where {T} = A.qTx2, A.qTy2 @inline function unpack_qT2(A::JustRelax.ThermalArrays{<:AbstractArray{T,3}}) where {T} return A.qTx2, A.qTy2, A.qTz2 end """ @strain(A) Unpacks the strain rate tensor `ε` from the StokesArrays `A`, where its components are defined in the staggered grid. Shear components are unpack following Voigt's notation. """ macro strain(A) return quote unpack_tensor_stag(($(esc(A))).ε) end end """ @plastic_strain(A) Unpacks the plastic strain rate tensor `ε_pl` from the StokesArrays `A`, where its components are defined in the staggered grid. Shear components are unpack following Voigt's notation. """ macro plastic_strain(A) return quote unpack_tensor_stag(($(esc(A))).ε_pl) end end """ @stress(A) Unpacks the deviatoric stress tensor `τ` from the StokesArrays `A`, where its components are defined in the staggered grid. Shear components are unpack following Voigt's notation. """ macro stress(A) return quote unpack_tensor_stag(($(esc(A))).τ) end end """ @tensor(A) Unpacks the symmetric tensor `A`, where its components are defined in the staggered grid. Shear components are unpack following Voigt's notation. """ macro tensor(A) return quote unpack_tensor_stag(($(esc(A)))) end end @inline function unpack_tensor_stag( A::JustRelax.SymmetricTensor{<:AbstractArray{T,2}} ) where {T} return A.xx, A.yy, A.xy end @inline function unpack_tensor_stag( A::JustRelax.SymmetricTensor{<:AbstractArray{T,3}} ) where {T} return A.xx, A.yy, A.zz, A.yz, A.xz, A.xy end """ @shear(A) Unpacks the shear components of the symmetric tensor `A`, where its components are defined in the staggered grid. Shear components are unpack following Voigt's notation. """ macro shear(A) return quote unpack_shear_components_stag(($(esc(A)))) end end @inline function unpack_shear_components_stag( A::JustRelax.SymmetricTensor{<:AbstractArray{T,2}} ) where {T} return A.xy end @inline function unpack_shear_components_stag( A::JustRelax.SymmetricTensor{<:AbstractArray{T,3}} ) where {T} return A.yz, A.xz, A.xy end """ @normal(A) Unpacks the normal components of the symmetric tensor `A`, where its components are defined in the staggered grid. Shear components are unpack following Voigt's notation. """ macro normal(A) return quote unpack_normal_components_stag(($(esc(A)))) end end @generated function unpack_normal_components_stag( A::JustRelax.SymmetricTensor{<:AbstractArray{T,N}} ) where {T,N} syms = (:xx, :yy, :zz) quote Base.@_inline_meta Base.@nexprs $N i -> f_i = getfield(A, $syms[i]) Base.@ncall $N tuple f end end """ @strain_center(A) Unpacks the strain rate tensor `ε` from the StokesArrays `A`, where its components are defined in the center of the grid cells. Shear components are unpack following Voigt's notation. """ macro strain_center(A) return quote unpack_tensor_center(($(esc(A))).ε) end end """ @stress_center(A) Unpacks the deviatoric stress tensor `τ` from the StokesArrays `A`, where its components are defined in the center of the grid cells. Shear components are unpack following Voigt's notation. """ macro stress_center(A) return quote unpack_tensor_center(($(esc(A))).τ) end end """ @tensor_center(A) Unpacks the symmetric tensor `A`, where its components are defined in the center of the grid cells. Shear components are unpack following Voigt's notation. """ macro tensor_center(A) return quote unpack_tensor_center(($(esc(A)))) end end @inline function unpack_tensor_center( A::JustRelax.SymmetricTensor{<:AbstractArray{T,2}} ) where {T} return A.xx, A.yy, A.xy_c end @inline function unpack_tensor_center( A::JustRelax.SymmetricTensor{<:AbstractArray{T,3}} ) where {T} return A.xx, A.yy, A.zz, A.yz_c, A.xz_c, A.xy_c end """ @residuals(A) Unpacks the momentum residuals from `A`. """ macro residuals(A) return quote unpack_residuals(($(esc(A)))) end end @inline function unpack_residuals(A::JustRelax.Residual{<:AbstractArray{T,2}}) where {T} return A.Rx, A.Ry end @inline function unpack_residuals(A::JustRelax.Residual{<:AbstractArray{T,3}}) where {T} return A.Rx, A.Ry, A.Rz end ## Memory allocators macro allocate(ni...) return esc(:(PTArray(undef, $(ni...)))) end function indices(::NTuple{3,T}) where {T} i = (blockIdx().x - 1) * blockDim().x + threadIdx().x j = (blockIdx().y - 1) * blockDim().y + threadIdx().y k = (blockIdx().z - 1) * blockDim().z + threadIdx().z return i, j, k end function indices(::NTuple{2,T}) where {T} i = (blockIdx().x - 1) * blockDim().x + threadIdx().x j = (blockIdx().y - 1) * blockDim().y + threadIdx().y return i, j end """ maxloc!(B, A; window) Compute the maximum value of `A` in the `window = (width_x, width_y, width_z)` and store the result in `B`. """ function compute_maxloc!(B, A; window=(1, 1, 1)) ni = size(A) @parallel_indices (I...) function _maxloc!(B, A, window) B[I...] = _maxloc_window_clamped(A, I..., window...) return nothing end @parallel (@idx ni) _maxloc!(B, A, window) return nothing end @inline function _maxloc_window_clamped(A, I, J, width_x, width_y) nx, ny = size(A) I_range = (I - width_x):(I + width_x) J_range = (J - width_y):(J + width_y) x = -Inf for j in J_range jj = clamp(j, 1, ny) # handle boundary cells for i in I_range ii = clamp(i, 1, nx) # handle boundary cells Aij = A[ii, jj] if Aij > x x = Aij end end end return x end @inline function _maxloc_window_clamped(A, I, J, K, width_x, width_y, width_z) nx, ny, nz = size(A) I_range = (I - width_x):(I + width_x) J_range = (J - width_y):(J + width_y) K_range = (K - width_z):(K + width_z) x = -Inf for k in K_range kk = clamp(k, 1, nz) # handle boundary cells for j in J_range jj = clamp(j, 1, ny) # handle boundary cells for i in I_range ii = clamp(i, 1, nx) # handle boundary cells Aijk = A[ii, jj, kk] if Aijk > x x = Aijk end end end end return x end # unpacks fields of the struct x into a tuple @generated function unpack(x::T) where {T} return quote Base.@_inline_meta tuple(_unpack(x, fieldnames($T))...) end end _unpack(a, fields) = (getfield(a, fi) for fi in fields) macro unpack(x) return quote unpack($(esc(x))) end end """ compute_dt(S::JustRelax.StokesArrays, args...) Compute the time step `dt` for the simulation. """ function compute_dt(S::JustRelax.StokesArrays, args...) return compute_dt(backend(S), S, args...) end function compute_dt(::CPUBackendTrait, S::JustRelax.StokesArrays, args...) return _compute_dt(S, args...) end @inline _compute_dt(S::JustRelax.StokesArrays, di) = _compute_dt(@velocity(S), di, Inf, maximum) @inline _compute_dt(S::JustRelax.StokesArrays, di, dt_diff) = _compute_dt(@velocity(S), di, dt_diff, maximum) @inline _compute_dt(S::JustRelax.StokesArrays, di, dt_diff, ::IGG) = _compute_dt(@velocity(S), di, dt_diff, maximum_mpi) @inline _compute_dt(S::JustRelax.StokesArrays, di, ::IGG) = _compute_dt(@velocity(S), di, Inf, maximum_mpi) @inline function _compute_dt(V::NTuple, di, dt_diff, max_fun::F) where {F<:Function} n = inv(length(V) + 0.1) dt_adv = mapreduce(x -> x[1] * inv(max_fun(abs.(x[2]))), min, zip(di, V)) * n return min(dt_diff, dt_adv) end @inline tupleize(v) = (v,) @inline tupleize(v::Tuple) = v """ allzero(x::Vararg{T,N}) where {T,N} Check if all elements in `x` are zero. # Arguments - `x::Vararg{T,N}`: The input array. # Returns - `Bool`: `true` if all elements in `x` are zero, `false` otherwise. """ @inline allzero(x::Vararg{T,N}) where {T,N} = all(x -> x == 0, x) """ take(fldr::String) Create folder `fldr` if it does not exist. """ take(fldr::String) = !isdir(fldr) && mkpath(fldr) """ continuation_log(x_new, x_old, ν) Do a continuation step `exp((1-ν)*log(x_old) + ν*log(x_new))` with damping parameter `ν` """ @inline function continuation_log(x_new::T, x_old::T, ν) where {T} x_cont = exp((1 - ν) * log(x_old) + ν * log(x_new)) return isnan(x_cont) ? 0.0 : x_cont end @inline continuation_linear(x_new, x_old, ν) = muladd((1 - ν), x_old, ν * x_new) # (1 - ν) * x_old + ν * x_new # Others """ assign!(B::AbstractArray{T,N}, A::AbstractArray{T,N}) where {T,N} Assigns the values of array `A` to array `B` in parallel. # Arguments - `B::AbstractArray{T,N}`: The destination array. - `A::AbstractArray{T,N}`: The source array. """ @parallel function assign!(B::AbstractArray{T,N}, A::AbstractArray{T,N}) where {T,N} @all(B) = @all(A) return nothing end # MPI reductions function mean_mpi(A) mean_l = _mean(A) return MPI.Allreduce(mean_l, MPI.SUM, MPI.COMM_WORLD) / MPI.Comm_size(MPI.COMM_WORLD) end function norm_mpi(A) sum2_l = _sum(A .^ 2) return sqrt(MPI.Allreduce(sum2_l, MPI.SUM, MPI.COMM_WORLD)) end function minimum_mpi(A) min_l = _minimum(A) return MPI.Allreduce(min_l, MPI.MIN, MPI.COMM_WORLD) end function maximum_mpi(A) max_l = _maximum(A) return MPI.Allreduce(max_l, MPI.MAX, MPI.COMM_WORLD) end for (f1, f2) in zip( (:_mean, :_norm, :_minimum, :_maximum, :_sum), (:mean, :norm, :minimum, :maximum, :sum) ) @eval begin $f1(A::AbstractArray) = $f2(Array(A)) $f1(A) = $f2(A) end end
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
1918
include("types/constructors/stokes.jl") export StokesArrays, PTStokesCoeffs include("types/constructors/heat_diffusion.jl") export ThermalArrays, PTThermalCoeffs include("types/constructors/phases.jl") export PhaseRatio include("Utils.jl") export @allocate, @add, @idx, @copy, @velocity, @displacement, @strain, @plastic_strain, @stress, @tensor, @shear, @normal, @stress_center, @strain_center, @tensor_center, @qT, @qT2, @residuals, compute_dt, multi_copy!, take include("types/displacement.jl") export velocity2displacement!, displacement2velocity! include("boundaryconditions/BoundaryConditions.jl") export AbstractBoundaryConditions, TemperatureBoundaryConditions, AbstractFlowBoundaryConditions, DisplacementBoundaryConditions, VelocityBoundaryConditions, flow_bcs!, thermal_bcs!, pureshear_bc! include("MiniKernels.jl") include("phases/phases.jl") export fn_ratio, phase_ratios_center!, numphases, nphases include("rheology/BuoyancyForces.jl") export compute_ρg! include("rheology/Viscosity.jl") export compute_viscosity! include("rheology/Melting.jl") export compute_melt_fraction! # include("thermal_diffusion/DiffusionExplicit.jl") # export ThermalParameters include("particles/subgrid_diffusion.jl") export subgrid_characteristic_time! include("Interpolations.jl") export vertex2center!, center2vertex!, temperature2center!, velocity2vertex! include("advection/weno5.jl") export WENO5, WENO_advection! # Stokes include("rheology/GeoParams.jl") include("rheology/StressUpdate.jl") include("stokes/StressRotation.jl") include("stokes/StressKernels.jl") export tensor_invariant! include("stokes/PressureKernels.jl") include("stokes/VelocityKernels.jl") # thermal diffusion include("thermal_diffusion/DiffusionPT.jl") export PTThermalCoeffs, heatdiffusion_PT!, compute_shear_heating!
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
936
module DataIO using WriteVTK using HDF5 using JLD2 using MPI import ..JustRelax: Geometry import ..JustRelax: IGG include("H5.jl") export save_hdf5, checkpointing_hdf5, load_checkpoint_hdf5, metadata, center_coordinates, vertex_coordinates, save_data include("JLD2.jl") export checkpointing_jld2, load_checkpoint_jld2 include("VTK.jl") export VTKDataSeries, append!, save_vtk export metadata """ metadata(src, dst, files...) Copy `files...`, Manifest.toml, and Project.toml from `src` to `dst` """ function metadata(src, dst, files...) @assert dst != pwd() if !ispath(dst) println("Created $dst folder") mkpath(dst) end for f in vcat(collect(files), ["Manifest.toml", "Project.toml"]) !isfile(joinpath(f)) && continue newfile = joinpath(dst, basename(f)) isfile(newfile) && rm(newfile) cp(joinpath(src, f), newfile) end end end
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
4800
# if input is a structure, take the innermost name # i.e. stokes.V.Vx => "Vx" macro namevar(x) name = split(string(x), ".")[end] return quote tmp = $(esc(x)) if tmp isa Float64 $(esc(name)), tmp else $(esc(name)), Array(tmp) end end end """ checkpointing_hdf5(dst, stokes, T, η, time, timestep) Save necessary data in `dst` as and HDF5 file to restart the model from the state at `time` """ function checkpointing_hdf5(dst, stokes, T, time, timestep) !isdir(dst) && mkpath(dst) # create folder in case it does not exist fname = joinpath(dst, "checkpoint") # Create a temporary directory mktempdir() do tmpdir # Save the checkpoint file in the temporary directory tmpfname = joinpath(tmpdir, basename(fname)) h5open("$(tmpfname).h5", "w") do file write(file, @namevar(time)...) write(file, @namevar(timestep)...) write(file, @namevar(stokes.V.Vx)...) write(file, @namevar(stokes.V.Vy)...) if !isnothing(stokes.V.Vz) write(file, @namevar(stokes.V.Vz)...) end write(file, @namevar(stokes.P)...) write(file, @namevar(stokes.viscosity.η)...) write(file, @namevar(T)...) end # Move the checkpoint file from the temporary directory to the destination directory mv("$(tmpfname).h5", "$(fname).h5"; force=true) end return nothing end """ load_checkpoint_hdf5(file_path) Load the state of the simulation from an .h5 file. # Arguments - `file_path`: The path to the .h5 file. # Returns - `P`: The loaded state of the pressure variable. - `T`: The loaded state of the temperature variable. - `Vx`: The loaded state of the x-component of the velocity variable. - `Vy`: The loaded state of the y-component of the velocity variable. - `Vz`: The loaded state of the z-component of the velocity variable. - `η`: The loaded state of the viscosity variable. - `t`: The loaded simulation time. - `dt`: The loaded simulation time. # Example ```julia # Define the path to the .h5 file file_path = "path/to/your/file.h5" # Use the load_checkpoint function to load the variables from the file P, T, Vx, Vy, Vz, η, t, dt = `load_checkpoint(file_path)`` """ function load_checkpoint_hdf5(file_path) h5file = h5open(file_path, "r") # Open the file in read mode P = read(h5file["P"]) # Read the stokes variable T = read(h5file["T"]) # Read the thermal.T variable Vx = read(h5file["Vx"]) # Read the stokes.V.Vx variable Vy = read(h5file["Vy"]) # Read the stokes.V.Vy variable if "Vz" in keys(h5file) # Check if the "Vz" key exists Vz = read(h5file["Vz"]) # Read the stokes.V.Vz variable else Vz = nothing # Assign a default value to Vz end η = read(h5file["η"]) # Read the stokes.viscosity.η variable t = read(h5file["time"]) # Read the t variable dt = read(h5file["timestep"]) # Read the t variable close(h5file) # Close the file return P, T, Vx, Vy, Vz, η, t, dt end """ function save_hdf5(dst, fname, data) Save `data` as the `fname.h5` HDF5 file in the folder `dst` """ function save_hdf5(dst, fname, data::Vararg{Any,N}) where {N} !isdir(dst) && mkpath(dst) # creat folder in case it does not exist pth_name = joinpath(dst, fname) return save_hdf5(pth_name, data) end # comm_cart, info comm_cart, MPI.Info() function save_hdf5(fname, dim_g, I, comm_cart, info, data::Vararg{Any,N}) where {N} @assert HDF5.has_parallel() h5open("$(fname).h5", "w", comm_cart, info) do file for data_i in data name, field = @namevar data_i dset = create_dataset( file, "/" * name, datatype(eltype(field)), dataspace(dim_g) ) dset[I.indices...] = Array(field) end end return nothing end """ function save_hdf5(fname, data) Save `data` as the `fname.h5` HDF5 file """ function save_hdf5(fname, data::Vararg{Any,N}) where {N} h5open("$(fname).h5", "w") do file for data_i in data save_data(file, data_i) end end end @inline save_data(file, data) = write(file, @namevar(data)...) function save_data(file, data::Geometry{N}) where {N} xci = center_coordinates(data) xvi = vertex_coordinates(data) write(file, "Xc", xci[1]) write(file, "Yc", xci[2]) write(file, "Xv", xvi[1]) write(file, "Yv", xvi[2]) if N == 3 write(file, "Zc", xci[3]) write(file, "Zv", xvi[3]) end return nothing end center_coordinates(data::Geometry{N}) where {N} = ntuple(i -> collect(data.xci[i]), Val(N)) vertex_coordinates(data::Geometry{N}) where {N} = ntuple(i -> collect(data.xvi[i]), Val(N))
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
2557
""" checkpointing_jld2(dst, stokes, thermal, time, timestep, igg) Save necessary data in `dst` as a jld2 file to restart the model from the state at `time`. If run in parallel, the file will be named after the corresponidng rank e.g. `checkpoint0000.jld2` and thus can be loaded by the processor while restarting the simulation. If you want to restart your simulation from the checkpoint you can use load() and specify the MPI rank by providing a dollar sign and the rank number. # Example ```julia checkpointing_jld2( "path/to/dst", stokes, thermal, t, igg, ) ``` """ checkpoint_name(dst) = "$dst/checkpoint.jld2" checkpoint_name(dst, igg::IGG) = "$dst/checkpoint" * lpad("$(igg.me)", 4, "0") * ".jld2" function checkpointing_jld2(dst, stokes, thermal, time, timestep) fname = checkpoint_name(dst) checkpointing_jld2(dst, stokes, thermal, time, timestep, fname) return nothing end function checkpointing_jld2(dst, stokes, thermal, time, timestep, igg::IGG) fname = checkpoint_name(dst, igg) checkpointing_jld2(dst, stokes, thermal, time, timestep, fname) return nothing end function checkpointing_jld2(dst, stokes, thermal, time, timestep, fname::String) !isdir(dst) && mkpath(dst) # create folder in case it does not exist # Create a temporary directory mktempdir() do tmpdir # Save the checkpoint file in the temporary directory tmpfname = joinpath(tmpdir, basename(fname)) jldsave( tmpfname; stokes=Array(stokes), thermal=Array(thermal), time=time, timestep=timestep, ) # Move the checkpoint file from the temporary directory to the destination directory mv(tmpfname, fname; force=true) end return nothing end """ load_checkpoint_jld2(file_path) Load the state of the simulation from a .jld2 file. # Arguments - `file_path`: The path to the .jld2 file. # Returns - `stokes`: The loaded state of the stokes variable. - `thermal`: The loaded state of the thermal variable. - `time`: The loaded simulation time. - `timestep`: The loaded time step. """ function load_checkpoint_jld2(file_path) restart = load(file_path) # Load the file stokes = restart["stokes"] # Read the stokes variable thermal = restart["thermal"] # Read the thermal variable time = restart["time"] # Read the time variable timestep = restart["timestep"] # Read the timestep variable return stokes, thermal, time, timestep end
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
2657
struct VTKDataSeries{T,S,G} series::T path::S name::S grid::G function VTKDataSeries(full_name::String, xi) split_path = splitpath(full_name) name = last(split_path) path = if length(split_path) > 1 joinpath(split_path[1:(end - 1)]) else pwd() end series = paraview_collection(full_name; append=true) return new{typeof(series),String,typeof(xi)}(series, path, name, xi) end end function append!(data_series, data::NamedTuple, time_step, seconds) # unpack data names and arrays data_names = string.(keys(data)) data_arrays = values(data) # create vtk file vtk_name = joinpath(data_series.path, "$time_step") vtk = vtk_grid(vtk_name, data_series.grid...) # add data to vtk file for (name_i, array_i) in zip(data_names, data_arrays) vtk[name_i] = Array(array_i) end # close vtk file vtk_save(vtk) # open pvd file pvd_name = joinpath(data_series.path, data_series.name) pvd = paraview_collection(pvd_name; append=true) # add vtk file to time series collection_add_timestep(pvd, vtk, seconds) # close pvd file vtk_save(pvd) return nothing end function save_vtk( fname::String, xvi, xci, data_v::NamedTuple, data_c::NamedTuple, velocity::NTuple{N,T} ) where {N,T} # unpack data names and arrays data_names_v = string.(keys(data_v)) data_arrays_v = values(data_v) data_names_c = string.(keys(data_c)) data_arrays_c = values(data_c) velocity_field = rand(N, size(first(velocity))...) for (i, v) in enumerate(velocity) velocity_field[i, :, :, :] = v end vtk_multiblock(fname) do vtm # First block. # Variables stores in cell centers vtk_grid(vtm, xci...) do vtk for (name_i, array_i) in zip(data_names_c, data_arrays_c) vtk[name_i] = Array(array_i) end end # Second block. # Variables stores in cell vertices vtk_grid(vtm, xvi...) do vtk for (name_i, array_i) in zip(data_names_v, data_arrays_v) vtk[name_i] = Array(array_i) end vtk["Velocity"] = velocity_field end end return nothing end function save_vtk(fname::String, xi, data::NamedTuple) # unpack data names and arrays data_names = string.(keys(data)) data_arrays = values(data) # make and save VTK file vtk_grid(fname, xi...) do vtk for (name_i, array_i) in zip(data_names, data_arrays) vtk[name_i] = Array(array_i) end end return nothing end
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
9243
using MuladdMacro, Adapt ## Weno5 advection scheme. Implementation based on the repository from # https://gmd.copernicus.org/preprints/gmd-2023-189/ abstract type AbstractWENO end """ WENO5{T, N, A, M} <: AbstractWENO The `WENO5` is a structure representing the Weighted Essentially Non-Oscillatory (WENO) scheme of order 5 for the solution of hyperbolic partial differential equations. # Fields - `d0L`, `d1L`, `d2L`: Upwind constants. - `d0R`, `d1R`, `d2R`: Downwind constants. - `c1`, `c2`: Constants for betas. - `sc1`, `sc2`, `sc3`, `sc4`, `sc5`: Stencil weights. - `ϵ`: Tolerance. - `ni`: Grid size. - `ut`: Intermediate buffer array. - `fL`, `fR`, `fB`, `fT`: Fluxes. - `method`: Method (1:JS, 2:Z). # Description The `WENO5` structure contains the parameters and temporary variables used in the WENO scheme. These include the upwind and downwind constants, the constants for betas, the stencil candidate weights, the tolerance, the grid size, the fluxes, and the method. """ @kwdef struct WENO5{T,N,A,M} <: AbstractWENO # upwind constants d0L::T = 1 / 10 d1L::T = 3 / 5 d2L::T = 3 / 10 # downwind constants d0R::T = 3 / 10 d1R::T = 3 / 5 d2R::T = 1 / 10 # for betas c1::T = 13 / 12 c2::T = 1 / 4 # stencil weights sc1::T = 1 / 3 sc2::T = 7 / 6 sc3::T = 11 / 6 sc4::T = 1 / 6 sc5::T = 5 / 6 # tolerance ϵ::T = 1e-6 # grid size ni::NTuple{N,Int64} # fluxes ut::A = zeros(ni...) fL::A = zeros(ni...) fR::A = zeros(ni...) fB::A = zeros(ni...) fT::A = zeros(ni...) # method method::M = Val{1} # 1:JS, 2:Z end Adapt.@adapt_structure WENO5 # check if index is on the boundary, if yes take value on the opposite for periodic, if not, don't change the value # @inline limit_periodic(a, n) = a > n ? n : (a < 1 ? 1 : a) @inline function limit_periodic(a, n) a > n && return n a < 1 && return 1 return a end ## Betas @inline function weno_betas(u1, u2, u3, u4, u5, weno) β0 = @muladd weno.c1 * (u1 - 2 * u2 + u3)^2 + weno.c2 * (u1 - 4 * u2 + 3 * u3)^2 β1 = @muladd weno.c1 * (u2 - 2 * u3 + u4)^2 + weno.c2 * (u2 - u4)^2 β2 = @muladd weno.c1 * (u3 - 2 * u4 + u5)^2 + weno.c2 * (3 * u3 - 4 * u4 + u5)^2 return β0, β1, β2 end ## Upwind alphas @inline function weno_alphas_upwind(::WENO5, ::Type{Any}, β0, β1, β2) return error("Unknown method for the WENO Scheme") end @inline function weno_alphas_upwind(weno::WENO5, ::Val{1}, β0, β1, β2) α0L = weno.d0L * inv(β0 + weno.ϵ)^2 α1L = weno.d1L * inv(β1 + weno.ϵ)^2 α2L = weno.d2L * inv(β2 + weno.ϵ)^2 return α0L, α1L, α2L end @inline function weno_alphas_upwind(weno::WENO5, ::Val{2}, β0, β1, β2) τ = abs(β0 - β2) α0L = weno.d0L * (1 + (τ * inv(β0 + weno.ϵ))^2) α1L = weno.d1L * (1 + (τ * inv(β1 + weno.ϵ))^2) α2L = weno.d2L * (1 + (τ * inv(β2 + weno.ϵ))^2) return α0L, α1L, α2L end ## Downwind alphas @inline function weno_alphas_downwind(::WENO5, ::Any, β0, β1, β2) return error("Unknown method for the WENO Scheme") end @inline function weno_alphas_downwind(weno::WENO5, ::Val{1}, β0, β1, β2) α0R = weno.d0R * inv(β0 + weno.ϵ)^2 α1R = weno.d1R * inv(β1 + weno.ϵ)^2 α2R = weno.d2R * inv(β2 + weno.ϵ)^2 return α0R, α1R, α2R end @inline function weno_alphas_downwind(weno::WENO5, ::Val{2}, β0, β1, β2) τ = abs(β0 - β2) α0R = weno.d0R * (1 + (τ * inv(β0 + weno.ϵ))^2) α1R = weno.d1R * (1 + (τ * inv(β1 + weno.ϵ))^2) α2R = weno.d2R * (1 + (τ * inv(β2 + weno.ϵ))^2) return α0R, α1R, α2R end ## Stencil candidates @inline function stencil_candidate_upwind(u1, u2, u3, u4, u5, weno) s0 = @muladd weno.sc1 * u1 - weno.sc2 * u2 + weno.sc3 * u3 s1 = @muladd -weno.sc4 * u2 + weno.sc5 * u3 + weno.sc1 * u4 s2 = @muladd weno.sc1 * u3 + weno.sc5 * u4 - weno.sc4 * u5 return s0, s1, s2 end @inline function stencil_candidate_downwind(u1, u2, u3, u4, u5, weno) s0 = @muladd -weno.sc4 * u1 + weno.sc5 * u2 + weno.sc1 * u3 s1 = @muladd weno.sc1 * u2 + weno.sc5 * u3 - weno.sc4 * u4 s2 = @muladd weno.sc3 * u3 - weno.sc2 * u4 + weno.sc1 * u5 return s0, s1, s2 end # UP/DOWN-WIND FLUXES @inline function WENO_u_downwind(u1, u2, u3, u4, u5, weno) return _WENO_u( u1, u2, u3, u4, u5, weno, weno_alphas_downwind, stencil_candidate_downwind ) end @inline function WENO_u_upwind(u1, u2, u3, u4, u5, weno) return _WENO_u(u1, u2, u3, u4, u5, weno, weno_alphas_upwind, stencil_candidate_upwind) end @inline function _WENO_u( u1, u2, u3, u4, u5, weno, fun_alphas::F1, fun_stencil::F2 ) where {F1,F2} # Smoothness indicators β = weno_betas(u1, u2, u3, u4, u5, weno) # classical approach α0, α1, α2 = fun_alphas(weno, weno.method, β...) _α = inv(α0 + α1 + α2) w0 = α0 * _α w1 = α1 * _α w2 = α2 * _α # Candidate stencils s0, s1, s2 = fun_stencil(u1, u2, u3, u4, u5, weno) # flux down/up-wind f = @muladd w0 * s0 + w1 * s1 + w2 * s2 return f end # FLUXES ## x-axis @inline function WENO_flux_downwind_x(u, nx, weno, i, j) return _WENO_flux_x(u, nx, weno, i, j, WENO_u_downwind) end @inline function WENO_flux_upwind_x(u, nx, weno, i, j) return _WENO_flux_x(u, nx, weno, i, j, WENO_u_upwind) end @inline function _WENO_flux_x(u, nx, weno, i, j, fun::F) where {F} jw, jww = clamp(j - 1, 1, nx), clamp(j - 2, 1, nx) je, jee = clamp(j + 1, 1, nx), clamp(j + 2, 1, nx) u1 = @inbounds u[i, jww] u2 = @inbounds u[i, jw] u3 = @inbounds u[i, j] u4 = @inbounds u[i, je] u5 = @inbounds u[i, jee] return f = fun(u1, u2, u3, u4, u5, weno) end ## y-axis @inline function WENO_flux_downwind_y(u, ny, weno, i, j) return _WENO_flux_y(u, ny, weno, i, j, WENO_u_downwind) end @inline function WENO_flux_upwind_y(u, ny, weno, i, j) return _WENO_flux_y(u, ny, weno, i, j, WENO_u_upwind) end @inline function _WENO_flux_y(u, ny, weno, i, j, fun::F) where {F} iw, iww = clamp(i - 1, 1, ny), clamp(i - 2, 1, ny) ie, iee = clamp(i + 1, 1, ny), clamp(i + 2, 1, ny) u1 = @inbounds u[iww, j] u2 = @inbounds u[iw, j] u3 = @inbounds u[i, j] u4 = @inbounds u[ie, j] u5 = @inbounds u[iee, j] return f = fun(u1, u2, u3, u4, u5, weno) end @inline function weno_rhs(vy, vx, weno, _dx, _dy, nx, ny, i, j) jW, jE = clamp(j - 1, 1, ny), clamp(j + 1, 1, ny) iS, iN = clamp(i - 1, 1, nx), clamp(i + 1, 1, nx) vx_ij = vx[i, j] vy_ij = vy[i, j] return r = @inbounds begin @muladd begin max(vx_ij, 0) * (weno.fL[i, j] - weno.fL[i, jW]) * _dx + min(vx_ij, 0) * (weno.fR[i, jE] - weno.fR[i, j]) * _dx + max(vy_ij, 0) * (weno.fB[i, j] - weno.fB[iS, j]) * _dy + min(vy_ij, 0) * (weno.fT[iN, j] - weno.fT[i, j]) * _dy end end end @parallel_indices (i, j) function weno_f!(u, weno, nx, ny) weno.fL[i, j] = WENO_flux_upwind_x(u, nx, weno, i, j) weno.fR[i, j] = WENO_flux_downwind_x(u, nx, weno, i, j) weno.fB[i, j] = WENO_flux_upwind_y(u, ny, weno, i, j) weno.fT[i, j] = WENO_flux_downwind_y(u, ny, weno, i, j) return nothing end ## WENO-5 ADVECTION """ WENO_advection!(u, Vxi, weno, di, ni, dt) Perform the advection step of the Weighted Essentially Non-Oscillatory (WENO) scheme for the solution of hyperbolic partial differential equations. # Arguments - `u`: field to be advected. - `Vxi`: velocity field. - `weno`: structure containing the WENO scheme parameters and temporary variables. - `di`: grid spacing. - `ni`: number of grid points. - `dt`: time step. # Description The function first calculates the fluxes using the WENO scheme. Then it performs three steps of the WENO scheme. Each step involves calculating the right-hand side of the WENO equation and updating the solution `u`. The updating of the solution `u` is done using different combinations of the original solution and the temporary solution `weno.ut`. """ function WENO_advection!(u, Vxi, weno, di, dt) _di = inv.(di) ni = nx, ny = size(u) one_third = inv(3) two_thirds = 2 * one_third @parallel (1:nx, 1:ny) weno_f!(u, weno, nx, ny) @parallel (1:nx, 1:ny) weno_step1!(weno, u, Vxi, _di, ni, dt) @parallel (1:nx, 1:ny) weno_f!(weno.ut, weno, nx, ny) @parallel (1:nx, 1:ny) weno_step2!(weno, u, Vxi, _di, ni, dt) @parallel (1:nx, 1:ny) weno_f!(weno.ut, weno, nx, ny) @parallel (1:nx, 1:ny) weno_step3!(u, weno, Vxi, _di, ni, dt, one_third, two_thirds) end @parallel_indices (i, j) function weno_step1!(weno, u, Vxi, _di, ni, dt) rᵢ = weno_rhs(Vxi..., weno, _di..., ni..., i, j) @inbounds weno.ut[i, j] = muladd(-dt, rᵢ, u[i, j]) return nothing end @parallel_indices (i, j) function weno_step2!(weno, u, Vxi, _di, ni, dt) rᵢ = weno_rhs(Vxi..., weno, _di..., ni..., i, j) @inbounds weno.ut[i, j] = @muladd 0.75 * u[i, j] + 0.25 * weno.ut[i, j] - 0.25 * dt * rᵢ return nothing end @parallel_indices (i, j) function weno_step3!( u, weno, Vxi, _di, ni, dt, one_third, two_thirds ) rᵢ = weno_rhs(Vxi..., weno, _di..., ni..., i, j) @inbounds u[i, j] = @muladd one_third * u[i, j] + two_thirds * weno.ut[i, j] - two_thirds * dt * rᵢ return nothing end
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
2417
# BOUNDARY CONDITIONS KERNELS include("free_slip.jl") include("free_surface.jl") include("no_slip.jl") include("pure_shear.jl") @inline bc_index(x::NTuple{2,T}) where {T} = mapreduce(xi -> max(size(xi)...), max, x) @inline bc_index(x::T) where {T<:AbstractArray} = max(size(x)...) @inline function bc_index(x::NTuple{3,T}) where {T} n = mapreduce(xi -> max(size(xi)...), max, x) return n, n end @inline do_bc(bc) = reduce(|, values(bc)) """ thermal_bcs!(T, bcs::TemperatureBoundaryConditions) Apply the prescribed heat boundary conditions `bc` on the `T` """ thermal_bcs!(thermal, bcs) = thermal_bcs!(backend(thermal), thermal, bcs) function thermal_bcs!( ::CPUBackendTrait, thermal::JustRelax.ThermalArrays, bcs::TemperatureBoundaryConditions ) return thermal_bcs!(thermal.T, bcs) end function thermal_bcs!(T::AbstractArray, bcs::TemperatureBoundaryConditions) n = bc_index(T) # no flux boundary conditions do_bc(bcs.no_flux) && (@parallel (@idx n) free_slip!(T, bcs.no_flux)) return nothing end # @inline thermal_bcs!(thermal::ThermalArrays, bcs::TemperatureBoundaryConditions) = thermal_bcs!(thermal.T, bcs) """ flow_bcs!(stokes, bcs::VelocityBoundaryConditions) Apply the prescribed flow boundary conditions `bc` on the `stokes` """ flow_bcs!(stokes, bcs) = flow_bcs!(backend(stokes), stokes, bcs) function flow_bcs!(::CPUBackendTrait, stokes, bcs::VelocityBoundaryConditions) return _flow_bcs!(bcs, @velocity(stokes)) end """ flow_bcs!(stokes, bcs::DisplacementBoundaryConditions) Apply the prescribed flow boundary conditions `bc` on the `stokes` """ function flow_bcs!(::CPUBackendTrait, stokes, bcs::DisplacementBoundaryConditions) return _flow_bcs!(bcs, @displacement(stokes)) end function flow_bcs!(bcs, V::Vararg{T,N}) where {T,N} return _flow_bcs!(bcs, tuple(V...)) end function _flow_bcs!(bcs, V) n = bc_index(V) # no slip boundary conditions # do_bc(bcs.no_slip) && (@parallel (@idx n) no_slip!(V..., bcs.no_slip)) if do_bc(bcs.no_slip) # @parallel (@idx n) no_slip1!(V..., bcs.no_slip) # @parallel (@idx n) no_slip2!(V..., bcs.no_slip) no_slip!(V..., bcs.no_slip) end # free slip boundary conditions do_bc(bcs.free_slip) && (@parallel (@idx n) free_slip!(V..., bcs.free_slip)) return nothing end
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
3186
@parallel_indices (i) function free_slip!(Ax, Ay, bc) @inbounds begin if i ≤ size(Ax, 1) bc.bot && (Ax[i, 1] = Ax[i, 2]) bc.top && (Ax[i, end] = Ax[i, end - 1]) end if i ≤ size(Ay, 2) bc.left && (Ay[1, i] = Ay[2, i]) bc.right && (Ay[end, i] = Ay[end - 1, i]) end end return nothing end @parallel_indices (i, j) function free_slip!(Ax, Ay, Az, bc) @inbounds begin # free slip in the front and back XZ planes if bc.front if i ≤ size(Ax, 1) && j ≤ size(Ax, 3) Ax[i, 1, j] = Ax[i, 2, j] end if i ≤ size(Az, 1) && j ≤ size(Az, 3) Az[i, 1, j] = Az[i, 2, j] end end if bc.back if i ≤ size(Ax, 1) && j ≤ size(Ax, 3) Ax[i, end, j] = Ax[i, end - 1, j] end if i ≤ size(Az, 1) && j ≤ size(Az, 3) Az[i, end, j] = Az[i, end - 1, j] end end # free slip in the front and back XY planes if bc.top if i ≤ size(Ax, 1) && j ≤ size(Ax, 2) Ax[i, j, 1] = Ax[i, j, 2] end if i ≤ size(Ay, 1) && j ≤ size(Ay, 2) Ay[i, j, 1] = Ay[i, j, 2] end end if bc.bot if i ≤ size(Ax, 1) && j ≤ size(Ax, 2) Ax[i, j, end] = Ax[i, j, end - 1] end if i ≤ size(Ay, 1) && j ≤ size(Ay, 2) Ay[i, j, end] = Ay[i, j, end - 1] end end # free slip in the front and back YZ planes if bc.left if i ≤ size(Ay, 2) && j ≤ size(Ay, 3) Ay[1, i, j] = Ay[2, i, j] end if i ≤ size(Az, 2) && j ≤ size(Az, 3) Az[1, i, j] = Az[2, i, j] end end if bc.right if i ≤ size(Ay, 2) && j ≤ size(Ay, 3) Ay[end, i, j] = Ay[end - 1, i, j] end if i ≤ size(Az, 2) && j ≤ size(Az, 3) Az[end, i, j] = Az[end - 1, i, j] end end end return nothing end @parallel_indices (i) function free_slip!(T::_T, bc) where {_T<:AbstractArray{<:Any,2}} @inbounds begin if i ≤ size(T, 1) bc.bot && (T[i, 1] = T[i, 2]) bc.top && (T[i, end] = T[i, end - 1]) end if i ≤ size(T, 2) bc.left && (T[1, i] = T[2, i]) bc.right && (T[end, i] = T[end - 1, i]) end end return nothing end @parallel_indices (i, j) function free_slip!(T::_T, bc) where {_T<:AbstractArray{<:Any,3}} nx, ny, nz = size(T) @inbounds begin if i ≤ nx && j ≤ ny bc.bot && (T[i, j, 1] = T[i, j, 2]) bc.top && (T[i, j, end] = T[i, j, end - 1]) end if i ≤ ny && j ≤ nz bc.left && (T[1, i, j] = T[2, i, j]) bc.right && (T[end, i, j] = T[end - 1, i, j]) end if i ≤ nx && j ≤ nz bc.front && (T[i, 1, j] = T[i, 2, j]) bc.back && (T[i, end, j] = T[i, end - 1, j]) end end return nothing end
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
2321
function free_surface_bcs!( stokes, bcs::AbstractFlowBoundaryConditions, η, rheology, phase_ratios, dt, di ) indices_range(::Any, Vy) = @idx (size(Vy, 1) - 2) indices_range(::Any, ::Any, Vz) = @idx (size(Vz, 1) - 2, size(Vz, 2) - 2) V = @velocity(stokes) n = indices_range(V...) if bcs.free_surface # apply boundary conditions @parallel n FreeSurface_Vy!( V..., stokes.P, stokes.P0, stokes.τ_o.yy, η, rheology, phase_ratios.center, dt, di..., ) end end @parallel_indices (i) function FreeSurface_Vy!( Vx::AbstractArray{T,2}, Vy::AbstractArray{T,2}, P::AbstractArray{T,2}, P_old::AbstractArray{T,2}, τyy_old::AbstractArray{T,2}, η::AbstractArray{T,2}, rheology, phase_ratios, dt::T, dx::T, dy::T, ) where {T} phase = @inbounds phase_ratios[i, end] Gdt = fn_ratio(get_shear_modulus, rheology, phase) * dt ν = 1e-2 Vy[i + 1, end] = ν * ( Vy[i + 1, end - 1] + (3 / 2) * ( P[i, end] / (2.0 * η[i, end]) + #- (τyy_old[i, end] + P_old[i, end]) / (2.0 * Gdt) + inv(3.0) * (Vx[i + 1, end - 1] - Vx[i, end - 1]) * inv(dx) ) * dy ) + (1 - ν) * Vy[i + 1, end] return nothing end @parallel_indices (i, j) function FreeSurface_Vy!( Vx::AbstractArray{T,3}, Vy::AbstractArray{T,3}, Vz::AbstractArray{T,3}, P::AbstractArray{T,3}, P_old::AbstractArray{T,3}, τyy_old::AbstractArray{T,3}, η::AbstractArray{T,3}, rheology, phase_ratios, dt::T, dx::T, dy::T, dz::T, ) where {T} phase = @inbounds phase_ratios[i, j, end] Gdt = fn_ratio(get_shear_modulus, rheology, phase) * dt Vz[i + 1, j + 1, end] = Vz[i + 1, j + 1, end - 1] + 3.0 / 2.0 * ( P[i, j, end] / (2.0 * η[i, j, end]) - (τyy_old[i, j, end] + P_old[i, j, end]) / (2.0 * Gdt) + inv(3.0) * ( (Vx[i + 1, j + 1, end - 1] - Vx[i, j + 1, end - 1]) * inv(dx) + (Vy[i + 1, j + 1, end - 1] - Vy[i + 1, j, end - 1]) * inv(dy) ) ) * dz return nothing end
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
1887
@views function no_slip!(Ax, Ay, bc) if bc.left Ax[1, :] .= 0 Ay[2, :] .= Ay[3, :] / 3 Ay[1, :] .= -Ay[2, :] end if bc.right Ax[end, :] .= 0 Ay[end - 1, :] .= Ay[end - 2, :] / 3 Ay[end, :] .= -Ay[end - 1, :] end if bc.bot Ax[:, 2] .= Ax[:, 3] / 3 Ax[:, 1] .= -Ax[:, 2] Ay[:, 1] .= 0 end if bc.top Ax[:, end - 1] .= Ax[:, end - 2] / 3 Ax[:, end] .= -Ax[:, end - 1] Ay[:, end] .= 0 end end @views function no_slip!(Ax, Ay, Az, bc) if bc.left Ax[1, :, :] .= 0 Ay[2, :, :] .= Ay[3, :, :] / 3 Ay[1, :, :] .= -Ay[2, :, :] Az[2, :, :] .= Az[3, :, :] / 3 Az[1, :, :] .= -Az[2, :, :] end if bc.right Ax[end, :, :] .= 0 Ay[end - 1, :, :] .= Ay[end - 2, :, :] / 3 Ay[end, :, :] .= -Ay[end - 1, :, :] Az[end - 1, :, :] .= Az[end - 2, :, :] / 3 Az[end, :, :] .= -Az[end - 1, :, :] end if bc.front Ax[:, 2, :] .= -Ax[:, 3, :] / 3 Ax[:, 1, :] .= -Ax[:, 2, :] Ay[:, 1, :] .= 0 Az[:, 2, :] .= -Az[:, 3, :] / 3 Az[:, 1, :] .= -Az[:, 2, :] end if bc.back Ax[:, end - 1, :] .= -Ax[:, end - 2, :] / 3 Ax[:, end, :] .= -Ax[:, end - 1, :] Ay[:, end, :] .= 0 Az[:, end - 1, :] .= -Az[:, end - 2, :] / 3 Az[:, end, :] .= -Az[:, end - 1, :] end if bc.bot Ax[:, :, 1] .= -Ax[:, :, 3] / 3 Ax[:, :, 1] .= -Ax[:, :, 2] Ay[:, :, 1] .= -Ay[:, :, 3] / 3 Ay[:, :, 1] .= -Ay[:, :, 2] Az[:, :, 1] .= 0 end if bc.top Ax[:, :, end - 1] .= -Ax[:, :, end - 2] / 3 Ax[:, :, end] .= -Ax[:, :, end - 1] Ay[:, :, end - 1] .= -Ay[:, :, end - 2] / 3 Ay[:, :, end] .= -Ay[:, :, end - 1] Az[:, :, end] .= 0 end end
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
852
function pureshear_bc!( stokes::JustRelax.StokesArrays, xci::NTuple{2}, xvi::NTuple{2}, εbg, backend ) stokes.V.Vx[:, 2:(end - 1)] .= PTArray(backend)([εbg * x for x in xvi[1], y in xci[2]]) stokes.V.Vy[2:(end - 1), :] .= PTArray(backend)([-εbg * y for x in xci[1], y in xvi[2]]) return nothing end function pureshear_bc!( stokes::JustRelax.StokesArrays, xci::NTuple{3}, xvi::NTuple{3}, εbg, backend ) xv, yv, zv = xvi xc, yc, zc = xci stokes.V.Vx[:, 2:(end - 1), 2:(end - 1)] .= PTArray(backend)([ εbg * x for x in xv, y in yc, z in zc ]) stokes.V.Vy[2:(end - 1), :, 2:(end - 1)] .= PTArray(backend)([ εbg * y for x in xc, y in xv, z in zc ]) stokes.V.Vz[2:(end - 1), 2:(end - 1), :] .= PTArray(backend)([ -εbg * z for x in xc, y in xc, z in zv ]) return nothing end
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
1944
abstract type AbstractBoundaryConditions end abstract type AbstractFlowBoundaryConditions <: AbstractBoundaryConditions end struct TemperatureBoundaryConditions{T,nD} <: AbstractBoundaryConditions no_flux::T function TemperatureBoundaryConditions(; no_flux::T=(left=true, right=false, top=false, bot=false) ) where {T} nD = length(no_flux) == 4 ? 2 : 3 return new{T,nD}(no_flux) end end struct DisplacementBoundaryConditions{T,nD} <: AbstractFlowBoundaryConditions no_slip::T free_slip::T free_surface::Bool function DisplacementBoundaryConditions(; no_slip::T=(left=false, right=false, top=false, bot=false), free_slip::T=(left=true, right=true, top=true, bot=true), free_surface::Bool=false, ) where {T} @assert length(no_slip) === length(free_slip) check_flow_bcs(no_slip, free_slip) nD = length(no_slip) == 4 ? 2 : 3 return new{T,nD}(no_slip, free_slip, free_surface) end end struct VelocityBoundaryConditions{T,nD} <: AbstractFlowBoundaryConditions no_slip::T free_slip::T free_surface::Bool function VelocityBoundaryConditions(; no_slip::T=(left=false, right=false, top=false, bot=false), free_slip::T=(left=true, right=true, top=true, bot=true), free_surface::Bool=false, ) where {T} @assert length(no_slip) === length(free_slip) check_flow_bcs(no_slip, free_slip) nD = length(no_slip) == 4 ? 2 : 3 return new{T,nD}(no_slip, free_slip, free_surface) end end function check_flow_bcs(no_slip::T, free_slip::T) where {T} v1 = values(no_slip) v2 = values(free_slip) k = keys(no_slip) for (v1, v2, k) in zip(v1, v2, k) if v1 == v2 error( "Incompatible boundary conditions. The $k boundary condition can't be the same for no_slip and free_slip", ) end end end
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
9761
module JustRelax2D using JustRelax: JustRelax using AMDGPU using StaticArrays using CellArrays using ParallelStencil, ParallelStencil.FiniteDifferences2D using ImplicitGlobalGrid using GeoParams, LinearAlgebra, Printf using MPI import JustRelax.JustRelax2D as JR2D import JustRelax: IGG, BackendTrait, CPUBackendTrait, AMDGPUBackendTrait, backend, CPUBackend, AMDGPUBackend, Geometry, @cell import JustRelax: AbstractBoundaryConditions, TemperatureBoundaryConditions, AbstractFlowBoundaryConditions, DisplacementBoundaryConditions, VelocityBoundaryConditions @init_parallel_stencil(AMDGPU, Float64, 2) include("../../common.jl") include("../../stokes/Stokes2D.jl") # Types function JR2D.StokesArrays(::Type{AMDGPUBackend}, ni::NTuple{N,Integer}) where {N} return StokesArrays(ni) end function JR2D.ThermalArrays(::Type{AMDGPUBackend}, ni::NTuple{N,Number}) where {N} return ThermalArrays(ni...) end function JR2D.ThermalArrays(::Type{AMDGPUBackend}, ni::Vararg{Number,N}) where {N} return ThermalArrays(ni...) end function JR2D.PhaseRatio(::Type{AMDGPUBackend}, ni, num_phases) return PhaseRatio(ni, num_phases) end function JR2D.PTThermalCoeffs( ::Type{AMDGPUBackend}, K, ρCp, dt, di::NTuple, li::NTuple; ϵ=1e-8, CFL=0.9 / √3 ) return PTThermalCoeffs(K, ρCp, dt, di, li; ϵ=ϵ, CFL=CFL) end function JR2D.PTThermalCoeffs( ::Type{AMDGPUBackend}, rheology, phase_ratios, args, dt, ni, di::NTuple{nDim,T}, li::NTuple{nDim,Any}; ϵ=1e-8, CFL=0.9 / √3, ) where {nDim,T} return PTThermalCoeffs(rheology, phase_ratios, args, dt, ni, di, li; ϵ=ϵ, CFL=CFL) end function JR2D.PTThermalCoeffs( ::Type{AMDGPUBackend}, rheology::MaterialParams, args, dt, ni, di::NTuple, li::NTuple; ϵ=1e-8, CFL=0.9 / √3, ) return PTThermalCoeffs(rheology, args, dt, ni, di, li; ϵ=ϵ, CFL=CFL) end function JR2D.update_thermal_coeffs!( pt_thermal::JustRelax.PTThermalCoeffs{T,<:ROCArray}, rheology, phase_ratios, args, dt ) where {T} ni = size(pt_thermal.dτ_ρ) @parallel (@idx ni) compute_pt_thermal_arrays!( pt_thermal.θr_dτ, pt_thermal.dτ_ρ, rheology, phase_ratios.center, args, pt_thermal.max_lxyz, pt_thermal.Vpdτ, inv(dt), ) return nothing end function JR2D.update_thermal_coeffs!( pt_thermal::JustRelax.PTThermalCoeffs{T,<:ROCArray}, rheology, args, dt ) where {T} ni = size(pt_thermal.dτ_ρ) @parallel (@idx ni) compute_pt_thermal_arrays!( pt_thermal.θr_dτ, pt_thermal.dτ_ρ, rheology, args, pt_thermal.max_lxyz, pt_thermal.Vpdτ, inv(dt), ) return nothing end function JR2D.update_thermal_coeffs!( pt_thermal::JustRelax.PTThermalCoeffs{T,<:ROCArray}, rheology, ::Nothing, args, dt ) where {T} ni = size(pt_thermal.dτ_ρ) @parallel (@idx ni) compute_pt_thermal_arrays!( pt_thermal.θr_dτ, pt_thermal.dτ_ρ, rheology, args, pt_thermal.max_lxyz, pt_thermal.Vpdτ, inv(dt), ) return nothing end # Boundary conditions function JR2D.flow_bcs!( ::AMDGPUBackendTrait, stokes::JustRelax.StokesArrays, bcs::VelocityBoundaryConditions ) return _flow_bcs!(bcs, @velocity(stokes)) end function flow_bcs!( ::AMDGPUBackendTrait, stokes::JustRelax.StokesArrays, bcs::VelocityBoundaryConditions ) return _flow_bcs!(bcs, @velocity(stokes)) end function JR2D.flow_bcs!( ::AMDGPUBackendTrait, stokes::JustRelax.StokesArrays, bcs::DisplacementBoundaryConditions, ) return _flow_bcs!(bcs, @displacement(stokes)) end function flow_bcs!( ::AMDGPUBackendTrait, stokes::JustRelax.StokesArrays, bcs::DisplacementBoundaryConditions, ) return _flow_bcs!(bcs, @displacement(stokes)) end function JR2D.thermal_bcs!(::AMDGPUBackendTrait, thermal::JustRelax.ThermalArrays, bcs) return thermal_bcs!(thermal.T, bcs) end function thermal_bcs!(::AMDGPUBackendTrait, thermal::JustRelax.ThermalArrays, bcs) return thermal_bcs!(thermal.T, bcs) end # Phases function JR2D.phase_ratios_center!( ::AMDGPUBackendTrait, phase_ratios::JustRelax.PhaseRatio, particles, grid::Geometry, phases, ) return _phase_ratios_center!(phase_ratios, particles, grid, phases) end # Rheology ## viscosity function JR2D.compute_viscosity!(::AMDGPUBackendTrait, stokes, ν, args, rheology, cutoff) return _compute_viscosity!(stokes, ν, args, rheology, cutoff) end function JR2D.compute_viscosity!( ::AMDGPUBackendTrait, stokes, ν, phase_ratios, args, rheology, cutoff ) return _compute_viscosity!(stokes, ν, phase_ratios, args, rheology, cutoff) end function JR2D.compute_viscosity!(η, ν, εII::ROCArray, args, rheology, cutoff) return compute_viscosity!(η, ν, εII, args, rheology, cutoff) end function compute_viscosity!(::AMDGPUBackendTrait, stokes, ν, args, rheology, cutoff) return _compute_viscosity!(stokes, ν, args, rheology, cutoff) end function compute_viscosity!( ::AMDGPUBackendTrait, stokes, ν, phase_ratios, args, rheology, cutoff ) return _compute_viscosity!(stokes, ν, phase_ratios, args, rheology, cutoff) end function compute_viscosity!(η, ν, εII::ROCArray, args, rheology, cutoff) return compute_viscosity!(η, ν, εII, args, rheology, cutoff) end ## Stress function JR2D.tensor_invariant!(::AMDGPUBackendTrait, A::JustRelax.SymmetricTensor) return _tensor_invariant!(A) end ## Buoyancy forces function JR2D.compute_ρg!(ρg::ROCArray, rheology, args) return compute_ρg!(ρg, rheology, args) end function JR2D.compute_ρg!(ρg::ROCArray, phase_ratios::JustRelax.PhaseRatio, rheology, args) return compute_ρg!(ρg, phase_ratios, rheology, args) end ## Melt fraction function JR2D.compute_melt_fraction!(ϕ::ROCArray, rheology, args) return compute_melt_fraction!(ϕ, rheology, args) end function JR2D.compute_melt_fraction!( ϕ::ROCArray, phase_ratios::JustRelax.PhaseRatio, rheology, args ) return compute_melt_fraction!(ϕ, phase_ratios, rheology, args) end # Interpolations function JR2D.temperature2center!(::AMDGPUBackendTrait, thermal::JustRelax.ThermalArrays) return _temperature2center!(thermal) end function temperature2center!(::AMDGPUBackendTrait, thermal::JustRelax.ThermalArrays) return _temperature2center!(thermal) end function JR2D.vertex2center!(center::T, vertex::T) where {T<:ROCArray} return vertex2center!(center, vertex) end function JR2D.center2vertex!(vertex::T, center::T) where {T<:ROCArray} return center2vertex!(vertex, center) end function JR2D.center2vertex!( vertex_yz::T, vertex_xz::T, vertex_xy::T, center_yz::T, center_xz::T, center_xy::T ) where {T<:ROCArray} return center2vertex!(vertex_yz, vertex_xz, vertex_xy, center_yz, center_xz, center_xy) end function JR2D.velocity2vertex!( Vx_v::ROCArray, Vy_v::ROCArray, Vx::ROCArray, Vy::ROCArray; ghost_nodes=true ) velocity2vertex!(Vx_v, Vy_v, Vx, Vy; ghost_nodes=ghost_nodes) return nothing end function JR2D.velocity2displacement!( ::AMDGPUBackendTrait, stokes::JustRelax.StokesArrays, dt ) return _velocity2displacement!(stokes, dt) end function velocity2displacement!(::AMDGPUBackendTrait, stokes::JustRelax.StokesArrays, dt) return _velocity2displacement!(stokes, dt) end function JR2D.displacement2velocity!( ::AMDGPUBackendTrait, stokes::JustRelax.StokesArrays, dt ) return _displacement2velocity!(stokes, dt) end function displacement2velocity!(::AMDGPUBackendTrait, stokes::JustRelax.StokesArrays, dt) return _displacement2velocity!(stokes, dt) end # Solvers function JR2D.solve!(::AMDGPUBackendTrait, stokes, args...; kwargs) return _solve!(stokes, args...; kwargs...) end function JR2D.heatdiffusion_PT!(::AMDGPUBackendTrait, thermal, args...; kwargs) return _heatdiffusion_PT!(thermal, args...; kwargs...) end # Utils function JR2D.compute_dt(::AMDGPUBackendTrait, S::JustRelax.StokesArrays, args...) return _compute_dt(S, args...) end # Subgrid diffusion function JR2D.subgrid_characteristic_time!( subgrid_arrays, particles, dt₀::ROCArray, phases::JustRelax.PhaseRatio, rheology, thermal::JustRelax.ThermalArrays, stokes::JustRelax.StokesArrays, xci, di, ) ni = size(stokes.P) @parallel (@idx ni) subgrid_characteristic_time!( dt₀, phases.center, rheology, thermal.Tc, stokes.P, di ) return nothing end function JR2D.subgrid_characteristic_time!( subgrid_arrays, particles, dt₀::ROCArray, phases::AbstractArray{Int,N}, rheology, thermal::JustRelax.ThermalArrays, stokes::JustRelax.StokesArrays, xci, di, ) where {N} ni = size(stokes.P) @parallel (@idx ni) subgrid_characteristic_time!( dt₀, phases, rheology, thermal.Tc, stokes.P, di ) return nothing end # shear heating function JR2D.compute_shear_heating!(::AMDGPUBackendTrait, thermal, stokes, rheology, dt) ni = size(thermal.shear_heating) @parallel (ni) compute_shear_heating_kernel!( thermal.shear_heating, @tensor_center(stokes.τ), @tensor_center(stokes.τ_o), @strain(stokes), rheology, dt, ) return nothing end function JR2D.compute_shear_heating!( ::AMDGPUBackendTrait, thermal, stokes, phase_ratios::JustRelax.PhaseRatio, rheology, dt ) ni = size(thermal.shear_heating) @parallel (@idx ni) compute_shear_heating_kernel!( thermal.shear_heating, @tensor_center(stokes.τ), @tensor_center(stokes.τ_o), @strain(stokes), phase_ratios.center, rheology, dt, ) return nothing end end
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
9735
module JustRelax3D using JustRelax: JustRelax using AMDGPU using StaticArrays using CellArrays using ParallelStencil, ParallelStencil.FiniteDifferences3D using ImplicitGlobalGrid using GeoParams, LinearAlgebra, Printf using MPI import JustRelax.JustRelax3D as JR3D import JustRelax: IGG, BackendTrait, CPUBackendTrait, AMDGPUBackendTrait, backend, CPUBackend, AMDGPUBackend, Geometry, @cell import JustRelax: AbstractBoundaryConditions, TemperatureBoundaryConditions, AbstractFlowBoundaryConditions, DisplacementBoundaryConditions, VelocityBoundaryConditions @init_parallel_stencil(AMDGPU, Float64, 3) include("../../common.jl") include("../../stokes/Stokes3D.jl") # Types function JR3D.StokesArrays(::Type{AMDGPUBackend}, ni::NTuple{N,Integer}) where {N} return StokesArrays(ni) end function JR3D.ThermalArrays(::Type{AMDGPUBackend}, ni::NTuple{N,Number}) where {N} return ThermalArrays(ni...) end function JR3D.ThermalArrays(::Type{AMDGPUBackend}, ni::Vararg{Number,N}) where {N} return ThermalArrays(ni...) end function JR3D.PhaseRatio(::Type{AMDGPUBackend}, ni, num_phases) return PhaseRatio(ni, num_phases) end function JR3D.PTThermalCoeffs( ::Type{AMDGPUBackend}, K, ρCp, dt, di::NTuple, li::NTuple; ϵ=1e-8, CFL=0.9 / √3 ) return PTThermalCoeffs(K, ρCp, dt, di, li; ϵ=ϵ, CFL=CFL) end function JR3D.PTThermalCoeffs( ::Type{AMDGPUBackend}, rheology, phase_ratios, args, dt, ni, di::NTuple{nDim,T}, li::NTuple{nDim,Any}; ϵ=1e-8, CFL=0.9 / √3, ) where {nDim,T} return PTThermalCoeffs(rheology, phase_ratios, args, dt, ni, di, li; ϵ=ϵ, CFL=CFL) end function JR3D.PTThermalCoeffs( ::Type{AMDGPUBackend}, rheology::MaterialParams, args, dt, ni, di::NTuple, li::NTuple; ϵ=1e-8, CFL=0.9 / √3, ) return PTThermalCoeffs(rheology, args, dt, ni, di, li; ϵ=ϵ, CFL=CFL) end function JR3D.update_thermal_coeffs!( pt_thermal::JustRelax.PTThermalCoeffs{T,<:ROCArray}, rheology, phase_ratios, args, dt ) where {T} ni = size(pt_thermal.dτ_ρ) @parallel (@idx ni) compute_pt_thermal_arrays!( pt_thermal.θr_dτ, pt_thermal.dτ_ρ, rheology, phase_ratios.center, args, pt_thermal.max_lxyz, pt_thermal.Vpdτ, inv(dt), ) return nothing end function JR3D.update_thermal_coeffs!( pt_thermal::JustRelax.PTThermalCoeffs{T,<:ROCArray}, rheology, args, dt ) where {T} ni = size(pt_thermal.dτ_ρ) @parallel (@idx ni) compute_pt_thermal_arrays!( pt_thermal.θr_dτ, pt_thermal.dτ_ρ, rheology, args, pt_thermal.max_lxyz, pt_thermal.Vpdτ, inv(dt), ) return nothing end function JR3D.update_thermal_coeffs!( pt_thermal::JustRelax.PTThermalCoeffs{T,<:ROCArray}, rheology, ::Nothing, args, dt ) where {T} ni = size(pt_thermal.dτ_ρ) @parallel (@idx ni) compute_pt_thermal_arrays!( pt_thermal.θr_dτ, pt_thermal.dτ_ρ, rheology, args, pt_thermal.max_lxyz, pt_thermal.Vpdτ, inv(dt), ) return nothing end # Boundary conditions function JR3D.flow_bcs!( ::AMDGPUBackendTrait, stokes::JustRelax.StokesArrays, bcs::VelocityBoundaryConditions ) return _flow_bcs!(bcs, @velocity(stokes)) end function flow_bcs!( ::AMDGPUBackendTrait, stokes::JustRelax.StokesArrays, bcs::VelocityBoundaryConditions ) return _flow_bcs!(bcs, @velocity(stokes)) end function JR3D.flow_bcs!( ::AMDGPUBackendTrait, stokes::JustRelax.StokesArrays, bcs::DisplacementBoundaryConditions, ) return _flow_bcs!(bcs, @displacement(stokes)) end function flow_bcs!( ::AMDGPUBackendTrait, stokes::JustRelax.StokesArrays, bcs::DisplacementBoundaryConditions, ) return _flow_bcs!(bcs, @displacement(stokes)) end function JR3D.thermal_bcs!(::AMDGPUBackendTrait, thermal::JustRelax.ThermalArrays, bcs) return thermal_bcs!(thermal.T, bcs) end function thermal_bcs!(::AMDGPUBackendTrait, thermal::JustRelax.ThermalArrays, bcs) return thermal_bcs!(thermal.T, bcs) end # Phases function JR3D.phase_ratios_center!( ::AMDGPUBackendTrait, phase_ratios::JustRelax.PhaseRatio, particles, grid::Geometry, phases, ) return _phase_ratios_center!(phase_ratios, particles, grid, phases) end # Rheology ## viscosity function JR3D.compute_viscosity!(::AMDGPUBackendTrait, stokes, ν, args, rheology, cutoff) return _compute_viscosity!(stokes, ν, args, rheology, cutoff) end function JR3D.compute_viscosity!( ::AMDGPUBackendTrait, stokes, ν, phase_ratios, args, rheology, cutoff ) return _compute_viscosity!(stokes, ν, phase_ratios, args, rheology, cutoff) end function JR3D.compute_viscosity!(η, ν, εII::ROCArray, args, rheology, cutoff) return compute_viscosity!(η, ν, εII, args, rheology, cutoff) end function compute_viscosity!(::AMDGPUBackendTrait, stokes, ν, args, rheology, cutoff) return _compute_viscosity!(stokes, ν, args, rheology, cutoff) end function compute_viscosity!( ::AMDGPUBackendTrait, stokes, ν, phase_ratios, args, rheology, cutoff ) return _compute_viscosity!(stokes, ν, phase_ratios, args, rheology, cutoff) end function compute_viscosity!(η, ν, εII::ROCArray, args, rheology, cutoff) return compute_viscosity!(η, ν, εII, args, rheology, cutoff) end ## Stress function JR3D.tensor_invariant!(::AMDGPUBackendTrait, A::JustRelax.SymmetricTensor) return _tensor_invariant!(A) end ## Buoyancy forces function JR3D.compute_ρg!(ρg::ROCArray, rheology, args) return compute_ρg!(ρg, rheology, args) end function JR3D.compute_ρg!(ρg::ROCArray, phase_ratios::JustRelax.PhaseRatio, rheology, args) return compute_ρg!(ρg, phase_ratios, rheology, args) end ## Melt fraction function JR3D.compute_melt_fraction!(ϕ::ROCArray, rheology, args) return compute_melt_fraction!(ϕ, rheology, args) end function JR3D.compute_melt_fraction!( ϕ::ROCArray, phase_ratios::JustRelax.PhaseRatio, rheology, args ) return compute_melt_fraction!(ϕ, phase_ratios, rheology, args) end # Interpolations function JR3D.temperature2center!(::AMDGPUBackendTrait, thermal::JustRelax.ThermalArrays) return _temperature2center!(thermal) end function temperature2center!(::AMDGPUBackendTrait, thermal::JustRelax.ThermalArrays) return _temperature2center!(thermal) end function JR3D.vertex2center!(center::T, vertex::T) where {T<:ROCArray} return vertex2center!(center, vertex) end function JR3D.center2vertex!(vertex::T, center::T) where {T<:ROCArray} return center2vertex!(vertex, center) end function JR3D.center2vertex!( vertex_yz::T, vertex_xz::T, vertex_xy::T, center_yz::T, center_xz::T, center_xy::T ) where {T<:ROCArray} return center2vertex!(vertex_yz, vertex_xz, vertex_xy, center_yz, center_xz, center_xy) end function JR3D.velocity2vertex!( Vx_v::ROCArray, Vy_v::ROCArray, Vz_v::ROCArray, Vx::ROCArray, Vy::ROCArray, Vz::ROCArray ) velocity2vertex!(Vx_v, Vy_v, Vz_v, Vx, Vy, Vz) return nothing end function JR3D.velocity2displacement!( ::AMDGPUBackendTrait, stokes::JustRelax.StokesArrays, dt ) return _velocity2displacement!(stokes, dt) end function velocity2displacement!(::AMDGPUBackendTrait, stokes::JustRelax.StokesArrays, dt) return _velocity2displacement!(stokes, dt) end function JR3D.displacement2velocity!( ::AMDGPUBackendTrait, stokes::JustRelax.StokesArrays, dt ) return _displacement2velocity!(stokes, dt) end function displacement2velocity!(::AMDGPUBackendTrait, stokes::JustRelax.StokesArrays, dt) return _displacement2velocity!(stokes, dt) end # Solvers function JR3D.solve!(::AMDGPUBackendTrait, stokes, args...; kwargs) return _solve!(stokes, args...; kwargs...) end function JR3D.heatdiffusion_PT!(::AMDGPUBackendTrait, thermal, args...; kwargs) return _heatdiffusion_PT!(thermal, args...; kwargs...) end # Utils function JR3D.compute_dt(::AMDGPUBackendTrait, S::JustRelax.StokesArrays, args...) return _compute_dt(S, args...) end function JR3D.subgrid_characteristic_time!( subgrid_arrays, particles, dt₀::ROCArray, phases::JustRelax.PhaseRatio, rheology, thermal::JustRelax.ThermalArrays, stokes::JustRelax.StokesArrays, xci, di, ) ni = size(stokes.P) @parallel (@idx ni) subgrid_characteristic_time!( dt₀, phases.center, rheology, thermal.Tc, stokes.P, di ) return nothing end function JR3D.subgrid_characteristic_time!( subgrid_arrays, particles, dt₀::ROCArray, phases::AbstractArray{Int,N}, rheology, thermal::JustRelax.ThermalArrays, stokes::JustRelax.StokesArrays, xci, di, ) where {N} ni = size(stokes.P) @parallel (@idx ni) subgrid_characteristic_time!( dt₀, phases, rheology, thermal.Tc, stokes.P, di ) return nothing end # shear heating function JR3D.compute_shear_heating!(::AMDGPUBackendTrait, thermal, stokes, rheology, dt) ni = size(thermal.shear_heating) @parallel (ni) compute_shear_heating_kernel!( thermal.shear_heating, @tensor_center(stokes.τ), @tensor_center(stokes.τ_o), @strain(stokes), rheology, dt, ) return nothing end function JR3D.compute_shear_heating!( ::AMDGPUBackendTrait, thermal, stokes, phase_ratios::JustRelax.PhaseRatio, rheology, dt ) ni = size(thermal.shear_heating) @parallel (@idx ni) compute_shear_heating_kernel!( thermal.shear_heating, @tensor_center(stokes.τ), @tensor_center(stokes.τ_o), @strain(stokes), phase_ratios.center, rheology, dt, ) return nothing end end
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
9629
module JustRelax2D using JustRelax: JustRelax using CUDA using StaticArrays using CellArrays using ParallelStencil, ParallelStencil.FiniteDifferences2D using ImplicitGlobalGrid using GeoParams, LinearAlgebra, Printf using MPI import JustRelax.JustRelax2D as JR2D import JustRelax: IGG, BackendTrait, CPUBackendTrait, CUDABackendTrait, backend, CPUBackend, Geometry, @cell import JustRelax: AbstractBoundaryConditions, TemperatureBoundaryConditions, AbstractFlowBoundaryConditions, DisplacementBoundaryConditions, VelocityBoundaryConditions @init_parallel_stencil(CUDA, Float64, 2) include("../../common.jl") include("../../stokes/Stokes2D.jl") # Types function JR2D.StokesArrays(::Type{CUDABackend}, ni::NTuple{N,Integer}) where {N} return StokesArrays(ni) end function JR2D.ThermalArrays(::Type{CUDABackend}, ni::NTuple{N,Number}) where {N} return ThermalArrays(ni...) end function JR2D.ThermalArrays(::Type{CUDABackend}, ni::Vararg{Number,N}) where {N} return ThermalArrays(ni...) end function JR2D.PhaseRatio(::Type{CUDABackend}, ni, num_phases) return PhaseRatio(ni, num_phases) end function JR2D.PTThermalCoeffs( ::Type{CUDABackend}, K, ρCp, dt, di::NTuple, li::NTuple; ϵ=1e-8, CFL=0.9 / √3 ) return PTThermalCoeffs(K, ρCp, dt, di, li; ϵ=ϵ, CFL=CFL) end function JR2D.PTThermalCoeffs( ::Type{CUDABackend}, rheology, phase_ratios, args, dt, ni, di::NTuple{nDim,T}, li::NTuple{nDim,Any}; ϵ=1e-8, CFL=0.9 / √3, ) where {nDim,T} return PTThermalCoeffs(rheology, phase_ratios, args, dt, ni, di, li; ϵ=ϵ, CFL=CFL) end function JR2D.PTThermalCoeffs( ::Type{CUDABackend}, rheology::MaterialParams, args, dt, ni, di::NTuple, li::NTuple; ϵ=1e-8, CFL=0.9 / √3, ) return PTThermalCoeffs(rheology, args, dt, ni, di, li; ϵ=ϵ, CFL=CFL) end function JR2D.update_thermal_coeffs!( pt_thermal::JustRelax.PTThermalCoeffs{T,<:CuArray}, rheology, phase_ratios, args, dt ) where {T} ni = size(pt_thermal.dτ_ρ) @parallel (@idx ni) compute_pt_thermal_arrays!( pt_thermal.θr_dτ, pt_thermal.dτ_ρ, rheology, phase_ratios.center, args, pt_thermal.max_lxyz, pt_thermal.Vpdτ, inv(dt), ) return nothing end function JR2D.update_thermal_coeffs!( pt_thermal::JustRelax.PTThermalCoeffs{T,<:CuArray}, rheology, args, dt ) where {T} ni = size(pt_thermal.dτ_ρ) @parallel (@idx ni) compute_pt_thermal_arrays!( pt_thermal.θr_dτ, pt_thermal.dτ_ρ, rheology, args, pt_thermal.max_lxyz, pt_thermal.Vpdτ, inv(dt), ) return nothing end function JR2D.update_thermal_coeffs!( pt_thermal::JustRelax.PTThermalCoeffs{T,<:CuArray}, rheology, ::Nothing, args, dt ) where {T} ni = size(pt_thermal.dτ_ρ) @parallel (@idx ni) compute_pt_thermal_arrays!( pt_thermal.θr_dτ, pt_thermal.dτ_ρ, rheology, args, pt_thermal.max_lxyz, pt_thermal.Vpdτ, inv(dt), ) return nothing end # Boundary conditions function JR2D.flow_bcs!( ::CUDABackendTrait, stokes::JustRelax.StokesArrays, bcs::VelocityBoundaryConditions ) return _flow_bcs!(bcs, @velocity(stokes)) end function flow_bcs!( ::CUDABackendTrait, stokes::JustRelax.StokesArrays, bcs::VelocityBoundaryConditions ) return _flow_bcs!(bcs, @velocity(stokes)) end function JR2D.flow_bcs!( ::CUDABackendTrait, stokes::JustRelax.StokesArrays, bcs::DisplacementBoundaryConditions ) return _flow_bcs!(bcs, @displacement(stokes)) end function flow_bcs!( ::CUDABackendTrait, stokes::JustRelax.StokesArrays, bcs::DisplacementBoundaryConditions ) return _flow_bcs!(bcs, @displacement(stokes)) end function JR2D.thermal_bcs!(::CUDABackendTrait, thermal::JustRelax.ThermalArrays, bcs) return thermal_bcs!(thermal.T, bcs) end function thermal_bcs!(::CUDABackendTrait, thermal::JustRelax.ThermalArrays, bcs) return thermal_bcs!(thermal.T, bcs) end # Phases function JR2D.phase_ratios_center!( ::CUDABackendTrait, phase_ratios::JustRelax.PhaseRatio, particles, grid::Geometry, phases, ) return _phase_ratios_center!(phase_ratios, particles, grid, phases) end # Rheology ## viscosity function JR2D.compute_viscosity!(::CUDABackendTrait, stokes, ν, args, rheology, cutoff) return _compute_viscosity!(stokes, ν, args, rheology, cutoff) end function JR2D.compute_viscosity!( ::CUDABackendTrait, stokes, ν, phase_ratios, args, rheology, cutoff ) return _compute_viscosity!(stokes, ν, phase_ratios, args, rheology, cutoff) end function JR2D.compute_viscosity!(η, ν, εII::CuArray, args, rheology, cutoff) return compute_viscosity!(η, ν, εII, args, rheology, cutoff) end function compute_viscosity!(::CUDABackendTrait, stokes, ν, args, rheology, cutoff) return _compute_viscosity!(stokes, ν, args, rheology, cutoff) end function compute_viscosity!( ::CUDABackendTrait, stokes, ν, phase_ratios, args, rheology, cutoff ) return _compute_viscosity!(stokes, ν, phase_ratios, args, rheology, cutoff) end function compute_viscosity!(η, ν, εII::CuArray, args, rheology, cutoff) return compute_viscosity!(η, ν, εII, args, rheology, cutoff) end ## Stress function JR2D.tensor_invariant!(::CUDABackendTrait, A::JustRelax.SymmetricTensor) return _tensor_invariant!(A) end ## Buoyancy forces function JR2D.compute_ρg!(ρg::CuArray, rheology, args) return compute_ρg!(ρg, rheology, args) end function JR2D.compute_ρg!(ρg::CuArray, phase_ratios::JustRelax.PhaseRatio, rheology, args) return compute_ρg!(ρg, phase_ratios, rheology, args) end ## Melt fraction function JR2D.compute_melt_fraction!(ϕ::CuArray, rheology, args) return compute_melt_fraction!(ϕ, rheology, args) end function JR2D.compute_melt_fraction!( ϕ::CuArray, phase_ratios::JustRelax.PhaseRatio, rheology, args ) return compute_melt_fraction!(ϕ, phase_ratios, rheology, args) end # Interpolations function JR2D.temperature2center!(::CUDABackendTrait, thermal::JustRelax.ThermalArrays) return _temperature2center!(thermal) end function temperature2center!(::CUDABackendTrait, thermal::JustRelax.ThermalArrays) return _temperature2center!(thermal) end function JR2D.vertex2center!(center::T, vertex::T) where {T<:CuArray} return vertex2center!(center, vertex) end function JR2D.center2vertex!(vertex::T, center::T) where {T<:CuArray} return center2vertex!(vertex, center) end function JR2D.center2vertex!( vertex_yz::T, vertex_xz::T, vertex_xy::T, center_yz::T, center_xz::T, center_xy::T ) where {T<:CuArray} return center2vertex!(vertex_yz, vertex_xz, vertex_xy, center_yz, center_xz, center_xy) end function JR2D.velocity2vertex!( Vx_v::CuArray, Vy_v::CuArray, Vx::CuArray, Vy::CuArray; ghost_nodes=true ) velocity2vertex!(Vx_v, Vy_v, Vx, Vy; ghost_nodes=ghost_nodes) return nothing end function JR2D.velocity2displacement!(::CUDABackendTrait, stokes::JustRelax.StokesArrays, dt) return _velocity2displacement!(stokes, dt) end function velocity2displacement!(::CUDABackendTrait, stokes::JustRelax.StokesArrays, dt) return _velocity2displacement!(stokes, dt) end function JR2D.displacement2velocity!(::CUDABackendTrait, stokes::JustRelax.StokesArrays, dt) return _displacement2velocity!(stokes, dt) end function displacement2velocity!(::CUDABackendTrait, stokes::JustRelax.StokesArrays, dt) return _displacement2velocity!(stokes, dt) end # Solvers function JR2D.solve!(::CUDABackendTrait, stokes, args...; kwargs) return _solve!(stokes, args...; kwargs...) end function JR2D.heatdiffusion_PT!(::CUDABackendTrait, thermal, args...; kwargs) return _heatdiffusion_PT!(thermal, args...; kwargs...) end # Utils function JR2D.compute_dt(::CUDABackendTrait, S::JustRelax.StokesArrays, args...) return _compute_dt(S, args...) end # Subgrid diffusion function JR2D.subgrid_characteristic_time!( subgrid_arrays, particles, dt₀::CuArray, phases::JustRelax.PhaseRatio, rheology, thermal::JustRelax.ThermalArrays, stokes::JustRelax.StokesArrays, xci, di, ) ni = size(stokes.P) @parallel (@idx ni) subgrid_characteristic_time!( dt₀, phases.center, rheology, thermal.Tc, stokes.P, di ) return nothing end function JR2D.subgrid_characteristic_time!( subgrid_arrays, particles, dt₀::CuArray, phases::AbstractArray{Int,N}, rheology, thermal::JustRelax.ThermalArrays, stokes::JustRelax.StokesArrays, xci, di, ) where {N} ni = size(stokes.P) @parallel (@idx ni) subgrid_characteristic_time!( dt₀, phases, rheology, thermal.Tc, stokes.P, di ) return nothing end # shear heating function JR2D.compute_shear_heating!(::CUDABackendTrait, thermal, stokes, rheology, dt) ni = size(thermal.shear_heating) @parallel (ni) compute_shear_heating_kernel!( thermal.shear_heating, @tensor_center(stokes.τ), @tensor_center(stokes.τ_o), @strain(stokes), rheology, dt, ) return nothing end function JR2D.compute_shear_heating!( ::CUDABackendTrait, thermal, stokes, phase_ratios::JustRelax.PhaseRatio, rheology, dt ) ni = size(thermal.shear_heating) @parallel (@idx ni) compute_shear_heating_kernel!( thermal.shear_heating, @tensor_center(stokes.τ), @tensor_center(stokes.τ_o), @strain(stokes), phase_ratios.center, rheology, dt, ) return nothing end end
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
9907
module JustRelax3D using JustRelax: JustRelax using CUDA using StaticArrays using CellArrays using ParallelStencil, ParallelStencil.FiniteDifferences3D using ImplicitGlobalGrid using GeoParams, LinearAlgebra, Printf using MPI import JustRelax.JustRelax3D as JR3D import JustRelax: IGG, BackendTrait, CPUBackendTrait, CUDABackendTrait, backend, CPUBackend, Geometry, @cell import JustRelax: AbstractBoundaryConditions, TemperatureBoundaryConditions, AbstractFlowBoundaryConditions, DisplacementBoundaryConditions, VelocityBoundaryConditions @init_parallel_stencil(CUDA, Float64, 3) include("../../common.jl") include("../../stokes/Stokes3D.jl") # Types function JR3D.StokesArrays(::Type{CUDABackend}, ni::NTuple{N,Integer}) where {N} return StokesArrays(ni) end function JR3D.ThermalArrays(::Type{CUDABackend}, ni::NTuple{N,Number}) where {N} return ThermalArrays(ni...) end function JR3D.ThermalArrays(::Type{CUDABackend}, ni::Vararg{Number,N}) where {N} return ThermalArrays(ni...) end function JR3D.PhaseRatio(::Type{CUDABackend}, ni, num_phases) return PhaseRatio(ni, num_phases) end function JR3D.PTThermalCoeffs( ::Type{CUDABackend}, K, ρCp, dt, di::NTuple, li::NTuple; ϵ=1e-8, CFL=0.9 / √3 ) return PTThermalCoeffs(K, ρCp, dt, di, li; ϵ=ϵ, CFL=CFL) end function JR3D.PTThermalCoeffs( ::Type{CUDABackend}, rheology, phase_ratios, args, dt, ni, di::NTuple{nDim,T}, li::NTuple{nDim,Any}; ϵ=1e-8, CFL=0.9 / √3, ) where {nDim,T} return PTThermalCoeffs(rheology, phase_ratios, args, dt, ni, di, li; ϵ=ϵ, CFL=CFL) end function JR3D.PTThermalCoeffs( ::Type{CUDABackend}, rheology::MaterialParams, args, dt, ni, di::NTuple, li::NTuple; ϵ=1e-8, CFL=0.9 / √3, ) return PTThermalCoeffs(rheology, args, dt, ni, di, li; ϵ=ϵ, CFL=CFL) end function JR3D.update_pt_thermal_arrays!( pt_thermal::JustRelax.PTThermalCoeffs{T,<:CuArray}, phase_ratios::JustRelax.PhaseRatio, rheology, args, _dt, ) where {T} update_pt_thermal_arrays!(pt_thermal, phase_ratios, rheology, args, _dt) return nothing end function JR3D.update_thermal_coeffs!( pt_thermal::JustRelax.PTThermalCoeffs{T,<:CuArray}, rheology, phase_ratios, args, dt ) where {T} ni = size(pt_thermal.dτ_ρ) @parallel (@idx ni) compute_pt_thermal_arrays!( pt_thermal.θr_dτ, pt_thermal.dτ_ρ, rheology, phase_ratios.center, args, pt_thermal.max_lxyz, pt_thermal.Vpdτ, inv(dt), ) return nothing end function JR3D.update_thermal_coeffs!( pt_thermal::JustRelax.PTThermalCoeffs{T,<:CuArray}, rheology, args, dt ) where {T} ni = size(pt_thermal.dτ_ρ) @parallel (@idx ni) compute_pt_thermal_arrays!( pt_thermal.θr_dτ, pt_thermal.dτ_ρ, rheology, args, pt_thermal.max_lxyz, pt_thermal.Vpdτ, inv(dt), ) return nothing end function JR3D.update_thermal_coeffs!( pt_thermal::JustRelax.PTThermalCoeffs{T,<:CuArray}, rheology, ::Nothing, args, dt ) where {T} ni = size(pt_thermal.dτ_ρ) @parallel (@idx ni) compute_pt_thermal_arrays!( pt_thermal.θr_dτ, pt_thermal.dτ_ρ, rheology, args, pt_thermal.max_lxyz, pt_thermal.Vpdτ, inv(dt), ) return nothing end # Boundary conditions function JR3D.flow_bcs!( ::CUDABackendTrait, stokes::JustRelax.StokesArrays, bcs::VelocityBoundaryConditions ) return _flow_bcs!(bcs, @velocity(stokes)) end function flow_bcs!( ::CUDABackendTrait, stokes::JustRelax.StokesArrays, bcs::VelocityBoundaryConditions ) return _flow_bcs!(bcs, @velocity(stokes)) end # Boundary conditions function JR3D.flow_bcs!( ::CUDABackendTrait, stokes::JustRelax.StokesArrays, bcs::DisplacementBoundaryConditions ) return _flow_bcs!(bcs, @displacement(stokes)) end function flow_bcs!( ::CUDABackendTrait, stokes::JustRelax.StokesArrays, bcs::DisplacementBoundaryConditions ) return _flow_bcs!(bcs, @displacement(stokes)) end function JR3D.thermal_bcs!(::CUDABackendTrait, thermal::JustRelax.ThermalArrays, bcs) return thermal_bcs!(thermal.T, bcs) end function thermal_bcs!(::CUDABackendTrait, thermal::JustRelax.ThermalArrays, bcs) return thermal_bcs!(thermal.T, bcs) end # Phases function JR3D.phase_ratios_center!( ::CUDABackendTrait, phase_ratios::JustRelax.PhaseRatio, particles, grid::Geometry, phases, ) return _phase_ratios_center!(phase_ratios, particles, grid, phases) end # Rheology ## viscosity function JR3D.compute_viscosity!(::CUDABackendTrait, stokes, ν, args, rheology, cutoff) return _compute_viscosity!(stokes, ν, args, rheology, cutoff) end function JR3D.compute_viscosity!( ::CUDABackendTrait, stokes, ν, phase_ratios, args, rheology, cutoff ) return _compute_viscosity!(stokes, ν, phase_ratios, args, rheology, cutoff) end function JR3D.compute_viscosity!(η, ν, εII::CuArray, args, rheology, cutoff) return compute_viscosity!(η, ν, εII, args, rheology, cutoff) end function compute_viscosity!(::CUDABackendTrait, stokes, ν, args, rheology, cutoff) return _compute_viscosity!(stokes, ν, args, rheology, cutoff) end function compute_viscosity!( ::CUDABackendTrait, stokes, ν, phase_ratios, args, rheology, cutoff ) return _compute_viscosity!(stokes, ν, phase_ratios, args, rheology, cutoff) end function compute_viscosity!(η, ν, εII::CuArray, args, rheology, cutoff) return compute_viscosity!(η, ν, εII, args, rheology, cutoff) end ## Stress function JR3D.tensor_invariant!(::CUDABackendTrait, A::JustRelax.SymmetricTensor) return _tensor_invariant!(A) end ## Buoyancy forces function JR3D.compute_ρg!(ρg::CuArray, rheology, args) return compute_ρg!(ρg, rheology, args) end function JR3D.compute_ρg!(ρg::CuArray, phase_ratios::JustRelax.PhaseRatio, rheology, args) return compute_ρg!(ρg, phase_ratios, rheology, args) end ## Melt fraction function JR3D.compute_melt_fraction!(ϕ::CuArray, rheology, args) return compute_melt_fraction!(ϕ, rheology, args) end function JR3D.compute_melt_fraction!( ϕ::CuArray, phase_ratios::JustRelax.PhaseRatio, rheology, args ) return compute_melt_fraction!(ϕ, phase_ratios, rheology, args) end # Interpolations function JR3D.temperature2center!(::CUDABackendTrait, thermal::JustRelax.ThermalArrays) return _temperature2center!(thermal) end function temperature2center!(::CUDABackendTrait, thermal::JustRelax.ThermalArrays) return _temperature2center!(thermal) end function JR3D.vertex2center!(center::T, vertex::T) where {T<:CuArray} return vertex2center!(center, vertex) end function JR3D.center2vertex!(vertex::T, center::T) where {T<:CuArray} return center2vertex!(vertex, center) end function JR3D.center2vertex!( vertex_yz::T, vertex_xz::T, vertex_xy::T, center_yz::T, center_xz::T, center_xy::T ) where {T<:CuArray} return center2vertex!(vertex_yz, vertex_xz, vertex_xy, center_yz, center_xz, center_xy) end function JR3D.velocity2vertex!( Vx_v::CuArray, Vy_v::CuArray, Vz_v::CuArray, Vx::CuArray, Vy::CuArray, Vz::CuArray ) velocity2vertex!(Vx_v, Vy_v, Vz_v, Vx, Vy, Vz) return nothing end function JR3D.velocity2displacement!(::CUDABackendTrait, stokes::JustRelax.StokesArrays, dt) return _velocity2displacement!(stokes, dt) end function velocity2displacement!(::CUDABackendTrait, stokes::JustRelax.StokesArrays, dt) return _velocity2displacement!(stokes, dt) end function JR3D.displacement2velocity!(::CUDABackendTrait, stokes::JustRelax.StokesArrays, dt) return _displacement2velocity!(stokes, dt) end function displacement2velocity!(::CUDABackendTrait, stokes::JustRelax.StokesArrays, dt) return _displacement2velocity!(stokes, dt) end # Solvers function JR3D.solve!(::CUDABackendTrait, stokes, args...; kwargs) return _solve!(stokes, args...; kwargs...) end function JR3D.heatdiffusion_PT!(::CUDABackendTrait, thermal, args...; kwargs) return _heatdiffusion_PT!(thermal, args...; kwargs...) end # Utils function JR3D.compute_dt(::CUDABackendTrait, S::JustRelax.StokesArrays, args...) return _compute_dt(S, args...) end function JR3D.subgrid_characteristic_time!( subgrid_arrays, particles, dt₀::CuArray, phases::JustRelax.PhaseRatio, rheology, thermal::JustRelax.ThermalArrays, stokes::JustRelax.StokesArrays, xci, di, ) ni = size(stokes.P) @parallel (@idx ni) subgrid_characteristic_time!( dt₀, phases.center, rheology, thermal.Tc, stokes.P, di ) return nothing end function JR3D.subgrid_characteristic_time!( subgrid_arrays, particles, dt₀::CuArray, phases::AbstractArray{Int,N}, rheology, thermal::JustRelax.ThermalArrays, stokes::JustRelax.StokesArrays, xci, di, ) where {N} ni = size(stokes.P) @parallel (@idx ni) subgrid_characteristic_time!( dt₀, phases, rheology, thermal.Tc, stokes.P, di ) return nothing end # shear heating function JR3D.compute_shear_heating!(::CUDABackendTrait, thermal, stokes, rheology, dt) ni = size(thermal.shear_heating) @parallel (ni) compute_shear_heating_kernel!( thermal.shear_heating, @tensor_center(stokes.τ), @tensor_center(stokes.τ_o), @strain(stokes), rheology, dt, ) return nothing end function JR3D.compute_shear_heating!( ::CUDABackendTrait, thermal, stokes, phase_ratios::JustRelax.PhaseRatio, rheology, dt ) ni = size(thermal.shear_heating) @parallel (@idx ni) compute_shear_heating_kernel!( thermal.shear_heating, @tensor_center(stokes.τ), @tensor_center(stokes.τ_o), @strain(stokes), phase_ratios.center, rheology, dt, ) return nothing end end
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
4015
# import JustRelax.compute_ρCp function subgrid_characteristic_time!( subgrid_arrays, particles, dt₀, phases::JustRelax.PhaseRatio, rheology, thermal::JustRelax.ThermalArrays, stokes::JustRelax.StokesArrays, xci, di, ) ni = size(stokes.P) @parallel (@idx ni) subgrid_characteristic_time!( dt₀, phases.center, rheology, thermal.Tc, stokes.P, di ) return nothing end function subgrid_characteristic_time!( subgrid_arrays, particles, dt₀, phases::AbstractArray{Int,N}, rheology, thermal::JustRelax.ThermalArrays, stokes::JustRelax.StokesArrays, xci, di, ) where {N} ni = size(stokes.P) @parallel (@idx ni) subgrid_characteristic_time!( dt₀, phases, rheology, thermal.Tc, stokes.P, di ) return nothing end @parallel_indices (I...) function subgrid_characteristic_time!( dt₀, phase_ratios, rheology, T, P, di ) Pᵢ, Tᵢ = P[I...], T[I...] argsᵢ = (; P=Pᵢ, T=Tᵢ) phaseᵢ = phase_ratios[I...] # Compute the characteristic timescale `dt₀` of the local cell ρCp = compute_ρCp(rheology, phaseᵢ, argsᵢ) K = compute_conductivity(rheology, phaseᵢ, argsᵢ) sum_dxi = mapreduce(x -> inv(x)^2, +, di) dt₀[I...] = ρCp / (2 * K * sum_dxi) return nothing end # struct SubgridDiffusionArrays{T, CA} # pT0::CA # CellArray # pΔT::CA # CellArray # ΔT::T # Array # function SubgridDiffusionArrays(particles, ni) # pΔT, pT0 = init_cell_arrays(particles, Val(2)) # ΔT = @zeros(ni.+1) # CA, T = typeof(pΔT), typeof(ΔT) # new{T, CA}(pT0, pΔT, ΔT) # end # end # @inline function init_cell_arrays(particles, ::Val{N}) where {N} # return ntuple( # _ -> @fill( # 0.0, size(particles.coords[1])..., celldims = (cellsize(particles.index)) # ), # Val(N), # ) # end # function subgrid_diffusion!( # pT, thermal, subgrid_arrays, pPhases, rheology, stokes, particles, T_buffer, xvi, di, dt # ) # (; pT0, pΔT) = subgrid_arrays # # ni = size(pT) # @copy pT0.data pT.data # grid2particle!(pT, xvi, T_buffer, particles) # @parallel (@idx ni) subgrid_diffusion!(pT, pT0, pΔT, pPhases, rheology, stokes.P, particles.index, di, dt) # particle2grid!(subgrid_arrays.ΔT, pΔT, xvi, particles) # @parallel (@idx size(subgrid_arrays.ΔT)) update_ΔT_subgrid!(subgrid_arrays.ΔT, thermal.ΔT) # grid2particle!(pΔT, xvi, subgrid_arrays.ΔT, particles) # @. pT.data = pT0.data + pΔT.data # return nothing # end # @parallel_indices (i, j) function update_ΔT_subgrid!(ΔTsubgrid::_T, ΔT::_T) where _T<:AbstractMatrix # ΔTsubgrid[i, j] = ΔT[i+1, j] - ΔTsubgrid[i, j] # return nothing # end # function subgrid_diffusion!(pT, pT0, pΔT, pPhases, rheology, stokes, particles, di, dt) # ni = size(pT) # @parallel (@idx ni) subgrid_diffusion!(pT, pT0, pΔT, pPhases, rheology, stokes.P, particles.index, di, dt) # end # @parallel_indices (I...) function subgrid_diffusion!(pT, pT0, pΔT, pPhases, rheology, P, index, di, dt) # P_cell = P[I...] # for ip in JustRelax.cellaxes(pT) # # early escape if there is no particle in this memory locations # doskip(index, ip, I...) && continue # pT0ᵢ = @cell pT0[ip, I...] # pTᵢ = @cell pT[ip, I...] # phase = Int(@cell(pPhases[ip, I...])) # argsᵢ = (; T = pTᵢ, P = P_cell) # # dimensionless numerical diffusion coefficient (0 ≤ d ≤ 1) # d = 1 # # Compute the characteristic timescale `dt₀` of the local cell # ρCp = compute_ρCp(rheology, phase, argsᵢ) # K = compute_conductivity(rheology, phase, argsᵢ) # sum_dxi = mapreduce(x-> inv(x)^2, +, di) # dt₀ = ρCp / (2 * K * sum_dxi) # # subgrid diffusion of the i-th particle # pΔTᵢ = (pTᵢ - pT0ᵢ) * (1-exp(-d * dt / dt₀)) # @cell pT0[ip, I...] = pT0ᵢ + pΔTᵢ # @cell pΔT[ip, I...] = pΔTᵢ # end # return nothing # end
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
4770
@inline cellnum(A::CellArray) = prod(cellsize(A)) @inline cellaxes(A) = map(Base.oneto, cellnum(A)) @inline new_empty_cell(::CellArray{T,N}) where {T,N} = zeros(T) import Base.setindex! Base.@propagate_inbounds @inline function Base.getindex( x::CellArray{SVector{Nv,T},N1,N2,T}, I::Vararg{Int,N} ) where {Nv,N,N1,N2,T} idx_cell = cart2ind(x.dims, I...) return SVector{Nv,T}(@inbounds x.data[idx_cell, i, 1] for i in 1:Nv) end Base.@propagate_inbounds @inline function Base.getindex( x::CPUCellArray{SVector{Nv,T},N1,N2,T}, I::Vararg{Int,N} ) where {Nv,N,N1,N2,T} idx_cell = cart2ind(x.dims, I...) return SVector{Nv,T}(@inbounds x.data[1, i, idx_cell] for i in 1:Nv) end Base.@propagate_inbounds @inline function setindex!( A::CellArray, x, cell::Int, I::Vararg{Int,N} ) where {N} Base.@propagate_inbounds @inline f(A::Array, x, cell, idx) = A[1, cell, idx] = x Base.@propagate_inbounds @inline f(A, x, cell, idx) = A[idx, cell, 1] = x idx = LinearIndices(n)[CartesianIndex(I...)] return f(A.data, x, cell, idx) end """ element(A, element_indices..., cell_indices...) Return a the element with `element_indices` of the Cell with `cell_indices` of the CellArray `A`. ## Arguments - `element_indices::Int|NTuple{N,Int}`: the `element_indices` that designate the field in accordance with `A`'s cell type. - `cell_indices::Int|NTuple{N,Int}`: the `cell_indices` that designate the cell in accordance with `A`'s cell type. """ Base.@propagate_inbounds @inline function element( A::CellArray{SVector,N,D,T_elem}, i::Int, icell::Vararg{Int,Nc} ) where {T_elem,N,Nc,D} return viewelement(A, i, icell...) end Base.@propagate_inbounds @inline function element( A::CellArray, i::T, j::T, icell::Vararg{Int,Nc} ) where {Nc,T<:Int} return viewelement(A, i, j, icell...) end Base.@propagate_inbounds @inline function viewelement( A::CellArray{SMatrix{Ni,Nj,T,N_array},N,D,T_elem}, i, j, icell::Vararg{Int,Nc} ) where {Nc,Ni,Nj,N_array,T,N,T_elem,D} idx_element = cart2ind((Ni, Nj), i, j) idx_cell = cart2ind(A.dims, icell...) return _viewelement(A.data, idx_element, idx_cell) end Base.@propagate_inbounds @inline function viewelement( A::CellArray{SVector{Ni,T},N,D,T_elem}, i, icell::Vararg{Int,Nc} ) where {Nc,Ni,N,T,T_elem,D} idx_cell = cart2ind(A.dims, icell...) return _viewelement(A.data, i, idx_cell) end Base.@propagate_inbounds @inline _viewelement(A::Array, idx, icell) = A[1, idx, icell] Base.@propagate_inbounds @inline _viewelement(A, idx, icell) = A[icell, idx, 1] """ setelement!(A, x, element_indices..., cell_indices...) Store the given value `x` at the given element with `element_indices` of the cell with the indices `cell_indices` ## Arguments - `x::Number`: value to be stored in the index `element_indices` of the cell with `cell_indices`. - `element_indices::Int|NTuple{N,Int}`: the `element_indices` that designate the field in accordance with `A`'s cell type. - `cell_indices::Int|NTuple{N,Int}`: the `cell_indices` that designate the cell in accordance with `A`'s cell type. """ Base.@propagate_inbounds @inline function setelement!( A::CellArray{SMatrix{Ni,Nj,T,N_array},N,D,T_elem}, x::T, i, j, icell::Vararg{Int,Nc} ) where {Nc,Ni,Nj,N_array,T,N,T_elem,D} idx_element = cart2ind((Ni, Nj), i, j) idx_cell = cart2ind(A.dims, icell...) return _setelement!(A.data, x, idx_element, idx_cell) end Base.@propagate_inbounds @inline function setelement!( A::CellArray{SVector{Ni,T},N,D,T_elem}, x::T, i, icell::Vararg{Int,Nc} ) where {Nc,Ni,T,N,T_elem,D} idx_cell = cart2ind(A.dims, icell...) return _setelement!(A.data, x, i, idx_cell) end Base.@propagate_inbounds @inline function _setelement!(A::Array, x, idx::Int, icell::Int) return (A[1, idx, icell] = x) end Base.@propagate_inbounds @inline function _setelement!(A, x, idx::Int, icell::Int) return (A[icell, idx, 1] = x) end ## Helper functions """ cart2ind(A) Return the linear index of a `n`-dimensional array corresponding to the cartesian indices `I` """ @inline function cart2ind(n::NTuple{N1,Int}, I::Vararg{Int,N2}) where {N1,N2} return LinearIndices(n)[CartesianIndex(I...)] end @inline cart2ind(ni::T, nj::T, i::T, j::T) where {T<:Int} = cart2ind((ni, nj), i, j) @inline function cart2ind(ni::T, nj::T, nk::T, i::T, j::T, k::T) where {T<:Int} return cart2ind((ni, nj, nk), i, j, k) end ## convenience macros macro cell(ex) ex = if ex.head === (:(=)) _set(ex) else _get(ex) end return :($(esc(ex))) end @inline _get(ex) = Expr(:call, element, ex.args...) @inline function _set(ex) return Expr( :call, setelement!, ex.args[1].args[1], ex.args[2], ex.args[1].args[2:end]... ) end
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
3695
""" nphases(x::JustRelax.PhaseRatio) Return the number of phases in `x::JustRelax.PhaseRatio`. """ @inline nphases(x::JustRelax.PhaseRatio) = nphases(x.center) @inline function nphases( ::CellArray{StaticArraysCore.SArray{Tuple{N},T,N1,N},N2,N3,T_Array} ) where {N,T,N1,N2,N3,T_Array} return Val(N) end @inline function numphases( ::CellArray{StaticArraysCore.SArray{Tuple{N},T,N1,N},N2,N3,T_Array} ) where {N,T,N1,N2,N3,T_Array} return N end """ fn_ratio(fn::F, rheology::NTuple{N, AbstractMaterialParamsStruct}, ratio) where {N, F} Average the function `fn` over the material phases in `rheology` using the phase ratios `ratio`. """ @generated function fn_ratio( fn::F, rheology::NTuple{N,AbstractMaterialParamsStruct}, ratio ) where {N,F} quote Base.@_inline_meta x = 0.0 Base.@nexprs $N i -> x += iszero(ratio[i]) ? 0.0 : fn(rheology[i]) * ratio[i] return x end end @generated function fn_ratio( fn::F, rheology::NTuple{N,AbstractMaterialParamsStruct}, ratio, args::NamedTuple ) where {N,F} quote Base.@_inline_meta x = 0.0 Base.@nexprs $N i -> x += begin r = ratio[i] isone(r) && return fn(rheology[i], args) * r iszero(r) ? 0.0 : fn(rheology[i], args) * r end return x end end function phase_ratios_center!(phase_ratios, particles, grid, phases) return phase_ratios_center!( backend(phase_ratios), phase_ratios, particles, grid, phases ) end function phase_ratios_center!( ::CPUBackendTrait, phase_ratios::JustRelax.PhaseRatio, particles, grid::Geometry, phases ) return _phase_ratios_center!(phase_ratios, particles, grid, phases) end function _phase_ratios_center!( phase_ratios::JustRelax.PhaseRatio, particles, grid::Geometry, phases ) ni = size(phases) @parallel (@idx ni) phase_ratios_center_kernel!( phase_ratios.center, particles.coords, grid.xci, grid.di, phases ) return nothing end @parallel_indices (I...) function phase_ratios_center_kernel!( ratio_centers, pxi::NTuple{N,T1}, xci::NTuple{N,T2}, di::NTuple{N,T3}, phases ) where {N,T1,T2,T3} # index corresponding to the cell center cell_center = ntuple(i -> xci[i][I[i]], Val(N)) # phase ratios weights (∑w = 1.0) w = phase_ratio_weights( getindex.(pxi, I...), phases[I...], cell_center, di, nphases(ratio_centers) ) # update phase ratios array for k in 1:numphases(ratio_centers) @cell ratio_centers[k, I...] = w[k] end return nothing end function phase_ratio_weights( pxi::NTuple{NP,C}, ph::SVector{N1,T}, cell_center, di, ::Val{NC} ) where {N1,NC,NP,T,C} # Initiaze phase ratio weights (note: can't use ntuple() here because of the @generated function) w = ntuple(_ -> zero(T), Val(NC)) sumw = zero(T) for i in eachindex(ph) # bilinear weight (1-(xᵢ-xc)/dx)*(1-(yᵢ-yc)/dy) p = getindex.(pxi, i) isnan(first(p)) && continue x = @inline bilinear_weight(cell_center, p, di) sumw += x # reduce ph_local = ph[i] # this is doing sum(w * δij(i, phase)), where δij is the Kronecker delta # w = w .+ x .* ntuple(j -> δ(Int(ph_local), j), Val(NC)) w = w .+ x .* ntuple(j -> (ph_local == j), Val(NC)) end w = w .* inv(sumw) return w end @generated function bilinear_weight( a::NTuple{N,T}, b::NTuple{N,T}, di::NTuple{N,T} ) where {N,T} quote Base.@_inline_meta val = one($T) Base.Cartesian.@nexprs $N i -> @inbounds val *= muladd(-abs(a[i] - b[i]), inv(di[i]), one($T)) return val end end
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
3746
""" compute_ρg!(ρg, rheology, args) Calculate the buoyance forces `ρg` for the given GeoParams.jl `rheology` object and correspondent arguments `args`. """ function compute_ρg!(ρg, rheology, args) ni = size(ρg) @parallel (@idx ni) compute_ρg_kernel!(ρg, rheology, args) return nothing end @parallel_indices (I...) function compute_ρg_kernel!(ρg, rheology, args) args_ijk = ntuple_idx(args, I...) ρg[I...] = compute_buoyancy(rheology, args_ijk) return nothing end """ compute_ρg!(ρg, phase_ratios, rheology, args) Calculate the buoyance forces `ρg` for the given GeoParams.jl `rheology` object and correspondent arguments `args`. The `phase_ratios` are used to compute the density of the composite rheology. """ function compute_ρg!(ρg, phase_ratios::JustRelax.PhaseRatio, rheology, args) ni = size(ρg) @parallel (@idx ni) compute_ρg_kernel!(ρg, phase_ratios.center, rheology, args) return nothing end @parallel_indices (I...) function compute_ρg_kernel!(ρg, phase_ratios, rheology, args) args_ijk = ntuple_idx(args, I...) ρg[I...] = compute_buoyancy(rheology, args_ijk, phase_ratios[I...]) return nothing end ## Inner buoyancy force kernels """ compute_buoyancy(rheology::MaterialParams, args) Compute the buoyancy forces based on the given rheology parameters and arguments. # Arguments - `rheology::MaterialParams`: The material parameters for the rheology. - `args`: The arguments for the computation. """ @inline function compute_buoyancy(rheology::MaterialParams, args) return compute_density(rheology, args) * compute_gravity(rheology) end """ compute_buoyancy(rheology::MaterialParams, args, phase_ratios) Compute the buoyancy forces for a given set of material parameters, arguments, and phase ratios. # Arguments - `rheology`: The material parameters. - `args`: The arguments. - `phase_ratios`: The phase ratios. """ @inline function compute_buoyancy(rheology::MaterialParams, args, phase_ratios) return compute_density_ratio(phase_ratios, rheology, args) * compute_gravity(rheology) end """ compute_buoyancy(rheology, args) Compute the buoyancy forces based on the given rheology and arguments. # Arguments - `rheology`: The rheology used to compute the buoyancy forces. - `args`: Additional arguments required for the computation. """ @inline function compute_buoyancy(rheology, args) return compute_density(rheology, args) * compute_gravity(rheology[1]) end """ compute_buoyancy(rheology, args, phase_ratios) Compute the buoyancy forces based on the given rheology, arguments, and phase ratios. # Arguments - `rheology`: The rheology used to compute the buoyancy forces. - `args`: Additional arguments required by the rheology. - `phase_ratios`: The ratios of the different phases. """ @inline function compute_buoyancy(rheology, args, phase_ratios) return fn_ratio(compute_density, rheology, phase_ratios, args) * compute_gravity(rheology[1]) end # without phase ratios @inline update_ρg!(ρg::AbstractArray, rheology, args) = update_ρg!(isconstant(rheology), ρg, rheology, args) @inline update_ρg!(::ConstantDensityTrait, ρg, rheology, args) = nothing @inline update_ρg!(::NonConstantDensityTrait, ρg, rheology, args) = compute_ρg!(ρg, rheology, args) # with phase ratios @inline update_ρg!(ρg::AbstractArray, phase_ratios::JustRelax.PhaseRatio, rheology, args) = update_ρg!(isconstant(rheology), ρg, phase_ratios, rheology, args) @inline update_ρg!( ::ConstantDensityTrait, ρg, phase_ratios::JustRelax.PhaseRatio, rheology, args ) = nothing @inline update_ρg!( ::NonConstantDensityTrait, ρg, phase_ratios::JustRelax.PhaseRatio, rheology, args ) = compute_ρg!(ρg, phase_ratios, rheology, args)
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
945
function get_bulk_modulus(args::Vararg{Any,N}) where {N} Kb = GeoParams.get_Kb(args...) if isnan(Kb) || iszero(Kb) return Inf end return Kb end function get_shear_modulus(args::Vararg{Any,N}) where {N} Kb = GeoParams.get_G(args...) if isnan(Kb) || iszero(Kb) return Inf end return Kb end get_thermal_expansion(args::Vararg{Any,N}) where {N} = get_α(args...) function get_α(rho::MeltDependent_Density; ϕ::T=0.0, kwargs...) where {T} αsolid = get_α(rho.ρsolid) αmelt = get_α(rho.ρmelt) return ϕ * αmelt + (1 - ϕ) * αsolid end @inline get_α(p::MaterialParams) = get_α(p.Density[1]) @inline get_α(p::MaterialParams, args::NamedTuple) = get_α(p.Density[1], args) @inline get_α(p::Union{T_Density,PT_Density}) = GeoParams.get_α(p) @inline get_α(rho::MeltDependent_Density, args) = get_α(rho; args...) @inline get_α(rho::ConstantDensity, args) = 0 @inline get_α(rho::ConstantDensity) = 0
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
995
function compute_melt_fraction!(ϕ, rheology, args) ni = size(ϕ) @parallel (@idx ni) compute_melt_fraction_kernel!(ϕ, rheology, args) end @parallel_indices (I...) function compute_melt_fraction_kernel!(ϕ, rheology, args) args_ijk = ntuple_idx(args, I...) ϕ[I...] = compute_melt_frac(rheology, args_ijk) return nothing end @inline function compute_melt_frac(rheology, args) return compute_meltfraction(rheology, args) end function compute_melt_fraction!(ϕ, phase_ratios, rheology, args) ni = size(ϕ) @parallel (@idx ni) compute_melt_fraction_kernel!(ϕ, phase_ratios, rheology, args) end @parallel_indices (I...) function compute_melt_fraction_kernel!( ϕ, phase_ratios, rheology, args ) args_ijk = ntuple_idx(args, I...) ϕ[I...] = compute_melt_frac(rheology, args_ijk, phase_ratios[I...]) return nothing end @inline function compute_melt_frac(rheology, args, phase_ratios) return compute_meltfraction_ratio(phase_ratios, rheology, args) end
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
8041
# inner kernel to compute the plastic stress update within Pseudo-Transient stress continuation function _compute_τ_nonlinear!( τ::NTuple{N1,T}, τII, τ_old::NTuple{N1,T}, ε::NTuple{N1,T}, ε_pl::NTuple{N1,T}, P, ηij, η_vep, λ, dτ_r, _Gdt, plastic_parameters, idx::Vararg{Integer,N2}, ) where {N1,N2,T} # cache tensors τij, τij_o, εij = cache_tensors(τ, τ_old, ε, idx...) # Stress increment and trial stress dτij, τII_trial = compute_stress_increment_and_trial(τij, τij_o, ηij, εij, _Gdt, dτ_r) # visco-elastic strain rates εij_ve = ntuple(Val(N1)) do i Base.@_inline_meta fma(0.5 * τij_o[i], _Gdt, εij[i]) end # get plastic parameters (if any...) (; is_pl, C, sinϕ, cosϕ, η_reg, volume) = plastic_parameters # yield stess (GeoParams could be used here...) τy = max(C * cosϕ + P[idx...] * sinϕ, 0) # check if yielding; if so, compute plastic strain rate (λdQdτ), # plastic stress increment (dτ_pl), and update the plastic # multiplier (λ) dτij, λdQdτ = if isyielding(is_pl, τII_trial, τy) # derivatives plastic stress correction dτ_pl, λ[idx...], λdQdτ = compute_dτ_pl( τij, dτij, τy, τII_trial, ηij, λ[idx...], η_reg, dτ_r, volume ) dτ_pl, λdQdτ else # in this case the plastic strain rate is a tuples of zeros dτij, ntuple(_ -> zero(eltype(T)), Val(N1)) end # fill plastic strain rate tensor update_plastic_strain_rate!(ε_pl, λdQdτ, idx) # update and correct stress correct_stress!(τ, τij .+ dτij, idx...) τII[idx...] = τII_ij = second_invariant(τij...) η_vep[idx...] = τII_ij * 0.5 * inv(second_invariant(εij_ve...)) return nothing end # fill plastic strain rate tensor @generated function update_plastic_strain_rate!(ε_pl::NTuple{N,T}, λdQdτ, idx) where {N,T} quote Base.@_inline_meta Base.@nexprs $N i -> ε_pl[i][idx...] = !isinf(λdQdτ[i]) * λdQdτ[i] end end # check if plasticity is active @inline isyielding(is_pl, τII_trial, τy) = is_pl * (τII_trial > τy) @inline compute_dτ_r(θ_dτ, ηij, _Gdt) = inv(θ_dτ + fma(ηij, _Gdt, 1.0)) function compute_stress_increment_and_trial( τij::NTuple{N,T}, τij_o::NTuple{N,T}, ηij, εij::NTuple{N,T}, _Gdt, dτ_r ) where {N,T} dτij = ntuple(Val(N)) do i Base.@_inline_meta dτ_r * fma(2.0 * ηij, εij[i], fma(-((τij[i] - τij_o[i])) * ηij, _Gdt, -τij[i])) end return dτij, second_invariant((τij .+ dτij)...) end function compute_dτ_pl( τij::NTuple{N,T}, dτij, τy, τII_trial, ηij, λ0, η_reg, dτ_r, volume ) where {N,T} # yield function F = τII_trial - τy # Plastic multiplier ν = 0.5 λ = ν * λ0 + (1 - ν) * (F > 0.0) * F * inv(ηij * dτ_r + η_reg + volume) λ_τII = λ * 0.5 * inv(τII_trial) λdQdτ = ntuple(Val(N)) do i Base.@_inline_meta # derivatives of the plastic potential (τij[i] + dτij[i]) * λ_τII end dτ_pl = ntuple(Val(N)) do i Base.@_inline_meta # corrected stress fma(-dτ_r * 2.0, ηij * λdQdτ[i], dτij[i]) end return dτ_pl, λ, λdQdτ end # update the global arrays τ::NTuple{N, AbstractArray} with the local τij::NTuple{3, Float64} at indices idx::Vararg{Integer, N} @generated function correct_stress!( τ, τij::NTuple{N1}, idx::Vararg{Integer,N2} ) where {N1,N2} quote Base.@_inline_meta Base.@nexprs $N1 i -> τ[i][idx...] = τij[i] end end @inline function correct_stress!(τxx, τyy, τxy, τij, i, j) return correct_stress!((τxx, τyy, τxy), τij, i, j) end @inline function correct_stress!(τxx, τyy, τzz, τyz, τxz, τxy, τij, i, j, k) return correct_stress!((τxx, τyy, τzz, τyz, τxz, τxy), τij, i, j, k) end @inline isplastic(x::AbstractPlasticity) = true @inline isplastic(x) = false @inline plastic_params(v) = plastic_params(v.CompositeRheology[1].elements) @inline plastic_params(v, EII) = plastic_params(v.CompositeRheology[1].elements, EII) @generated function plastic_params(v::NTuple{N,Any}, EII) where {N} quote Base.@_inline_meta Base.@nexprs $N i -> begin vᵢ = v[i] if isplastic(vᵢ) C = soften_cohesion(vᵢ, EII) sinϕ, cosϕ = soften_friction_angle(vᵢ, EII) return (true, C, sinϕ, cosϕ, vᵢ.sinΨ.val, vᵢ.η_vp.val) end end (false, 0.0, 0.0, 0.0, 0.0, 0.0) end end function plastic_params_phase( rheology::NTuple{N,AbstractMaterialParamsStruct}, EII, ratio, kwargs ) where {N} return plastic_params_phase(rheology, EII, ratio; kwargs...) end function plastic_params_phase( rheology::NTuple{N,AbstractMaterialParamsStruct}, EII, ratio; perturbation_C=nothing, kwargs..., ) where {N} @inline perturbation(::Nothing) = 1.0 @inline perturbation(x::Real) = x data = _plastic_params_phase(rheology, EII, ratio) # average over phases is_pl = false C = sinϕ = cosϕ = sinψ = η_reg = 0.0 for n in 1:N ratio_n = ratio[n] data[n][1] && (is_pl = true) C += data[n][2] * ratio_n * perturbation(perturbation_C) sinϕ += data[n][3] * ratio_n cosϕ += data[n][4] * ratio_n sinψ += data[n][5] * ratio_n η_reg += data[n][6] * ratio_n end return is_pl, C, sinϕ, cosϕ, sinψ, η_reg end @generated function _plastic_params_phase( rheology::NTuple{N,AbstractMaterialParamsStruct}, EII, ratio ) where {N} quote Base.@_inline_meta empty_args = false, 0.0, 0.0, 0.0, 0.0, 0.0 Base.@nexprs $N i -> a_i = ratio[i] == 0 ? empty_args : plastic_params(rheology[i], EII) Base.@ncall $N tuple a end end # cache tensors function cache_tensors( τ::NTuple{3,Any}, τ_old::NTuple{3,Any}, ε::NTuple{3,Any}, idx::Vararg{Integer,2} ) @inline av_shear(A) = 0.25 * sum(_gather(A, idx...)) εij = ε[1][idx...], ε[2][idx...], av_shear(ε[3]) τij = getindex.(τ, idx...) τij_o = getindex.(τ_old, idx...) return τij, τij_o, εij end function cache_tensors( τ::NTuple{6,Any}, τ_old::NTuple{6,Any}, ε::NTuple{6,Any}, idx::Vararg{Integer,3} ) @inline av_yz(A) = _av_yz(A, idx...) @inline av_xz(A) = _av_xz(A, idx...) @inline av_xy(A) = _av_xy(A, idx...) # normal components of the strain rate and old-stress tensors ε_normal = ntuple(i -> ε[i][idx...], Val(3)) # shear components of the strain rate and old-stress tensors ε_shear = av_yz(ε[4]), av_xz(ε[5]), av_xy(ε[6]) # cache ij-th components of the tensors into a tuple in Voigt notation εij = (ε_normal..., ε_shear...) τij_o = getindex.(τ_old, idx...) τij = getindex.(τ, idx...) return τij, τij_o, εij end ## softening kernels @inline function soften_cohesion( v::DruckerPrager{T,U,U1,S1,NoSoftening}, ::T ) where {T,U,U1,S1} return v.C.val end @inline function soften_cohesion( v::DruckerPrager_regularised{T,U,U1,U2,S1,NoSoftening}, ::T ) where {T,U,U1,U2,S1} return v.C.val end @inline function soften_cohesion( v::DruckerPrager{T,U,U1,S1,S2}, EII::T ) where {T,U,U1,S1,S2} return v.softening_C(EII, v.C.val) end @inline function soften_cohesion( v::DruckerPrager_regularised{T,U,U1,U2,S1,S2}, EII::T ) where {T,U,U1,U2,S1,S2} return v.softening_C(EII, v.C.val) end @inline function soften_friction_angle( v::DruckerPrager{T,U,U1,NoSoftening,S2}, ::T ) where {T,U,U1,S2} return (v.sinϕ.val, v.cosϕ.val) end @inline function soften_friction_angle( v::DruckerPrager_regularised{T,U,U1,U2,NoSoftening,S2}, ::T ) where {T,U,U1,U2,S2} return (v.sinϕ.val, v.cosϕ.val) end @inline function soften_friction_angle( v::DruckerPrager{T,U,U1,S1,S2}, EII::T ) where {T,U,U1,S1,S2} ϕ = v.softening_ϕ(EII, v.ϕ.val) return sincosd(ϕ) end @inline function soften_friction_angle( v::DruckerPrager_regularised{T,U,U1,U2,S1,S2}, EII::T ) where {T,U,U1,U2,S1,S2} ϕ = v.softening_ϕ(EII, v.ϕ.val) return sincosd(ϕ) end
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
9228
# # Traits # without phase ratios @inline function update_viscosity!( stokes::JustRelax.StokesArrays, args, rheology, cutoff; relaxation=1e0 ) update_viscosity!( islinear(rheology), stokes, args, rheology, cutoff; relaxation=relaxation ) return nothing end @inline function update_viscosity!( ::LinearRheologyTrait, stokes::JustRelax.StokesArrays, args, rheology, cutoff; relaxation=1e0, ) return nothing end @inline function update_viscosity!( ::NonLinearRheologyTrait, stokes::JustRelax.StokesArrays, args, rheology, cutoff; relaxation=1e0, ) compute_viscosity!(stokes, args, rheology, cutoff; relaxation=relaxation) return nothing end # with phase ratios @inline function update_viscosity!( stokes::JustRelax.StokesArrays, phase_ratios, args, rheology, cutoff; relaxation=1e0 ) update_viscosity!( islinear(rheology), stokes, phase_ratios, args, rheology, cutoff; relaxation=relaxation, ) return nothing end @inline function update_viscosity!( ::LinearRheologyTrait, stokes::JustRelax.StokesArrays, phase_ratios, args, rheology, cutoff; relaxation=1e0, ) return nothing end @inline function update_viscosity!( ::NonLinearRheologyTrait, stokes::JustRelax.StokesArrays, phase_ratios, args, rheology, cutoff; relaxation=1e0, ) compute_viscosity!(stokes, phase_ratios, args, rheology, cutoff; relaxation=relaxation) return nothing end ## 2D KERNELS function compute_viscosity!( stokes::JustRelax.StokesArrays, args, rheology, cutoff; relaxation=1e0 ) return compute_viscosity!(backend(stokes), stokes, relaxation, args, rheology, cutoff) end function compute_viscosity!(::CPUBackendTrait, stokes, ν, args, rheology, cutoff) return _compute_viscosity!(stokes, ν, args, rheology, cutoff) end function _compute_viscosity!(stokes::JustRelax.StokesArrays, ν, args, rheology, cutoff) ni = size(stokes.viscosity.η) @parallel (@idx ni) compute_viscosity_kernel!( stokes.viscosity.η, ν, @strain(stokes)..., args, rheology, cutoff ) return nothing end @parallel_indices (I...) function compute_viscosity_kernel!( η, ν, εxx, εyy, εxyv, args, rheology, cutoff ) # convenience closure @inline gather(A) = _gather(A, I...) @inbounds begin # cache ε = εxx[I...], εyy[I...] # we need strain rate not to be zero, otherwise we get NaNs εII_0 = allzero(ε...) * eps() # argument fields at local index args_ij = local_viscosity_args(args, I...) # compute second invariant of strain rate tensor εij = εII_0 + ε[1], -εII_0 + ε[1], gather(εxyv) εII = second_invariant(εij...) # compute and update stress viscosity ηi = compute_viscosity_εII(rheology, εII, args_ij) ηi = continuation_log(ηi, η[I...], ν) η[I...] = clamp(ηi, cutoff...) end return nothing end function compute_viscosity!(η::AbstractArray, ν, εII::AbstractArray, args, rheology, cutoff) ni = size(stokes.viscosity.η) @parallel (@idx ni) compute_viscosity_kernel!(η, ν, εII, args, rheology, cutoff) return nothing end @parallel_indices (I...) function compute_viscosity_kernel!( η, ν, εII, args, rheology, cutoff ) @inbounds begin # argument fields at local index args_ij = local_viscosity_args(args, I...) # compute second invariant of strain rate tensor εII_ij = εII[I...] # compute and update stress viscosity ηi = compute_viscosity_εII(rheology, εII_ij, args_ij) ηi = continuation_log(ηi, η[I...], ν) η[I...] = clamp(ηi, cutoff...) end return nothing end function compute_viscosity!( stokes::JustRelax.StokesArrays, phase_ratios, args, rheology, cutoff; relaxation=1e0 ) return compute_viscosity!( backend(stokes), stokes, relaxation, phase_ratios, args, rheology, cutoff ) end function compute_viscosity!( ::CPUBackendTrait, stokes::JustRelax.StokesArrays, ν, phase_ratios, args, rheology, cutoff, ) return _compute_viscosity!(stokes, ν, phase_ratios, args, rheology, cutoff) end function _compute_viscosity!( stokes::JustRelax.StokesArrays, ν, phase_ratios::JustRelax.PhaseRatio, args, rheology, cutoff, ) ni = size(stokes.viscosity.η) @parallel (@idx ni) compute_viscosity_kernel!( stokes.viscosity.η, ν, phase_ratios.center, @strain(stokes)..., args, rheology, cutoff, ) return nothing end @parallel_indices (I...) function compute_viscosity_kernel!( η, ν, ratios_center, εxx, εyy, εxyv, args, rheology, cutoff ) # convenience closure @inline gather(A) = _gather(A, I...) @inbounds begin # cache ε = εxx[I...], εyy[I...] # we need strain rate not to be zero, otherwise we get NaNs εII_0 = allzero(ε...) * eps() # argument fields at local index args_ij = local_viscosity_args(args, I...) # local phase ratio ratio_ij = ratios_center[I...] # compute second invariant of strain rate tensor εij = εII_0 + ε[1], -εII_0 + ε[1], gather(εxyv) εII = second_invariant(εij...) # compute and update stress viscosity ηi = compute_phase_viscosity_εII(rheology, ratio_ij, εII, args_ij) ηi = continuation_log(ηi, η[I...], ν) η[I...] = clamp(ηi, cutoff...) end return nothing end ## 3D KERNELS @parallel_indices (I...) function compute_viscosity_kernel!( η, ν, εxx, εyy, εzz, εyzv, εxzv, εxyv, args, rheology, cutoff ) # convenience closures @inline gather_yz(A) = _gather_yz(A, I...) @inline gather_xz(A) = _gather_xz(A, I...) @inline gather_xy(A) = _gather_xy(A, I...) @inbounds begin εij_normal = εxx[I...], εyy[I...], εzz[I...] # we need strain rate not to be zero, otherwise we get NaNs εII_0 = allzero(εij_normal...) * eps() # # argument fields at local index args_ijk = local_viscosity_args(args, I...) # compute second invariant of strain rate tensor εij_normal = εij_normal .+ (εII_0, -εII_0 * 0.5, -εII_0 * 0.5) εij_shear = gather_yz(εyzv), gather_xz(εxzv), gather_xy(εxyv) εij = (εij_normal..., εij_shear...) εII = second_invariant(εij...) # update stress and effective viscosity ηi = compute_viscosity_εII(rheology, εII, args_ijk) ηi = continuation_log(ηi, η[I...], ν) η[I...] = clamp(ηi, cutoff...) end return nothing end @parallel_indices (I...) function compute_viscosity_kernel!( η, ν, ratios_center, εxx, εyy, εzz, εyzv, εxzv, εxyv, args, rheology, cutoff ) # convenience closures @inline gather_yz(A) = _gather_yz(A, I...) @inline gather_xz(A) = _gather_xz(A, I...) @inline gather_xy(A) = _gather_xy(A, I...) @inbounds begin εij_normal = εxx[I...], εyy[I...], εzz[I...] # we need strain rate not to be zero, otherwise we get NaNs εII_0 = allzero(εij_normal...) * eps() # # argument fields at local index args_ijk = local_viscosity_args(args, I...) # local phase ratio ratio_ijk = ratios_center[I...] # compute second invariant of strain rate tensor εij_normal = εij_normal .+ (εII_0, -εII_0 * 0.5, -εII_0 * 0.5) εij_shear = gather_yz(εyzv), gather_xz(εxzv), gather_xy(εxyv) εij = (εij_normal..., εij_shear...) εII = second_invariant(εij...) # update stress and effective viscosity ηi = compute_phase_viscosity_εII(rheology, ratio_ijk, εII, args_ijk) ηi = continuation_log(ηi, η[I...], ν) η[I...] = clamp(ηi, cutoff...) end return nothing end ## HELPER FUNCTIONS @inline function local_viscosity_args(args, I::Vararg{Integer,N}) where {N} v = getindex.(values(args), I...) local_args = (; zip(keys(args), v)..., dt=args.dt, τII_old=0.0) return local_args end @inline function local_args(args, I::Vararg{Integer,N}) where {N} v = getindex.(values(args), I...) local_args = (; zip(keys(args), v)...) return local_args end @generated function compute_phase_viscosity_εII( rheology::NTuple{N,AbstractMaterialParamsStruct}, ratio, εII, args ) where {N} quote Base.@_inline_meta η = 0.0 Base.@nexprs $N i -> ( η += if iszero(ratio[i]) 0.0 else inv(compute_viscosity_εII(rheology[i].CompositeRheology[1], εII, args)) * ratio[i] end ) inv(η) end end # @generated function compute_phase_viscosity_εII( # rheology::NTuple{N,AbstractMaterialParamsStruct}, ratio, εII, args # ) where {N} # quote # Base.@_inline_meta # η = 0.0 # Base.@nexprs $N i -> ( # η += if iszero(ratio[i]) # 0.0 # else # compute_viscosity_εII(rheology[i].CompositeRheology[1], εII, args) * ratio[i] # end # ) # η # end # end
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
3984
# Continuity equation ## Incompressible @parallel_indices (I...) function compute_P!(P, RP, ∇V, η, r, θ_dτ) RP[I...], P[I...] = _compute_P!(P[I...], ∇V[I...], η[I...], r, θ_dτ) return nothing end ## Compressible @parallel_indices (I...) function compute_P!(P, P0, RP, ∇V, η, K, dt, r, θ_dτ) RP[I...], P[I...] = _compute_P!( P[I...], P0[I...], ∇V[I...], η[I...], K[I...], dt, r, θ_dτ ) return nothing end # With GeoParams @parallel_indices (I...) function compute_P!( P, P0, RP, ∇V, η, rheology::NTuple{N,MaterialParams}, phase, dt, r, θ_dτ, args ) where {N} K = get_bulk_modulus(rheology, phase[I...]) RP[I...], P[I...] = _compute_P!(P[I...], P0[I...], ∇V[I...], η[I...], K, dt, r, θ_dτ) return nothing end """ compute_P!(P, P0, RP, ∇V, ΔTc, η, rheology::NTuple{N,MaterialParams}, phase_ratio::C, dt, r, θ_dτ) Compute the pressure field `P` and the residual `RP` for the compressible case. This function introduces thermal stresses after the implementation of Kiss et al. (2023). The temperature difference `ΔTc` on the cell center is used to compute this as well as α as the thermal expansivity. """ function compute_P!( P, P0, RP, ∇V, η, rheology::NTuple{N,MaterialParams}, phase_ratio, dt, r, θ_dτ, kwargs::NamedTuple, ) where {N} return compute_P!(P, P0, RP, ∇V, η, rheology, phase_ratio, dt, r, θ_dτ; kwargs...) end function compute_P!( P, P0, RP, ∇V, η, rheology::NTuple{N,MaterialParams}, phase_ratio, dt, r, θ_dτ; ΔTc=nothing, ϕ=nothing, kwargs..., ) where {N} ni = size(P) @parallel (@idx ni) compute_P_kernel!( P, P0, RP, ∇V, η, rheology, phase_ratio, dt, r, θ_dτ, ΔTc, ϕ ) return nothing end @parallel_indices (I...) function compute_P_kernel!( P, P0, RP, ∇V, η, rheology::NTuple{N,MaterialParams}, phase_ratio::C, dt, r, θ_dτ, ::Nothing, ::Nothing, ) where {N,C<:JustRelax.CellArray} K = fn_ratio(get_bulk_modulus, rheology, phase_ratio[I...]) RP[I...], P[I...] = _compute_P!(P[I...], P0[I...], ∇V[I...], η[I...], K, dt, r, θ_dτ) return nothing end @parallel_indices (I...) function compute_P_kernel!( P, P0, RP, ∇V, η, rheology::NTuple{N,MaterialParams}, phase_ratio::C, dt, r, θ_dτ, ΔTc, ::Nothing, ) where {N,C<:JustRelax.CellArray} K = fn_ratio(get_bulk_modulus, rheology, phase_ratio[I...]) α = fn_ratio(get_thermal_expansion, rheology, phase_ratio[I...]) RP[I...], P[I...] = _compute_P!( P[I...], P0[I...], ∇V[I...], ΔTc[I...], α, η[I...], K, dt, r, θ_dτ ) return nothing end @parallel_indices (I...) function compute_P_kernel!( P, P0, RP, ∇V, η, rheology::NTuple{N,MaterialParams}, phase_ratio::C, dt, r, θ_dτ, ΔTc, ϕ, ) where {N,C<:JustRelax.CellArray} K = fn_ratio(get_bulk_modulus, rheology, phase_ratio[I...]) α = fn_ratio(get_thermal_expansion, rheology, phase_ratio[I...], (; ϕ=ϕ[I...])) RP[I...], P[I...] = _compute_P!( P[I...], P0[I...], ∇V[I...], ΔTc[I...], α, η[I...], K, dt, r, θ_dτ ) return nothing end # Pressure innermost kernels function _compute_P!(P, ∇V, η, r, θ_dτ) RP = -∇V P += RP * r / θ_dτ * η return RP, P end function _compute_P!(P, P0, ∇V, η, K, dt, r, θ_dτ) _Kdt = inv(K * dt) RP = fma(-(P - P0), _Kdt, -∇V) ψ = inv(inv(r / θ_dτ * η) + _Kdt) P = ((fma(P0, _Kdt, -∇V)) * ψ + P) / (1 + _Kdt * ψ) # P += RP / (1.0 / (r / θ_dτ * η) + 1.0 * _Kdt) return RP, P end function _compute_P!(P, P0, ∇V, ΔTc, α, η, K, dt, r, θ_dτ) _Kdt = inv(K * dt) _dt = inv(dt) RP = fma(-(P - P0), _Kdt, (-∇V + (α * (ΔTc * _dt)))) ψ = inv(inv(r / θ_dτ * η) + _Kdt) P = ((fma(P0, _Kdt, (-∇V + (α * (ΔTc * _dt))))) * ψ + P) / (1 + _Kdt * ψ) # P += RP / (1.0 / (r / θ_dτ * η) + 1.0 * _Kdt) return RP, P end
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
20227
## 2D STOKES MODULE function update_τ_o!(stokes::JustRelax.StokesArrays) @parallel (@idx size(τxy)) multi_copy!( @tensor_center(stokes.τ_o), @tensor_center(stokes.τ) ) return nothing end ## 2D VISCO-ELASTIC STOKES SOLVER # backend trait function solve!(stokes::JustRelax.StokesArrays, args...; kwargs) return solve!(backend(stokes), stokes, args...; kwargs) end # entry point for extensions solve!(::CPUBackendTrait, stokes, args...; kwargs) = _solve!(stokes, args...; kwargs...) function _solve!( stokes::JustRelax.StokesArrays, pt_stokes, di::NTuple{2,T}, flow_bcs::AbstractFlowBoundaryConditions, ρg, K, dt, igg::IGG; iterMax=10e3, nout=500, b_width=(4, 4, 1), verbose=true, kwargs..., ) where {T} # unpack _dx, _dy = inv.(di) (; ϵ, r, θ_dτ, ηdτ) = pt_stokes (; η) = stokes.viscosity ni = size(stokes.P) # ~preconditioner ητ = deepcopy(η) # @hide_communication b_width begin # communication/computation overlap compute_maxloc!(ητ, η; window=(1, 1)) update_halo!(ητ) # end # errors err = 2 * ϵ iter = 0 err_evo1 = Float64[] err_evo2 = Float64[] norm_Rx = Float64[] norm_Ry = Float64[] norm_∇V = Float64[] # convert displacement to velocity displacement2velocity!(stokes, dt, flow_bcs) # solver loop wtime0 = 0.0 while iter < 2 || (err > ϵ && iter ≤ iterMax) wtime0 += @elapsed begin @parallel (@idx ni) compute_∇V!(stokes.∇V, @velocity(stokes)..., _di...) @parallel (@idx ni .+ 1) compute_strain_rate!( @strain(stokes)..., stokes.∇V, @velocity(stokes)..., _di... ) @parallel compute_P!( stokes.P, stokes.P0, stokes.RP, stokes.∇V, η, K, dt, r, θ_dτ ) @parallel (@idx ni .+ 1) compute_τ!( @stress(stokes)..., @strain(stokes)..., η, θ_dτ ) @hide_communication b_width begin @parallel compute_V!( @velocity(stokes)..., stokes.P, @stress(stokes)..., pt_stokes.ηdτ, ρg..., ητ, _di..., dt, ) # apply boundary conditions velocity2displacement!(stokes, dt) flow_bcs!(stokes, flow_bcs) update_halo!(@velocity(stokes)...) end end iter += 1 if iter % nout == 0 && iter > 1 @parallel (@idx ni) compute_Res!( stokes.R.Rx, stokes.R.Ry, @velocity(stokes)..., stokes.P, @stress(stokes)..., ρg..., _di..., dt, ) Vmin, Vmax = extrema(stokes.V.Vx) Pmin, Pmax = extrema(stokes.P) push!( norm_Rx, norm_mpi(stokes.R.Rx) / (Pmax - Pmin) * lx / sqrt(length(stokes.R.Rx)), ) push!( norm_Ry, norm_mpi(stokes.R.Ry) / (Pmax - Pmin) * lx / sqrt(length(stokes.R.Ry)), ) push!( norm_∇V, norm_mpi(stokes.∇V) / (Vmax - Vmin) * lx / sqrt(length(stokes.∇V)) ) err = maximum_mpi(norm_Rx[end], norm_Ry[end], norm_∇V[end]) push!(err_evo1, err) push!(err_evo2, iter) if igg.me == 0 && ((verbose && err > ϵ) || iter == iterMax) @printf( "Total steps = %d, err = %1.3e [norm_Rx=%1.3e, norm_Ry=%1.3e, norm_∇V=%1.3e] \n", iter, err, norm_Rx[end], norm_Ry[end], norm_∇V[end] ) end isnan(err) && error("NaN(s)") end if igg.me == 0 && err ≤ ϵ println("Pseudo-transient iterations converged in $iter iterations") end end @parallel (@idx ni .+ 1) multi_copy!(@tensor(stokes.τ_o), @tensor(stokes.τ)) @parallel (@idx ni) multi_copy!(@tensor_center(stokes.τ_o), @tensor_center(stokes.τ)) return ( iter=iter, err_evo1=err_evo1, err_evo2=err_evo2, norm_Rx=norm_Rx, norm_Ry=norm_Ry, norm_∇V=norm_∇V, ) end # visco-elastic solver function _solve!( stokes::JustRelax.StokesArrays, pt_stokes, di::NTuple{2,T}, flow_bcs::AbstractFlowBoundaryConditions, ρg, G, K, dt, igg::IGG; iterMax=10e3, nout=500, b_width=(4, 4, 1), verbose=true, kwargs..., ) where {T} # unpack _di = inv.(di) (; ϵ, r, θ_dτ) = pt_stokes (; η) = stokes.viscosity ni = size(stokes.P) # ~preconditioner ητ = deepcopy(η) # @hide_communication b_width begin # communication/computation overlap compute_maxloc!(ητ, η; window=(1, 1)) update_halo!(ητ) # end # errors err = 2 * ϵ iter = 0 err_evo1 = Float64[] err_evo2 = Float64[] norm_Rx = Float64[] norm_Ry = Float64[] norm_∇V = Float64[] # convert displacement to velocity displacement2velocity!(stokes, dt, flow_bcs) # solver loop wtime0 = 0.0 while iter < 2 || (err > ϵ && iter ≤ iterMax) wtime0 += @elapsed begin @parallel (@idx ni) compute_∇V!(stokes.∇V, stokes.V.Vx, stokes.V.Vy, _di...) @parallel (@idx ni .+ 1) compute_strain_rate!( @strain(stokes)..., stokes.∇V, @velocity(stokes)..., _di... ) @parallel compute_P!( stokes.P, stokes.P0, stokes.R.RP, stokes.∇V, η, K, dt, r, θ_dτ ) @parallel (@idx ni) compute_τ!( @stress(stokes)..., @tensor(stokes.τ_o)..., @strain(stokes)..., η, G, θ_dτ, dt, ) @hide_communication b_width begin # communication/computation overlap @parallel compute_V!( @velocity(stokes)..., stokes.P, @stress(stokes)..., pt_stokes.ηdτ, ρg..., ητ, _di..., ) # free slip boundary conditions velocity2displacement!(stokes, dt) flow_bcs!(stokes, flow_bcs) update_halo!(@velocity(stokes)...) end end iter += 1 if iter % nout == 0 && iter > 1 @parallel (@idx ni) compute_Res!( stokes.R.Rx, stokes.R.Ry, stokes.P, @stress(stokes)..., ρg..., _di... ) errs = maximum_mpi.((abs.(stokes.R.Rx), abs.(stokes.R.Ry), abs.(stokes.R.RP))) push!(norm_Rx, errs[1]) push!(norm_Ry, errs[2]) push!(norm_∇V, errs[3]) err = maximum_mpi(errs) push!(err_evo1, err) push!(err_evo2, iter) if igg.me == 0 && ((verbose && err > ϵ) || iter == iterMax) @printf( "Total steps = %d, err = %1.3e [norm_Rx=%1.3e, norm_Ry=%1.3e, norm_∇V=%1.3e] \n", iter, err, norm_Rx[end], norm_Ry[end], norm_∇V[end] ) end end if igg.me == 0 && err ≤ ϵ println("Pseudo-transient iterations converged in $iter iterations") end end @parallel (@idx ni .+ 1) multi_copy!(@tensor(stokes.τ_o), @tensor(stokes.τ)) @parallel (@idx ni) multi_copy!(@tensor_center(stokes.τ_o), @tensor_center(stokes.τ)) return ( iter=iter, err_evo1=err_evo1, err_evo2=err_evo2, norm_Rx=norm_Rx, norm_Ry=norm_Ry, norm_∇V=norm_∇V, ) end # GeoParams: general (visco-elasto-plastic) solver function _solve!( stokes::JustRelax.StokesArrays, pt_stokes, di::NTuple{2,T}, flow_bcs::AbstractFlowBoundaryConditions, ρg, rheology::MaterialParams, args, dt, igg::IGG; viscosity_cutoff=(-Inf, Inf), viscosity_relaxation=1e-2, iterMax=10e3, nout=500, b_width=(4, 4, 0), verbose=true, free_surface=false, kwargs..., ) where {T} # unpack _di = inv.(di) (; ϵ, r, θ_dτ) = pt_stokes (; η, η_vep) = stokes.viscosity ni = size(stokes.P) # ~preconditioner ητ = deepcopy(η) # @hide_communication b_width begin # communication/computation overlap compute_maxloc!(ητ, η; window=(1, 1)) update_halo!(ητ) # end Kb = get_Kb(rheology) # errors err = 2 * ϵ iter = 0 err_evo1 = Float64[] err_evo2 = Float64[] norm_Rx = Float64[] norm_Ry = Float64[] norm_∇V = Float64[] for Aij in @tensor_center(stokes.ε_pl) Aij .= 0.0 end # solver loop wtime0 = 0.0 λ = @zeros(ni...) θ = @zeros(ni...) Vx_on_Vy = @zeros(size(stokes.V.Vy)) # compute buoyancy forces and viscosity compute_ρg!(ρg[end], rheology, args) compute_viscosity!(stokes, args, rheology, viscosity_cutoff) # convert displacement to velocity displacement2velocity!(stokes, dt, flow_bcs) while iter < 2 || (err > ϵ && iter ≤ iterMax) wtime0 += @elapsed begin @parallel (@idx ni) compute_∇V!(stokes.∇V, @velocity(stokes)..., _di...) @parallel compute_P!( stokes.P, stokes.P0, stokes.R.RP, stokes.∇V, η, Kb, dt, r, θ_dτ ) update_ρg!(ρg[2], rheology, args) @parallel (@idx ni .+ 1) compute_strain_rate!( @strain(stokes)..., stokes.∇V, @velocity(stokes)..., _di... ) update_viscosity!( stokes, args, rheology, viscosity_cutoff; relaxation=viscosity_relaxation ) compute_maxloc!(ητ, η; window=(1, 1)) update_halo!(ητ) @parallel (@idx ni) compute_τ_nonlinear!( @tensor_center(stokes.τ), stokes.τ.II, @tensor(stokes.τ_o), @strain(stokes), @tensor_center(stokes.ε_pl), stokes.EII_pl, stokes.P, θ, η, η_vep, λ, tupleize(rheology), # needs to be a tuple dt, θ_dτ, args, ) center2vertex!(stokes.τ.xy, stokes.τ.xy_c) update_halo!(stokes.τ.xy) @parallel (1:(size(stokes.V.Vy, 1) - 2), 1:size(stokes.V.Vy, 2)) interp_Vx_on_Vy!( Vx_on_Vy, stokes.V.Vx ) @hide_communication b_width begin # communication/computation overlap @parallel compute_V!( @velocity(stokes)..., Vx_on_Vy, θ, @stress(stokes)..., pt_stokes.ηdτ, ρg..., ητ, _di..., dt * free_surface, ) # apply boundary conditions velocity2displacement!(stokes, dt) flow_bcs!(stokes, flow_bcs) update_halo!(@velocity(stokes)...) end end iter += 1 if iter % nout == 0 && iter > 1 @parallel (@idx ni) compute_Res!( stokes.R.Rx, stokes.R.Ry, @velocity(stokes)..., Vx_on_Vy, stokes.P, @stress(stokes)..., ρg..., _di..., dt * free_surface, ) errs = maximum.((abs.(stokes.R.Rx), abs.(stokes.R.Ry), abs.(stokes.R.RP))) push!(norm_Rx, errs[1]) push!(norm_Ry, errs[2]) push!(norm_∇V, errs[3]) err = maximum(errs) push!(err_evo1, err) push!(err_evo2, iter) if igg.me == 0 && ((verbose && err > ϵ) || iter == iterMax) @printf( "Total steps = %d, err = %1.3e [norm_Rx=%1.3e, norm_Ry=%1.3e, norm_∇V=%1.3e] \n", iter, err, norm_Rx[end], norm_Ry[end], norm_∇V[end] ) end isnan(err) && error("NaN(s)") end if igg.me == 0 && err ≤ ϵ println("Pseudo-transient iterations converged in $iter iterations") end end stokes.P .= θ # θ = P + plastic_overpressure @parallel (@idx ni .+ 1) multi_copy!(@tensor(stokes.τ_o), @tensor(stokes.τ)) @parallel (@idx ni) multi_copy!(@tensor_center(stokes.τ_o), @tensor_center(stokes.τ)) # accumulate plastic strain tensor @parallel (@idx ni) accumulate_tensor!(stokes.EII_pl, @tensor_center(stokes.ε_pl), dt) return ( iter=iter, err_evo1=err_evo1, err_evo2=err_evo2, norm_Rx=norm_Rx, norm_Ry=norm_Ry, norm_∇V=norm_∇V, ) end ## With phase ratios function _solve!( stokes::JustRelax.StokesArrays, pt_stokes, di::NTuple{2,T}, flow_bcs::AbstractFlowBoundaryConditions, ρg, phase_ratios::JustRelax.PhaseRatio, rheology, args, dt, igg::IGG; viscosity_cutoff=(-Inf, Inf), viscosity_relaxation=1e-2, iterMax=50e3, iterMin=1e2, free_surface=false, nout=500, b_width=(4, 4, 0), verbose=true, kwargs..., ) where {T} # unpack _di = inv.(di) (; ϵ, r, θ_dτ, ηdτ) = pt_stokes (; η, η_vep) = stokes.viscosity ni = size(stokes.P) # ~preconditioner ητ = deepcopy(η) # @hide_communication b_width begin # communication/computation overlap compute_maxloc!(ητ, η; window=(1, 1)) update_halo!(ητ) # end # errors err = 2 * ϵ iter = 0 err_evo1 = Float64[] err_evo2 = Float64[] norm_Rx = Float64[] norm_Ry = Float64[] norm_∇V = Float64[] sizehint!(norm_Rx, Int(iterMax)) sizehint!(norm_Ry, Int(iterMax)) sizehint!(norm_∇V, Int(iterMax)) sizehint!(err_evo1, Int(iterMax)) sizehint!(err_evo2, Int(iterMax)) # solver loop @copy stokes.P0 stokes.P wtime0 = 0.0 θ = @zeros(ni...) λ = @zeros(ni...) η0 = deepcopy(η) do_visc = true for Aij in @tensor_center(stokes.ε_pl) Aij .= 0.0 end Vx_on_Vy = @zeros(size(stokes.V.Vy)) # compute buoyancy forces and viscosity compute_ρg!(ρg[end], phase_ratios, rheology, args) compute_viscosity!(stokes, phase_ratios, args, rheology, viscosity_cutoff) displacement2velocity!(stokes, dt, flow_bcs) while iter ≤ iterMax iterMin < iter && err < ϵ && break wtime0 += @elapsed begin compute_maxloc!(ητ, η; window=(1, 1)) update_halo!(ητ) @parallel (@idx ni) compute_∇V!(stokes.∇V, @velocity(stokes)..., _di...) compute_P!( stokes.P, stokes.P0, stokes.R.RP, stokes.∇V, ητ, rheology, phase_ratios.center, dt, r, θ_dτ, args, ) # stokes.P[1, 1] = stokes.P[2, 1] # stokes.P[end, 1] = stokes.P[end - 1, 1] # stokes.P[1, end] = stokes.P[2, end] # stokes.P[end, end] = stokes.P[end - 1, end] update_ρg!(ρg[2], phase_ratios, rheology, args) @parallel (@idx ni .+ 1) compute_strain_rate!( @strain(stokes)..., stokes.∇V, @velocity(stokes)..., _di... ) if rem(iter, nout) == 0 @copy η0 η end if do_visc update_viscosity!( stokes, phase_ratios, args, rheology, viscosity_cutoff; relaxation=viscosity_relaxation, ) end @parallel (@idx ni) compute_τ_nonlinear!( @tensor_center(stokes.τ), stokes.τ.II, @tensor_center(stokes.τ_o), @strain(stokes), @tensor_center(stokes.ε_pl), stokes.EII_pl, stokes.P, θ, η, η_vep, λ, phase_ratios.center, tupleize(rheology), # needs to be a tuple dt, θ_dτ, args, ) center2vertex!(stokes.τ.xy, stokes.τ.xy_c) # update_halo!(stokes.τ.xy) # @parallel (1:(size(stokes.V.Vy, 1) - 2), 1:size(stokes.V.Vy, 2)) interp_Vx_on_Vy!( # Vx_on_Vy, stokes.V.Vx # ) @parallel (1:(size(stokes.V.Vy, 1) - 2), 1:size(stokes.V.Vy, 2)) interp_Vx∂ρ∂x_on_Vy!( Vx_on_Vy, stokes.V.Vx, ρg[2], _di[1] ) @hide_communication b_width begin # communication/computation overlap @parallel compute_V!( @velocity(stokes)..., Vx_on_Vy, θ, @stress(stokes)..., pt_stokes.ηdτ, ρg..., ητ, _di..., dt * free_surface, ) # apply boundary conditions velocity2displacement!(stokes, dt) free_surface_bcs!(stokes, flow_bcs, η, rheology, phase_ratios, dt, di) flow_bcs!(stokes, flow_bcs) # update_halo!(@velocity(stokes)...) end end iter += 1 if iter % nout == 0 && iter > 1 er_η = norm_mpi(@.(log10(η) - log10(η0))) er_η < 1e-3 && (do_visc = false) @parallel (@idx ni) compute_Res!( stokes.R.Rx, stokes.R.Ry, @velocity(stokes)..., Vx_on_Vy, stokes.P, @stress(stokes)..., ρg..., _di..., dt * free_surface, ) # errs = maximum_mpi.((abs.(stokes.R.Rx), abs.(stokes.R.Ry), abs.(stokes.R.RP))) errs = ( norm_mpi(@views stokes.R.Rx[2:(end - 1), 2:(end - 1)]) / length(stokes.R.Rx), norm_mpi(@views stokes.R.Ry[2:(end - 1), 2:(end - 1)]) / length(stokes.R.Ry), norm_mpi(stokes.R.RP) / length(stokes.R.RP), ) push!(norm_Rx, errs[1]) push!(norm_Ry, errs[2]) push!(norm_∇V, errs[3]) err = maximum_mpi(errs) push!(err_evo1, err) push!(err_evo2, iter) if igg.me == 0 #&& ((verbose && err > ϵ) || iter == iterMax) @printf( "Total steps = %d, err = %1.3e [norm_Rx=%1.3e, norm_Ry=%1.3e, norm_∇V=%1.3e] \n", iter, err, norm_Rx[end], norm_Ry[end], norm_∇V[end] ) end isnan(err) && error("NaN(s)") end if igg.me == 0 && err ≤ ϵ && iter ≥ 20000 println("Pseudo-transient iterations converged in $iter iterations") end end stokes.P .= θ # θ = P + plastic_overpressure @parallel (@idx ni .+ 1) multi_copy!(@tensor(stokes.τ_o), @tensor(stokes.τ)) @parallel (@idx ni) multi_copy!(@tensor_center(stokes.τ_o), @tensor_center(stokes.τ)) # accumulate plastic strain tensor @parallel (@idx ni) accumulate_tensor!(stokes.EII_pl, @tensor_center(stokes.ε_pl), dt) return ( iter=iter, err_evo1=err_evo1, err_evo2=err_evo2, norm_Rx=norm_Rx, norm_Ry=norm_Ry, norm_∇V=norm_∇V, ) end
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
16494
@parallel function update_τ_o!( τxx_o, τyy_o, τzz_o, τxy_o, τxz_o, τyz_o, τxx, τyy, τzz, τxy, τxz, τyz ) @all(τxx_o) = @all(τxx) @all(τyy_o) = @all(τyy) @all(τzz_o) = @all(τzz) @all(τxy_o) = @all(τxy) @all(τxz_o) = @all(τxz) @all(τyz_o) = @all(τyz) return nothing end function update_τ_o!(stokes::JustRelax.StokesArrays) @parallel update_τ_o!(@tensor(stokes.τ_o)..., @stress(stokes)...) end ## 3D VISCO-ELASTIC STOKES SOLVER function solve!(stokes::JustRelax.StokesArrays, args...; kwargs) return solve!(backend(stokes), stokes, args...; kwargs) end # entry point for extensions solve!(::CPUBackendTrait, stokes, args...; kwargs) = _solve!(stokes, args...; kwargs...) function _solve!( stokes::JustRelax.StokesArrays, pt_stokes, di::NTuple{3,T}, flow_bcs::AbstractFlowBoundaryConditions, ρg, K, G, dt, igg::IGG; viscosity_relaxation=1e-2, iterMax=10e3, nout=500, b_width=(4, 4, 4), verbose=true, kwargs..., ) where {T} # solver related ϵ = pt_stokes.ϵ # geometry _di = @. 1 / di ni = size(stokes.P) (; η) = stokes.viscosity # ~preconditioner ητ = deepcopy(η) compute_maxloc!(ητ, η) update_halo!(ητ) # errors err = 2 * ϵ iter = 0 cont = 0 err_evo1 = Float64[] err_evo2 = Int64[] norm_Rx = Float64[] norm_Ry = Float64[] norm_Rz = Float64[] norm_∇V = Float64[] # convert displacement to velocity displacement2velocity!(stokes, dt, flow_bcs) # solver loop wtime0 = 0.0 while iter < 2 || (err > ϵ && iter ≤ iterMax) wtime0 += @elapsed begin @parallel (@idx ni) compute_∇V!(stokes.∇V, @velocity(stokes)..., _di...) @parallel compute_P!( stokes.P, stokes.P0, stokes.R.RP, stokes.∇V, η, K, dt, pt_stokes.r, pt_stokes.θ_dτ, ) @parallel (@idx ni .+ 1) compute_strain_rate!( stokes.∇V, @strain(stokes)..., @velocity(stokes)..., _di... ) @parallel (@idx ni .+ 1) compute_τ!( @stress(stokes)..., @tensor(stokes.τ_o)..., @strain(stokes)..., η, G, dt, pt_stokes.θ_dτ, ) @hide_communication b_width begin # communication/computation overlap @parallel compute_V!( @velocity(stokes)..., stokes.R.Rx, stokes.R.Ry, stokes.R.Rz, stokes.P, ρg..., @stress(stokes)..., ητ, pt_stokes.ηdτ, _di..., ) # apply boundary conditions velocity2displacement!(stokes, dt) flow_bcs!(stokes, flow_bcs) update_halo!(@velocity(stokes)...) end end iter += 1 if iter % nout == 0 && iter > 1 cont += 1 push!(norm_Rx, maximum_mpi(abs.(stokes.R.Rx))) push!(norm_Ry, maximum_mpi(abs.(stokes.R.Ry))) push!(norm_Rz, maximum_mpi(abs.(stokes.R.Rz))) push!(norm_∇V, maximum_mpi(abs.(stokes.R.RP))) err = max(norm_Rx[cont], norm_Ry[cont], norm_Rz[cont], norm_∇V[cont]) push!(err_evo1, err) push!(err_evo2, iter) if igg.me == 0 && ((verbose && err > ϵ) || iter == iterMax) @printf( "iter = %d, err = %1.3e [norm_Rx=%1.3e, norm_Ry=%1.3e, norm_Rz=%1.3e, norm_∇V=%1.3e] \n", iter, err, norm_Rx[cont], norm_Ry[cont], norm_Rz[cont], norm_∇V[cont] ) end isnan(err) && error("NaN(s)") end if igg.me == 0 && err ≤ ϵ println("Pseudo-transient iterations converged in $iter iterations") end end av_time = wtime0 / (iter - 1) # average time per iteration update_τ_o!(stokes) # copy τ into τ_o return ( iter=iter, err_evo1=err_evo1, err_evo2=err_evo2, norm_Rx=norm_Rx, norm_Ry=norm_Ry, norm_Rz=norm_Rz, norm_∇V=norm_∇V, time=wtime0, av_time=av_time, ) end ## 3D VISCO-ELASTO-PLASTIC STOKES SOLVER WITH GeoParams.jl function _solve!( stokes::JustRelax.StokesArrays, pt_stokes, di::NTuple{3,T}, flow_bcs::AbstractFlowBoundaryConditions, ρg, rheology::MaterialParams, args, dt, igg::IGG; iterMax=10e3, nout=500, b_width=(4, 4, 4), viscosity_relaxation=1e-2, viscosity_cutoff=(-Inf, Inf), verbose=true, kwargs..., ) where {T} # solver related ϵ = pt_stokes.ϵ # geometry _di = @. 1 / di ni = size(stokes.P) (; η, η_vep) = stokes.viscosity # ~preconditioner ητ = deepcopy(η) # errors err = 2 * ϵ iter = 0 cont = 0 err_evo1 = Float64[] err_evo2 = Int64[] norm_Rx = Float64[] norm_Ry = Float64[] norm_Rz = Float64[] norm_∇V = Float64[] Kb = get_Kb(rheology) G = get_shear_modulus(rheology) @copy stokes.P0 stokes.P λ = @zeros(ni...) θ = @zeros(ni...) # compute buoyancy forces and viscosity compute_ρg!(ρg[end], phase_ratios, rheology, args) compute_viscosity!(stokes, phase_ratios, args, rheology, viscosity_cutoff) # convert displacement to velocity displacement2velocity!(stokes, dt, flow_bcs) # solver loop wtime0 = 0.0 while iter < 2 || (err > ϵ && iter ≤ iterMax) wtime0 += @elapsed begin compute_maxloc!(ητ, η) update_halo!(ητ) @parallel (@idx ni) compute_∇V!(stokes.∇V, @velocity(stokes)..., _di...) @parallel (@idx ni) compute_P!( stokes.P, stokes.P0, stokes.R.RP, stokes.∇V, ητ, Kb, dt, pt_stokes.r, pt_stokes.θ_dτ, ) @parallel (@idx ni) compute_strain_rate!( stokes.∇V, @strain(stokes)..., @velocity(stokes)..., _di... ) # Update buoyancy update_ρg!(ρg[3], rheology, args) update_viscosity!( stokes, phase_ratios, args, rheology, viscosity_cutoff; relaxation=viscosity_relaxation, ) @parallel (@idx ni) compute_τ_nonlinear!( @tensor_center(stokes.τ), stokes.τ.II, @tensor(stokes.τ_o), @strain(stokes), @tensor_center(stokes.ε_pl), stokes.EII_pl, stokes.P, θ, η, @ones(ni...), λ, tupleize(rheology), # needs to be a tuple dt, pt_stokes.θ_dτ, args, ) @parallel (@idx ni .+ 1) compute_τ_vertex!( @shear(stokes.τ)..., @shear(stokes.τ_o)..., @shear(stokes.ε)..., η_vep, G, dt, pt_stokes.θ_dτ, ) @hide_communication b_width begin # communication/computation overlap @parallel compute_V!( @velocity(stokes)..., stokes.R.Rx, stokes.R.Ry, stokes.R.Rz, stokes.P, ρg..., @stress(stokes)..., ητ, pt_stokes.ηdτ, _di..., ) # apply boundary conditions velocity2displacement!(stokes, dt) flow_bcs!(stokes, flow_bcs) update_halo!(@velocity(stokes)...) end end iter += 1 if iter % nout == 0 && iter > 1 cont += 1 # push!(norm_Rx, maximum_mpi(abs.(stokes.R.Rx))) # push!(norm_Ry, maximum_mpi(abs.(stokes.R.Ry))) # push!(norm_Rz, maximum_mpi(abs.(stokes.R.Rz))) # push!(norm_∇V, maximum_mpi(abs.(stokes.R.RP))) push!( norm_Rx, norm_mpi(stokes.R.Rx[2:(end - 1), 2:(end - 1), 2:(end - 1)]) / length(stokes.R.Rx), ) push!( norm_Ry, norm_mpi(stokes.R.Ry[2:(end - 1), 2:(end - 1), 2:(end - 1)]) / length(stokes.R.Ry), ) push!( norm_Rz, norm_mpi(stokes.R.Rz[2:(end - 1), 2:(end - 1), 2:(end - 1)]) / length(stokes.R.Rz), ) push!(norm_∇V, norm_mpi(stokes.R.RP) / length(stokes.R.RP)) err = max(norm_Rx[cont], norm_Ry[cont], norm_Rz[cont], norm_∇V[cont]) push!(err_evo1, err) push!(err_evo2, iter) if igg.me == 0 && (verbose || iter == iterMax) @printf( "iter = %d, err = %1.3e [norm_Rx=%1.3e, norm_Ry=%1.3e, norm_Rz=%1.3e, norm_∇V=%1.3e] \n", iter, err, norm_Rx[cont], norm_Ry[cont], norm_Rz[cont], norm_∇V[cont] ) end isnan(err) && error("NaN(s)") end if igg.me == 0 && err ≤ ϵ println("Pseudo-transient iterations converged in $iter iterations") end end av_time = wtime0 / (iter - 1) # average time per iteration @parallel (@idx ni .+ 1) multi_copy!(@tensor(stokes.τ_o), @tensor(stokes.τ)) @parallel (@idx ni) multi_copy!(@tensor_center(stokes.τ_o), @tensor_center(stokes.τ)) # accumulate plastic strain tensor @parallel (@idx ni) accumulate_tensor!(stokes.EII_pl, @tensor_center(stokes.ε_pl), dt) return ( iter=iter, err_evo1=err_evo1, err_evo2=err_evo2, norm_Rx=norm_Rx, norm_Ry=norm_Ry, norm_Rz=norm_Rz, norm_∇V=norm_∇V, time=wtime0, av_time=av_time, ) end # GeoParams and multiple phases function _solve!( stokes::JustRelax.StokesArrays, pt_stokes, di::NTuple{3,T}, flow_bcs::AbstractFlowBoundaryConditions, ρg, phase_ratios::JustRelax.PhaseRatio, rheology::NTuple{N,AbstractMaterialParamsStruct}, args, dt, igg::IGG; iterMax=10e3, nout=500, b_width=(4, 4, 4), verbose=true, viscosity_relaxation=1e-2, viscosity_cutoff=(-Inf, Inf), kwargs..., ) where {T,N} ## UNPACK # solver related ϵ = pt_stokes.ϵ # geometry _di = @. 1 / di ni = size(stokes.P) (; η, η_vep) = stokes.viscosity # errors err = Inf iter = 0 cont = 0 err_evo1 = Float64[] err_evo2 = Int64[] norm_Rx = Float64[] norm_Ry = Float64[] norm_Rz = Float64[] norm_∇V = Float64[] @copy stokes.P0 stokes.P λ = @zeros(ni...) θ = @zeros(ni...) # solver loop wtime0 = 0.0 ητ = deepcopy(η) # compute buoyancy forces and viscosity compute_ρg!(ρg[end], phase_ratios, rheology, args) compute_viscosity!(stokes, phase_ratios, args, rheology, viscosity_cutoff) # convert displacement to velocity displacement2velocity!(stokes, dt, flow_bcs) while iter < 2 || (err > ϵ && iter ≤ iterMax) wtime0 += @elapsed begin # ~preconditioner compute_maxloc!(ητ, η) update_halo!(ητ) @parallel (@idx ni) compute_∇V!(stokes.∇V, @velocity(stokes)..., _di...) compute_P!( stokes.P, stokes.P0, stokes.R.RP, stokes.∇V, ητ, rheology, phase_ratios.center, dt, pt_stokes.r, pt_stokes.θ_dτ, args, ) @parallel (@idx ni) compute_strain_rate!( stokes.∇V, @strain(stokes)..., @velocity(stokes)..., _di... ) # Update buoyancy update_ρg!(ρg[end], phase_ratios, rheology, args) # Update viscosity update_viscosity!( stokes, phase_ratios, args, rheology, viscosity_cutoff; relaxation=viscosity_relaxation, ) # update_stress!(stokes, θ, λ, phase_ratios, rheology, dt, pt_stokes.θ_dτ) @parallel (@idx ni) compute_τ_nonlinear!( @tensor_center(stokes.τ), stokes.τ.II, @tensor_center(stokes.τ_o), @strain(stokes), @tensor_center(stokes.ε_pl), stokes.EII_pl, stokes.P, θ, η, η_vep, λ, phase_ratios.center, tupleize(rheology), # needs to be a tuple dt, pt_stokes.θ_dτ, args, ) center2vertex!( stokes.τ.yz, stokes.τ.xz, stokes.τ.xy, stokes.τ.yz_c, stokes.τ.xz_c, stokes.τ.xy_c, ) update_halo!(stokes.τ.yz, stokes.τ.xz, stokes.τ.xy) # @parallel (@idx ni .+ 1) compute_τ_vertex!( # @shear(stokes.τ)..., @shear(stokes.ε)..., η_vep, pt_stokes.θ_dτ # ) @hide_communication b_width begin # communication/computation overlap @parallel compute_V!( @velocity(stokes)..., @residuals(stokes.R)..., θ, ρg..., @stress(stokes)..., ητ, pt_stokes.ηdτ, _di..., ) # apply boundary conditions velocity2displacement!(stokes, dt) free_surface_bcs!(stokes, flow_bcs, η, rheology, phase_ratios, dt, di) flow_bcs!(stokes, flow_bcs) update_halo!(@velocity(stokes)...) end end stokes.P .= θ iter += 1 if iter % nout == 0 && iter > 1 cont += 1 for (norm_Ri, Ri) in zip((norm_Rx, norm_Ry, norm_Rz), @residuals(stokes.R)) push!( norm_Ri, norm_mpi(Ri[2:(end - 1), 2:(end - 1), 2:(end - 1)]) / length(Ri), ) end push!(norm_∇V, norm_mpi(stokes.R.RP) / length(stokes.R.RP)) err = max(norm_Rx[cont], norm_Ry[cont], norm_Rz[cont], norm_∇V[cont]) push!(err_evo1, err) push!(err_evo2, iter) if igg.me == 0 && (verbose || iter == iterMax) @printf( "iter = %d, err = %1.3e [norm_Rx=%1.3e, norm_Ry=%1.3e, norm_Rz=%1.3e, norm_∇V=%1.3e] \n", iter, err, norm_Rx[cont], norm_Ry[cont], norm_Rz[cont], norm_∇V[cont] ) end isnan(err) && error("NaN(s)") end if igg.me == 0 && err ≤ ϵ println("Pseudo-transient iterations converged in $iter iterations") end end av_time = wtime0 / (iter - 1) # average time per iteration stokes.P .= θ @parallel (@idx ni .+ 1) multi_copy!(@tensor(stokes.τ_o), @tensor(stokes.τ)) @parallel (@idx ni) multi_copy!(@tensor_center(stokes.τ_o), @tensor_center(stokes.τ)) # accumulate plastic strain tensor @parallel (@idx ni) accumulate_tensor!(stokes.EII_pl, @tensor_center(stokes.ε_pl), dt) return ( iter=iter, err_evo1=err_evo1, err_evo2=err_evo2, norm_Rx=norm_Rx, norm_Ry=norm_Ry, norm_Rz=norm_Rz, norm_∇V=norm_∇V, time=wtime0, av_time=av_time, ) end
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
13551
# Viscous @parallel_indices (i, j) function compute_τ!( τxx::AbstractArray{T,2}, τyy, τxy, εxx, εyy, εxy, η, θ_dτ ) where {T} @inline av(A) = _av_a(A, i, j) @inline harm(A) = _harm_a(A, i, j) denominator = inv(θ_dτ + 1.0) η_ij = η[i, j] # Normal components τxx[i, j] += (-τxx[i, j] + 2.0 * η_ij * εxx[i, j]) * denominator τyy[i, j] += (-τyy[i, j] + 2.0 * η_ij * εyy[i, j]) * denominator # Shear components if all((i, j) .< size(τxy) .- 1) τxy[i + 1, j + 1] += (-τxy[i + 1, j + 1] + 2.0 * av(η) * εxy[i + 1, j + 1]) * denominator end return nothing end # Visco-elastic @parallel_indices (i, j) function compute_τ!( τxx::AbstractArray{T,2}, τyy, τxy, τxx_o, τyy_o, τxy_o, εxx, εyy, εxy, η, G, θ_dτ, dt ) where {T} @inline av(A) = _av_a(A, i, j) @inline harm(A) = _harm_a(A, i, j) # Normal components _Gdt = inv(G[i, j] * dt) η_ij = η[i, j] denominator = inv(θ_dτ + η_ij * _Gdt + 1.0) τxx[i, j] += (-(τxx[i, j] - τxx_o[i, j]) * η_ij * _Gdt - τxx[i, j] + 2.0 * η_ij * εxx[i, j]) * denominator τyy[i, j] += (-(τyy[i, j] - τyy_o[i, j]) * η_ij * _Gdt - τyy[i, j] + 2.0 * η_ij * εyy[i, j]) * denominator # Shear components if all((i, j) .< size(τxy) .- 1) av_η_ij = av(η) _av_Gdt = inv(av(G) * dt) denominator = inv(θ_dτ + av_η_ij * _av_Gdt + 1.0) τxy[i + 1, j + 1] += ( -(τxy[i + 1, j + 1] - τxy_o[i + 1, j + 1]) * av_η_ij * _av_Gdt + 2.0 * av_η_ij * εxy[i + 1, j + 1] ) * denominator end return nothing end @parallel_indices (i, j) function compute_τ!( τxx::AbstractArray{T,2}, # centers τyy, # centers τxy, # centers τxx_o, # centers τyy_o, # centers τxy_o, # centers εxx, # centers εyy, # centers εxy, # vertices η, # centers θ_dτ, dt, phase_center, rheology, ) where {T} @inline av(A) = _av_a(A, i, j) # Normal components phase = phase_center[i, j] _Gdt = inv(fn_ratio(get_shear_modulus, rheology, phase) * dt) η_ij = η[i, j] multiplier = inv(θ_dτ + η_ij * _Gdt + 1.0) τxx[i, j] += (-(τxx[i, j] - τxx_o[i, j]) * η_ij * _Gdt - τxx[i, j] + 2.0 * η_ij * εxx[i, j]) * multiplier τyy[i, j] += (-(τyy[i, j] - τyy_o[i, j]) * η_ij * _Gdt - τyy[i, j] + 2.0 * η_ij * εyy[i, j]) * multiplier τxy[i, j] += (-(τxy[i, j] - τxy_o[i, j]) * η_ij * _Gdt - τxy[i, j] + 2.0 * η_ij * av(εxy)) * multiplier return nothing end @parallel_indices (i, j) function compute_τ_vertex!( τxy::AbstractArray{T,2}, εxy, η, θ_dτ ) where {T} @inline av(A) = _av_a(A, i, j) @inline harm(A) = _harm_a(A, i, j) # Shear components if all((i, j) .< size(τxy) .- 1) I = i + 1, j + 1 av_η_ij = harm(η) denominator = inv(θ_dτ + 1.0) τxy[I...] += (-τxy[I...] + 2.0 * av_η_ij * εxy[I...]) * denominator end return nothing end @parallel_indices (i, j, k) function compute_τ!( τxx::AbstractArray{T,3}, τyy, τzz, τyz, τxz, τxy, τxx_o, τyy_o, τzz_o, τyz_o, τxz_o, τxy_o, εxx, εyy, εzz, εyz, εxz, εxy, η, G, dt, θ_dτ, ) where {T} harm_xy(A) = _harm_xyi(A, i, j, k) harm_xz(A) = _harm_xzi(A, i, j, k) harm_yz(A) = _harm_yzi(A, i, j, k) av_xy(A) = _av_xyi(A, i, j, k) av_xz(A) = _av_xzi(A, i, j, k) av_yz(A) = _av_yzi(A, i, j, k) get(x) = x[i, j, k] @inbounds begin if all((i, j, k) .≤ size(τxx)) _Gdt = inv(get(G) * dt) η_ij = get(η) denominator = inv(θ_dτ + η_ij * _Gdt + 1.0) # Compute τ_xx τxx[i, j, k] += ( -(get(τxx) - get(τxx_o)) * η_ij * _Gdt - get(τxx) + 2.0 * η_ij * get(εxx) ) * denominator # Compute τ_yy τyy[i, j, k] += ( -(get(τyy) - get(τyy_o)) * η_ij * _Gdt - get(τyy) + 2.0 * η_ij * get(εyy) ) * denominator # Compute τ_zz τzz[i, j, k] += ( -(get(τzz) - get(τzz_o)) * η_ij * _Gdt - get(τzz) + 2.0 * η_ij * get(εzz) ) * denominator end # Compute τ_xy if (1 < i < size(τxy, 1)) && (1 < j < size(τxy, 2)) && k ≤ size(τxy, 3) _Gdt = inv(harm_xy(G) * dt) η_ij = harm_xy(η) denominator = inv(θ_dτ + η_ij * _Gdt + 1.0) τxy[i, j, k] += ( -(get(τxy) - get(τxy_o)) * η_ij * _Gdt - get(τxy) + 2.0 * η_ij * get(εxy) ) * denominator end # Compute τ_xz if (1 < i < size(τxz, 1)) && j ≤ size(τxz, 2) && (1 < k < size(τxz, 3)) _Gdt = inv(harm_xz(G) * dt) η_ij = harm_xz(η) denominator = inv(θ_dτ + η_ij * _Gdt + 1.0) τxz[i, j, k] += ( -(get(τxz) - get(τxz_o)) * η_ij * _Gdt - get(τxz) + 2.0 * η_ij * get(εxz) ) * denominator end # Compute τ_yz if i ≤ size(τyz, 1) && (1 < j < size(τyz, 2)) && (1 < k < size(τyz, 3)) _Gdt = inv(harm_yz(G) * dt) η_ij = harm_yz(η) denominator = inv(θ_dτ + η_ij * _Gdt + 1.0) τyz[i, j, k] += ( -(get(τyz) - get(τyz_o)) * η_ij * _Gdt - get(τyz) + 2.0 * η_ij * get(εyz) ) * denominator end end return nothing end @parallel_indices (i, j, k) function compute_τ_vertex!( τyz, τxz, τxy, εyz, εxz, εxy, ηvep, θ_dτ ) harm_xy(A) = _harm_xyi(A, i, j, k) harm_xz(A) = _harm_xzi(A, i, j, k) harm_yz(A) = _harm_yzi(A, i, j, k) av_xy(A) = _av_xyi(A, i, j, k) av_xz(A) = _av_xzi(A, i, j, k) av_yz(A) = _av_yzi(A, i, j, k) get(x) = x[i, j, k] @inbounds begin # Compute τ_xy if (1 < i < size(τxy, 1)) && (1 < j < size(τxy, 2)) && k ≤ size(τxy, 3) η_ij = harm_xy(ηvep) denominator = inv(θ_dτ + 1.0) τxy[i, j, k] += (-get(τxy) + 2.0 * η_ij * get(εxy)) * denominator end # Compute τ_xz if (1 < i < size(τxz, 1)) && j ≤ size(τxz, 2) && (1 < k < size(τxz, 3)) η_ij = harm_xz(ηvep) denominator = inv(θ_dτ + 1.0) τxz[i, j, k] += (-get(τxz) + 2.0 * η_ij * get(εxz)) * denominator end # Compute τ_yz if i ≤ size(τyz, 1) && (1 < j < size(τyz, 2)) && (1 < k < size(τyz, 3)) η_ij = harm_yz(ηvep) denominator = inv(θ_dτ + 1.0) τyz[i, j, k] += (-get(τyz) + 2.0 * η_ij * get(εyz)) * denominator end end return nothing end # Single phase visco-elasto-plastic flow @parallel_indices (I...) function compute_τ_nonlinear!( τ, # @ centers τII, # @ centers τ_old, # @ centers ε, # @ vertices ε_pl, # @ centers EII, # accumulated plastic strain rate @ centers P, θ, η, η_vep, λ, rheology, dt, θ_dτ, args, ) # numerics ηij = η[I...] _Gdt = inv(get_shear_modulus(rheology[1]) * dt) dτ_r = compute_dτ_r(θ_dτ, ηij, _Gdt) # get plastic parameters (if any...) is_pl, C, sinϕ, cosϕ, sinψ, η_reg = plastic_params_phase( rheology, EII[I...], 1, ntuple_idx(args, I...) ) # plastic volumetric change K * dt * sinϕ * sinψ K = get_bulk_modulus(rheology[1]) volume = isinf(K) ? 0.0 : K * dt * sinϕ * sinψ plastic_parameters = (; is_pl, C, sinϕ, cosϕ, η_reg, volume) _compute_τ_nonlinear!( τ, τII, τ_old, ε, ε_pl, P, ηij, η_vep, λ, dτ_r, _Gdt, plastic_parameters, I... ) # augmented pressure with plastic volumetric strain over pressure θ[I...] = P[I...] + (isinf(K) ? 0.0 : K * dt * λ[I...] * sinψ) return nothing end # multi phase visco-elasto-plastic flow, where phases are defined in the cell center @parallel_indices (I...) function compute_τ_nonlinear!( τ, # @ centers τII, # @ centers τ_old, # @ centers ε, # @ vertices ε_pl, # @ centers EII, # accumulated plastic strain rate @ centers P, θ, η, η_vep, λ, phase_center, rheology, dt, θ_dτ, args, ) # numerics ηij = @inbounds η[I...] phase = @inbounds phase_center[I...] _Gdt = inv(fn_ratio(get_shear_modulus, rheology, phase) * dt) dτ_r = compute_dτ_r(θ_dτ, ηij, _Gdt) # get plastic parameters (if any...) is_pl, C, sinϕ, cosϕ, sinψ, η_reg = plastic_params_phase(rheology, EII[I...], phase) # plastic volumetric change K * dt * sinϕ * sinψ K = fn_ratio(get_bulk_modulus, rheology, phase) volume = isinf(K) ? 0.0 : K * dt * sinϕ * sinψ plastic_parameters = (; is_pl, C, sinϕ, cosϕ, η_reg, volume) _compute_τ_nonlinear!( τ, τII, τ_old, ε, ε_pl, P, ηij, η_vep, λ, dτ_r, _Gdt, plastic_parameters, I... ) # augmented pressure with plastic volumetric strain over pressure @inbounds θ[I...] = P[I...] + (isinf(K) ? 0.0 : K * dt * λ[I...] * sinψ) return nothing end ## Accumulate tensor @parallel_indices (I...) function accumulate_tensor!( II, tensor::NTuple{N,T}, dt ) where {N,T} @inbounds II[I...] += second_invariant(getindex.(tensor, I...)...) * dt return nothing end ## Stress invariants @parallel_indices (I...) function tensor_invariant_center!( II, tensor::NTuple{N,T} ) where {N,T} @inbounds II[I...] = second_invariant_staggered(getindex.(tensor, I...)...) return nothing end """ tensor_invariant!(A::JustRelax.SymmetricTensor) Compute the tensor invariant of the given symmetric tensor `A`. # Arguments - `A::JustRelax.SymmetricTensor`: The input symmetric tensor. """ function tensor_invariant!(A::JustRelax.SymmetricTensor) tensor_invariant!(backend(A), A) return nothing end function tensor_invariant!(::CPUBackendTrait, A::JustRelax.SymmetricTensor) return _tensor_invariant!(A) end function _tensor_invariant!(A::JustRelax.SymmetricTensor) ni = size(A.II) @parallel (@idx ni) tensor_invariant_kernel!(A.II, @tensor(A)...) return nothing end @parallel_indices (I...) function tensor_invariant_kernel!(II, xx, yy, xy) # convenience closure @inline gather(A) = _gather(A, I...) @inbounds begin τ = xx[I...], yy[I...], gather(xy) II[I...] = second_invariant_staggered(τ...) end return nothing end @parallel_indices (I...) function tensor_invariant_kernel!(II, xx, yy, zz, yz, xz, xy) # convenience closures @inline gather_yz(A) = _gather_yz(A, I...) @inline gather_xz(A) = _gather_xz(A, I...) @inline gather_xy(A) = _gather_xy(A, I...) @inbounds begin τ = xx[I...], yy[I...], zz[I...], gather_yz(yz), gather_xz(xz), gather_xy(xy) II[I...] = second_invariant_staggered(τ...) end return nothing end #### function update_stress!(stokes, θ, λ, phase_ratios, rheology, dt, θ_dτ, args) return update_stress!( islinear(rheology), stokes, θ, λ, phase_ratios, rheology, dt, θ_dτ, args ) end function update_stress!( ::LinearRheologyTrait, stokes, ::Any, ::Any, phase_ratios, rheology, dt, θ_dτ, args ) dim(::AbstractArray{T,N}) where {T,N} = Val(N) function f!(stokes, ::Val{2}) center2vertex!(stokes.τ.xy, stokes.τ.xy_c) update_halo!(stokes.τ.xy) return nothing end function f!(stokes, ::Val{3}) center2vertex!( stokes.τ.yz, stokes.τ.xz, stokes.τ.xy, stokes.τ.yz_c, stokes.τ.xz_c, stokes.τ.xy_c, ) update_halo!(stokes.τ.yz, stokes.τ.xz, stokes.τ.xy) return nothing end ni = size(phase_ratios.center) nDim = dim(stokes.viscosity.η) @parallel (@idx ni) compute_τ!( @tensor_center(stokes.τ)..., @tensor_center(stokes.τ_o)..., @strain(stokes)..., stokes.viscosity.η, θ_dτ, dt, phase_ratios.center, tupleize(rheology), # needs to be a tuple ) f!(stokes, nDim) return nothing end function update_stress!( ::NonLinearRheologyTrait, stokes, θ, λ::AbstractArray{T,N}, phase_ratios, rheology, dt, θ_dτ, args, ) where {N,T} ni = size(phase_ratios.center) nDim = Val(N) function f!(stokes, ::Val{2}) center2vertex!(stokes.τ.xy, stokes.τ.xy_c) update_halo!(stokes.τ.xy) return nothing end function f!(stokes, ::Val{3}) center2vertex!( stokes.τ.yz, stokes.τ.xz, stokes.τ.xy, stokes.τ.yz_c, stokes.τ.xz_c, stokes.τ.xy_c, ) update_halo!(stokes.τ.yz, stokes.τ.xz, stokes.τ.xy) return nothing end @parallel (@idx ni) compute_τ_nonlinear!( @tensor_center(stokes.τ), stokes.τ.II, @tensor_center(stokes.τ_o), @strain(stokes), @tensor_center(stokes.ε_pl), stokes.EII_pl, stokes.P, θ, stokes.viscosity.η, stokes.viscosity.η_vep, λ, phase_ratios.center, tupleize(rheology), # needs to be a tuple dt, θ_dτ, ) f!(stokes, nDim) return nothing end
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
9071
using StaticArrays ## Stress Rotation on the particles @parallel_indices (i, j) function compute_vorticity!(vorticity, Vx, Vy, _dx, _dy) dx(A) = _d_xa(A, i, j, _dx) dy(A) = _d_ya(A, i, j, _dy) vorticity[i, j] = 0.5 * (dx(Vy) - dy(Vx)) return nothing end @parallel_indices (i, j) function rotate_stress_particles_jaumann!(xx, yy, xy, ω, index, dt) cell = i, j for ip in JustRelax.cellaxes(index) !@cell(index[ip, cell...]) && continue # no particle in this location ω_xy = @cell ω[ip, cell...] τ_xx = @cell xx[ip, cell...] τ_yy = @cell yy[ip, cell...] τ_xy = @cell xy[ip, cell...] tmp = τ_xy * ω_xy * 2.0 @cell xx[ip, cell...] = fma(dt, cte, τ_xx) @cell yy[ip, cell...] = fma(dt, cte, τ_yy) @cell xy[ip, cell...] = fma(dt, (τ_xx - τ_yy) * ω_xy, τ_xy) end return nothing end @parallel_indices (i, j) function rotate_stress_particles_rotation_matrix!( xx, yy, xy, ω, index, dt ) cell = i, j for ip in JustRelax.cellaxes(index) !@cell(index[ip, cell...]) && continue # no particle in this location θ = dt * @cell ω[ip, cell...] sinθ, cosθ = sincos(θ) τ_xx = @cell xx[ip, cell...] τ_yy = @cell yy[ip, cell...] τ_xy = @cell xy[ip, cell...] R = @SMatrix [ cosθ -sinθ sinθ cosθ ] τ = @SMatrix [ τ_xx τ_xy τ_xy τ_yy ] # this could be fully unrolled in 2D τr = R * τ * R' @cell xx[ip, cell...] = τr[1, 1] @cell yy[ip, cell...] = τr[2, 2] @cell xy[ip, cell...] = τr[1, 2] end return nothing end ## Stress Rotation on the grid @parallel_indices (I...) function rotate_stress!(V, τ::NTuple{3,T}, _di, dt) where {T} @inbounds rotate_stress!(V, τ, tuple(I...), _di, dt) return nothing end @inline function tensor2voigt(xx, yy, xy, i, j) av(A) = _av_a(A, i, j) voigt = xx[i, j], yy[i, j], av(xy) return voigt end @inline function tensor2voigt(xx, yy, zz, yz, xz, xy, i, j, k) av_yz(A) = _av_yz(A, i, j, k) av_xz(A) = _av_xz(A, i, j, k) av_xy(A) = _av_xy(A, i, j, k) voigt = xx[i, j], yy[i, j], zz[i, j], av_yz(yz), av_xz(xz), av_xy(xy) return voigt end """ Jaumann derivative τij_o += v_k * ∂τij_o/∂x_k - ω_ij * ∂τkj_o + ∂τkj_o * ω_ij """ Base.@propagate_inbounds function rotate_stress!( V, τ::NTuple{N,T}, idx, _di, dt ) where {N,T} ## 1) Advect stress Vᵢⱼ = velocity2center(V..., idx...) # averages @ cell center τij_adv = advect_stress(τ..., Vᵢⱼ..., idx..., _di...) ## 2) Rotate stress # average ∂Vx/∂y @ cell center ∂V∂x = cross_derivatives(V..., _di..., idx...) # compute xy component of the vorticity tensor; normal components = 0.0 ω = compute_vorticity(∂V∂x) # stress tensor in Voigt notation # τ_voigt = ntuple(Val(N)) do k # Base.@_inline_meta # τ[k][idx...] # end τ_voigt = tensor2voigt(τ..., idx...) # actually rotate stress tensor τr_voigt = GeoParams.rotate_elastic_stress2D(ω, τ_voigt, dt) R = @SMatrix [ 0.0 -ω ω 0.0 ] τm = @SMatrix [ τ_voigt[1] τ_voigt[3] τ_voigt[3] τ_voigt[2] ] τr = τm * R - R * τm τr_voigt = τr[1, 1], τr[2, 2], τr[1, 2] ## 3) Update stress for k in 1:N τ[k][idx...] = fma(τij_adv[k] * 0, dt, τr_voigt[k]) end return nothing end # 2D Base.@propagate_inbounds function advect_stress(τxx, τyy, τxy, Vx, Vy, i, j, _dx, _dy) τ = τxx, τyy, τxy τ_adv = ntuple(Val(3)) do k Base.@_inline_meta dx_right, dx_left, dy_up, dy_down = upwind_derivatives(τ[k], i, j) advection_term(Vx, Vy, dx_right, dx_left, dy_up, dy_down, _dx, _dy) end return τ_adv end # 3D Base.@propagate_inbounds function advect_stress( τxx, τyy, τzz, τyz, τxz, τxy, Vx, Vy, Vz, i, j, k, _dx, _dy, _dz ) τ = τxx, τyy, τzz, τyz, τxz, τxy τ_adv = ntuple(Val(6)) do l Base.@_inline_meta dx_right, dx_left, dy_back, dy_front, dz_up, dz_down = upwind_derivatives( τ[l], i, j, k ) advection_term( Vx, Vy, Vz, dx_right, dx_left, dy_back, dy_front, dz_up, dz_down, _dx, _dy, _dz, ) end return τ_adv end # 2D Base.@propagate_inbounds function upwind_derivatives(A, i, j) nx, ny = size(A) center = A[i, j] # dx derivatives x_left = i - 1 > 1 ? A[i - 1, j] : 0.0 x_right = i + 1 < nx ? A[i + 1, j] : 0.0 dx_right = x_right - center dx_left = center - x_left # dy derivatives y_down = j - 1 > 1 ? A[i, j - 1] : 0.0 y_up = j + 1 < ny ? A[i, j + 1] : 0.0 dy_up = y_up - center dy_down = center - y_down return dx_right, dx_left, dy_up, dy_down end # 3D Base.@propagate_inbounds function upwind_derivatives(A, i, j, k) nx, ny, nz = size(A) center = A[i, j, k] x_left = x_right = y_front = y_back = z_down = z_up = 0.0 # dx derivatives i - 1 > 1 && (x_left = A[i - 1, j, k]) i + 1 < nx && (x_right = A[i + 1, j, k]) dx_right = x_right - center dx_left = center - x_left # dy derivatives j - 1 > 1 && (y_front = A[i, j - 1, k]) j + 1 < ny && (y_back = A[i, j + 1, k]) dy_back = y_back - center dy_front = center - y_front # dz derivatives k - 1 > 1 && (z_down = A[i, j, k - 1]) k + 1 < nz && (z_up = A[i, j, k + 1]) dz_up = z_up - center dz_down = center - z_down return dx_right, dx_left, dy_back, dy_front, dz_up, dz_down end # 2D @inline function advection_term(Vx, Vy, dx_right, dx_left, dy_up, dy_down, _dx, _dy) return (Vx > 0 ? dx_right : dx_left) * Vx * _dx + (Vy > 0 ? dy_up : dy_down) * Vy * _dy end # 3D @inline function advection_term( Vx, Vy, Vz, dx_right, dx_left, dy_back, dy_front, dz_up, dz_down, _dx, _dy, _dz ) return (Vx > 0 ? dx_right : dx_left) * Vx * _dx + (Vy > 0 ? dy_back : dy_front) * Vy * _dy + (Vz > 0 ? dz_up : dz_down) * Vz * _dz end # averages @ cell center 2D Base.@propagate_inbounds function velocity2center(Vx, Vy, i, j) i1, j1 = @add 1 i j Vxᵢⱼ = 0.5 * (Vx[i, j1] + Vx[i1, j1]) Vyᵢⱼ = 0.5 * (Vy[i1, j] + Vy[i1, j1]) return Vxᵢⱼ, Vyᵢⱼ end # averages @ cell center 3D Base.@propagate_inbounds function velocity2center(Vx, Vy, Vz, i, j, k) i1, j1, k1 = @add 1 i j k Vxᵢⱼ = 0.5 * (Vx[i, j1, k1] + Vx[i1, j1, k1]) Vyᵢⱼ = 0.5 * (Vy[i1, j, k1] + Vy[i1, j1, k1]) Vzᵢⱼ = 0.5 * (Vz[i1, j1, k] + Vz[i1, j1, k1]) return Vxᵢⱼ, Vyᵢⱼ, Vzᵢⱼ end # 2D Base.@propagate_inbounds function cross_derivatives(Vx, Vy, _dx, _dy, i, j) i1, j1 = @add 1 i j i2, j2 = @add 2 i j # average @ cell center ∂Vx∂y = 0.25 * _dy * ( Vx[i, j1] - Vx[i, j] + Vx[i, j2] - Vx[i, j1] + Vx[i1, j1] - Vx[i1, j] + Vx[i1, j2] - Vx[i1, j1] ) ∂Vy∂x = 0.25 * _dx * ( Vy[i1, j] - Vy[i, j] + Vy[i2, j] - Vy[i1, j] + Vy[i1, j1] - Vy[i, j1] + Vy[i2, j1] - Vy[i1, j1] ) return ∂Vx∂y, ∂Vy∂x end Base.@propagate_inbounds function cross_derivatives(Vx, Vy, Vz, _dx, _dy, _dz, i, j, k) i1, j1, k2 = @add 1 i j k i2, j2, k2 = @add 2 i j k # cross derivatives @ cell centers ∂Vx∂y = 0.25 * _dy * ( Vx[i, j1, k1] - Vx[i, j, k1] + Vx[i, j2, k1] - Vx[i, j1, k1] + Vx[i1, j1, k1] - Vx[i1, j, k1] + Vx[i1, j2, k1] - Vx[i1, j1, k1] ) ∂Vx∂z = 0.25 * _dz * ( Vx[i, j1, k1] - Vx[i, j, k] + Vx[i, j2, k2] - Vx[i, j1, k1] + Vx[i1, j1, k1] - Vx[i1, j, k] + Vx[i1, j2, k2] - Vx[i1, j1, k1] ) ∂Vy∂x = 0.25 * _dx * ( Vy[i1, j, ki] - Vy[i, j, ki] + Vy[i2, j, ki] - Vy[i1, j, ki] + Vy[i1, j1, ki] - Vy[i, j1, ki] + Vy[i2, j1, ki] - Vy[i1, j1, ki] ) ∂Vy∂z = 0.25 * _dz * ( Vy[i1, j, k1] - Vy[i, j, k] + Vy[i2, j, k2] - Vy[i1, j, k1] + Vy[i1, j1, k1] - Vy[i, j1, k] + Vy[i2, j1, k2] - Vy[i1, j1, k1] ) ∂Vz∂x = 0.25 * _dx * ( Vz[i1, j, k] - Vz[i, j, k] + Vz[i2, j, k] - Vz[i1, j, k] + Vz[i1, j1, k1] - Vz[i, j1, 1k] + Vz[i2, j1, k1] - Vz[i1, j1, 1k] ) ∂Vz∂y = 0.25 * _dy * ( Vz[i1, j, k] - Vz[i, j, k] + Vz[i2, j, k] - Vz[i1, j, k] + Vz[i1, j1, k1] - Vz[i, j1, k1] + Vz[i2, j1, k1] - Vz[i1, j1, k1] ) return ∂Vx∂y, ∂Vx∂z, ∂Vy∂x, ∂Vy∂z, ∂Vz∂x, ∂Vz∂y end Base.@propagate_inbounds @inline function compute_vorticity(∂V∂x::NTuple{2,T}) where {T} return ∂V∂x[2] - ∂V∂x[1] end # 2D Base.@propagate_inbounds @inline function compute_vorticity(∂V∂x::NTuple{3,T}) where {T} return ∂V∂x[3] - ∂V∂x[2], ∂V∂x[1] - ∂V∂x[3], ∂V∂x[2] - ∂V∂x[1] end # 3D
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
10764
## DIVERGENCE @parallel_indices (i, j) function compute_∇V!( ∇V::AbstractArray{T,2}, Vx, Vy, _dx, _dy ) where {T} d_xi(A) = _d_xi(A, i, j, _dx) d_yi(A) = _d_yi(A, i, j, _dy) ∇V[i, j] = d_xi(Vx) + d_yi(Vy) return nothing end @parallel_indices (i, j, k) function compute_∇V!( ∇V::AbstractArray{T,3}, Vx, Vy, Vz, _dx, _dy, _dz ) where {T} d_xi(A) = _d_xi(A, i, j, k, _dx) d_yi(A) = _d_yi(A, i, j, k, _dy) d_zi(A) = _d_zi(A, i, j, k, _dz) @inbounds ∇V[i, j, k] = d_xi(Vx) + d_yi(Vy) + d_zi(Vz) return nothing end ## DEVIATORIC STRAIN RATE TENSOR @parallel_indices (i, j) function compute_strain_rate!( εxx::AbstractArray{T,2}, εyy, εxy, ∇V, Vx, Vy, _dx, _dy ) where {T} d_xi(A) = _d_xi(A, i, j, _dx) d_yi(A) = _d_yi(A, i, j, _dy) d_xa(A) = _d_xa(A, i, j, _dx) d_ya(A) = _d_ya(A, i, j, _dy) if all((i, j) .≤ size(εxx)) ∇V_ij = ∇V[i, j] / 3.0 εxx[i, j] = d_xi(Vx) - ∇V_ij εyy[i, j] = d_yi(Vy) - ∇V_ij end εxy[i, j] = 0.5 * (d_ya(Vx) + d_xa(Vy)) return nothing end @parallel_indices (i, j, k) function compute_strain_rate!( ∇V::AbstractArray{T,3}, εxx, εyy, εzz, εyz, εxz, εxy, Vx, Vy, Vz, _dx, _dy, _dz ) where {T} d_xi(A) = _d_xi(A, i, j, k, _dx) d_yi(A) = _d_yi(A, i, j, k, _dy) d_zi(A) = _d_zi(A, i, j, k, _dz) @inbounds begin # normal components are all located @ cell centers if all((i, j, k) .≤ size(εxx)) ∇Vijk = ∇V[i, j, k] * inv(3) # Compute ε_xx εxx[i, j, k] = d_xi(Vx) - ∇Vijk # Compute ε_yy εyy[i, j, k] = d_yi(Vy) - ∇Vijk # Compute ε_zz εzz[i, j, k] = d_zi(Vz) - ∇Vijk end # Compute ε_yz if all((i, j, k) .≤ size(εyz)) εyz[i, j, k] = 0.5 * ( _dz * (Vy[i + 1, j, k + 1] - Vy[i + 1, j, k]) + _dy * (Vz[i + 1, j + 1, k] - Vz[i + 1, j, k]) ) end # Compute ε_xz if all((i, j, k) .≤ size(εxz)) εxz[i, j, k] = 0.5 * ( _dz * (Vx[i, j + 1, k + 1] - Vx[i, j + 1, k]) + _dx * (Vz[i + 1, j + 1, k] - Vz[i, j + 1, k]) ) end # Compute ε_xy if all((i, j, k) .≤ size(εxy)) εxy[i, j, k] = 0.5 * ( _dy * (Vx[i, j + 1, k + 1] - Vx[i, j, k + 1]) + _dx * (Vy[i + 1, j, k + 1] - Vy[i, j, k + 1]) ) end end return nothing end ## VELOCITY @parallel_indices (i, j) function compute_V!( Vx::AbstractArray{T,2}, Vy, P, τxx, τyy, τxy, ηdτ, ρgx, ρgy, ητ, _dx, _dy ) where {T} d_xi(A) = _d_xi(A, i, j, _dx) d_yi(A) = _d_yi(A, i, j, _dy) d_xa(A) = _d_xa(A, i, j, _dx) d_ya(A) = _d_ya(A, i, j, _dy) av_xa(A) = _av_xa(A, i, j) av_ya(A) = _av_ya(A, i, j) harm_xa(A) = _av_xa(A, i, j) harm_ya(A) = _av_ya(A, i, j) if all((i, j) .< size(Vx) .- 1) Vx[i + 1, j + 1] += (-d_xa(P) + d_xa(τxx) + d_yi(τxy) - av_xa(ρgx)) * ηdτ / av_xa(ητ) end if all((i, j) .< size(Vy) .- 1) Vy[i + 1, j + 1] += (-d_ya(P) + d_ya(τyy) + d_xi(τxy) - av_ya(ρgy)) * ηdτ / av_ya(ητ) end return nothing end # with free surface stabilization @parallel_indices (i, j) function compute_V!( Vx::AbstractArray{T,2}, Vy, Vx_on_Vy, P, τxx, τyy, τxy, ηdτ, ρgx, ρgy, ητ, _dx, _dy, dt ) where {T} d_xi(A) = _d_xi(A, i, j, _dx) d_yi(A) = _d_yi(A, i, j, _dy) d_xa(A) = _d_xa(A, i, j, _dx) d_ya(A) = _d_ya(A, i, j, _dy) av_xa(A) = _av_xa(A, i, j) av_ya(A) = _av_ya(A, i, j) harm_xa(A) = _av_xa(A, i, j) harm_ya(A) = _av_ya(A, i, j) nx, ny = size(ρgy) if all((i, j) .< size(Vx) .- 1) Vx[i + 1, j + 1] += (-d_xa(P) + d_xa(τxx) + d_yi(τxy) - av_xa(ρgx)) * ηdτ / av_xa(ητ) end if all((i, j) .< size(Vy) .- 1) # θ = 1.0 # # Interpolate Vx into Vy node # Vxᵢⱼ = Vx_on_Vy[i + 1, j + 1] # # Vertical velocity # Vyᵢⱼ = Vy[i + 1, j + 1] # # Get necessary buoyancy forces # i_W, i_E = max(i - 1, 1), min(i + 1, nx) # j_N = min(j + 1, ny) # ρg_stencil = ( # ρgy[i_W, j], ρgy[i, j], ρgy[i_E, j], ρgy[i_W, j_N], ρgy[i, j_N], ρgy[i_E, j_N] # ) # ρg_W = (ρg_stencil[1] + ρg_stencil[2] + ρg_stencil[4] + ρg_stencil[5]) * 0.25 # ρg_E = (ρg_stencil[2] + ρg_stencil[3] + ρg_stencil[5] + ρg_stencil[6]) * 0.25 # ρg_S = ρg_stencil[2] # ρg_N = ρg_stencil[5] # # Spatial derivatives # ∂ρg∂x = (ρg_E - ρg_W) * _dx # ∂ρg∂y = (ρg_N - ρg_S) * _dy # # correction term # ρg_correction = (Vxᵢⱼ * ∂ρg∂x + Vyᵢⱼ * ∂ρg∂y) * θ * dt # Vy[i + 1, j + 1] += # (-d_ya(P) + d_ya(τyy) + d_xi(τxy) - av_ya(ρgy) - ρg_correction) * ηdτ / # av_ya(ητ) θ = 1.0 # Interpolated Vx into Vy node (includes density gradient) Vxᵢⱼ = Vx_on_Vy[i + 1, j + 1] # Vertical velocity Vyᵢⱼ = Vy[i + 1, j + 1] # Get necessary buoyancy forces # i_W, i_E = max(i - 1, 1), min(i + 1, nx) j_N = min(j + 1, ny) # ρg_stencil = ( # ρgy[i_W, j], ρgy[i, j], ρgy[i_E, j], ρgy[i_W, j_N], ρgy[i, j_N], ρgy[i_E, j_N] # ) # ρg_W = (ρg_stencil[1] + ρg_stencil[2] + ρg_stencil[4] + ρg_stencil[5]) * 0.25 # ρg_E = (ρg_stencil[2] + ρg_stencil[3] + ρg_stencil[5] + ρg_stencil[6]) * 0.25 ρg_S = ρgy[i, j] ρg_N = ρgy[i, j_N] # Spatial derivatives # ∂ρg∂x = (ρg_E - ρg_W) * _dx ∂ρg∂y = (ρg_N - ρg_S) * _dy # correction term ρg_correction = (Vxᵢⱼ + Vyᵢⱼ * ∂ρg∂y) * θ * dt Vy[i + 1, j + 1] += (-d_ya(P) + d_ya(τyy) + d_xi(τxy) - av_ya(ρgy) + ρg_correction) * ηdτ / av_ya(ητ) end return nothing end @parallel_indices (i, j, k) function compute_V!( Vx::AbstractArray{T,3}, Vy, Vz, Rx, Ry, Rz, P, fx, fy, fz, τxx, τyy, τzz, τyz, τxz, τxy, ητ, ηdτ, _dx, _dy, _dz, ) where {T} harm_x(A) = _harm_x(A, i, j, k) harm_y(A) = _harm_y(A, i, j, k) harm_z(A) = _harm_z(A, i, j, k) av_x(A) = _av_x(A, i, j, k) av_y(A) = _av_y(A, i, j, k) av_z(A) = _av_z(A, i, j, k) d_xa(A) = _d_xa(A, i, j, k, _dx) d_ya(A) = _d_ya(A, i, j, k, _dy) d_za(A) = _d_za(A, i, j, k, _dz) @inbounds begin if all((i, j, k) .< size(Vx) .- 1) Rx_ijk = Rx[i, j, k] = d_xa(τxx) + _dy * (τxy[i + 1, j + 1, k] - τxy[i + 1, j, k]) + _dz * (τxz[i + 1, j, k + 1] - τxz[i + 1, j, k]) - d_xa(P) - av_x(fx) Vx[i + 1, j + 1, k + 1] += Rx_ijk * ηdτ / av_x(ητ) end if all((i, j, k) .< size(Vy) .- 1) Ry_ijk = Ry[i, j, k] = _dx * (τxy[i + 1, j + 1, k] - τxy[i, j + 1, k]) + _dy * (τyy[i, j + 1, k] - τyy[i, j, k]) + _dz * (τyz[i, j + 1, k + 1] - τyz[i, j + 1, k]) - d_ya(P) - av_y(fy) Vy[i + 1, j + 1, k + 1] += Ry_ijk * ηdτ / av_y(ητ) end if all((i, j, k) .< size(Vz) .- 1) Rz_ijk = Rz[i, j, k] = _dx * (τxz[i + 1, j, k + 1] - τxz[i, j, k + 1]) + _dy * (τyz[i, j + 1, k + 1] - τyz[i, j, k + 1]) + d_za(τzz) - d_za(P) - av_z(fz) Vz[i + 1, j + 1, k + 1] += Rz_ijk * ηdτ / av_z(ητ) end end return nothing end ## RESIDUALS @parallel_indices (i, j) function compute_Res!( Rx::AbstractArray{T,2}, Ry, P, τxx, τyy, τxy, ρgx, ρgy, _dx, _dy ) where {T} @inline d_xa(A) = _d_xa(A, i, j, _dx) @inline d_ya(A) = _d_ya(A, i, j, _dy) @inline d_xi(A) = _d_xi(A, i, j, _dx) @inline d_yi(A) = _d_yi(A, i, j, _dy) @inline av_xa(A) = _av_xa(A, i, j) @inline av_ya(A) = _av_ya(A, i, j) @inbounds begin if all((i, j) .≤ size(Rx)) Rx[i, j] = d_xa(τxx) + d_yi(τxy) - d_xa(P) - av_xa(ρgx) end if all((i, j) .≤ size(Ry)) Ry[i, j] = d_ya(τyy) + d_xi(τxy) - d_ya(P) - av_ya(ρgy) end end return nothing end @parallel_indices (i, j) function compute_Res!( Rx::AbstractArray{T,2}, Ry, Vx, Vy, Vx_on_Vy, P, τxx, τyy, τxy, ρgx, ρgy, _dx, _dy, dt ) where {T} @inline d_xa(A) = _d_xa(A, i, j, _dx) @inline d_ya(A) = _d_ya(A, i, j, _dy) @inline d_xi(A) = _d_xi(A, i, j, _dx) @inline d_yi(A) = _d_yi(A, i, j, _dy) @inline av_xa(A) = _av_xa(A, i, j) @inline av_ya(A) = _av_ya(A, i, j) nx, ny = size(ρgy) @inbounds begin if all((i, j) .≤ size(Rx)) Rx[i, j] = d_xa(τxx) + d_yi(τxy) - d_xa(P) - av_xa(ρgx) end if all((i, j) .≤ size(Ry)) # θ = 1.0 # Vxᵢⱼ = Vx_on_Vy[i + 1, j + 1] # # Vertical velocity # Vyᵢⱼ = Vy[i + 1, j + 1] # # Get necessary buoyancy forces # i_W, i_E = max(i - 1, 1), min(i + 1, nx) # j_N = min(j + 1, ny) # ρg_stencil = ( # ρgy[i_W, j], # ρgy[i, j], # ρgy[i_E, j], # ρgy[i_W, j_N], # ρgy[i, j_N], # ρgy[i_E, j_N], # ) # ρg_W = (ρg_stencil[1] + ρg_stencil[2] + ρg_stencil[4] + ρg_stencil[5]) * 0.25 # ρg_E = (ρg_stencil[2] + ρg_stencil[3] + ρg_stencil[5] + ρg_stencil[6]) * 0.25 # ρg_S = ρg_stencil[2] # ρg_N = ρg_stencil[5] # # Spatial derivatives # ∂ρg∂x = (ρg_E - ρg_W) * _dx # ∂ρg∂y = (ρg_N - ρg_S) * _dy # # correction term # ρg_correction = (Vxᵢⱼ * ∂ρg∂x + Vyᵢⱼ * ∂ρg∂y) * θ * dt # Ry[i, j] = d_ya(τyy) + d_xi(τxy) - d_ya(P) - av_ya(ρgy) + ρg_correction # # Ry[i, j] = d_ya(τyy) + d_xi(τxy) - d_ya(P) - av_ya(ρgy) θ = 1.0 # Interpolated Vx into Vy node (includes density gradient) Vxᵢⱼ = Vx_on_Vy[i + 1, j + 1] # Vertical velocity Vyᵢⱼ = Vy[i + 1, j + 1] # Get necessary buoyancy forces j_N = min(j + 1, ny) ρg_S = ρgy[i, j] ρg_N = ρgy[i, j_N] # Spatial derivatives ∂ρg∂y = (ρg_N - ρg_S) * _dy # correction term ρg_correction = (Vxᵢⱼ + Vyᵢⱼ * ∂ρg∂y) * θ * dt Ry[i, j] = d_ya(τyy) + d_xi(τxy) - d_ya(P) - av_ya(ρgy) + ρg_correction end end return nothing end
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
29899
struct ThermalParameters{T} κ::T # thermal diffusivity function ThermalParameters(K::AbstractArray, ρCp::AbstractArray) κ = K ./ ρCp return new{typeof(κ)}(κ) end end @parallel function update_T!(ΔT, T, Told) @all(ΔT) = @all(T) - @all(Told) return nothing end # 1D THERMAL DIFFUSION MODULE module ThermalDiffusion1D using ParallelStencil using ParallelStencil.FiniteDifferences1D using JustRelax using LinearAlgebra using Printf using CUDA, AMDGPU import JustRelax: ThermalParameters, solve!, assign!, thermal_boundary_conditions!, update_T! import JustRelax: ThermalArrays, PTThermalCoeffs, backend export solve! @eval @init_parallel_stencil($backend, Float64, 1) ## KERNELS @parallel function compute_flux!(qTx, qTx2, T, K, θr_dτ, _dx) @all(qTx) = (@all(qTx) * @all(θr_dτ) - @all(K) * @d(T) * _dx) / (1.0 + @all(θr_dτ)) @all(qTx2) = -@all(K) * @d(T) * _dx return nothing end @parallel function compute_update!(T, Told, qTx, ρCp, dτ_ρ, _dt, _dx) @inn(T) = @inn(T) + @all(dτ_ρ) * ((-(@d(qTx) * _dx)) - @all(ρCp) * (@inn(T) - @inn(Told)) * _dt) return nothing end @parallel function check_res!(ResT, T, Told, qTx2, ρCp, _dt, _dx) @all(ResT) = -@all(ρCp) * (@inn(T) - @inn(Told)) * _dt - @d(qTx2) * _dx return nothing end ## SOLVER function JustRelax.solve!( thermal::JustRelax.ThermalArrays{M}, pt_thermal::JustRelax.PTThermalCoeffs, thermal_parameters::ThermalParameters{<:AbstractArray{_T,1}}, ni::NTuple{1,Integer}, di::NTuple{1,_T}, dt; iterMax=10e3, nout=500, verbose=true, ) where {_T,M<:AbstractArray{<:Any,1}} @assert size(thermal.T) == ni @parallel assign!(thermal.Told, thermal.T) # Compute some constant stuff _dt = 1 / dt _dx = 1 / di[1] _sqrt_len_RT = 1.0 / sqrt(length(thermal.ResT)) ϵ = pt_thermal.ϵ # errors iter_count = Int64[] norm_ResT = Float64[] # Pseudo-transient iteration iter = 0 wtime0 = 0e0 err = 2 * ϵ while err > ϵ && iter < iterMax wtime0 += @elapsed begin @parallel compute_flux!( thermal.qTx, thermal.qTx2, thermal.T, thermal_parameters.K, pt_thermal.θr_dτ, _dx, ) @parallel compute_update!( thermal.T, thermal.Told, thermal.qTx, thermal_parameters.ρCp, pt_thermal.dτ_ρ, _dt, _dx, ) end iter += 1 if iter % nout == 0 wtime0 += @elapsed begin @parallel check_res!( thermal.ResT, thermal.T, thermal.Told, thermal.qTx2, thermal_parameters.ρCp, _dt, _dx, ) end err = norm(thermal.ResT) * _sqrt_len_RT push!(norm_ResT, err) push!(iter_count, iter) if verbose && (err < ϵ) || (iter === iterMax) @printf("iter = %d, err = %1.3e \n", iter, err) end end end if iter < iterMax @printf("Converged in %d iterations with err = %1.3e \n", iter, err) else println("Model not fully converged") end av_time = wtime0 / iter # average time per iteration @parallel update_T!(thermal.ΔT, thermal.T, thermal.Told) if isnan(err) error("NaN") end return ( iter=iter, err_evo1=norm_ResT, err_evo2=iter_count, time=wtime0, av_time=av_time ) end end # 2D THERMAL DIFFUSION MODULE module ThermalDiffusion2D using ParallelStencil using ParallelStencil.FiniteDifferences2D using JustRelax using CUDA, AMDGPU using GeoParams import JustRelax: ThermalParameters, solve!, assign!, thermal_boundary_conditions! import JustRelax: ThermalArrays, PTThermalCoeffs, solve!, compute_diffusivity, backend export solve! @eval @init_parallel_stencil($backend, Float64, 2) ## KERNELS @parallel function compute_flux!(qTx, qTy, T, κ, _dx, _dy) @all(qTx) = -@av_xi(κ) * @d_xi(T) * _dx @all(qTy) = -@av_yi(κ) * @d_yi(T) * _dy return nothing end @parallel_indices (i, j) function compute_flux!(qTx, qTy, T, rheology, args, _dx, _dy) i1, j1 = @add 1 i j # augment indices by 1 nPx = size(args.P, 1) @inbounds if all((i, j) .≤ size(qTx)) Tx = (T[i1, j1] + T[i, j1]) * 0.5 Pvertex = (args.P[clamp(i - 1, 1, nPx), j1] + args.P[clamp(i - 1, 1, nPx), j]) * 0.5 argsx = (; T=Tx, P=Pvertex) qTx[i, j] = -compute_diffusivity(rheology, argsx) * (T[i1, j1] - T[i, j1]) * _dx end @inbounds if all((i, j) .≤ size(qTy)) Ty = (T[i1, j1] + T[i1, j]) * 0.5 Pvertex = (args.P[clamp(i, 1, nPx), j] + args.P[clamp(i - 1, 1, nPx), j]) * 0.5 argsy = (; T=Ty, P=Pvertex) qTy[i, j] = -compute_diffusivity(rheology, argsy) * (T[i1, j1] - T[i1, j]) * _dy end return nothing end @parallel_indices (i, j) function compute_flux!( qTx, qTy, T, phases, rheology, args, _dx, _dy ) i1, j1 = @add 1 i j # augment indices by 1 nPx = size(args.P, 1) @inbounds if all((i, j) .≤ size(qTx)) Tx = (T[i1, j1] + T[i, j1]) * 0.5 Pvertex = (args.P[clamp(i - 1, 1, nPx), j1] + args.P[clamp(i - 1, 1, nPx), j]) * 0.5 argsx = (; T=Tx, P=Pvertex) qTx[i, j] = -compute_diffusivity(rheology, phases[i, j], ntuple_idx(argsx, i, j)) * (T[i1, j1] - T[i, j1]) * _dx end @inbounds if all((i, j) .≤ size(qTy)) Ty = (T[i1, j1] + T[i1, j]) * 0.5 Pvertex = (args.P[clamp(i, 1, nPx), j] + args.P[clamp(i - 1, 1, nPx), j]) * 0.5 argsy = (; T=Ty, P=Pvertex) qTy[i, j] = -compute_diffusivity(rheology, phases[i, j], ntuple_idx(argsy, i, j)) * (T[i1, j1] - T[i1, j]) * _dy end return nothing end @parallel_indices (i, j) function compute_flux!( qTx, qTy, T, rheology::NTuple{N,AbstractMaterialParamsStruct}, phase_ratios, args, _dx, _dy, ) where {N} i1, j1 = @add 1 i j # augment indices by 1 nPx = size(args.P, 1) if all((i, j) .≤ size(qTx)) Tx = (T[i1, j1] + T[i, j1]) * 0.5 - 273.0 Pvertex = (args.P[clamp(i - 1, 1, nPx), j1] + args.P[clamp(i - 1, 1, nPx), j]) * 0.5 phase_ratios_vertex = ( phase_ratios[clamp(i - 1, 1, nPx), j1] + phase_ratios[clamp(i - 1, 1, nPx), j] ) * 0.5 argsx = (; T=Tx, P=Pvertex) qTx[i, j] = -compute_diffusivity(rheology, phase_ratios_vertex, argsx) * (T[i1, j1] - T[i, j1]) * _dx end if all((i, j) .≤ size(qTy)) Ty = (T[i1, j1] + T[i1, j]) * 0.5 - 273.0 Pvertex = (args.P[clamp(i, 1, nPx), j] + args.P[clamp(i - 1, 1, nPx), j]) * 0.5 phase_ratios_vertex = (phase_ratios[clamp(i, 1, nPx), j] + phase_ratios[clamp(i - 1, 1, nPx), j]) * 0.5 argsy = (; T=Ty, P=Pvertex) qTy[i, j] = -compute_diffusivity(rheology, phase_ratios_vertex, argsy) * (T[i1, j1] - T[i1, j]) * _dy end return nothing end @parallel_indices (i, j) function advect_T!(dT_dt, qTx, qTy, T, Vx, Vy, _dx, _dy) if all((i, j) .≤ size(dT_dt)) i1, j1 = @add 1 i j # augment indices by 1 i2, j2 = @add 2 i j # augment indices by 2 @inbounds begin Vxᵢⱼ = 0.5 * (Vx[i1, j2] + Vx[i, j2]) Vyᵢⱼ = 0.5 * (Vy[i1, j2] + Vy[i1, j1]) dT_dt[i, j] = -((qTx[i1, j] - qTx[i, j]) * _dx + (qTy[i, j1] - qTy[i, j]) * _dy) - (Vxᵢⱼ > 0) * Vxᵢⱼ * (T[i1, j1] - T[i, j1]) * _dx - (Vxᵢⱼ < 0) * Vxᵢⱼ * (T[i2, j1] - T[i1, j1]) * _dx - (Vyᵢⱼ > 0) * Vyᵢⱼ * (T[i1, j1] - T[i1, j]) * _dy - (Vyᵢⱼ < 0) * Vyᵢⱼ * (T[i1, j2] - T[i1, j1]) * _dy end end return nothing end @parallel function advect_T!(dT_dt, qTx, qTy, _dx, _dy) @all(dT_dt) = -(@d_xa(qTx) * _dx + @d_ya(qTy) * _dy) return nothing end @parallel function update_T!(T, dT_dt, dt) @inn(T) = @inn(T) + @all(dT_dt) * dt return nothing end ## SOLVER function JustRelax.solve!( thermal::JustRelax.ThermalArrays{M}, thermal_parameters::ThermalParameters{<:AbstractArray{_T,2}}, thermal_bc::NamedTuple, di::NTuple{2,_T}, dt, ) where {_T,M<:AbstractArray{<:Any,2}} # Compute some constant stuff _dx, _dy = inv.(di) @parallel assign!(thermal.Told, thermal.T) @parallel compute_flux!( thermal.qTx, thermal.qTy, thermal.T, thermal_parameters.κ, _dx, _dy ) @parallel advect_T!(thermal.dT_dt, thermal.qTx, thermal.qTy, _dx, _dy) @parallel update_T!(thermal.T, thermal.dT_dt, dt) thermal_boundary_conditions!(thermal_bc, thermal.T) @. thermal.ΔT = thermal.T - thermal.Told @parallel (@idx size(thermal.Tc)...) temperature2center!(thermal.Tc, thermal.T) return nothing end # upwind advection function JustRelax.solve!( thermal::JustRelax.ThermalArrays{M}, thermal_parameters::ThermalParameters{<:AbstractArray{_T,2}}, stokes, thermal_bc::TemperatureBoundaryConditions, di::NTuple{2,_T}, dt, ) where {_T,M<:AbstractArray{<:Any,2}} # Compute some constant stuff _dx, _dy = inv.(di) @parallel assign!(thermal.Told, thermal.T) @parallel compute_flux!( thermal.qTx, thermal.qTy, thermal.T, thermal_parameters.κ, _dx, _dy ) @parallel advect_T!( thermal.dT_dt, thermal.qTx, thermal.qTy, thermal.T, stokes.V.Vx, stokes.V.Vy, _dx, _dy, ) @parallel update_T!(thermal.T, thermal.dT_dt, dt) thermal_bcs!(thermal.T, thermal_bc) # thermal_boundary_conditions!(thermal_bc, thermal.T) @. thermal.ΔT = thermal.T - thermal.Told @parallel (@idx size(thermal.Tc)...) temperature2center!(thermal.Tc, thermal.T) return nothing end # GEOPARAMS VERSION function JustRelax.solve!( thermal::JustRelax.ThermalArrays{M}, thermal_bc::TemperatureBoundaryConditions, rheology, args::NamedTuple, di::NTuple{2,_T}, dt; advection=true, ) where {_T,M<:AbstractArray{<:Any,2}} # Compute some constant stuff _dx, _dy = inv.(di) nx, ny = size(thermal.T) # solve heat diffusion @parallel assign!(thermal.Told, thermal.T) @parallel (1:(nx - 1), 1:(ny - 1)) compute_flux!( thermal.qTx, thermal.qTy, thermal.T, rheology, args, _dx, _dy ) @parallel advect_T!(thermal.dT_dt, thermal.qTx, thermal.qTy, _dx, _dy) @parallel update_T!(thermal.T, thermal.dT_dt, dt) thermal_bcs!(thermal.T, thermal_bc) # thermal_boundary_conditions!(thermal_bc, thermal.T) @. thermal.ΔT = thermal.T - thermal.Told @parallel (@idx size(thermal.Tc)...) temperature2center!(thermal.Tc, thermal.T) return nothing end # with multiple material phases function JustRelax.solve!( thermal::JustRelax.ThermalArrays{M}, thermal_bc::TemperatureBoundaryConditions, rheology::NTuple{N,AbstractMaterialParamsStruct}, phase_ratios::JustRelax.PhaseRatio, args::NamedTuple, di::NTuple{2,_T}, dt, ) where {_T,N,M<:AbstractArray{<:Any,2}} # Compute some constant stuff _di = inv.(di) nx, ny = size(thermal.T) # solve heat diffusion @parallel assign!(thermal.Told, thermal.T) @parallel (1:(nx - 1), 1:(ny - 1)) compute_flux!( thermal.qTx, thermal.qTy, thermal.T, rheology, phase_ratios.center, args, _di... ) @parallel advect_T!(thermal.dT_dt, thermal.qTx, thermal.qTy, _di...) @parallel update_T!(thermal.T, thermal.dT_dt, dt) thermal_bcs!(thermal.T, thermal_bc) @. thermal.ΔT = thermal.T - thermal.Told @parallel (@idx size(thermal.Tc)...) temperature2center!(thermal.Tc, thermal.T) return nothing end # Upwind advection function JustRelax.solve!( thermal::JustRelax.ThermalArrays{M}, thermal_bc::TemperatureBoundaryConditions, stokes, rheology, args::NamedTuple, di::NTuple{2,_T}, dt, ) where {_T,M<:AbstractArray{<:Any,2}} # Compute some constant stuff _dx, _dy = inv.(di) nx, ny = size(thermal.T) # solve heat diffusion @parallel assign!(thermal.Told, thermal.T) @parallel (1:(nx - 1), 1:(ny - 1)) compute_flux!( thermal.qTx, thermal.qTy, thermal.T, rheology, args, _dx, _dy ) @parallel advect_T!( thermal.dT_dt, thermal.qTx, thermal.qTy, thermal.T, stokes.V.Vx, stokes.V.Vy, _dx, _dy, ) @parallel update_T!(thermal.T, thermal.dT_dt, dt) thermal_bcs!(thermal.T, thermal_bc) @. thermal.ΔT = thermal.T - thermal.Told @parallel (@idx size(thermal.Tc)...) temperature2center!(thermal.Tc, thermal.T) return nothing end # Upwind advection function JustRelax.solve!( thermal::JustRelax.ThermalArrays{M}, thermal_bc::TemperatureBoundaryConditions, stokes, phases, rheology, args::NamedTuple, di::NTuple{2,_T}, dt, ) where {_T,M<:AbstractArray{<:Any,2}} # Compute some constant stuff _dx, _dy = inv.(di) nx, ny = size(thermal.T) # solve heat diffusion @parallel assign!(thermal.Told, thermal.T) @parallel (1:(nx - 1), 1:(ny - 1)) compute_flux!( thermal.qTx, thermal.qTy, thermal.T, phases, rheology, args, _dx, _dy ) @parallel advect_T!( thermal.dT_dt, thermal.qTx, thermal.qTy, thermal.T, stokes.V.Vx, stokes.V.Vy, _dx, _dy, ) @parallel update_T!(thermal.T, thermal.dT_dt, dt) thermal_bcs!(thermal.T, thermal_bc) @. thermal.ΔT = thermal.T - thermal.Told @parallel (@idx size(thermal.Tc)...) temperature2center!(thermal.Tc, thermal.T) return nothing end end # 3D THERMAL DIFFUSION MODULE module ThermalDiffusion3D using ImplicitGlobalGrid using ParallelStencil using ParallelStencil.FiniteDifferences3D using JustRelax using MPI using Printf using CUDA, AMDGPU using GeoParams import JustRelax: IGG, ThermalParameters, solve!, assign!, norm_mpi, thermal_boundary_conditions! import JustRelax: ThermalArrays, PTThermalCoeffs, solve!, compute_diffusivity, backend export solve! @eval @init_parallel_stencil($backend, Float64, 3) ## KERNELS @parallel function compute_flux!(qTx, qTy, qTz, T, κ, _dx, _dy, _dz) @all(qTx) = -@av_xi(κ) * @d_xi(T) * _dx @all(qTy) = -@av_yi(κ) * @d_yi(T) * _dy @all(qTz) = -@av_yi(κ) * @d_zi(T) * _dz return nothing end @parallel_indices (i, j, k) function compute_flux!( qTx, qTy, qTz, T, rheology, args, _dx, _dy, _dz ) i1, j1, k1 = (i, j, k) .+ 1 # augment indices by 1 nx, ny, nz = size(args.P) @inbounds begin if all((i, j, k) .≤ size(qTx)) Tx = (T[i1, j1, k1] + T[i, j1, k1]) * 0.5 Pvertex = 0.0 for jj in 0:1, kk in 0:1 Pvertex += args.P[i, clamp(j + jj, 1, ny), clamp(k + kk, 1, nz)] end argsx = (; T=Tx, P=Pvertex * 0.25) qTx[i, j, k] = -compute_diffusivity(rheology, argsx) * (T[i1, j1, k1] - T[i, j1, k1]) * _dx end if all((i, j, k) .≤ size(qTy)) Ty = (T[i1, j1, k1] + T[i1, j, k1]) * 0.5 Pvertex = 0.0 for kk in 0:1, ii in 0:1 args.P[clamp(i + ii, 1, nx), j, clamp(k + kk, 1, nz)] end argsy = (; T=Ty, P=Pvertex * 0.25) qTy[i, j, k] = -compute_diffusivity(rheology, argsy) * (T[i1, j1, k1] - T[i1, j, k1]) * _dy end if all((i, j, k) .≤ size(qTz)) Tz = (T[i1, j1, k1] + T[i1, j1, k]) * 0.5 Pvertex = 0.0 for jj in 0:1, ii in 0:1 args.P[clamp(i + ii, 1, nx), clamp(j + jj, 1, ny), k] end argsz = (; T=Tz, P=Pvertex * 0.25) qTz[i, j, k] = -compute_diffusivity(rheology, argsz) * (T[i1, j1, k1] - T[i1, j1, k]) * _dz end end return nothing end @parallel_indices (i, j, k) function compute_flux!( qTx, qTy, qTz, T, phases, rheology, args, _dx, _dy, _dz ) i1, j1, k1 = (i, j, k) .+ 1 # augment indices by 1 nx, ny, nz = size(args.P) @inbounds begin if all((i, j, k) .≤ size(qTx)) Tx = (T[i1, j1, k1] + T[i, j1, k1]) * 0.5 Pvertex = 0.0 for jj in 0:1, kk in 0:1 Pvertex += args.P[i, clamp(j + jj, 1, ny), clamp(k + kk, 1, nz)] end argsx = (; T=Tx, P=Pvertex * 0.25) qTx[i, j, k] = -compute_diffusivity( rheology, phases[i, j, k], ntuple_idx(argsx, i, j, k) ) * (T[i1, j1, k1] - T[i, j1, k1]) * _dx end if all((i, j, k) .≤ size(qTy)) Ty = (T[i1, j1, k1] + T[i1, j, k1]) * 0.5 Pvertex = 0.0 for kk in 0:1, ii in 0:1 args.P[clamp(i + ii, 1, nx), j, clamp(k + kk, 1, nz)] end argsy = (; T=Ty, P=Pvertex * 0.25) qTy[i, j, k] = -compute_diffusivity( rheology, phases[i, j, k], ntuple_idx(argsy, i, j, k) ) * (T[i1, j1, k1] - T[i1, j, k1]) * _dy end if all((i, j, k) .≤ size(qTz)) Tz = (T[i1, j1, k1] + T[i1, j1, k]) * 0.5 Pvertex = 0.0 for jj in 0:1, ii in 0:1 args.P[clamp(i + ii, 1, nx), clamp(j + jj, 1, ny), k] end argsz = (; T=Tz, P=Pvertex * 0.25) qTz[i, j, k] = -compute_diffusivity( rheology, phases[i, j, k], ntuple_idx(argsz, i, j, k) ) * (T[i1, j1, k1] - T[i1, j1, k]) * _dz end end return nothing end # multiple phases with GeoParams @parallel_indices (i, j, k) function compute_flux!( qTx, qTy, qTz, T, rheology::NTuple{N,AbstractMaterialParamsStruct}, phase_ratios, args, _dx, _dy, _dz, ) where {N} i1, j1, k1 = (i, j, k) .+ 1 # augment indices by 1 nx, ny, nz = size(args.P) @inbounds begin if all((i, j, k) .≤ size(qTx)) Tx = (T[i1, j1, k1] + T[i, j1, k1]) * 0.5 Pvertex = 0.0 phase_ratios_vertex = new_empty_cell(phase_ratios) for jj in 0:1, kk in 0:1 Pvertex += args.P[i, clamp(j + jj, 1, ny), clamp(k + kk, 1, nz)] phase_ratios_vertex += phase_ratios[ i, clamp(j + jj, 1, ny), clamp(k + kk, 1, nz) ] end argsx = (; T=Tx, P=Pvertex * 0.25) phase_ratios_vertex *= 0.25 qTx[i, j, k] = -compute_diffusivity(rheology, phase_ratios_vertex, argsx) * (T[i1, j1, k1] - T[i, j1, k1]) * _dx end if all((i, j, k) .≤ size(qTy)) Ty = (T[i1, j1, k1] + T[i1, j, k1]) * 0.5 Pvertex = 0.0 phase_ratios_vertex = new_empty_cell(phase_ratios) for kk in 0:1, ii in 0:1 Pvertex += args.P[clamp(i + ii, 1, nx), j, clamp(k + kk, 1, nz)] phase_ratios_vertex += phase_ratios[ clamp(i + ii, 1, nx), j, clamp(k + kk, 1, nz) ] end argsy = (; T=Ty, P=Pvertex * 0.25) phase_ratios_vertex *= 0.25 qTy[i, j, k] = -compute_diffusivity(rheology, phase_ratios_vertex, argsy) * (T[i1, j1, k1] - T[i1, j, k1]) * _dy end if all((i, j, k) .≤ size(qTz)) Tz = (T[i1, j1, k1] + T[i1, j1, k]) * 0.5 Pvertex = 0.0 phase_ratios_vertex = new_empty_cell(phase_ratios) for jj in 0:1, ii in 0:1 Pvertex += args.P[clamp(i + ii, 1, nx), clamp(j + jj, 1, ny), k] phase_ratios_vertex += phase_ratios[ clamp(i + ii, 1, nx), clamp(j + jj, 1, ny), k ] end argsz = (; T=Tz, P=Pvertex * 0.25) phase_ratios_vertex *= 0.25 qTz[i, j, k] = -compute_diffusivity(rheology, phase_ratios_vertex, argsz) * (T[i1, j1, k1] - T[i1, j1, k]) * _dz end end return nothing end @parallel_indices (i, j, k) function advect_T!( dT_dt, qTx, qTy, qTz, T, Vx, Vy, Vz, _dx, _dy, _dz ) if all((i, j, k) .≤ size(dT_dt)) i1, j1, k1 = (i, j, k) .+ 1 # augment indices by 1 i2, j2, k2 = (i, j, k) .+ 2 # augment indices by 2 @inbounds begin # Average velocityes at cell vertices Vxᵢⱼₖ = 0.25 * (Vx[i1, j1, k1] + Vx[i1, j2, k1] + Vx[i1, j1, k2] + Vx[i1, j2, k2]) Vyᵢⱼₖ = 0.25 * (Vy[i1, j1, k1] + Vy[i2, j1, k1] + Vy[i1, j1, k2] + Vy[i2, j1, k2]) Vzᵢⱼₖ = 0.25 * (Vz[i1, j1, k1] + Vz[i2, j1, k1] + Vz[i1, j2, k1] + Vz[i2, j2, k1]) # Cache out local temperature Tᵢⱼₖ = T[i1, j1, k1] # this should be moved to shared memory # Compute ∂T/∂t = ∇(-k∇T) - V*∇T dT_dt[i, j, k] = -( (qTx[i1, j, k] - qTx[i, j, k]) * _dx + (qTy[i, j1, k] - qTy[i, j, k]) * _dy + (qTz[i, j, k1] - qTz[i, j, k]) * _dz ) - (Vxᵢⱼₖ > 0 ? Tᵢⱼₖ - T[i, j1, k1] : T[i2, j1, k1] - Tᵢⱼₖ) * Vxᵢⱼₖ * _dx - (Vyᵢⱼₖ > 0 ? Tᵢⱼₖ - T[i1, j, k1] : T[i1, j2, k1] - Tᵢⱼₖ) * Vyᵢⱼₖ * _dy - (Vzᵢⱼₖ > 0 ? Tᵢⱼₖ - T[i1, j1, k] : T[i1, j1, k2] - Tᵢⱼₖ) * Vzᵢⱼₖ * _dz end end return nothing end @parallel function advect_T!(dT_dt, qTx, qTy, qTz, _dx, _dy, _dz) @all(dT_dt) = -(@d_xa(qTx) * _dx + @d_ya(qTy) * _dy + @d_za(qTz) * _dz) return nothing end @parallel_indices (i, j, k) function update_T!(T, dT_dt, dt) if all((i, j, k) .≤ size(dT_dt)) @inbounds T[i + 1, j + 1, k + 1] = muladd( dT_dt[i, j, k], dt, T[i + 1, j + 1, k + 1] ) end return nothing end ## SOLVER function JustRelax.solve!( thermal::JustRelax.ThermalArrays{M}, thermal_parameters::ThermalParameters{<:AbstractArray{_T,3}}, thermal_bc::NamedTuple, di::NTuple{3,_T}, dt; b_width=(4, 4, 4), ) where {_T,M<:AbstractArray{<:Any,3}} # Compute some constant stuff _di = inv.(di) @parallel assign!(thermal.Told, thermal.T) @parallel compute_flux!( thermal.qTx, thermal.qTy, thermal.qTz, thermal.T, thermal_parameters.κ, _di... ) @parallel advect_T!(thermal.dT_dt, thermal.qTx, thermal.qTy, thermal.qTz, _di...) @hide_communication b_width begin # communication/computation overlap @parallel update_T!(thermal.T, thermal.dT_dt, dt) update_halo!(thermal.T) end thermal_bcs!(thermal.T, thermal_bc) @parallel (@idx size(thermal.Tc)...) temperature2center!(thermal.Tc, thermal.T) return nothing end # upwind advection function JustRelax.solve!( thermal::JustRelax.ThermalArrays{M}, thermal_parameters::ThermalParameters{<:AbstractArray{_T,3}}, thermal_bc::NamedTuple, stokes, di::NTuple{3,_T}, dt; b_width=(4, 4, 4), ) where {_T,M<:AbstractArray{<:Any,3}} # Compute some constant stuff _di = inv.(di) # copy thermal array from previous time step @copy thermal.Told thermal.T # compute flux @parallel compute_flux!( thermal.qTx, thermal.qTy, thermal.qTz, thermal.T, thermal_parameters.κ, _di... ) # compute upwind advection @hide_communication b_width begin # communication/computation overlap @parallel advect_T!( thermal.dT_dt, thermal.qTx, thermal.qTy, thermal.qTz, thermal.T, stokes.V.Vx, stokes.V.Vy, stokes.V.Vz, _di..., ) update_halo!(thermal.T) end @parallel update_T!(thermal.T, thermal.dT_dt, dt) thermal_bcs!(thermal.T, thermal_bc) @parallel (@idx size(thermal.Tc)...) temperature2center!(thermal.Tc, thermal.T) return nothing end # GEOPARAMS VERSION function JustRelax.solve!( thermal::JustRelax.ThermalArrays{M}, thermal_bc::TemperatureBoundaryConditions, rheology, args::NamedTuple, di::NTuple{3,_T}, dt; b_width=(4, 4, 4), ) where {_T,M<:AbstractArray{<:Any,3}} # Compute some constant stuff _di = inv.(di) ni = size(thermal.T) ## SOLVE HEAT DIFFUSION # copy thermal array from previous time step @copy thermal.Told thermal.T # compute flux @parallel (@idx ni .- 1) compute_flux!( thermal.qTx, thermal.qTy, thermal.qTz, thermal.T, rheology, args, _di... ) # compute upwind advection @parallel advect_T!(thermal.dT_dt, thermal.qTx, thermal.qTy, thermal.qTz, _di...) # update thermal array @hide_communication b_width begin # communication/computation overlap @parallel update_T!(thermal.T, thermal.dT_dt, dt) update_halo!(thermal.T) end # apply boundary conditions thermal_bcs!(thermal.T, thermal_bc) @. thermal.ΔT = thermal.T - thermal.Told @parallel (@idx size(thermal.Tc)...) temperature2center!(thermal.Tc, thermal.T) return nothing end # with multiple material phases - no advection function JustRelax.solve!( thermal::JustRelax.ThermalArrays{M}, thermal_bc::TemperatureBoundaryConditions, rheology::NTuple{N,AbstractMaterialParamsStruct}, phase_ratios::JustRelax.PhaseRatio, args::NamedTuple, di::NTuple{3,_T}, dt; b_width=(4, 4, 4), ) where {_T,N,M<:AbstractArray{<:Any,3}} # Compute some constant stuff _di = inv.(di) ni = size(thermal.T) ## SOLVE HEAT DIFFUSION # copy thermal array from previous time step @copy thermal.Told thermal.T # compute flux @parallel (@idx ni .- 1) compute_flux!( thermal.qTx, thermal.qTy, thermal.qTz, thermal.T, rheology, phase_ratios.center, args, _di..., ) # compute upwind advection @parallel advect_T!(thermal.dT_dt, thermal.qTx, thermal.qTy, thermal.qTz, _di...) # update thermal array @hide_communication b_width begin # communication/computation overlap @parallel update_T!(thermal.T, thermal.dT_dt, dt) update_halo!(thermal.T) end # apply boundary conditions thermal_bcs!(thermal.T, thermal_bc) @. thermal.ΔT = thermal.T - thermal.Told @parallel (@idx size(thermal.Tc)...) temperature2center!(thermal.Tc, thermal.T) return nothing end # upwind advection function JustRelax.solve!( thermal::JustRelax.ThermalArrays{M}, thermal_bc::TemperatureBoundaryConditions, stokes, rheology, args::NamedTuple, di::NTuple{3,_T}, dt; b_width=(4, 4, 4), ) where {_T,M<:AbstractArray{<:Any,3}} # Compute some constant stuff _di = inv.(di) ni = size(thermal.T) ## SOLVE HEAT DIFFUSION # copy thermal array from previous time step @copy thermal.Told thermal.T # compute upwind advection @parallel (@idx ni .- 1) compute_flux!( thermal.qTx, thermal.qTy, thermal.qTz, thermal.T, rheology, args, _di... ) # update thermal array @hide_communication b_width begin # communication/computation overlap @parallel advect_T!( thermal.dT_dt, thermal.qTx, thermal.qTy, thermal.qTz, thermal.T, stokes.V.Vx, stokes.V.Vy, stokes.V.Vz, _di..., ) update_halo!(thermal.T) end # apply boundary conditions @hide_communication b_width begin # communication/computation overlap @parallel update_T!(thermal.T, thermal.dT_dt, dt) update_halo!(thermal.T) end thermal_bcs!(thermal.T, thermal_bc) @. thermal.ΔT = thermal.T - thermal.Told @parallel (@idx size(thermal.Tc)...) temperature2center!(thermal.Tc, thermal.T) return nothing end # upwind advection function JustRelax.solve!( thermal::JustRelax.ThermalArrays{M}, thermal_bc::TemperatureBoundaryConditions, stokes, phases, rheology, args::NamedTuple, di::NTuple{3,_T}, dt; b_width=(4, 4, 4), ) where {_T,M<:AbstractArray{<:Any,3}} # Compute some constant stuff _di = inv.(di) ni = size(thermal.T) ## SOLVE HEAT DIFFUSION # copy thermal array from previous time step @copy thermal.Told thermal.T # compute upwind advection @parallel (@idx ni .- 1) compute_flux!( thermal.qTx, thermal.qTy, thermal.qTz, thermal.T, phases, rheology, args, _di... ) # update thermal array @hide_communication b_width begin # communication/computation overlap @parallel advect_T!( thermal.dT_dt, thermal.qTx, thermal.qTy, thermal.qTz, thermal.T, stokes.V.Vx, stokes.V.Vy, stokes.V.Vz, _di..., ) update_halo!(thermal.T) end # apply boundary conditions @hide_communication b_width begin # communication/computation overlap @parallel update_T!(thermal.T, thermal.dT_dt, dt) update_halo!(thermal.T) end thermal_bcs!(thermal.T, thermal_bc) @. thermal.ΔT = thermal.T - thermal.Told @parallel (@idx size(thermal.Tc)...) temperature2center!(thermal.Tc, thermal.T) return nothing end end
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
169
include("DiffusionPT_GeoParams.jl") include("DiffusionPT_kernels.jl") include("DiffusionPT_coefficients.jl") include("ShearHeating.jl") include("DiffusionPT_solver.jl")
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
3846
## Phases @inline get_phase(x::JustRelax.PhaseRatio) = x.center @inline get_phase(x) = x # update_pt_thermal_arrays!(::Vararg{Any,N}) where {N} = nothing function update_pt_thermal_arrays!( pt_thermal, phase_ratios::JustRelax.PhaseRatio, rheology, args, _dt ) ni = size(phase_ratios.center) @parallel (@idx ni) compute_pt_thermal_arrays!( pt_thermal.θr_dτ, pt_thermal.dτ_ρ, rheology, phase_ratios.center, args, pt_thermal.max_lxyz, pt_thermal.Vpdτ, _dt, ) return nothing end @inline function compute_phase(fn::F, rheology, phase::Int, args) where {F} return fn(rheology, phase, args) end @inline function compute_phase(fn::F, rheology, phase::Int) where {F} return fn(rheology, phase, args) end @inline function compute_phase(fn::F, rheology, phase::SVector, args) where {F} return fn_ratio(fn, rheology, phase, args) end @inline function compute_phase(fn::F, rheology, phase::SVector) where {F} return fn_ratio(fn, rheology, phase) end @inline compute_phase(fn::F, rheology, ::Nothing, args) where {F} = fn(rheology, args) @inline compute_phase(fn::F, rheology, ::Nothing) where {F} = fn(rheology) @inline Base.@propagate_inbounds function getindex_phase( phase::AbstractArray, I::Vararg{Int,N} ) where {N} return phase[I...] end @inline getindex_phase(::Nothing, I::Vararg{Int,N}) where {N} = nothing # Diffusivity @inline function compute_diffusivity(rheology, args) return compute_conductivity(rheology, args) * inv(compute_heatcapacity(rheology, args) * compute_density(rheology, args)) end @inline function compute_diffusivity(rheology, phase::Union{Nothing,Int}, args) return compute_conductivity(rheology, phase, args) * inv( compute_heatcapacity(rheology, phase, args) * compute_density(rheology, phase, args) ) end @inline function compute_diffusivity(rheology, ρ, args) return compute_conductivity(rheology, args) * inv(compute_heatcapacity(rheology, args) * ρ) end @inline function compute_diffusivity(rheology, ρ, phase::Union{Nothing,Int}, args) return compute_conductivity(rheology, phase, args) * inv(compute_heatcapacity(rheology, phase, args) * ρ) end @inline function compute_diffusivity( rheology::NTuple{N,AbstractMaterialParamsStruct}, phase_ratios::SArray, args ) where {N} ρ = compute_density_ratio(phase_ratios, rheology, args) conductivity = fn_ratio(compute_conductivity, rheology, phase_ratios, args) heatcapacity = fn_ratio(compute_heatcapacity, rheology, phase_ratios, args) return conductivity * inv(heatcapacity * ρ) end # ρ*Cp @inline function compute_ρCp(rheology, args) return compute_heatcapacity(rheology, args) * compute_density(rheology, args) end @inline function compute_ρCp(rheology, phase::Union{Nothing,Int}, args) return compute_phase(compute_heatcapacity, rheology, phase, args) * compute_phase(compute_density, rheology, phase, args) end @inline function compute_ρCp(rheology, ρ, args) return compute_heatcapacity(rheology, args) * ρ end @inline function compute_ρCp(rheology, ρ, phase::Union{Nothing,Int}, args) return compute_phase(compute_heatcapacity, rheology, phase, args) * ρ end @inline function compute_ρCp(rheology, phase_ratios::SArray, args) return fn_ratio(compute_heatcapacity, rheology, phase_ratios, args) * fn_ratio(compute_density, rheology, phase_ratios, args) end @inline function compute_ρCp(rheology, ρ, phase_ratios::SArray, args) return fn_ratio(compute_heatcapacity, rheology, phase_ratios, args) * ρ end # α function compute_α(rheology, phase::SArray) return fn_ratio(get_α, rheology, phase) end function compute_α(rheology, phase::Union{Int,Nothing}) return compute_phase(get_α, rheology, phase) end
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
4677
function PTThermalCoeffs( ::Type{CPUBackend}, K, ρCp, dt, di::NTuple, li::NTuple; ϵ=1e-8, CFL=0.9 / √3 ) return PTThermalCoeffs(K, ρCp, dt, di, li; ϵ=ϵ, CFL=CFL) end function PTThermalCoeffs(K, ρCp, dt, di, li::NTuple; ϵ=1e-8, CFL=0.9 / √3) Vpdτ = min(di...) * CFL max_lxyz = max(li...) max_lxyz2 = max_lxyz^2 Re = @. π + √(π * π + ρCp * max_lxyz2 / K / dt) # Numerical Reynolds number θr_dτ = @. max_lxyz / Vpdτ / Re dτ_ρ = @. Vpdτ * max_lxyz / K / Re return JustRelax.PTThermalCoeffs(CFL, ϵ, max_lxyz, max_lxyz2, Vpdτ, θr_dτ, dτ_ρ) end # with phase ratios function PTThermalCoeffs( ::Type{CPUBackend}, rheology, phase_ratios, args, dt, ni, di::NTuple, li::NTuple; ϵ=1e-8, CFL=0.9 / √3, ) return PTThermalCoeffs(rheology, phase_ratios, args, dt, ni, di, li; ϵ=ϵ, CFL=CFL) end function PTThermalCoeffs( rheology, phase_ratios, args, dt, ni, di::NTuple, li::NTuple; ϵ=1e-8, CFL=0.9 / √3 ) Vpdτ = min(di...) * CFL max_lxyz = max(li...) θr_dτ, dτ_ρ = @zeros(ni...), @zeros(ni...) @parallel (@idx ni) compute_pt_thermal_arrays!( θr_dτ, dτ_ρ, rheology, phase_ratios.center, args, max_lxyz, Vpdτ, inv(dt) ) return JustRelax.PTThermalCoeffs(CFL, ϵ, max_lxyz, max_lxyz^2, Vpdτ, θr_dτ, dτ_ρ) end # without phase ratios function PTThermalCoeffs( ::Type{CPUBackend}, rheology::MaterialParams, args, dt, ni, di::NTuple, li::NTuple; ϵ=1e-8, CFL=0.9 / √3, ) return PTThermalCoeffs(rheology, args, dt, ni, di, li; ϵ=ϵ, CFL=CFL) end function PTThermalCoeffs( rheology::MaterialParams, args, dt, ni, di::NTuple, li::NTuple; ϵ=1e-8, CFL=0.9 / √3 ) Vpdτ = min(di...) * CFL max_lxyz = max(li...) θr_dτ, dτ_ρ = @zeros(ni...), @zeros(ni...) @parallel (@idx ni) compute_pt_thermal_arrays!( θr_dτ, dτ_ρ, rheology, args, max_lxyz, Vpdτ, inv(dt) ) return JustRelax.PTThermalCoeffs(CFL, ϵ, max_lxyz, max_lxyz^2, Vpdτ, θr_dτ, dτ_ρ) end @parallel_indices (I...) function compute_pt_thermal_arrays!( θr_dτ::AbstractArray, dτ_ρ, rheology, phase, args, max_lxyz, Vpdτ, _dt ) _compute_pt_thermal_arrays!( θr_dτ, dτ_ρ, rheology, phase, args, max_lxyz, Vpdτ, _dt, I... ) return nothing end @parallel_indices (I...) function compute_pt_thermal_arrays!( θr_dτ::AbstractArray, dτ_ρ, rheology, args, max_lxyz, Vpdτ, _dt ) _compute_pt_thermal_arrays!(θr_dτ, dτ_ρ, rheology, args, max_lxyz, Vpdτ, _dt, I...) return nothing end function _compute_pt_thermal_arrays!( θr_dτ, dτ_ρ, rheology, phase, args, max_lxyz, Vpdτ, _dt, Idx::Vararg{Int,N} ) where {N} args_ij = (; T=args.T[Idx...], P=args.P[Idx...]) phase_ij = phase[Idx...] ρCp = compute_ρCp(rheology, phase_ij, args_ij) _K = inv(fn_ratio(compute_conductivity, rheology, phase_ij, args_ij)) _Re = inv(π + √(π * π + ρCp * max_lxyz^2 * _K * _dt)) # Numerical Reynolds number θr_dτ[Idx...] = max_lxyz / Vpdτ * _Re dτ_ρ[Idx...] = Vpdτ * max_lxyz * _K * _Re return nothing end function _compute_pt_thermal_arrays!( θr_dτ, dτ_ρ, rheology, args, max_lxyz, Vpdτ, _dt, Idx::Vararg{Int,N} ) where {N} args_ij = (; T=args.T[Idx...], P=args.P[Idx...]) ρCp = compute_ρCp(rheology, args_ij) _K = inv(compute_conductivity(rheology, args_ij)) _Re = inv(π + √(π * π + ρCp * max_lxyz^2 * _K * _dt)) # Numerical Reynolds number θr_dτ[Idx...] = max_lxyz / Vpdτ * _Re dτ_ρ[Idx...] = Vpdτ * max_lxyz * _K * _Re return nothing end function update_thermal_coeffs!( pt_thermal::JustRelax.PTThermalCoeffs, rheology, phase_ratios, args, dt ) ni = size(pt_thermal.dτ_ρ) @parallel (@idx ni) compute_pt_thermal_arrays!( pt_thermal.θr_dτ, pt_thermal.dτ_ρ, rheology, phase_ratios.center, args, pt_thermal.max_lxyz, pt_thermal.Vpdτ, inv(dt), ) return nothing end function update_thermal_coeffs!(pt_thermal::JustRelax.PTThermalCoeffs, rheology, args, dt) ni = size(pt_thermal.dτ_ρ) @parallel (@idx ni) compute_pt_thermal_arrays!( pt_thermal.θr_dτ, pt_thermal.dτ_ρ, rheology, args, pt_thermal.max_lxyz, pt_thermal.Vpdτ, inv(dt), ) return nothing end function update_thermal_coeffs!( pt_thermal::JustRelax.PTThermalCoeffs, rheology, ::Nothing, args, dt ) ni = size(pt_thermal.dτ_ρ) @parallel (@idx ni) compute_pt_thermal_arrays!( pt_thermal.θr_dτ, pt_thermal.dτ_ρ, rheology, args, pt_thermal.max_lxyz, pt_thermal.Vpdτ, inv(dt), ) return nothing end
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
18410
## 3D KERNELS @parallel_indices (i, j, k) function compute_flux!( qTx::AbstractArray{_T,3}, qTy, qTz, qTx2, qTy2, qTz2, T, K, θr_dτ, _dx, _dy, _dz ) where {_T} d_xi(A) = _d_xi(A, i, j, k, _dx) d_yi(A) = _d_yi(A, i, j, k, _dy) d_zi(A) = _d_zi(A, i, j, k, _dz) av_xy(A) = _av_xy(A, i, j, k) av_xz(A) = _av_xz(A, i, j, k) av_yz(A) = _av_yz(A, i, j, k) I = i, j, k if all(I .≤ size(qTx)) qx = qTx2[I...] = -av_yz(K) * d_xi(T) qTx[I...] = (qTx[I...] * av_yz(θr_dτ) + qx) / (1.0 + av_yz(θr_dτ)) end if all(I .≤ size(qTy)) qy = qTy2[I...] = -av_xz(K) * d_yi(T) qTy[I...] = (qTy[I...] * av_xz(θr_dτ) + qy) / (1.0 + av_xz(θr_dτ)) end if all(I .≤ size(qTz)) qz = qTz2[I...] = -av_xy(K) * d_zi(T) qTz[I...] = (qTz[I...] * av_xy(θr_dτ) + qz) / (1.0 + av_xy(θr_dτ)) end return nothing end @parallel_indices (i, j, k) function compute_flux!( qTx::AbstractArray{_T,3}, qTy, qTz, qTx2, qTy2, qTz2, T, rheology, phase, θr_dτ, _dx, _dy, _dz, args, ) where {_T} d_xi(A) = _d_xi(A, i, j, k, _dx) d_yi(A) = _d_yi(A, i, j, k, _dy) d_zi(A) = _d_zi(A, i, j, k, _dz) av_xy(A) = _av_xy(A, i, j, k) av_xz(A) = _av_xz(A, i, j, k) av_yz(A) = _av_yz(A, i, j, k) get_K(idx, args) = compute_phase(compute_conductivity, rheology, idx, args) I = i, j, k @inbounds if all(I .≤ size(qTx)) T_ijk = (T[(I .+ 1)...] + T[i, j + 1, k + 1]) * 0.5 args_ijk = (; T=T_ijk, P=av_yz(args.P)) K = ( get_K(getindex_phase(phase, i, j + 1, k), args_ijk) + get_K(getindex_phase(phase, i, j, k + 1), args_ijk) + get_K(getindex_phase(phase, i, j + 1, k + 1), args_ijk) + get_K(getindex_phase(phase, i, j, k), args_ijk) ) * 0.25 qx = qTx2[I...] = -K * d_xi(T) qTx[I...] = (qTx[I...] * av_yz(θr_dτ) + qx) / (1.0 + av_yz(θr_dτ)) end @inbounds if all(I .≤ size(qTy)) T_ijk = (T[(I .+ 1)...] + T[i + 1, j, k + 1]) * 0.5 args_ijk = (; T=T_ijk, P=av_xz(args.P)) K = ( get_K(getindex_phase(phase, i + 1, j, k), args_ijk) + get_K(getindex_phase(phase, i, j, k + 1), args_ijk) + get_K(getindex_phase(phase, i + 1, j, k + 1), args_ijk) + get_K(getindex_phase(phase, i, j, k), args_ijk) ) * 0.25 qy = qTy2[I...] = -K * d_yi(T) qTy[I...] = (qTy[I...] * av_xz(θr_dτ) + qy) / (1.0 + av_xz(θr_dτ)) end @inbounds if all(I .≤ size(qTz)) T_ijk = (T[(I .+ 1)...] + T[i + 1, j + 1, k]) * 0.5 args_ijk = (; T=T_ijk, P=av_xy(args.P)) K = ( get_K(getindex_phase(phase, i + 1, j + 1, k), args_ijk) + get_K(getindex_phase(phase, i, j + 1, k), args_ijk) + get_K(getindex_phase(phase, i + 1, j, k), args_ijk) + get_K(getindex_phase(phase, i, j, k), args_ijk) ) * 0.25 qz = qTz2[I...] = -K * d_zi(T) qTz[I...] = (qTz[I...] * av_xy(θr_dτ) + qz) / (1.0 + av_xy(θr_dτ)) end return nothing end @parallel_indices (I...) function update_T!( T::AbstractArray{_T,3}, Told, qTx, qTy, qTz, H, shear_heating, ρCp, dτ_ρ, _dt, _dx, _dy, _dz, ) where {_T} av(A) = _av(A, I...) d_xa(A) = _d_xa(A, I..., _dx) d_ya(A) = _d_ya(A, I..., _dy) d_za(A) = _d_za(A, I..., _dz) I1 = I .+ 1 T[I1...] = ( av(dτ_ρ) * ( -(d_xa(qTx) + d_ya(qTy) + d_za(qTz)) + Told[I1...] * av(ρCp) * _dt + av(H) + av(shear_heating) ) + T[I1...] ) / (one(_T) + av(dτ_ρ) * av(ρCp) * _dt) return nothing end @parallel_indices (i, j, k) function update_T!( T::AbstractArray{_T,3}, Told, qTx, qTy, qTz, H, shear_heating, adiabatic, rheology, phase, dτ_ρ, _dt, _dx, _dy, _dz, args, ) where {_T} av(A) = _av(A, i, j, k) d_xa(A) = _d_xa(A, i, j, k, _dx) d_ya(A) = _d_ya(A, i, j, k, _dy) d_za(A) = _d_za(A, i, j, k, _dz) I = i + 1, j + 1, k + 1 T_ijk = T[I...] args_ijk = (; T=T_ijk, P=av(args.P)) phase_ijk = getindex_phase(phase, i, j, k) ρCp = compute_ρCp(rheology, phase_ijk, args_ijk) T[I...] = ( av(dτ_ρ) * ( -(d_xa(qTx) + d_ya(qTy) + d_za(qTz)) + Told[I...] * ρCp * _dt + av(H) + av(shear_heating) + adiabatic[i, j] * T_ijk ) + T_ijk ) / (one(_T) + av(dτ_ρ) * ρCp * _dt) return nothing end @parallel_indices (i, j, k) function check_res!( ResT::AbstractArray{_T,3}, T, Told, qTx2, qTy2, qTz2, H, shear_heating, ρCp, _dt, _dx, _dy, _dz, ) where {_T} d_xa(A) = _d_xa(A, i, j, k, _dx) d_ya(A) = _d_ya(A, i, j, k, _dy) d_za(A) = _d_za(A, i, j, k, _dz) av(A) = _av(A, i, j, k) I = i + 1, j + 1, k + 1 ResT[i, j, k] = -av(ρCp) * (T[I...] - Told[I...]) * _dt - (d_xa(qTx2) + d_ya(qTy2) + d_za(qTz2)) + av(H) + av(shear_heating) return nothing end @parallel_indices (i, j, k) function check_res!( ResT::AbstractArray{_T,3}, T, Told, qTx2, qTy2, qTz2, H, shear_heating, adiabatic, rheology, phase, _dt, _dx, _dy, _dz, args, ) where {_T} d_xa(A) = _d_xa(A, i, j, k, _dx) d_ya(A) = _d_ya(A, i, j, k, _dy) d_za(A) = _d_za(A, i, j, k, _dz) av(A) = _av(A, i, j, k) I = i + 1, j + 1, k + 1 T_ijk = T[I...] args_ijk = (; T=T_ijk, P=av(args.P)) phase_ijk = getindex_phase(phase, i, j, k) ResT[i, j, k] = -compute_ρCp(rheology, phase_ijk, args_ijk) * (T_ijk - Told[I...]) * _dt - (d_xa(qTx2) + d_ya(qTy2) + d_za(qTz2)) + av(H) + av(shear_heating) + adiabatic[i, j, k] * T_ijk return nothing end ## 2D KERNELS @parallel_indices (i, j) function compute_flux!( qTx::AbstractArray{_T,2}, qTy, qTx2, qTy2, T, K, θr_dτ, _dx, _dy ) where {_T} nx = size(θr_dτ, 1) d_xi(A) = _d_xi(A, i, j, _dx) d_yi(A) = _d_yi(A, i, j, _dy) av_xa(A) = (A[clamp(i - 1, 1, nx), j + 1] + A[clamp(i - 1, 1, nx), j]) * 0.5 av_ya(A) = (A[clamp(i, 1, nx), j] + A[clamp(i - 1, 1, nx), j]) * 0.5 @inbounds if all((i, j) .≤ size(qTx)) qx = qTx2[i, j] = -av_xa(K) * d_xi(T) qTx[i, j] = (qTx[i, j] * av_xa(θr_dτ) + qx) / (1.0 + av_xa(θr_dτ)) end @inbounds if all((i, j) .≤ size(qTy)) qy = qTy2[i, j] = -av_ya(K) * d_yi(T) qTy[i, j] = (qTy[i, j] * av_ya(θr_dτ) + qy) / (1.0 + av_ya(θr_dτ)) end return nothing end @parallel_indices (i, j) function compute_flux!( qTx::AbstractArray{_T,2}, qTy, qTx2, qTy2, T, rheology, phase, θr_dτ, _dx, _dy, args ) where {_T} nx = size(θr_dτ, 1) d_xi(A) = _d_xi(A, i, j, _dx) d_yi(A) = _d_yi(A, i, j, _dy) av_xa(A) = (A[clamp(i - 1, 1, nx), j + 1] + A[clamp(i - 1, 1, nx), j]) * 0.5 av_ya(A) = (A[clamp(i, 1, nx), j] + A[clamp(i - 1, 1, nx), j]) * 0.5 if all((i, j) .≤ size(qTx)) ii, jj = clamp(i - 1, 1, nx), j + 1 phase_ij = getindex_phase(phase, ii, jj) args_ij = ntuple_idx(args, ii, jj) K1 = compute_phase(compute_conductivity, rheology, phase_ij, args_ij) ii, jj = clamp(i - 1, 1, nx), j phase_ij = getindex_phase(phase, ii, jj) args_ij = ntuple_idx(args, ii, jj) K2 = compute_phase(compute_conductivity, rheology, phase_ij, args_ij) K = (K1 + K2) * 0.5 qx = qTx2[i, j] = -K * d_xi(T) qTx[i, j] = (qTx[i, j] * av_xa(θr_dτ) + qx) / (1.0 + av_xa(θr_dτ)) end if all((i, j) .≤ size(qTy)) ii, jj = min(i, nx), j phase_ij = getindex_phase(phase, ii, jj) args_ij = ntuple_idx(args, ii, jj) K1 = compute_phase(compute_conductivity, rheology, phase_ij, args_ij) ii, jj = max(i - 1, 1), j phase_ij = getindex_phase(phase, ii, jj) args_ij = ntuple_idx(args, ii, jj) K2 = compute_phase(compute_conductivity, rheology, phase_ij, args_ij) K = (K1 + K2) * 0.5 qy = qTy2[i, j] = -K * d_yi(T) qTy[i, j] = (qTy[i, j] * av_ya(θr_dτ) + qy) / (1.0 + av_ya(θr_dτ)) end return nothing end @parallel_indices (i, j) function compute_flux!( qTx::AbstractArray{_T,2}, qTy, qTx2, qTy2, T, rheology::NTuple{N,AbstractMaterialParamsStruct}, phase_ratios::CellArray{C1,C2,C3,C4}, θr_dτ, _dx, _dy, args, ) where {_T,N,C1,C2,C3,C4} nx = size(θr_dτ, 1) d_xi(A) = _d_xi(A, i, j, _dx) d_yi(A) = _d_yi(A, i, j, _dy) av_xa(A) = (A[clamp(i - 1, 1, nx), j + 1] + A[clamp(i - 1, 1, nx), j]) * 0.5 av_ya(A) = (A[clamp(i, 1, nx), j] + A[clamp(i - 1, 1, nx), j]) * 0.5 compute_K(phase, args) = fn_ratio(compute_conductivity, rheology, phase, args) @inbounds if all((i, j) .≤ size(qTx)) ii, jj = clamp(i - 1, 1, nx), j + 1 phase_ij = getindex_phase(phase_ratios, ii, jj) args_ij = ntuple_idx(args, ii, jj) K1 = compute_K(phase_ij, args_ij) ii, jj = clamp(i - 1, 1, nx), j phase_ij = getindex_phase(phase_ratios, ii, jj) K2 = compute_K(phase_ij, args_ij) K = (K1 + K2) * 0.5 qx = qTx2[i, j] = -K * d_xi(T) qTx[i, j] = (qTx[i, j] * av_xa(θr_dτ) + qx) / (1.0 + av_xa(θr_dτ)) end @inbounds if all((i, j) .≤ size(qTy)) ii, jj = min(i, nx), j phase_ij = getindex_phase(phase_ratios, ii, jj) args_ij = ntuple_idx(args, ii, jj) K1 = compute_K(phase_ij, args_ij) ii, jj = clamp(i - 1, 1, nx), j phase_ij = getindex_phase(phase_ratios, ii, jj) args_ij = ntuple_idx(args, ii, jj) K2 = compute_K(phase_ij, args_ij) K = (K1 + K2) * 0.5 qy = qTy2[i, j] = -K * d_yi(T) qTy[i, j] = (qTy[i, j] * av_ya(θr_dτ) + qy) / (1.0 + av_ya(θr_dτ)) end return nothing end @parallel_indices (i, j) function update_T!( T::AbstractArray{_T,2}, Told, qTx, qTy, H, shear_heating, ρCp, dτ_ρ, _dt, _dx, _dy ) where {_T} nx, ny = size(ρCp) d_xa(A) = _d_xa(A, i, j, _dx) d_ya(A) = _d_ya(A, i, j, _dy) #! format: off function av(A) ( A[clamp(i - 1, 1, nx), clamp(j - 1, 1, ny)] + A[clamp(i - 1, 1, nx), j] + A[i, clamp(j - 1, 1, ny)] + A[i, j] ) * 0.25 end #! format: on T[i + 1, j + 1] = ( av(dτ_ρ) * ( -(d_xa(qTx) + d_ya(qTy)) + Told[i + 1, j + 1] * av(ρCp) * _dt + av(H) + av(shear_heating) ) + T[i + 1, j + 1] ) / (one(_T) + av(dτ_ρ) * av(ρCp) * _dt) return nothing end @parallel_indices (i, j) function update_T!( T::AbstractArray{_T,2}, Told, qTx, qTy, H, shear_heating, adiabatic, rheology, phase, dτ_ρ, _dt, _dx, _dy, args::NamedTuple, ) where {_T} nx, ny = size(args.P) i0 = clamp(i - 1, 1, nx) i1 = clamp(i, 1, nx) j0 = clamp(j - 1, 1, ny) j1 = clamp(j, 1, ny) d_xa(A) = _d_xa(A, i, j, _dx) d_ya(A) = _d_ya(A, i, j, _dy) av(A) = (A[i0, j0] + A[i0, j1] + A[i1, j0] + A[i1, j1]) * 0.25 T_ij = T[i + 1, j + 1] args_ij = (; T=T_ij, P=av(args.P)) ρCp = ( compute_ρCp(rheology, getindex_phase(phase, i0, j0), args_ij) + compute_ρCp(rheology, getindex_phase(phase, i0, j1), args_ij) + compute_ρCp(rheology, getindex_phase(phase, i1, j0), args_ij) + compute_ρCp(rheology, getindex_phase(phase, i1, j1), args_ij) ) * 0.25 T[i + 1, j + 1] = ( av(dτ_ρ) * ( -(d_xa(qTx) + d_ya(qTy)) + Told[i + 1, j + 1] * ρCp * _dt + av(H) + av(shear_heating) + adiabatic[i, j] * T[i + 1, j + 1] ) + T[i + 1, j + 1] ) / (one(_T) + av(dτ_ρ) * ρCp * _dt) return nothing end @parallel_indices (i, j) function check_res!( ResT::AbstractArray{_T,2}, T, Told, qTx2, qTy2, H, shear_heating, ρCp, _dt, _dx, _dy ) where {_T} nx, ny = size(ρCp) d_xa(A) = _d_xa(A, i, j, _dx) d_ya(A) = _d_ya(A, i, j, _dy) #! format: off function av(A) ( A[clamp(i - 1, 1, nx), clamp(j - 1, 1, ny)] + A[clamp(i - 1, 1, nx), clamp(j, 1, ny)] + A[clamp(i, 1, nx), clamp(j - 1, 1, ny)] + A[clamp(i, 1, nx), clamp(j, 1, ny)] ) * 0.25 end #! format: on ResT[i, j] = -av(ρCp) * (T[i + 1, j + 1] - Told[i + 1, j + 1]) * _dt - (d_xa(qTx2) + d_ya(qTy2)) + av(H) + av(shear_heating) return nothing end @parallel_indices (i, j) function check_res!( ResT::AbstractArray{_T,2}, T, Told, qTx2, qTy2, H, shear_heating, adiabatic, rheology, phase, _dt, _dx, _dy, args, ) where {_T} nx, ny = size(args.P) i0 = clamp(i - 1, 1, nx) i1 = clamp(i, 1, nx) j0 = clamp(j - 1, 1, ny) j1 = clamp(j, 1, ny) d_xa(A) = _d_xa(A, i, j, _dx) d_ya(A) = _d_ya(A, i, j, _dy) av(A) = (A[i0, j0] + A[i0, j1] + A[i1, j0] + A[i1, j1]) * 0.25 T_ij = T[i + 1, j + 1] args_ij = (; T=T_ij, P=av(args.P)) ρCp = ( compute_ρCp(rheology, getindex_phase(phase, i0, j0), args_ij) + compute_ρCp(rheology, getindex_phase(phase, i0, j1), args_ij) + compute_ρCp(rheology, getindex_phase(phase, i1, j0), args_ij) + compute_ρCp(rheology, getindex_phase(phase, i1, j1), args_ij) ) * 0.25 ResT[i, j] = -ρCp * (T[i + 1, j + 1] - Told[i + 1, j + 1]) * _dt - (d_xa(qTx2) + d_ya(qTy2)) + av(H) + av(shear_heating) + adiabatic[i, j] * T[i + 1, j + 1] return nothing end @parallel_indices (I...) function update_ΔT!(ΔT, T, Told) ΔT[I...] = T[I...] - Told[I...] return nothing end function update_T(::Nothing, b_width, thermal, ρCp, pt_thermal, _dt, _di, ni) @parallel update_range(ni...) update_T!( thermal.T, thermal.Told, @qT(thermal)..., thermal.H, thermal.shear_heating, ρCp, pt_thermal.dτ_ρ, _dt, _di..., ) end function update_T( ::Nothing, b_width, thermal, rheology, phase, pt_thermal, _dt, _di, ni, args ) @parallel update_range(ni...) update_T!( thermal.T, thermal.Told, @qT(thermal)..., thermal.H, thermal.shear_heating, thermal.adiabatic, rheology, phase, pt_thermal.dτ_ρ, _dt, _di..., args, ) end @parallel_indices (i, j, k) function adiabatic_heating( A, Vx, Vy, Vz, P, rheology, phases, _dx, _dy, _dz ) I = i, j, k I1 = i1, j1, k1 = I .+ 1 @inbounds begin α = ( compute_α(rheology, getindex_phase(phases, I...)) + compute_α(rheology, getindex_phase(phases, i, j1, k)) + compute_α(rheology, getindex_phase(phases, i1, j, k)) + compute_α(rheology, getindex_phase(phases, i1, j1, k)) + compute_α(rheology, getindex_phase(phases, i, j1, k1)) + compute_α(rheology, getindex_phase(phases, i1, j, k1)) + compute_α(rheology, getindex_phase(phases, i1, j1, k1)) + compute_α(rheology, getindex_phase(phases, I1...)) ) * 0.125 # cache P around T node P111 = P[I...] P112 = P[i, j, k1] P121 = P[i, j1, k] P122 = P[i, j1, k1] P211 = P[i1, j, k] P212 = P[i1, j, k1] P221 = P[i1, j1, k] P222 = P[i1, j1, k1] # P averages Px_L = (P111 + P121 + P112 + P122) * 0.25 Px_R = (P211 + P221 + P212 + P222) * 0.25 Py_F = (P111 + P211 + P112 + P212) * 0.25 Py_B = (P121 + P221 + P122 + P222) * 0.25 Pz_B = (P111 + P211 + P121 + P221) * 0.25 Pz_T = (P112 + P212 + P122 + P222) * 0.25 # Vx average Vx_av = 0.25 * (Vx[I1...] + Vx[i1, j1, k1 + 1] + Vx[i1, j1 + 1, k1] + Vx[i1, j1 + 1, k1 + 1]) # Vy average Vy_av = 0.25 * (Vy[I1...] + Vy[i1 + 1, j1, k1] + Vy[i1, j1, k1 + 1] + Vy[i1 + 1, j1, k1 + 1]) # Vz average Vz_av = 0.25 * (Vz[I1...] + Vz[i1 + 1, j1, k1] + Vz[i1, j1 + 1, k1] + Vz[i1 + 1, j1 + 1, k1]) dPdx = Vx_av * (Px_R - Px_L) * _dx dPdy = Vy_av * (Py_B - Py_F) * _dy dPdz = Vz_av * (Pz_T - Pz_B) * _dz A[I...] = (dPdx + dPdy + dPdz) * α end return nothing end @parallel_indices (i, j) function adiabatic_heating( A, Vx, Vy, P, rheology, phases, _dx, _dy ) I = i, j I1 = i1, j1 = I .+ 1 @inbounds begin α = ( compute_α(rheology, getindex_phase(phases, I...)) + compute_α(rheology, getindex_phase(phases, i, j1)) + compute_α(rheology, getindex_phase(phases, i1, j)) + compute_α(rheology, getindex_phase(phases, I1...)) ) * 0.25 # cache P around T node P11 = P[I...] P12 = P[i, j1] P21 = P[i1, j] P22 = P[i1, j1] # P averages Px_L = (P11 + P12) * 0.5 Px_R = (P21 + P22) * 0.5 Py_T = (P12 + P22) * 0.5 Py_B = (P11 + P21) * 0.5 # Vx average Vx_av = (Vx[I1...] + Vx[i1, j1 + 1]) * 0.5 # Vy average Vy_av = (Vy[I1...] + Vy[i1 + 1, j1]) * 0.5 dPdx = (Px_R - Px_L) * _dx dPdy = (Py_T - Py_B) * _dy A[i1, j] = (Vx_av * dPdx + Vy_av * dPdy) * α end return nothing end function adiabatic_heating!(thermal, stokes, rheology, phases, di) idx = @idx (size(stokes.P) .- 1) _di = inv.(di) @parallel idx adiabatic_heating( thermal.adiabatic, @velocity(stokes)..., stokes.P, rheology, phases, _di... ) end @inline adiabatic_heating!(thermal, ::Nothing, ::Vararg{Any,N}) where {N} = nothing
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
6246
function heatdiffusion_PT!(thermal, args...; kwargs) return heatdiffusion_PT!(backend(thermal), thermal, args...; kwargs=kwargs) end function heatdiffusion_PT!(::CPUBackendTrait, thermal, args...; kwargs) return _heatdiffusion_PT!(thermal, args...; kwargs...) end """ heatdiffusion_PT!(thermal, pt_thermal, K, ρCp, dt, di; iterMax, nout, verbose) Heat diffusion solver using Pseudo-Transient iterations. Both `K` and `ρCp` are n-dimensional arrays. """ function _heatdiffusion_PT!( thermal::JustRelax.ThermalArrays, pt_thermal::JustRelax.PTThermalCoeffs, thermal_bc::TemperatureBoundaryConditions, K::AbstractArray, ρCp::AbstractArray, dt, di; igg=nothing, b_width=(4, 4, 1), iterMax=50e3, nout=1e3, verbose=true, kwargs..., ) # Compute some constant stuff _dt = inv(dt) _di = inv.(di) _sq_len_RT = inv(sqrt(length(thermal.ResT))) ϵ = pt_thermal.ϵ ni = size(thermal.Tc) @copy thermal.Told thermal.T # errors iter_count = Int64[] norm_ResT = Float64[] sizehint!(iter_count, Int(iterMax)) sizehint!(norm_ResT, Int(iterMax)) # Pseudo-transient iteration iter = 0 wtime0 = 0e0 err = 2 * ϵ println("\n ====================================\n") println("Starting thermal diffusion solver...\n") while err > ϵ && iter < iterMax wtime0 += @elapsed begin @parallel flux_range(ni...) compute_flux!( @qT(thermal)..., @qT2(thermal)..., thermal.T, K, pt_thermal.θr_dτ, _di... ) update_T(nothing, b_width, thermal, ρCp, pt_thermal, _dt, _di, ni) thermal_bcs!(thermal, thermal_bc) update_halo!(thermal.T) end iter += 1 if iter % nout == 0 wtime0 += @elapsed begin @parallel residual_range(ni...) check_res!( thermal.ResT, thermal.T, thermal.Told, @qT2(thermal)..., thermal.H, thermal.shear_heating, ρCp, _dt, _di..., ) end err = norm(thermal.ResT) * _sq_len_RT push!(norm_ResT, err) push!(iter_count, iter) if verbose @printf("iter = %d, err = %1.3e \n", iter, err) end end end println("\n ...solver finished in $(round(wtime0, sigdigits=5)) seconds \n") println("====================================\n") @parallel update_ΔT!(thermal.ΔT, thermal.T, thermal.Told) temperature2center!(thermal) return (iter_count=iter_count, norm_ResT=norm_ResT) end """ heatdiffusion_PT!(thermal, pt_thermal, rheology, dt, di; iterMax, nout, verbose) Heat diffusion solver using Pseudo-Transient iterations. """ function _heatdiffusion_PT!( thermal::JustRelax.ThermalArrays, pt_thermal::JustRelax.PTThermalCoeffs, thermal_bc::TemperatureBoundaryConditions, rheology, args::NamedTuple, dt, di; igg=nothing, phase=nothing, stokes=nothing, b_width=(4, 4, 4), iterMax=50e3, nout=1e3, verbose=true, kwargs..., ) phases = get_phase(phase) # Compute some constant stuff _dt = inv(dt) _di = inv.(di) _sq_len_RT = inv(sqrt(length(thermal.ResT))) ϵ = pt_thermal.ϵ ni = size(thermal.Tc) @copy thermal.Told thermal.T !isnothing(phase) && update_pt_thermal_arrays!(pt_thermal, phase, rheology, args, _dt) # compute constant part of the adiabatic heating term adiabatic_heating!(thermal, stokes, rheology, phases, di) # errors iter_count = Int64[] norm_ResT = Float64[] sizehint!(iter_count, Int(iterMax)) sizehint!(norm_ResT, Int(iterMax)) # Pseudo-transient iteration iter = 0 wtime0 = 0e0 err = 2 * ϵ println("\n ====================================\n") println("Starting thermal diffusion solver...\n") while err > ϵ && iter < iterMax wtime0 += @elapsed begin update_thermal_coeffs!(pt_thermal, rheology, phase, args, dt) @parallel flux_range(ni...) compute_flux!( @qT(thermal)..., @qT2(thermal)..., thermal.T, rheology, phases, pt_thermal.θr_dτ, _di..., args, ) update_T( nothing, b_width, thermal, rheology, phases, pt_thermal, _dt, _di, ni, args ) thermal_bcs!(thermal, thermal_bc) update_halo!(thermal.T) !isnothing(phase) && update_pt_thermal_arrays!(pt_thermal, phase, rheology, args, _dt) end iter += 1 if iter % nout == 0 wtime0 += @elapsed begin @parallel residual_range(ni...) check_res!( thermal.ResT, thermal.T, thermal.Told, @qT2(thermal)..., thermal.H, thermal.shear_heating, thermal.adiabatic, rheology, phases, _dt, _di..., args, ) end err = norm(thermal.ResT) * _sq_len_RT push!(norm_ResT, err) push!(iter_count, iter) if verbose @printf("iter = %d, err = %1.3e \n", iter, err) end end end println("\n ...solver finished in $(round(wtime0, sigdigits=5)) seconds \n") println("====================================\n") @parallel update_ΔT!(thermal.ΔT, thermal.T, thermal.Told) temperature2center!(thermal) return (iter_count=iter_count, norm_ResT=norm_ResT) end @inline flux_range(nx, ny) = @idx (nx + 3, ny + 1) @inline flux_range(nx, ny, nz) = @idx (nx, ny, nz) @inline update_range(nx, ny) = @idx (nx + 1, ny - 1) @inline update_range(nx, ny, nz) = residual_range(nx, ny, nz) @inline residual_range(nx, ny) = update_range(nx, ny) @inline residual_range(nx, ny, nz) = @idx (nx - 1, ny - 1, nz - 1)
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
2228
## GeoParams # Diffusivity @inline function compute_diffusivity(rheology, args) return compute_conductivity(rheology, args) * inv(compute_heatcapacity(rheology, args) * compute_density(rheology, args)) end @inline function compute_diffusivity(rheology, phase::Union{Nothing,Int}, args) return compute_conductivity(rheology, phase, args) * inv( compute_heatcapacity(rheology, phase, args) * compute_density(rheology, phase, args) ) end @inline function compute_diffusivity(rheology, ρ, args) return compute_conductivity(rheology, args) * inv(compute_heatcapacity(rheology, args) * ρ) end @inline function compute_diffusivity(rheology, ρ, phase::Union{Nothing,Int}, args) return compute_conductivity(rheology, phase, args) * inv(compute_heatcapacity(rheology, phase, args) * ρ) end @inline function compute_diffusivity( rheology::NTuple{N,AbstractMaterialParamsStruct}, phase_ratios::SArray, args ) where {N} ρ = compute_density_ratio(phase_ratios, rheology, args) conductivity = fn_ratio(compute_conductivity, rheology, phase_ratios, args) heatcapacity = fn_ratio(compute_heatcapacity, rheology, phase_ratios, args) return conductivity * inv(heatcapacity * ρ) end # ρ*Cp @inline function compute_ρCp(rheology, args) return compute_heatcapacity(rheology, args) * compute_density(rheology, args) end @inline function compute_ρCp(rheology, phase::Union{Nothing,Int}, args) return compute_phase(compute_heatcapacity, rheology, phase, args) * compute_phase(compute_density, rheology, phase, args) end @inline function compute_ρCp(rheology, phase_ratios::SArray, args) return fn_ratio(compute_heatcapacity, rheology, phase_ratios, args) * fn_ratio(compute_density, rheology, phase_ratios, args) end @inline function compute_ρCp(rheology, ρ, args) return compute_heatcapacity(rheology, args) * ρ end @inline function compute_ρCp(rheology, ρ, phase::Union{Nothing,Int}, args) return compute_phase(compute_heatcapacity, rheology, phase, args) * ρ end @inline function compute_ρCp(rheology, ρ, phase_ratios::SArray, args) return fn_ratio(compute_heatcapacity, rheology, phase_ratios, args) * ρ end
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
1847
function compute_shear_heating!(thermal, args...) return compute_shear_heating!(backend(thermal), thermal, args...) end function compute_shear_heating!(::CPUBackendTrait, thermal, stokes, rheology, dt) ni = size(thermal.shear_heating) @parallel (ni) compute_shear_heating_kernel!( thermal.shear_heating, @tensor_center(stokes.τ), @tensor_center(stokes.τ_o), @strain(stokes), rheology, dt, ) return nothing end @parallel_indices (I...) function compute_shear_heating_kernel!( shear_heating, τ::NTuple{N,T}, τ_old::NTuple{N,T}, ε::NTuple{N,T}, rheology, dt ) where {N,T} _Gdt = inv(get_shear_modulus(rheology) * dt) τij, τij_o, εij = cache_tensors(τ, τ_old, ε, I...) εij_el = @. 0.5 * ((τij - τij_o) * _Gdt) shear_heating[I...] = compute_shearheating(rheology, τij, εij, εij_el) return nothing end function compute_shear_heating!( ::CPUBackendTrait, thermal, stokes, phase_ratios::JustRelax.PhaseRatio, rheology, dt ) ni = size(thermal.shear_heating) @parallel (@idx ni) compute_shear_heating_kernel!( thermal.shear_heating, @tensor_center(stokes.τ), @tensor_center(stokes.τ_o), @strain(stokes), phase_ratios.center, rheology, dt, ) return nothing end @parallel_indices (I...) function compute_shear_heating_kernel!( shear_heating, τ::NTuple{N,T}, τ_old::NTuple{N,T}, ε::NTuple{N,T}, phase_ratios::CellArray, rheology, dt, ) where {N,T} phase = @inbounds phase_ratios[I...] _Gdt = inv(fn_ratio(get_shear_modulus, rheology, phase) * dt) τij, τij_o, εij = cache_tensors(τ, τ_old, ε, I...) εij_el = @. 0.5 * ((τij - τij_o) * _Gdt) shear_heating[I...] = compute_shearheating(rheology, phase, τij, εij, εij_el) return nothing end
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
4564
include("Utils.jl") # MPI struct struct IGG{T,M} me::T dims::Vector{T} nprocs::T coords::Vector{T} comm_cart::M end # Staggered grid """ struct Geometry{nDim,T} A struct representing the geometry of a topological object in nDim dimensions. # Arguments - `nDim`: The number of dimensions of the topological object. - `T`: The type of the elements in the topological object. """ struct Geometry{nDim,T} ni::NTuple{nDim,Int64} # number of grid cells li::NTuple{nDim,T} # length of the grid origin::NTuple{nDim,T} # origin of the grid max_li::T # maximum length of the grid di::NTuple{nDim,T} # grid spacing xci::NTuple{nDim,LinRange{T,Int64}} # cell-centered grid xvi::NTuple{nDim,LinRange{T,Int64}} # vertex-centered grid grid_v::NTuple{nDim,NTuple{nDim,LinRange{T,Int64}}} # velocity grid function Geometry( ni::NTuple{nDim,Integer}, li::NTuple{nDim,T}; origin=ntuple(_ -> 0.0, Val(nDim)) ) where {nDim,T} isMPI = ImplicitGlobalGrid.grid_is_initialized() Li, maxLi, di, xci, xvi, grid_v = if isMPI geometry_MPI(ni, li, origin) else geometry_nonMPI(ni, li, origin) end return new{nDim,Float64}(ni, Li, origin, maxLi, di, xci, xvi, grid_v) end end function geometry_MPI(ni::NTuple{nDim,Integer}, li::NTuple{nDim,T}, origin) where {nDim,T} f_g = (nx_g, ny_g, nz_g) ni_g = ntuple(i -> f_g[i](), Val(nDim)) Li = Float64.(li) di = Li ./ ni_g xci, xvi = lazy_grid_MPI(di, ni; origin=origin) grid_v = velocity_grids(xci, xvi, di) return Li, max(Li...), di, xci, xvi, grid_v end function geometry_nonMPI( ni::NTuple{nDim,Integer}, li::NTuple{nDim,T}, origin ) where {nDim,T} Li = Float64.(li) di = Li ./ ni xci, xvi = lazy_grid(di, ni, Li; origin=origin) grid_v = velocity_grids(xci, xvi, di) return Li, max(Li...), di, xci, xvi, grid_v end function lazy_grid_MPI( di::NTuple{N,T1}, ni; origin=ntuple(_ -> zero(T1), Val(N)) ) where {N,T1} f_g = (x_g, y_g, z_g) # nodes at the center of the grid cells xci = ntuple(Val(N)) do i Base.@_inline_meta rank_origin = f_g[i](1, di[i], ni[i]) local_origin = rank_origin + origin[i] rank_end = f_g[i](ni[i], di[i], ni[i]) local_end = rank_end + origin[i] @inbounds LinRange(local_origin[i] + di[i] / 2, local_end[i] + di[i] / 2, ni[i]) end # nodes at the vertices of the grid cells xvi = ntuple(Val(N)) do i # println("potato") Base.@_inline_meta rank_origin = f_g[i](1, di[i], ni[i]) local_origin = rank_origin + origin[i] rank_end = f_g[i](ni[i] + 1, di[i], ni[i]) local_end = rank_end + origin[i] @inbounds LinRange(local_origin[i], local_end[i], ni[i] + 1) end return xci, xvi end function lazy_grid( di::NTuple{N,T1}, ni, Li; origin=ntuple(_ -> zero(T1), Val(N)) ) where {N,T1} # nodes at the center of the grid cells xci = ntuple(Val(N)) do i Base.@_inline_meta @inbounds LinRange(origin[i] + di[i] / 2, origin[i] + Li[i] + di[i] / 2, ni[i]) end # nodes at the vertices of the grid cells xvi = ntuple(Val(N)) do i Base.@_inline_meta @inbounds LinRange(origin[i], origin[i] + Li[i], ni[i] + 1) end return xci, xvi end # Velocity helper grids for the particle advection """ velocity_grids(xci, xvi, di::NTuple{N,T}) where {N,T} Compute the velocity grids for N dimensionional problems. # Arguments - `xci`: The x-coordinate of the cell centers. - `xvi`: The x-coordinate of the cell vertices. - `di`: A tuple containing the cell dimensions. """ function velocity_grids(xci, xvi, di::NTuple{2,T}) where {T} dx, dy = di yVx = LinRange(xci[2][1] - dy, xci[2][end] + dy, length(xci[2]) + 2) xVy = LinRange(xci[1][1] - dx, xci[1][end] + dx, length(xci[1]) + 2) grid_vx = xvi[1], yVx grid_vy = xVy, xvi[2] return grid_vx, grid_vy end function velocity_grids(xci, xvi, di::NTuple{3,T}) where {T} xghost = ntuple(Val(3)) do i LinRange(xci[i][1] - di[i], xci[i][end] + di[i], length(xci[i]) + 2) end grid_vx = xvi[1], xghost[2], xghost[3] grid_vy = xghost[1], xvi[2], xghost[3] grid_vz = xghost[1], xghost[2], xvi[3] return grid_vx, grid_vy, grid_vz end
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
2492
import ImplicitGlobalGrid: global_grid, GGNumber, GGArray, @coordx, @nx, @nx_g, @olx, @periodx, @coordy, @ny, @ny_g, @oly, @periody, @coordz, @nz, @nz_g, @olz, @periodz # Functions modified from ImplicitGlobalGrid.jl x_g(idx::Integer, dxi::GGNumber, nxi::GGNumber) = _x_g(idx, dxi, nxi) x_g(idx::Integer, dxi::GGNumber, A::GGArray) = _x_g(idx, dxi, size(A, 1)) function _x_g(idx::Integer, dxi::GGNumber, nxi::GGNumber) x0i = 0.5 * (@nx() - nxi) * dxi xi = (@coordx() * (@nx() - @olx()) + idx - 1) * dxi + x0i if @periodx() xi = xi - dxi # The first cell of the global problem is a ghost cell; so, all must be shifted by dx to the left. if (xi > (@nx_g() - 1) * dx) xi = xi - @nx_g() * dxi end # It must not be (nx_g()-1)*dx as the distance between the local problems (1*dx) must also be taken into account! if (xi < 0) xi = xi + @nx_g() * dxi end end return xi end y_g(idx::Integer, dxi::GGNumber, nxi::GGNumber) = _y_g(idx, dxi, nxi) y_g(idx::Integer, dxi::GGNumber, A::GGArray) = _z_g(idx, dxi, size(A, 2)) function _y_g(idx::Integer, dxi::GGNumber, nxi::GGNumber) x0i = 0.5 * (@ny() - nxi) * dxi xi = (@coordy() * (@ny() - @oly()) + idx - 1) * dxi + x0i if @periody() xi = xi - dxi # The first cell of the global problem is a ghost cell; so, all must be shifted by dx to the left. if (xi > (@ny_g() - 1) * dx) xi = xi - @ny_g() * dxi end # It must not be (ny_g()-1)*dx as the distance between the local problems (1*dx) must also be taken into account! if (xi < 0) xi = xi + @ny_g() * dxi end end return xi end z_g(idx::Integer, dxi::GGNumber, nxi::GGNumber) = _z_g(idx, dxi, nxi) z_g(idx::Integer, dxi::GGNumber, A::GGArray) = _z_g(idx, dxi, size(A, 3)) function _z_g(idx::Integer, dxi::GGNumber, nxi::GGNumber) x0i = 0.5 * (@nz() - nxi) * dxi xi = (@coordz() * (@nz() - @olz()) + idx - 1) * dxi + x0i if @periodz() xi = xi - dxi # The first cell of the global problem is a ghost cell; so, all must be shifted by dx to the left. if (xi > (@nz_g() - 1) * dx) xi = xi - @nz_g() * dxi end # It must not be (nz_g()-1)*dx as the distance between the local problems (1*dx) must also be taken into account! if (xi < 0) xi = xi + @nz_g() * dxi end end return xi end
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
2085
# Velocity to displacement interpolation velocity2displacement!(stokes, dt) = velocity2displacement!(backend(stokes), stokes, dt) function velocity2displacement!(::CPUBackendTrait, stokes::JustRelax.StokesArrays, dt) return _velocity2displacement!(stokes, dt) end function _velocity2displacement!(stokes::JustRelax.StokesArrays, dt) ni = size(stokes.P) (; V, U) = stokes @parallel (@idx ni .+ 2) _velocity2displacement_kernel!( V.Vx, V.Vy, V.Vz, U.Ux, U.Uy, U.Uz, dt ) return nothing end @parallel_indices (I...) function _velocity2displacement_kernel!(Vx, Vy, Vz, Ux, Uy, Uz, dt) if all(I .≤ size(Ux)) Ux[I...] = Vx[I...] * dt end if all(I .≤ size(Uy)) Uy[I...] = Vy[I...] * dt end if !isnothing(Vz) && all(I .≤ size(Uz)) Uz[I...] = Vz[I...] * dt end return nothing end # Displacement to velocity interpolation displacement2velocity!(stokes, dt) = displacement2velocity!(backend(stokes), stokes, dt) function displacement2velocity!(::CPUBackendTrait, stokes::JustRelax.StokesArrays, dt) return _displacement2velocity!(stokes, dt) end function _displacement2velocity!(stokes::JustRelax.StokesArrays, dt) ni = size(stokes.P) (; V, U) = stokes @parallel (@idx ni .+ 2) _displacement2velocity_kernel!( U.Ux, U.Uy, U.Uz, V.Vx, V.Vy, V.Vz, 1 / dt ) return nothing end @parallel_indices (I...) function _displacement2velocity_kernel!( Ux, Uy, Uz, Vx, Vy, Vz, _dt ) if all(I .≤ size(Ux)) Vx[I...] = Ux[I...] * _dt end if all(I .≤ size(Uy)) Vy[I...] = Uy[I...] * _dt end if !isnothing(Vz) && all(I .≤ size(Uz)) Vz[I...] = Uz[I...] * _dt end return nothing end function displacement2velocity!(stokes, dt, ::DisplacementBoundaryConditions) return displacement2velocity!(backend(stokes), stokes, dt) end displacement2velocity!(::Any, ::Any, ::VelocityBoundaryConditions) = nothing function displacement2velocity!(::Any, ::Any, ::T) where {T} throw(ArgumentError("Unknown boundary conditions type: $T")) end
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
1263
struct ThermalArrays{_T} T::_T # Temperature @ grid nodes Tc::_T # Temperature @ cell centers Told::_T ΔT::_T ΔTc::_T adiabatic::_T # adiabatic term α (u ⋅ ∇P) dT_dt::_T qTx::_T qTy::_T qTz::Union{_T,Nothing} qTx2::_T qTy2::_T qTz2::Union{_T,Nothing} H::_T # source terms shear_heating::_T # shear heating terms ResT::_T end ThermalArrays(::Type{CPUBackend}, ni::NTuple{N,Number}) where {N} = ThermalArrays(ni...) ThermalArrays(::Type{CPUBackend}, ni::Vararg{Number,N}) where {N} = ThermalArrays(ni...) ThermalArrays(ni::NTuple{N,Number}) where {N} = ThermalArrays(ni...) function ThermalArrays(::Number, ::Number) throw(ArgumentError("ThermalArrays dimensions must be given as integers")) end function ThermalArrays(::Number, ::Number, ::Number) throw(ArgumentError("ThermalArrays dimensions must be given as integers")) end ## Thermal diffusion coefficients struct PTThermalCoeffs{T,M} CFL::T ϵ::T max_lxyz::T max_lxyz2::T Vpdτ::T θr_dτ::M dτ_ρ::M function PTThermalCoeffs( CFL::T, ϵ::T, max_lxyz::T, max_lxyz2::T, Vpdτ::T, θr_dτ::M, dτ_ρ::M ) where {T,M} return new{T,M}(CFL, ϵ, max_lxyz, max_lxyz2, Vpdτ, θr_dτ, dτ_ρ) end end
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
226
struct PhaseRatio{T} vertex::T center::T PhaseRatio(vertex::T, center::T) where {T<:AbstractArray} = new{T}(vertex, center) end @inline PhaseRatio(::Type{CPUBackend}, ni, num_phases) = PhaseRatio(ni, num_phases)
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
5118
## Velocity type struct Velocity{T} Vx::T Vy::T Vz::Union{T,Nothing} Velocity(Vx::T, Vy::T, Vz::Union{T,Nothing}) where {T} = new{T}(Vx, Vy, Vz) end Velocity(Vx::T, Vy::T) where {T} = Velocity(Vx, Vy, nothing) Velocity(ni::NTuple{N,Number}) where {N} = Velocity(ni...) function Velocity(::Number, ::Number) throw(ArgumentError("Velocity dimensions must be given as integers")) end function Velocity(::Number, ::Number, ::Number) throw(ArgumentError("Velocity dimensions must be given as integers")) end ## Displacement type struct Displacement{T} Ux::T Uy::T Uz::Union{T,Nothing} Displacement(Ux::T, Uy::T, Uz::Union{T,Nothing}) where {T} = new{T}(Ux, Uy, Uz) end Displacement(Ux::T, Uy::T) where {T} = Displacement(Ux, Uy, nothing) Displacement(ni::NTuple{N,Number}) where {N} = Displacement(ni...) function Displacement(::Number, ::Number) throw(ArgumentError("Displacement dimensions must be given as integers")) end function Displacement(::Number, ::Number, ::Number) throw(ArgumentError("Displacement dimensions must be given as integers")) end ## Vorticity type struct Vorticity{T} yz::Union{T,Nothing} xz::Union{T,Nothing} xy::T function Vorticity(yz::Union{T,Nothing}, xz::Union{T,Nothing}, xy::T) where {T} return new{T}(yz, xz, xy) end end Vorticity(nx::T, ny::T) where {T<:Number} = Vorticity((nx, ny)) Vorticity(nx::T, ny::T, nz::T) where {T<:Number} = Vorticity((nx, ny, nz)) function Vorticity(::NTuple{N,Number}) where {N} throw(ArgumentError("Dimensions must be given as integers")) end ## Viscosity type struct Viscosity{T} η::T # with no plasticity η_vep::T # with plasticity ητ::T # PT viscosi Viscosity(args::Vararg{T,N}) where {T,N} = new{T}(args...) end Viscosity(args...) = Viscosity(promote(args...)...) Viscosity(nx::T, ny::T) where {T<:Number} = Viscosity((nx, ny)) Viscosity(nx::T, ny::T, nz::T) where {T<:Number} = Viscosity((nx, ny, nz)) function Viscosity(::NTuple{N,Number}) where {N} throw(ArgumentError("Viscosity dimensions must be given as integers")) end ## SymmetricTensor type struct SymmetricTensor{T} xx::T yy::T zz::Union{T,Nothing} xy::T yz::Union{T,Nothing} xz::Union{T,Nothing} xy_c::T yz_c::Union{T,Nothing} xz_c::Union{T,Nothing} II::T function SymmetricTensor( xx::T, yy::T, zz::Union{T,Nothing}, xy::T, yz::Union{T,Nothing}, xz::Union{T,Nothing}, xy_c::T, yz_c::Union{T,Nothing}, xz_c::Union{T,Nothing}, II::T, ) where {T} return new{T}(xx, yy, zz, xy, yz, xz, xy_c, yz_c, xz_c, II) end end function SymmetricTensor(xx::T, yy::T, xy::T, xy_c::T, II::T) where {T} return SymmetricTensor( xx, yy, nothing, xy, nothing, nothing, xy_c, nothing, nothing, II ) end SymmetricTensor(ni::NTuple{N,Number}) where {N} = SymmetricTensor(ni...) function SymmetricTensor(::Number, ::Number) throw(ArgumentError("SymmetricTensor dimensions must be given as integers")) end function SymmetricTensor(::Number, ::Number, ::Number) throw(ArgumentError("SymmetricTensor dimensions must be given as integers")) end ## Residual type struct Residual{T} RP::T Rx::T Ry::T Rz::Union{T,Nothing} Residual(RP::T, Rx::T, Ry::T, Rz::Union{T,Nothing}) where {T} = new{T}(RP, Rx, Ry, Rz) end Residual(RP::T, Rx::T, Ry::T) where {T} = Residual(RP, Rx, Ry, nothing) Residual(ni::NTuple{N,Number}) where {N} = Residual(ni...) function Residual(::Number, ::Number) throw(ArgumentError("Residual dimensions must be given as integers")) end function Residual(::Number, ::Number, ::Number) throw(ArgumentError("Residual dimensions must be given as integers")) end ## StokesArrays type struct StokesArrays{A,B,C,D,E,F,T} P::T P0::T V::A ∇V::T τ::B ε::B ε_pl::B EII_pl::T viscosity::D τ_o::Union{B,Nothing} R::C U::E ω::F end function StokesArrays(::Type{CPUBackend}, ni::Vararg{Integer,N}) where {N} return StokesArrays(tuple(ni...)) end StokesArrays(::Type{CPUBackend}, ni::NTuple{N,Integer}) where {N} = StokesArrays(ni) StokesArrays(ni::Vararg{Integer,N}) where {N} = StokesArrays(tuple(ni...)) function StokesArrays(::Number, ::Number) throw(ArgumentError("StokesArrays dimensions must be given as integers")) end function StokesArrays(::Number, ::Number, ::Number) throw(ArgumentError("StokesArrays dimensions must be given as integers")) end ## PTStokesCoeffs type struct PTStokesCoeffs{T} CFL::T ϵ::T # PT tolerance Re::T # Reynolds Number r::T # Vpdτ::T θ_dτ::T ηdτ::T function PTStokesCoeffs( li::NTuple{N,T}, di; ϵ::Float64=1e-8, Re::Float64=3π, CFL::Float64=(N == 2 ? 0.9 / √2.1 : 0.9 / √3.1), r::Float64=0.7, ) where {N,T} lτ = min(li...) Vpdτ = min(di...) * CFL θ_dτ = lτ * (r + 4 / 3) / (Re * Vpdτ) ηdτ = Vpdτ * lτ / Re return new{Float64}(CFL, ϵ, Re, r, Vpdτ, θ_dτ, ηdτ) end end
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
1028
abstract type BackendTrait end abstract type GPUBackendTrait <: BackendTrait end struct CPUBackendTrait <: BackendTrait end struct NonCPUBackendTrait <: GPUBackendTrait end struct CUDABackendTrait <: GPUBackendTrait end struct AMDGPUBackendTrait <: GPUBackendTrait end # AbstractArray's @inline backend(::Array) = CPUBackendTrait() @inline backend(::Type{<:Array}) = CPUBackendTrait() @inline backend(::AbstractArray) = NonCPUBackendTrait() @inline backend(::Type{<:AbstractArray}) = NonCPUBackendTrait() # Custom struct's for type in ( JustRelax.Velocity, JustRelax.Displacement, JustRelax.Vorticity, JustRelax.SymmetricTensor, JustRelax.Residual, JustRelax.Viscosity, JustRelax.ThermalArrays, ) @eval @inline backend(::$(type){T}) where {T} = backend(T) end @inline backend(x::JustRelax.StokesArrays) = backend(x.P) @inline backend(x::JustRelax.PhaseRatio) = backend(x.center.data) # Error handling @inline backend(::T) where {T} = throw(ArgumentError("$(T) is not a supported backend"))
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
1019
import Base: Array, copy const JR_T = Union{ StokesArrays, SymmetricTensor, ThermalArrays, Velocity, Displacement, Vorticity, Residual, Viscosity, } ## Conversion of structs to CPU @inline remove_parameters(::T) where {T} = Base.typename(T).wrapper Array(x::T) where {T<:JR_T} = Array(backend(x), x) Array(::Nothing) = nothing Array(::CPUBackendTrait, x) = x function Array(::GPUBackendTrait, x::T) where {T<:JR_T} nfields = fieldcount(T) cpu_fields = ntuple(Val(nfields)) do i Base.@_inline_meta Array(getfield(x, i)) end T_clean = remove_parameters(x) return T_clean(cpu_fields...) end ## Copy JustRelax custom structs copy(::Nothing) = nothing function copy(x::T) where {T<:JR_T} nfields = fieldcount(T) fields = ntuple(Val(nfields)) do i Base.@_inline_meta field = copy(getfield(x, i)) # field === nothing ? nothing : copy(field) end T_clean = remove_parameters(x) return T_clean(fields...) end
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
1926
function ThermalArrays(::Type{CPUBackend}, ni::NTuple{N,Integer}) where {N} return ThermalArrays(ni...) end function ThermalArrays(::Type{CPUBackend}, ni::Vararg{Integer,N}) where {N} return ThermalArrays(ni...) end function ThermalArrays(nx::Integer, ny::Integer) T = @zeros(nx + 3, ny + 1) ΔT = @zeros(nx + 3, ny + 1) ΔTc = @zeros(nx, ny) adiabatic = @zeros(nx + 1, ny - 1) Told = @zeros(nx + 3, ny + 1) Tc = @zeros(nx, ny) H = @zeros(nx, ny) shear_heating = @zeros(nx, ny) dT_dt = @zeros(nx + 1, ny - 1) qTx = @zeros(nx + 2, ny - 1) qTy = @zeros(nx + 1, ny) qTx2 = @zeros(nx + 2, ny - 1) qTy2 = @zeros(nx + 1, ny) ResT = @zeros(nx + 1, ny - 1) return JustRelax.ThermalArrays( T, Tc, Told, ΔT, ΔTc, adiabatic, dT_dt, qTx, qTy, nothing, qTx2, qTy2, nothing, H, shear_heating, ResT, ) end function ThermalArrays(nx::Integer, ny::Integer, nz::Integer) T = @zeros(nx + 1, ny + 1, nz + 1) ΔT = @zeros(nx + 1, ny + 1, nz + 1) ΔTc = @zeros(nx, ny, ny) adiabatic = @zeros(nx - 1, ny - 1, nz - 1) Told = @zeros(nx + 1, ny + 1, nz + 1) Tc = @zeros(nx, ny, nz) H = @zeros(nx, ny, nz) shear_heating = @zeros(nx, ny, nz) dT_dt = @zeros(nx - 1, ny - 1, nz - 1) qTx = @zeros(nx, ny - 1, nz - 1) qTy = @zeros(nx - 1, ny, nz - 1) qTz = @zeros(nx - 1, ny - 1, nz) qTx2 = @zeros(nx, ny - 1, nz - 1) qTy2 = @zeros(nx - 1, ny, nz - 1) qTz2 = @zeros(nx - 1, ny - 1, nz) ResT = @zeros(nx - 1, ny - 1, nz - 1) return JustRelax.ThermalArrays( T, Tc, Told, ΔT, ΔTc, adiabatic, dT_dt, qTx, qTy, qTz, qTx2, qTy2, qTz2, H, shear_heating, ResT, ) end
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
413
function PhaseRatio( ::Type{CPUBackend}, ni::NTuple{N,Integer}, num_phases::Integer ) where {N} return PhaseRatio(ni, num_phases) end function PhaseRatio(ni::NTuple{N,Integer}, num_phases::Integer) where {N} center = @fill(0.0, ni..., celldims = (num_phases,)) vertex = @fill(0.0, ni .+ 1..., celldims = (num_phases,)) # T = typeof(center) return JustRelax.PhaseRatio(vertex, center) end
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
3400
## Velocity type function Velocity(nx::Integer, ny::Integer) nVx = (nx + 1, ny + 2) nVy = (nx + 2, ny + 1) Vx, Vy = @zeros(nVx...), @zeros(nVy) return JustRelax.Velocity(Vx, Vy, nothing) end function Velocity(nx::Integer, ny::Integer, nz::Integer) nVx = (nx + 1, ny + 2, nz + 2) nVy = (nx + 2, ny + 1, nz + 2) nVz = (nx + 2, ny + 2, nz + 1) Vx, Vy, Vz = @zeros(nVx...), @zeros(nVy), @zeros(nVz) return JustRelax.Velocity(Vx, Vy, Vz) end ## Displacement type function Displacement(nx::Integer, ny::Integer) nUx = (nx + 1, ny + 2) nUy = (nx + 2, ny + 1) Ux, Uy = @zeros(nUx...), @zeros(nUy) return JustRelax.Displacement(Ux, Uy, nothing) end function Displacement(nx::Integer, ny::Integer, nz::Integer) nUx = (nx + 1, ny + 2, nz + 2) nUy = (nx + 2, ny + 1, nz + 2) nUz = (nx + 2, ny + 2, nz + 1) Ux, Uy, Uz = @zeros(nUx...), @zeros(nUy), @zeros(nUz) return JustRelax.Displacement(Ux, Uy, Uz) end ## Vorticity type function Vorticity(nx::Integer, ny::Integer) xy = @zeros(nx, ny) return JustRelax.Vorticity(nothing, nothing, xy) end function Vorticity(nx::Integer, ny::Integer, nz::Integer) yz = @zeros(nx, ny, nz) xz = @zeros(nx, ny, nz) xy = @zeros(nx, ny, nz) return JustRelax.Vorticity(yz, xz, xy) end ## Viscosity type function Viscosity(ni::NTuple{N,Integer}) where {N} η = @ones(ni...) η_vep = @ones(ni...) ητ = @zeros(ni...) return JustRelax.Viscosity(η, η_vep, ητ) end ## SymmetricTensor type function SymmetricTensor(nx::Integer, ny::Integer) return JustRelax.SymmetricTensor( @zeros(nx, ny), # xx @zeros(nx, ny), # yy @zeros(nx + 1, ny + 1), # xy @zeros(nx, ny), # xy @ cell center @zeros(nx, ny) # II (second invariant) ) end function SymmetricTensor(nx::Integer, ny::Integer, nz::Integer) return JustRelax.SymmetricTensor( @zeros(nx, ny, nz), # xx @zeros(nx, ny, nz), # yy @zeros(nx, ny, nz), # zz @zeros(nx + 1, ny + 1, nz), # xy @zeros(nx, ny + 1, nz + 1), # yz @zeros(nx + 1, ny, nz + 1), # xz @zeros(nx, ny, nz), # yz @ cell center @zeros(nx, ny, nz), # xz @ cell center @zeros(nx, ny, nz), # xy @ cell center @zeros(nx, ny, nz), # II (second invariant) ) end ## Residual type function Residual(nx::Integer, ny::Integer) Rx = @zeros(nx - 1, ny) Ry = @zeros(nx, ny - 1) RP = @zeros(nx, ny) return JustRelax.Residual(RP, Rx, Ry) end function Residual(nx::Integer, ny::Integer, nz::Integer) Rx = @zeros(nx - 1, ny, nz) Ry = @zeros(nx, ny - 1, nz) Rz = @zeros(nx, ny, nz - 1) RP = @zeros(nx, ny, nz) return JustRelax.Residual(RP, Rx, Ry, Rz) end ## StokesArrays type function StokesArrays(::Type{CPUBackend}, ni::NTuple{N,Integer}) where {N} return StokesArrays(ni) end function StokesArrays(ni::NTuple{N,Integer}) where {N} P = @zeros(ni...) P0 = @zeros(ni...) ∇V = @zeros(ni...) V = Velocity(ni...) U = Displacement(ni...) ω = Vorticity(ni...) τ = SymmetricTensor(ni...) τ_o = SymmetricTensor(ni...) ε = SymmetricTensor(ni...) ε_pl = SymmetricTensor(ni...) EII_pl = @zeros(ni...) viscosity = Viscosity(ni) R = Residual(ni...) return JustRelax.StokesArrays(P, P0, V, ∇V, τ, ε, ε_pl, EII_pl, viscosity, τ_o, R, U, ω) end
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
328
push!(LOAD_PATH, "..") using Test, Suppressor using JustRelax using ParallelStencil model = PS_Setup(:cpu, Float64, 2) environment!(model) ParallelStencil.@reset_parallel_stencil model = PS_Setup(:cpu, Float32, 2) environment!(model) @testset begin @test true # Success if no exception is thrown before this point end
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
328
push!(LOAD_PATH, "..") using Test, Suppressor using JustRelax using ParallelStencil model = PS_Setup(:cpu, Float64, 3) environment!(model) ParallelStencil.@reset_parallel_stencil model = PS_Setup(:cpu, Float32, 3) environment!(model) @testset begin @test true # Success if no exception is thrown before this point end
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
705
push!(LOAD_PATH, "..") using Test, Suppressor using JustRelax using ParallelStencil @init_parallel_stencil(Threads, Float64, 3) # setup ParallelStencil.jl environment model = PS_Setup(:cpu, Float64, 3) environment!(model) include("../miniapps/benchmarks/stokes3D/taylor_green/TaylorGreen.jl") function check_convergence_case1() nx = 16 ny = 16 nz = 16 # run model _, _, iters = taylorGreen(; nx=nx, ny=ny, nz=ny, init_MPI=JustRelax.MPI.Initialized() ? false : true, finalize_MPI=false, ) tol = 1e-8 passed = iters.err_evo1[end] < tol return passed end @testset "TaylorGreen" begin @test check_convergence_case1() end
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
1819
using JustRelax using Pkg push!(LOAD_PATH, "..") function parse_flags!(args, flag; default=nothing, typ=typeof(default)) for f in args startswith(f, flag) || continue if f != flag val = split(f, '=')[2] if !(typ ≡ nothing || typ <: AbstractString) @show typ val val = parse(typ, val) end else val = default end filter!(x -> x != f, args) return true, val end return false, default end function runtests() testdir = pwd() istest(f) = endswith(f, ".jl") && startswith(basename(f), "test_") testfiles = sort( filter( istest, vcat([joinpath.(root, files) for (root, dirs, files) in walkdir(testdir)]...), ), ) nfail = 0 printstyled("Testing package JustRelax.jl\n"; bold=true, color=:white) f0 = ("test_traits.jl", "test_types.jl", "test_arrays_conversions.jl") for f in f0 include(f) end testfiles = [f for f in testfiles if basename(f) ∉ f0] for f in testfiles occursin("burstedde", f) && continue occursin("VanKeken", f) && continue println("") println("Running tests from $f") try run(`$(Base.julia_cmd()) -O3 --startup-file=no --check-bounds=no $(joinpath(testdir, f))`) catch ex nfail += 1 end end return nfail end _, backend_name = parse_flags!(ARGS, "--backend"; default="CPU", typ=String) @static if backend_name == "AMDGPU" Pkg.add("AMDGPU") ENV["JULIA_JUSTRELAX_BACKEND"] = "AMDGPU" elseif backend_name == "CUDA" Pkg.add("CUDA") ENV["JULIA_JUSTRELAX_BACKEND"] = "CUDA" elseif backend_name == "CPU" ENV["JULIA_JUSTRELAX_BACKEND"] = "CPU" end exit(runtests())
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
11275
push!(LOAD_PATH, "..") @static if ENV["JULIA_JUSTRELAX_BACKEND"] === "AMDGPU" using AMDGPU AMDGPU.allowscalar(true) elseif ENV["JULIA_JUSTRELAX_BACKEND"] === "CUDA" using CUDA CUDA.allowscalar(true) end using Test, Suppressor using GeoParams using JustRelax, JustRelax.JustRelax2D using ParallelStencil, ParallelStencil.FiniteDifferences2D const backend_JR = @static if ENV["JULIA_JUSTRELAX_BACKEND"] === "AMDGPU" @init_parallel_stencil(AMDGPU, Float64, 2) AMDGPUBackend elseif ENV["JULIA_JUSTRELAX_BACKEND"] === "CUDA" @init_parallel_stencil(CUDA, Float64, 2) CUDABackend else @init_parallel_stencil(Threads, Float64, 2) CPUBackend end using JustPIC, JustPIC._2D # Threads is the default backend, # to run on a CUDA GPU load CUDA.jl (i.e. "using CUDA") at the beginning of the script, # and to run on an AMD GPU load AMDGPU.jl (i.e. "using AMDGPU") at the beginning of the script. const backend = @static if ENV["JULIA_JUSTRELAX_BACKEND"] === "AMDGPU" JustPIC.AMDGPUBackend elseif ENV["JULIA_JUSTRELAX_BACKEND"] === "CUDA" CUDABackend else JustPIC.CPUBackend end import JustRelax.@cell # Load script dependencies using Printf, LinearAlgebra, CellArrays # Load file with all the rheology configurations include("../miniapps/benchmarks/stokes2D/Blankenbach2D/Blankenbach_Rheology.jl") ## SET OF HELPER FUNCTIONS PARTICULAR FOR THIS SCRIPT -------------------------------- function copyinn_x!(A, B) @parallel function f_x(A, B) @all(A) = @inn_x(B) return nothing end @parallel f_x(A, B) end # Initial thermal profile @parallel_indices (i, j) function init_T!(T, y) depth = -y[j] dTdZ = (1273-273)/1000e3 offset = 273e0 T[i, j] = (depth) * dTdZ + offset return nothing end # Thermal rectangular perturbation function rectangular_perturbation!(T, xc, yc, r, xvi) @parallel_indices (i, j) function _rectangular_perturbation!(T, xc, yc, r, x, y) @inbounds if ((x[i]-xc)^2 ≤ r^2) && ((y[j] - yc)^2 ≤ r^2) T[i, j] += 20.0 end return nothing end ni = size(T) @parallel (@idx ni) _rectangular_perturbation!(T, xc, yc, r, xvi...) return nothing end ## END OF HELPER FUNCTION ------------------------------------------------------------ ## BEGIN OF MAIN SCRIPT -------------------------------------------------------------- function main2D(igg; ar=1, nx=32, ny=32, nit = 10) # Physical domain ------------------------------------ ly = 1000e3 # domain length in y lx = ly # domain length in x ni = nx, ny # number of cells li = lx, ly # domain length in x- and y- di = @. li / ni # grid step in x- and -y origin = 0.0, -ly # origin coordinates grid = Geometry(ni, li; origin = origin) (; xci, xvi) = grid # nodes at the center and vertices of the cells # ---------------------------------------------------- # Physical properties using GeoParams ---------------- rheology = init_rheologies() κ = (rheology[1].Conductivity[1].k / (rheology[1].HeatCapacity[1].Cp * rheology[1].Density[1].ρ0)) dt = dt_diff = 0.9 * min(di...)^2 / κ / 4.0 # diffusive CFL timestep limiter # ---------------------------------------------------- # Initialize particles ------------------------------- nxcell, max_xcell, min_xcell = 24, 36, 12 particles = init_particles( backend, nxcell, max_xcell, min_xcell, xvi, di, ni ) subgrid_arrays = SubgridDiffusionCellArrays(particles) # velocity grids grid_vx, grid_vy = velocity_grids(xci, xvi, di) # temperature pT, pT0, pPhases = init_cell_arrays(particles, Val(3)) particle_args = (pT, pT0, pPhases) phase_ratios = PhaseRatio(backend_JR, ni, length(rheology)) init_phases!(pPhases, particles) phase_ratios_center!(phase_ratios, particles, grid, pPhases) # ---------------------------------------------------- # STOKES --------------------------------------------- # Allocate arrays needed for every Stokes problem stokes = StokesArrays(backend_JR, ni) pt_stokes = PTStokesCoeffs(li, di; ϵ=1e-4, CFL = 1 / √2.1) # ---------------------------------------------------- # TEMPERATURE PROFILE -------------------------------- thermal = ThermalArrays(backend_JR, ni) thermal_bc = TemperatureBoundaryConditions(; no_flux = (left = true, right = true, top = false, bot = false), ) # initialize thermal profile @parallel (@idx size(thermal.T)) init_T!(thermal.T, xvi[2]) # Elliptical temperature anomaly xc_anomaly = 0.0 # origin of thermal anomaly yc_anomaly = -600e3 # origin of thermal anomaly r_anomaly = 100e3 # radius of perturbation rectangular_perturbation!(thermal.T, xc_anomaly, yc_anomaly, r_anomaly, xvi) thermal_bcs!(thermal, thermal_bc) thermal.Told .= thermal.T temperature2center!(thermal) # ---------------------------------------------------- # Rayleigh number ΔT = thermal.T[1,1] - thermal.T[1,end] Ra = (rheology[1].Density[1].ρ0 * rheology[1].Gravity[1].g * rheology[1].Density[1].α * ΔT * ly^3.0 ) / (κ * rheology[1].CompositeRheology[1].elements[1].η ) @show Ra args = (; T = thermal.Tc, P = stokes.P, dt = Inf) # Buoyancy forces & viscosity ---------------------- ρg = @zeros(ni...), @zeros(ni...) η = @ones(ni...) compute_ρg!(ρg[2], phase_ratios, rheology, args) compute_viscosity!( stokes, phase_ratios, args, rheology, (-Inf, Inf) ) # PT coefficients for thermal diffusion ------------- pt_thermal = PTThermalCoeffs( backend_JR, rheology, phase_ratios, args, dt, ni, di, li; ϵ=1e-5, CFL = 0.5 / √2.1 ) # Boundary conditions ------------------------------- flow_bcs = VelocityBoundaryConditions(; free_slip = (left = true, right=true, top=true, bot=true), ) flow_bcs!(stokes, flow_bcs) # apply boundary conditions update_halo!(@velocity(stokes)...) T_buffer = @zeros(ni.+1) Told_buffer = similar(T_buffer) dt₀ = similar(stokes.P) for (dst, src) in zip((T_buffer, Told_buffer), (thermal.T, thermal.Told)) copyinn_x!(dst, src) end grid2particle!(pT, xvi, T_buffer, particles) pT0.data .= pT.data local Vx_v, Vy_v, iters # Time loop t, it = 0.0, 1 Urms = Float64[] Nu_top = Float64[] trms = Float64[] # Buffer arrays to compute velocity rms Vx_v = @zeros(ni.+1...) Vy_v = @zeros(ni.+1...) while it ≤ nit @show it # Update buoyancy and viscosity - args = (; T = thermal.Tc, P = stokes.P, dt=Inf) compute_viscosity!(stokes, phase_ratios, args, rheology, (-Inf, Inf)) compute_ρg!(ρg[2], phase_ratios, rheology, args) # ------------------------------ # Stokes solver ---------------- iters = solve!( stokes, pt_stokes, di, flow_bcs, ρg, phase_ratios, rheology, args, Inf, igg; kwargs = (; iterMax = 150e3, nout = 200, viscosity_cutoff = (-Inf, Inf), verbose = true ) ) dt = compute_dt(stokes, di, dt_diff) # ------------------------------ # Thermal solver --------------- heatdiffusion_PT!( thermal, pt_thermal, thermal_bc, rheology, args, dt, di; kwargs = (; igg = igg, phase = phase_ratios, iterMax = 10e3, nout = 1e2, verbose = true, ) ) for (dst, src) in zip((T_buffer, Told_buffer), (thermal.T, thermal.Told)) copyinn_x!(dst, src) end subgrid_characteristic_time!( subgrid_arrays, particles, dt₀, phase_ratios, rheology, thermal, stokes, xci, di ) centroid2particle!(subgrid_arrays.dt₀, xci, dt₀, particles) subgrid_diffusion!( pT, T_buffer, thermal.ΔT[2:end-1, :], subgrid_arrays, particles, xvi, di, dt ) # ------------------------------ # Advection -------------------- # advect particles in space advection!(particles, RungeKutta2(), @velocity(stokes), (grid_vx, grid_vy), dt) # advect particles in memory move_particles!(particles, xvi, particle_args) # check if we need to inject particles inject_particles_phase!(particles, pPhases, (pT, ), (T_buffer, ), xvi) # update phase ratios phase_ratios_center!(phase_ratios, particles, grid, pPhases) # Nusselt number, Nu = H/ΔT/L ∫ ∂T/∂z dx ---- Nu_it = (ly / (1000.0*lx)) * sum( ((abs.(thermal.T[2:end-1,end] - thermal.T[2:end-1,end-1])) ./ di[2]) .*di[1]) push!(Nu_top, Nu_it) # ------------------------------------------- # Compute U rms ----------------------------- # U₍ᵣₘₛ₎ = H*ρ₀*c₍ₚ₎/k * √ 1/H/L * ∫∫ (vx²+vz²) dx dz Urms_it = let JustRelax.JustRelax2D.velocity2vertex!(Vx_v, Vy_v, stokes.V.Vx, stokes.V.Vy; ghost_nodes=true) @. Vx_v .= hypot.(Vx_v, Vy_v) # we reuse Vx_v to store the velocity magnitude sqrt( sum( Vx_v.^2 .* prod(di)) / lx /ly ) * ((ly * rheology[1].Density[1].ρ0 * rheology[1].HeatCapacity[1].Cp) / rheology[1].Conductivity[1].k ) end push!(Urms, Urms_it) push!(trms, t) # ------------------------------------------- # interpolate fields from particle to grid vertices particle2grid!(T_buffer, pT, xvi, particles) @views T_buffer[:, end] .= 273.0 @views T_buffer[:, 1] .= 1273.0 @views thermal.T[2:end-1, :] .= T_buffer flow_bcs!(stokes, flow_bcs) # apply boundary conditions temperature2center!(thermal) it += 1 t += dt # ------------------------------ end # Horizontally averaged depth profile Tmean = @zeros(ny+1) Emean = @zeros(ny) @show Urms[Int64(nit)] Nu_top[Int64(nit)] return Urms, Nu_top, iters end ## END OF MAIN SCRIPT ---------------------------------------------------------------- @testset "Blankenbach 2D" begin @suppress begin nx, ny = 32, 32 # number of cells igg = if !(JustRelax.MPI.Initialized()) # initialize (or not) MPI grid IGG(init_global_grid(nx, ny, 1; init_MPI= true)...) else igg end Urms, Nu_top, iters = main2D(igg; nx = nx, ny = ny); @test Urms[end] ≈ 0.33 rtol=1e-1 @test Nu_top[end] ≈ 1.0312 rtol=1e-2 @test iters.err_evo1[end] < 1e-4 end end
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
1067
@static if ENV["JULIA_JUSTRELAX_BACKEND"] === "AMDGPU" using AMDGPU AMDGPU.allowscalar(true) elseif ENV["JULIA_JUSTRELAX_BACKEND"] === "CUDA" using CUDA CUDA.allowscalar(true) end using Test, StaticArrays using JustRelax, JustRelax.JustRelax2D using ParallelStencil @static if ENV["JULIA_JUSTRELAX_BACKEND"] === "AMDGPU" @init_parallel_stencil(AMDGPU, Float64, 2) elseif ENV["JULIA_JUSTRELAX_BACKEND"] === "CUDA" @init_parallel_stencil(CUDA, Float64, 2) else @init_parallel_stencil(Threads, Float64, 2) end @testset "CellArrays 2D" begin ni = 5, 5 A = @fill(false, ni..., celldims=(2,), eltype=Bool) @test cellaxes(A) === Base.OneTo(2) @test cellnum(A) == 2 @test new_empty_cell(A) === SA[false, false] @test @cell(A[1, 1, 1]) === false # @test (@allocated @cell A[1, 1, 1]) === 0 @cell A[1, 1, 1] = true @test @cell(A[1, 1, 1]) === true # @test (@allocated @cell A[1, 1, 1] = true) === 0 @test A[1, 1] === SA[true, false] end
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
1113
using Test, StaticArrays, AllocCheck using Suppressor @static if ENV["JULIA_JUSTRELAX_BACKEND"] === "AMDGPU" using AMDGPU AMDGPU.allowscalar(true) elseif ENV["JULIA_JUSTRELAX_BACKEND"] === "CUDA" using CUDA CUDA.allowscalar(true) end using JustRelax, JustRelax.JustRelax3D using ParallelStencil @static if ENV["JULIA_JUSTRELAX_BACKEND"] === "AMDGPU" @init_parallel_stencil(AMDGPU, Float64, 3) elseif ENV["JULIA_JUSTRELAX_BACKEND"] === "CUDA" @init_parallel_stencil(CUDA, Float64, 3) else @init_parallel_stencil(Threads, Float64, 3) end @testset "CellArrays 3D" begin @suppress begin ni = 5, 5, 5 A = @fill(false, ni..., celldims=(2,), eltype=Bool) @test @cell(A[1, 1, 1, 1]) === false # @test (@allocated @cell A[1, 1, 1, 1]) == 0 ; @cell A[1, 1, 1, 1] = true @test @cell(A[1, 1, 1, 1]) === true # @test (@allocated @cell A[1, 1, 1, 1] = true) == 0 @test A[1, 1, 1] == SA[true, false] # allocs = check_allocs(getindex, (typeof(A), Int64, Int64, Int64)) # @test isempty(allocs) end end
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
7275
using Test, Suppressor using JustRelax, JustRelax.JustRelax2D, JustRelax.DataIO const backend_JR = CPUBackend using ParallelStencil, ParallelStencil.FiniteDifferences2D @init_parallel_stencil(Threads, Float64, 2) #or (CUDA, Float64, 2) or (AMDGPU, Float64, 2) using JustPIC, JustPIC._2D # Threads is the default backend, # to run on a CUDA GPU load CUDA.jl (i.e. "using CUDA") at the beginning of the script, # and to run on an AMD GPU load AMDGPU.jl (i.e. "using AMDGPU") at the beginning of the script. const backend = CPUBackend # Options: CPUBackend, CUDABackend, AMDGPUBackend # const backend = CUDABackend # Options: CPUBackend, CUDABackend, AMDGPUBackend # Load script dependencies using GeoParams using WriteVTK @testset "Test IO" begin @suppress begin # Set up mock data # Physical domain ------------------------------------ ly = 1.0 # domain length in y lx = 1.0 # domain length in x nx, ny, nz = 4, 4, 4 # number of cells ni = nx, ny # number of cells igg = IGG(init_global_grid(nx, ny, 1; init_MPI= true)...) li = lx, ly # domain length in x- and y- di = @. li / ni # grid step in x- and -y origin = 0.0, -ly # origin coordinates (15km f sticky air layer) grid = Geometry(ni, li; origin = origin) (; xci, xvi) = grid # 2D case dst = "test_IO" stokes = StokesArrays(backend_JR, ni) thermal = ThermalArrays(backend_JR, 4,4) @test size(thermal.Tc) === (4,4) thermal = ThermalArrays(backend_JR, ni) @test size(thermal.Tc) === (4,4) nxcell, max_xcell, min_xcell = 20, 32, 12 particles = init_particles( backend, nxcell, max_xcell, min_xcell, xvi...) # temperature pT, pPhases = init_cell_arrays(particles, Val(2)) time = 1.0 dt = 0.1 stokes.viscosity.η .= @fill(1.0) stokes.V.Vy .= @fill(10) thermal.T .= @fill(100) # Save metadata to directory metadata(pwd(), dst, "test_traits.jl", "test_types.jl") @test isfile(joinpath(dst, "test_traits.jl")) @test isfile(joinpath(dst, "test_types.jl")) @test isfile(joinpath(dst, "Project.toml")) # Call the function checkpointing_jld2(dst, stokes, thermal, time, dt, igg) checkpointing_jld2(dst, stokes, thermal, time, dt) # Check that the file was created fname = joinpath(dst, "checkpoint" * lpad("$(igg.me)", 4, "0") * ".jld2") @test isfile(fname) # Load the data from the file stokes1, thermal1, t, dt1 = load_checkpoint_jld2(fname) @test stokes1.viscosity.η[1] == 1.0 @test stokes1.V.Vy[1] == 10 @test thermal1.T[1] == 100 @test isnothing(stokes.V.Vz) @test dt1 == 0.1 # check the if the hdf5 function also works checkpointing_hdf5(dst, stokes, thermal.T, time, dt) # Check that the file was created fname = joinpath(dst, "checkpoint.h5") @test isfile(fname) # Load the data from the file P, T, Vx, Vy, Vz, η, t, dt = load_checkpoint_hdf5(fname) stokes.viscosity.η .= η stokes.V.Vy .= Vy thermal.T .= T @test stokes.viscosity.η[1] == 1.0 @test stokes.V.Vy[1] == 10 @test thermal.T[1] == 100 @test isnothing(Vz) @test dt == 0.1 # test VTK save Vx_v = @zeros(ni.+1...) Vy_v = @zeros(ni.+1...) velocity2vertex!(Vx_v, Vy_v, @velocity(stokes)...) data_v = (; T = Array(thermal.T), τII = Array(stokes.τ.II), εII = Array(stokes.ε.II), Vx = Array(Vx_v), Vy = Array(Vy_v), ) data_c = (; P = Array(stokes.P), η = Array(stokes.viscosity.η), ) velocity_v = ( Array(Vx_v), Array(Vy_v), ) save_vtk( joinpath(dst, "vtk_" * lpad("1", 6, "0")), xvi, xci, data_v, data_c, velocity_v ) @test isfile(joinpath(dst, "vtk_000001_1.vti")) @test isfile(joinpath(dst, "vtk_000001_2.vti")) @test isfile(joinpath(dst, "vtk_000001.vtm")) save_vtk( joinpath(dst, "vtk_" * lpad("2", 6, "0")), xci, (P=stokes.P, η=stokes.viscosity.η), ) @test isfile(joinpath(dst, "vtk_000002.vti")) # VTK data series vtk = VTKDataSeries(joinpath(dst, "vtk_series"), xci) @test vtk isa VTKDataSeries DataIO.append!(vtk, (Vy=stokes.V.Vy, η=stokes.viscosity.η), dt, time) @test isfile(joinpath(dst, "vtk_series.pvd")) # 3D case ni = nx, ny, nz stokes = StokesArrays(backend_JR, ni) thermal = ThermalArrays(backend_JR, 4,4,4) @test size(thermal.Tc) === (4,4,4) thermal = ThermalArrays(backend_JR, ni) @test size(thermal.Tc) === (4,4,4) nxcell, max_xcell, min_xcell = 20, 32, 12 particles = init_particles( backend, nxcell, max_xcell, min_xcell, xvi...) # temperature pT, pPhases = init_cell_arrays(particles, Val(2)) time = 1.0 dt = 0.1 stokes.viscosity.η .= fill(1.0) stokes.V.Vy .= fill(10) thermal.T .= fill(100) # Call the function checkpointing_jld2(dst, stokes, thermal, time, dt, igg) checkpointing_jld2(dst, stokes, thermal, time, dt) # Check that the file was created fname = joinpath(dst, "checkpoint" * lpad("$(igg.me)", 4, "0") * ".jld2") @test isfile(fname) # Load the data from the file load_checkpoint_jld2(fname) @test stokes.viscosity.η[1] == 1.0 @test stokes.V.Vy[1] == 10 @test thermal.T[1] == 100 @test !isnothing(stokes.V.Vz) # check the if the hdf5 function also works checkpointing_hdf5(dst, stokes, thermal.T, time, dt) # Check that the file was created fname = joinpath(dst, "checkpoint.h5") @test isfile(fname) # Load the data from the file P, T, Vx, Vy, Vz, η, t, dt = load_checkpoint_hdf5(fname) stokes.viscosity.η .= η stokes.V.Vy .= Vy thermal.T .= T @test stokes.viscosity.η[1] == 1.0 @test stokes.V.Vy[1] == 10 @test thermal.T[1] == 100 @test !isnothing(Vz) # Test center and vertex coordinates function xci_c = center_coordinates(grid) @test (xci_c[1][1],xci_c[1][end]) === (0.125, 0.875) @test (xci_c[2][1],xci_c[2][end]) === (-0.875,-0.125) xvi_v = vertex_coordinates(grid) @test (xvi_v[1][1],xvi_v[1][end]) === (0.0, 1.0) @test (xvi_v[2][1],xvi_v[2][end]) === (-1.0, 0.0) # test save_data function save_data(joinpath(dst,"save_data.hdf5"), grid) @test isfile(joinpath(dst,"save_data.hdf5")) # Remove the generated directory rm(dst, recursive=true) end end
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
2370
push!(LOAD_PATH, "..") @static if ENV["JULIA_JUSTRELAX_BACKEND"] === "AMDGPU" using AMDGPU AMDGPU.allowscalar(true) elseif ENV["JULIA_JUSTRELAX_BACKEND"] === "CUDA" using CUDA CUDA.allowscalar(true) end using Test using JustRelax, JustRelax.JustRelax2D import JustRelax.JustRelax2D: interp_Vx∂ρ∂x_on_Vy!, interp_Vx_on_Vy! using ParallelStencil, ParallelStencil.FiniteDifferences2D const backend_JR = @static if ENV["JULIA_JUSTRELAX_BACKEND"] === "AMDGPU" @init_parallel_stencil(AMDGPU, Float64, 2) AMDGPUBackend elseif ENV["JULIA_JUSTRELAX_BACKEND"] === "CUDA" @init_parallel_stencil(CUDA, Float64, 2) CUDABackend else @init_parallel_stencil(Threads, Float64, 2) CPUBackend end @testset "Interpolations" begin # Set up mock data # Physical domain ------------------------------------ ly = 1.0 # domain length in y lx = 1.0 # domain length in x nx, ny, nz = 4, 4, 4 # number of cells ni = nx, ny # number of cells li = lx, ly # domain length in x- and y-direction di = @. li / ni # grid step in x- and y-direction origin = 0.0, -ly # origin coordinates (15km f sticky air layer) grid = Geometry(ni, li; origin = origin) (; xci, xvi) = grid # 2D case stokes = StokesArrays(backend_JR, ni) thermal = ThermalArrays(backend_JR, ni) ρg = @ones(ni) stokes.viscosity.η .= 1 stokes.V.Vy .= 10 thermal.T .= 100 thermal.Told .= 50 stokes.τ.xy_c .= 1 temperature2center!(thermal) @test thermal.Tc[1,1] == 100 thermal.ΔT .= thermal.T .- thermal.Told vertex2center!(thermal.ΔTc, thermal.ΔT) @test thermal.ΔTc[1,1] == 50 center2vertex!(stokes.τ.xy, stokes.τ.xy_c) @test stokes.τ.xy[2,2] == 1 Vx_v = @ones(ni.+1...) Vy_v = @ones(ni.+1...) velocity2vertex!(Vx_v, Vy_v, stokes.V.Vx, stokes.V.Vy) @test iszero(Vx_v[1,1]) @test Vy_v[1,1] == 10 Vx_v = @ones(ni.+1...) Vy_v = @ones(ni.+1...) velocity2vertex!(Vx_v, Vy_v, stokes.V.Vx, stokes.V.Vy; ghost_nodes=false) @test iszero(Vx_v[1,1]) @test Vy_v[1,1] == 10 end
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
6836
@static if ENV["JULIA_JUSTRELAX_BACKEND"] === "AMDGPU" using AMDGPU elseif ENV["JULIA_JUSTRELAX_BACKEND"] === "CUDA" using CUDA end using Test using Statistics using JustRelax, JustRelax.JustRelax2D, JustRelax.DataIO import JustRelax.JustRelax2D: detect_args_size, _tuple, continuation_linear, continuation_log, assign!, mean_mpi, norm_mpi, minimum_mpi, maximum_mpi using ParallelStencil, ParallelStencil.FiniteDifferences2D const backend_JR = @static if ENV["JULIA_JUSTRELAX_BACKEND"] === "AMDGPU" @init_parallel_stencil(AMDGPU, Float64, 2) AMDGPUBackend elseif ENV["JULIA_JUSTRELAX_BACKEND"] === "CUDA" @init_parallel_stencil(CUDA, Float64, 2) CUDABackend else @init_parallel_stencil(Threads, Float64, 2) CPUBackend end using JustPIC, JustPIC._2D # Threads is the default backend, # to run on a CUDA GPU load CUDA.jl (i.e. "using CUDA") at the beginning of the script, # and to run on an AMD GPU load AMDGPU.jl (i.e. "using AMDGPU") at the beginning of the script. const backend = @static if ENV["JULIA_JUSTRELAX_BACKEND"] === "AMDGPU" JustPIC.AMDGPUBackend elseif ENV["JULIA_JUSTRELAX_BACKEND"] === "CUDA" CUDABackend else JustPIC.CPUBackend end @testset "Utils" begin @testset "Macros" begin # Set up mock data # Physical domain ------------------------------------ ly = 1.0 # domain length in y lx = 1.0 # domain length in x nx, ny, nz = 4, 4, 4 # number of cells ni = nx, ny # number of cells igg = IGG(init_global_grid(nx, ny, 1; init_MPI= true)...) li = lx, ly # domain length in x- and y- di = @. li / ni # grid step in x- and -y origin = 0.0, -ly # origin coordinates (15km f sticky air layer) grid = Geometry(ni, li; origin = origin) (; xci, xvi) = grid # 2D case dst = "test_Utils" stokes = StokesArrays(backend_JR, ni) thermal = ThermalArrays(backend_JR, ni) take(dst) @test isdir(dst) rm(dst; recursive=true) nxcell, max_xcell, min_xcell = 20, 32, 12 particles = init_particles(backend, nxcell, max_xcell, min_xcell, xvi...) # temperature pT, pPhases = init_cell_arrays(particles, Val(2)) time = 1.0 dt = 0.1 stokes.viscosity.η .= @fill(1.0) stokes.V.Vy .= @fill(10) thermal.T .= @fill(100) args = (P = stokes.P, T = thermal.T) tuple_args = (args.P, args.T) @test detect_args_size(tuple_args) == (7, 5) # Stokes @test _tuple(stokes.τ) === (stokes.τ.xx, stokes.τ.yy, stokes.τ.xy_c) @test _tuple(stokes.V) === (stokes.V.Vx, stokes.V.Vy) @test @velocity(stokes) === (stokes.V.Vx, stokes.V.Vy) @test @displacement(stokes) === (stokes.U.Ux, stokes.U.Uy) @test @strain(stokes) === (stokes.ε.xx, stokes.ε.yy, stokes.ε.xy) @test @strain_center(stokes) === (stokes.ε.xx, stokes.ε.yy, stokes.ε.xy_c) @test @plastic_strain(stokes) === (stokes.ε_pl.xx, stokes.ε_pl.yy, stokes.ε_pl.xy) @test @stress(stokes) === (stokes.τ.xx, stokes.τ.yy, stokes.τ.xy) @test @stress_center(stokes) === (stokes.τ.xx, stokes.τ.yy, stokes.τ.xy_c) @test @tensor(stokes.τ_o) === (stokes.τ_o.xx, stokes.τ_o.yy, stokes.τ_o.xy) @test @tensor_center(stokes.τ) === (stokes.τ.xx, stokes.τ.yy, stokes.τ.xy_c) @test @shear(stokes.τ) === (stokes.τ.xy) @test @normal(stokes.τ) === (stokes.τ.xx, stokes.τ.yy) @test @residuals(stokes.R) === (stokes.R.Rx, stokes.R.Ry) # Thermal @test @qT(thermal) === (thermal.qTx, thermal.qTy) @test @qT2(thermal) === (thermal.qTx2, thermal.qTy2) # other functions dt_diff = 0.1 @test compute_dt(stokes, di, dt_diff, igg) === 0.011904761904761904 @test compute_dt(stokes, di, dt_diff) === 0.011904761904761904 @test compute_dt(stokes, di) ≈ 0.011904761904761904 @test continuation_log(1.0, 0.8, 0.05) ≈ 0.8089757207980266 @test continuation_linear(1.0, 0.8, 0.05) === 0.81 #MPI @test mean_mpi(stokes.viscosity.η) === 1.0 @test norm_mpi(stokes.viscosity.η) === 4.0 @test minimum_mpi(stokes.viscosity.η) === 1.0 @test maximum_mpi(stokes.viscosity.η) === 1.0 # 3D case ni = nx, ny, nz stokes = StokesArrays(backend_JR, ni) thermal = ThermalArrays(backend_JR, ni) stokes.viscosity.η .= @fill(1.0) stokes.V.Vy .= @fill(10) thermal.T .= @fill(100) # Stokes @test _tuple(stokes.τ) === (stokes.τ.xx, stokes.τ.yy, stokes.τ.zz, stokes.τ.yz_c, stokes.τ.xz_c, stokes.τ.xy_c) @test _tuple(stokes.V) === (stokes.V.Vx,stokes.V.Vy, stokes.V.Vz) @test @velocity(stokes) === (stokes.V.Vx, stokes.V.Vy, stokes.V.Vz) @test @displacement(stokes) === (stokes.U.Ux, stokes.U.Uy, stokes.U.Uz) @test @strain(stokes) === (stokes.ε.xx, stokes.ε.yy, stokes.ε.zz, stokes.ε.yz, stokes.ε.xz, stokes.ε.xy) @test @strain_center(stokes) === (stokes.ε.xx, stokes.ε.yy, stokes.ε.zz, stokes.ε.yz_c, stokes.ε.xz_c, stokes.ε.xy_c) @test @plastic_strain(stokes) === (stokes.ε_pl.xx, stokes.ε_pl.yy, stokes.ε_pl.zz, stokes.ε_pl.yz, stokes.ε_pl.xz, stokes.ε_pl.xy) @test @stress(stokes) === (stokes.τ.xx, stokes.τ.yy, stokes.τ.zz, stokes.τ.yz, stokes.τ.xz, stokes.τ.xy) @test @stress_center(stokes) === (stokes.τ.xx, stokes.τ.yy, stokes.τ.zz, stokes.τ.yz_c, stokes.τ.xz_c, stokes.τ.xy_c) @test @tensor(stokes.τ_o) === (stokes.τ_o.xx, stokes.τ_o.yy, stokes.τ_o.zz, stokes.τ_o.yz, stokes.τ_o.xz, stokes.τ_o.xy) @test @tensor_center(stokes.τ) === (stokes.τ.xx, stokes.τ.yy, stokes.τ.zz, stokes.τ.yz_c, stokes.τ.xz_c, stokes.τ.xy_c) @test @shear(stokes.τ) === (stokes.τ.yz, stokes.τ.xz, stokes.τ.xy) @test @normal(stokes.τ) === (stokes.τ.xx, stokes.τ.yy, stokes.τ.zz) @test @residuals(stokes.R) === (stokes.R.Rx, stokes.R.Ry, stokes.R.Rz) # Thermal @test @qT(thermal) === (thermal.qTx, thermal.qTy, thermal.qTz) @test @qT2(thermal) === (thermal.qTx2, thermal.qTy2, thermal.qTz2) # other functions dt_diff = 0.1 @test compute_dt(stokes, di, dt_diff, igg) === 0.008064516129032258 @test compute_dt(stokes, di, dt_diff) ≈ 0.008064516129032258 @test compute_dt(stokes, di) ≈ 0.008064516129032258 #MPI @test mean_mpi(stokes.viscosity.η) === 1.0 @test norm_mpi(stokes.viscosity.η) === 8.0 @test minimum_mpi(stokes.viscosity.η) === 1.0 @test maximum_mpi(stokes.viscosity.η) === 1.0 end end
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
6856
push!(LOAD_PATH, "..") using Test, Suppressor @static if ENV["JULIA_JUSTRELAX_BACKEND"] === "AMDGPU" using AMDGPU elseif ENV["JULIA_JUSTRELAX_BACKEND"] === "CUDA" using CUDA end using Printf, LinearAlgebra, GeoParams, CellArrays using JustRelax, JustRelax.JustRelax2D import JustRelax.@cell using ParallelStencil const backend_JR = @static if ENV["JULIA_JUSTRELAX_BACKEND"] === "AMDGPU" @init_parallel_stencil(AMDGPU, Float64, 2) AMDGPUBackend elseif ENV["JULIA_JUSTRELAX_BACKEND"] === "CUDA" @init_parallel_stencil(CUDA, Float64, 2) CUDABackend else @init_parallel_stencil(Threads, Float64, 2) CPUBackend end using JustPIC, JustPIC._2D # Threads is the default backend, # to run on a CUDA GPU load CUDA.jl (i.e. "using CUDA") at the beginning of the script, # and to run on an AMD GPU load AMDGPU.jl (i.e. "using AMDGPU") at the beginning of the script. const backend = @static if ENV["JULIA_JUSTRELAX_BACKEND"] === "AMDGPU" JustPIC.AMDGPUBackend elseif ENV["JULIA_JUSTRELAX_BACKEND"] === "CUDA" JustPIC.CUDABackend else JustPIC.CPUBackend end # x-length of the domain const λ = 0.9142 # HELPER FUNCTIONS --------------------------------------------------------------- # Initialize phases on the particles function init_phases!(phases, particles) ni = size(phases) @parallel_indices (i, j) function init_phases!(phases, px, py, index) @inbounds for ip in JustRelax.cellaxes(phases) # quick escape JustRelax.@cell(index[ip, i, j]) == 0 && continue x = JustRelax.@cell px[ip, i, j] y = JustRelax.@cell py[ip, i, j] # plume - rectangular if y > 0.2 + 0.02 * cos(π * x / λ) JustRelax.@cell phases[ip, i, j] = 2.0 else JustRelax.@cell phases[ip, i, j] = 1.0 end end return nothing end @parallel (@idx ni) init_phases!(phases, particles.coords..., particles.index) end # END OF HELPER FUNCTIONS -------------------------------------------------------- # MAIN SCRIPT -------------------------------------------------------------------- function VanKeken2D(ny=32, nx=32) init_mpi = JustRelax.MPI.Initialized() ? false : true igg = IGG(init_global_grid(nx, ny, 1; init_MPI = init_mpi)...) # Physical domain ------------------------------------ ly = 1 # domain length in y lx = ly # domain length in x ni = nx, ny # number of cells li = lx, ly # domain length in x- and y- di = @. li / ni # grid step in x- and -y origin = 0.0, 0.0 # origin coordinates grid = Geometry(ni, li; origin = origin) (; xci, xvi) = grid # nodes at the center and vertices of the cells dt = 1 # Physical properties using GeoParams ---------------- rheology = ( # Low density phase SetMaterialParams(; Phase = 1, Density = ConstantDensity(; ρ = 1), Gravity = ConstantGravity(; g = 1), CompositeRheology = CompositeRheology((LinearViscous(; η = 1e0),)), ), # High density phase SetMaterialParams(; Phase = 2, Density = ConstantDensity(; ρ = 2), Gravity = ConstantGravity(; g = 1), CompositeRheology = CompositeRheology((LinearViscous(;η = 1e0),)), ), ) # Initialize particles ------------------------------- nxcell, max_p, min_p = 40, 80, 20 particles = init_particles( backend, nxcell, max_p, min_p, xvi..., di..., nx, ny ) # velocity grids grid_vx, grid_vy = velocity_grids(xci, xvi, di) # temperature pPhases, = init_cell_arrays(particles, Val(1)) particle_args = (pPhases, ) phase_ratios = PhaseRatio(backend_JR, ni, length(rheology)) init_phases!(pPhases, particles) phase_ratios_center!(phase_ratios, particles, grid, pPhases) # STOKES --------------------------------------------- # Allocate arrays needed for every Stokes problem stokes = StokesArrays(backend_JR, ni) pt_stokes = PTStokesCoeffs(li, di; r=1e0, ϵ=1e-8, CFL = 1 / √2.1) # Buoyancy forces ρg = @zeros(ni...), @zeros(ni...) args = (; T = @zeros(ni...), P = stokes.P, dt = dt) compute_ρg!(ρg[2], phase_ratios, rheology, args) # Rheology compute_viscosity!(stokes, phase_ratios, args, rheology, (-Inf, Inf)) # Boundary conditions flow_bcs = VelocityBoundaryConditions(; free_slip = (left = true, right = true, top = false, bot = false), no_slip = (left = false, right = false, top = true, bot = true), ) flow_bcs!(stokes, flow_bcs) update_halo!(@velocity(stokes)...) # Buffer arrays to compute velocity rms Vx_v = @zeros(ni.+1...) Vy_v = @zeros(ni.+1...) # Time loop t, it = 0.0, 0 tmax = 0.5e3 nt = 500 Urms = Float64[] trms = Float64[] sizehint!(Urms, 100000) sizehint!(trms, 100000) local iters, Urms while it < nt # Stokes solver ---------------- iters = solve!( stokes, pt_stokes, di, flow_bcs, ρg, phase_ratios, rheology, args, dt, igg; kwargs = ( iterMax = 10e3, nout = 50, viscosity_cutoff = (-Inf, Inf) ) ) dt = compute_dt(stokes, di) / 10 # ------------------------------ # Compute U rms --------------- Urms_it = let velocity2vertex!(Vx_v, Vy_v, stokes.V.Vx, stokes.V.Vy; ghost_nodes=true) @. Vx_v .= hypot.(Vx_v, Vy_v) # we reuse Vx_v to store the velocity magnitude sum(Vx_v.^2) * prod(di) |> sqrt end push!(Urms, Urms_it) push!(trms, t) # ------------------------------ # advect particles in space advection!(particles, RungeKutta2(), @velocity(stokes), (grid_vx, grid_vy), dt) # # advect particles in memory move_particles!(particles, xvi, particle_args) # inject && break inject_particles_phase!(particles, pPhases, (), (), xvi) # update phase ratios phase_ratios_center!(phase_ratios, particles, grid, pPhases) @show it += 1 t += dt end return iters, Urms end @testset "VanKeken" begin @suppress begin iters, Urms = VanKeken2D() @test passed = iters.err_evo1[end] < 1e-4 @test all(<(1e-2), Urms) end end
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
10176
push!(LOAD_PATH, "..") @static if ENV["JULIA_JUSTRELAX_BACKEND"] === "AMDGPU" using AMDGPU AMDGPU.allowscalar(true) elseif ENV["JULIA_JUSTRELAX_BACKEND"] === "CUDA" using CUDA CUDA.allowscalar(true) end using Test, Suppressor using JustRelax, JustRelax.JustRelax2D using ParallelStencil, ParallelStencil.FiniteDifferences2D const backend_JR = @static if ENV["JULIA_JUSTRELAX_BACKEND"] === "AMDGPU" @init_parallel_stencil(AMDGPU, Float64, 2) AMDGPUBackend elseif ENV["JULIA_JUSTRELAX_BACKEND"] === "CUDA" @init_parallel_stencil(CUDA, Float64, 2) CUDABackend else @init_parallel_stencil(Threads, Float64, 2) CPUBackend end import JustRelax.@cell using GeoParams, SpecialFunctions # function to compute strain rate (compulsory) @inline function custom_εII(a::CustomRheology, TauII; args...) η = custom_viscosity(a; args...) return TauII / η * 0.5 end # function to compute deviatoric stress (compulsory) @inline function custom_τII(a::CustomRheology, EpsII; args...) η = custom_viscosity(a; args...) return 2.0 * η * EpsII end # helper function (optional) @inline function custom_viscosity(a::CustomRheology; P=0.0, T=273.0, depth=0.0, kwargs...) (; η0, Ea, Va, T0, R, cutoff) = a.args η = η0 * exp((Ea + P * Va) / (R * T) - Ea / (R * T0)) correction = (depth ≤ 660e3) + (2740e3 ≥ depth > 660e3) * 1e1 + (depth > 2700e3) * 1e-1 η = clamp(η * correction, cutoff...) end # HELPER FUNCTIONS --------------------------------------------------------------- import ParallelStencil.INDICES const idx_j = INDICES[2] macro all_j(A) esc(:($A[$idx_j])) end @parallel function init_P!(P, ρg, z) @all(P) = @all(ρg) * abs(@all_j(z)) return nothing end # Half-space-cooling model @parallel_indices (i, j) function init_T!(T, z, κ, Tm, Tp, Tmin, Tmax) yr = 3600*24*365.25 dTdz = (Tm-Tp)/2890e3 zᵢ = abs(z[j]) Tᵢ = Tp + dTdz*(zᵢ) time = 100e6 * yr Ths = Tmin + (Tm -Tmin) * erf((zᵢ)*0.5/(κ*time)^0.5) T[i, j] = min(Tᵢ, Ths) return end function circular_perturbation!(T, δT, xc, yc, r, xvi) @parallel_indices (i, j) function _circular_perturbation!(T, δT, xc, yc, r, x, y) @inbounds if (((x[i] - xc))^2 + ((y[j] - yc))^2) ≤ r^2 T[i, j] *= δT / 100 + 1 end return nothing end @parallel _circular_perturbation!(T, δT, xc, yc, r, xvi...) end function random_perturbation!(T, δT, xbox, ybox, xvi) @parallel_indices (i, j) function _random_perturbation!(T, δT, xbox, ybox, x, y) @inbounds if (xbox[1] ≤ x[i] ≤ xbox[2]) && (abs(ybox[1]) ≤ abs(y[j]) ≤ abs(ybox[2])) δTi = δT * (rand() - 0.5) # random perturbation within ±δT [%] T[i, j] *= δTi / 100 + 1 end return nothing end @parallel (@idx size(T)) _random_perturbation!(T, δT, xbox, ybox, xvi...) end # -------------------------------------------------------------------------------- # BEGIN MAIN SCRIPT # -------------------------------------------------------------------------------- function thermal_convection2D(igg; ar=8, ny=16, nx=ny*8, thermal_perturbation = :circular) # Physical domain ------------------------------------ ly = 2890e3 lx = ly * ar origin = 0.0, -ly # origin coordinates ni = nx, ny # number of cells li = lx, ly # domain length in x- and y- di = @. li / ni # grid step in x- and -y grid = Geometry(ni, li; origin = origin) (; xci, xvi) = grid # nodes at the center and vertices of the cells # ---------------------------------------------------- # Weno model ----------------------------------------- weno = WENO5(ni = ni .+ 1, method = Val(2)) # ni.+1 for Temp # ---------------------------------------------------- # create rheology struct v_args = (; η0=5e20, Ea=200e3, Va=2.6e-6, T0=1.6e3, R=8.3145, cutoff=(1e16, 1e25)) creep = CustomRheology(custom_εII, custom_τII, v_args) # Physical properties using GeoParams ---------------- η_reg = 1e16 G0 = 70e9 # shear modulus cohesion = 30e6 friction = asind(0.01) pl = DruckerPrager_regularised(; C = cohesion, ϕ=friction, η_vp=η_reg, Ψ=0.0) # non-regularized plasticity el = SetConstantElasticity(; G=G0, ν=0.5) # elastic spring β = inv(get_Kb(el)) rheology = SetMaterialParams(; Name = "Mantle", Phase = 1, Density = PT_Density(; ρ0=3.1e3, β=β, T0=0.0, α = 1.5e-5), HeatCapacity = ConstantHeatCapacity(; Cp=1.2e3), Conductivity = ConstantConductivity(; k=3.0), CompositeRheology = CompositeRheology((creep, el, )), Elasticity = el, Gravity = ConstantGravity(; g=9.81), ) rheology_plastic = SetMaterialParams(; Name = "Mantle", Phase = 1, Density = PT_Density(; ρ0=3.5e3, β=β, T0=0.0, α = 1.5e-5), HeatCapacity = ConstantHeatCapacity(; Cp=1.2e3), Conductivity = ConstantConductivity(; k=3.0), CompositeRheology = CompositeRheology((creep, el, pl)), Elasticity = el, Gravity = ConstantGravity(; g=9.81), ) # heat diffusivity κ = (rheology.Conductivity[1].k / (rheology.HeatCapacity[1].Cp * rheology.Density[1].ρ0)).val dt = dt_diff = 0.5 * min(di...)^2 / κ / 2.01 # diffusive CFL timestep limiter # ---------------------------------------------------- # TEMPERATURE PROFILE -------------------------------- thermal = ThermalArrays(backend_JR, ni) thermal_bc = TemperatureBoundaryConditions(; no_flux = (left = true, right = true, top = false, bot = false), ) # initialize thermal profile - Half space cooling adiabat = 0.3 # adiabatic gradient Tp = 1900 Tm = Tp + adiabat * 2890 Tmin, Tmax = 300.0, 3.5e3 @parallel init_T!(thermal.T, xvi[2], κ, Tm, Tp, Tmin, Tmax) thermal_bcs!(thermal, thermal_bc) # Temperature anomaly if thermal_perturbation == :random δT = 5.0 # thermal perturbation (in %) random_perturbation!(thermal.T, δT, (lx*1/8, lx*7/8), (-2000e3, -2600e3), xvi) elseif thermal_perturbation == :circular δT = 10.0 # thermal perturbation (in %) xc, yc = 0.5*lx, -0.75*ly # center of the thermal anomaly r = 150e3 # radius of perturbation circular_perturbation!(thermal.T, δT, xc, yc, r, xvi) end @views thermal.T[:, 1] .= Tmax @views thermal.T[:, end] .= Tmin update_halo!(thermal.T) temperature2center!(thermal) # ---------------------------------------------------- # STOKES --------------------------------------------- # Allocate arrays needed for every Stokes problem stokes = StokesArrays(backend_JR, ni) pt_stokes = PTStokesCoeffs(li, di; ϵ=1e-4, CFL = 0.8 / √2.1) # Buoyancy forces args = (; T = thermal.Tc, P = stokes.P, dt = Inf) ρg = @zeros(ni...), @zeros(ni...) for _ in 1:1 compute_ρg!(ρg[2], rheology, args) @parallel init_P!(stokes.P, ρg[2], xci[2]) end # Rheology viscosity_cutoff = (1e16, 1e24) compute_viscosity!(stokes, args, rheology, viscosity_cutoff) # PT coefficients for thermal diffusion pt_thermal = PTThermalCoeffs( backend_JR, rheology, args, dt, ni, di, li; ϵ=1e-5, CFL=1e-3 / √2.1 ) # Boundary conditions flow_bcs = VelocityBoundaryConditions(; free_slip = (left = true , right = true , top = true , bot = true), ) flow_bcs!(stokes, flow_bcs) # apply boundary conditions update_halo!(@velocity(stokes)...) # ---------------------------------------------------- # WENO arrays T_WENO = @zeros(ni.+1) Vx_v = @zeros(ni.+1...) Vy_v = @zeros(ni.+1...) # Time loop t, it = 0.0, 0 local iters while it < 5 # Update buoyancy and viscosity - args = (; T = thermal.Tc, P = stokes.P, dt=Inf) compute_ρg!(ρg[end], rheology, (T=thermal.Tc, P=stokes.P)) compute_viscosity!( stokes, args, rheology, viscosity_cutoff ) # ------------------------------ iters = solve!( stokes, pt_stokes, di, flow_bcs, ρg, rheology, args, dt, igg; kwargs = (; iterMax = 150e3, nout = 1e3, viscosity_cutoff = viscosity_cutoff ) ); dt = compute_dt(stokes, di, dt_diff, igg) # ------------------------------ # Thermal solver --------------- heatdiffusion_PT!( thermal, pt_thermal, thermal_bc, rheology, args, dt, di; kwargs = ( igg = igg, iterMax = 10e3, nout = 1e2, verbose = true ), ) # Weno advection T_WENO .= @views thermal.T[2:end-1, :] velocity2vertex!(Vx_v, Vy_v, @velocity(stokes)...) WENO_advection!(T_WENO, (Vx_v, Vy_v), weno, di, dt) @views thermal.T[2:end-1, :] .= T_WENO # ------------------------------ it += 1 t += dt end finalize_global_grid(; finalize_MPI=true) return iters end @testset "WENO5 2D" begin @suppress begin n = 32 nx = n ny = n igg = if !(JustRelax.MPI.Initialized()) IGG(init_global_grid(nx, ny, 1; init_MPI=true)...) else igg end iters = thermal_convection2D(igg; ar=8, ny=ny, nx=nx, thermal_perturbation = :circular) @test passed = iters.err_evo1[end] < 1e-4 end end
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
1770
@static if ENV["JULIA_JUSTRELAX_BACKEND"] === "AMDGPU" using AMDGPU elseif ENV["JULIA_JUSTRELAX_BACKEND"] === "CUDA" using CUDA end using JustRelax, JustRelax.JustRelax2D, Test const backend = @static if ENV["JULIA_JUSTRELAX_BACKEND"] === "AMDGPU" AMDGPUBackend elseif ENV["JULIA_JUSTRELAX_BACKEND"] === "CUDA" CUDABackend else CPUBackend end ni = 2, 2 stokes = StokesArrays(backend, ni) thermal = ThermalArrays(backend, ni) @testset "Type conversions" begin A1 = Array(stokes.V) A2 = Array(stokes.τ) A3 = Array(stokes.R) A4 = Array(stokes.P) A5 = Array(stokes) A6 = Array(thermal) A7 = Array(stokes.U) A8 = Array(stokes.ω) @test typeof(A1) <: JustRelax.Velocity{<:Array} @test typeof(A2) <: JustRelax.SymmetricTensor{<:Array} @test typeof(A3) <: JustRelax.Residual{<:Array} @test typeof(A4) <: Array @test typeof(A5) <: JustRelax.StokesArrays @test typeof(A6) <: JustRelax.ThermalArrays{<:Array} @test typeof(A7) <: JustRelax.Displacement{<:Array} @test typeof(A8) <: JustRelax.Vorticity{<:Array} end @testset "Type copy" begin S1 = copy(stokes.V) S2 = copy(stokes.τ) S3 = copy(stokes.R) S4 = copy(stokes.P) S5 = copy(stokes) S6 = copy(stokes.U) S7 = copy(stokes.ω) T1 = copy(thermal) @test typeof(S1) <: JustRelax.Velocity @test typeof(S2) <: JustRelax.SymmetricTensor @test typeof(S3) <: JustRelax.Residual @test typeof(S4) <: typeof(stokes.P) @test typeof(S5) <: JustRelax.StokesArrays @test typeof(S6) <: JustRelax.Displacement @test typeof(S7) <: JustRelax.Vorticity @test typeof(T1) <: JustRelax.ThermalArrays end
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
9311
@static if ENV["JULIA_JUSTRELAX_BACKEND"] === "AMDGPU" using AMDGPU AMDGPU.allowscalar(true) elseif ENV["JULIA_JUSTRELAX_BACKEND"] === "CUDA" using CUDA CUDA.allowscalar(true) end using JustRelax, JustRelax.JustRelax2D using Test, Suppressor const backend = @static if ENV["JULIA_JUSTRELAX_BACKEND"] === "AMDGPU" AMDGPUBackend elseif ENV["JULIA_JUSTRELAX_BACKEND"] === "CUDA" CUDABackend else CPUBackend end @testset "Boundary Conditions 2D" begin @suppress begin @testset "VelocityBoundaryConditions" begin if backend === CPUBackend # test incompatible boundary conditions @test_throws ErrorException VelocityBoundaryConditions(; no_slip = (left=false, right=false, top=false, bot=false), free_slip = (left=false, right=true, top=true, bot=true), ) @test_throws ErrorException VelocityBoundaryConditions(; no_slip = (left=false, right=false, top=false, bot=false), free_slip = (left=true , right=true , top=true , bot=false), ) n = 5 # number of elements Vx, Vy = PTArray(backend)(rand(n + 1, n + 2)), PTArray(backend)(rand(n + 2, n + 1)) # free-slip bcs = VelocityBoundaryConditions(; no_slip = (left=false, right=false, top=false, bot=false), free_slip = (left=true, right=true, top=true, bot=true), ) flow_bcs!(bcs, Vx, Vy) @test @views Vx[: , 1] == Vx[:, 2] @test @views Vx[: , end] == Vx[:, end - 1] @test @views Vy[1 , :] == Vy[2, :] @test @views Vy[end, :] == Vy[end - 1, :] @test typeof(bcs) <: AbstractFlowBoundaryConditions @test typeof(bcs) <: VelocityBoundaryConditions # no-slip Vx, Vy = PTArray(backend)(rand(n + 1, n + 2)), PTArray(backend)(rand(n + 2, n + 1)) bcs = VelocityBoundaryConditions(; no_slip = (left=true, right=true, top=true, bot=true), free_slip = (left=false, right=false, top=false, bot=false), ) flow_bcs!(bcs, Vx, Vy) @test sum(!iszero(Vx[1 , i]) for i in axes(Vx,2)) == 0 @test sum(!iszero(Vx[end, i]) for i in axes(Vx,2)) == 0 @test sum(!iszero(Vy[i, 1]) for i in axes(Vy,1)) == 0 @test sum(!iszero(Vy[i, 1]) for i in axes(Vy,1)) == 0 @test @views Vy[1 , :] == -Vy[2 , :] @test @views Vy[end, :] == -Vy[end - 1, :] @test @views Vx[: , 1] == -Vx[: , 2] @test @views Vx[: , end] == -Vx[: , end - 1] # test with StokesArrays ni = 5, 5 stokes = StokesArrays(backend, ni) stokes.V.Vx .= PTArray(backend)(rand(n + 1, n + 2)) stokes.V.Vy .= PTArray(backend)(rand(n + 2, n + 1)) # free-slip flow_bcs = VelocityBoundaryConditions(; no_slip = (left=false, right=false, top=false, bot=false), free_slip = (left=true, right=true, top=true, bot=true), ) flow_bcs!(stokes, flow_bcs) @test @views stokes.V.Vx[:, 1] == stokes.V.Vx[:, 2] @test @views stokes.V.Vx[:, end] == stokes.V.Vx[:, end - 1] @test @views stokes.V.Vy[1, :] == stokes.V.Vy[2, :] @test @views stokes.V.Vy[end, :] == stokes.V.Vy[end - 1, :] # no-slip flow_bcs = VelocityBoundaryConditions(; no_slip = (left=true, right=true, top=true, bot=true), free_slip = (left=false, right=false, top=false, bot=false), ) flow_bcs!(stokes, flow_bcs) @test sum(!iszero(stokes.V.Vx[1 , i]) for i in axes(Vx,2)) == 0 @test sum(!iszero(stokes.V.Vx[end, i]) for i in axes(Vx,2)) == 0 @test sum(!iszero(stokes.V.Vy[i, 1]) for i in axes(Vy,1)) == 0 @test sum(!iszero(stokes.V.Vy[i, 1]) for i in axes(Vy,1)) == 0 @test @views stokes.V.Vy[1 , :] == -stokes.V.Vy[2 , :] @test @views stokes.V.Vy[end, :] == -stokes.V.Vy[end - 1, :] @test @views stokes.V.Vx[: , 1] == -stokes.V.Vx[: , 2] @test @views stokes.V.Vx[: , end] == -stokes.V.Vx[: , end - 1] else @test true === true end end @testset "DisplacementBoundaryConditions" begin if backend === CPUBackend # test incompatible boundary conditions @test_throws ErrorException DisplacementBoundaryConditions(; no_slip = (left=false, right=false, top=false, bot=false), free_slip = (left=false, right=true, top=true, bot=true), ) @test_throws ErrorException DisplacementBoundaryConditions(; no_slip = (left=false, right=false, top=false, bot=false), free_slip = (left=true , right=true , top=true , bot=false), ) n = 5 # number of elements Ux, Uy = PTArray(backend)(rand(n + 1, n + 2)), PTArray(backend)(rand(n + 2, n + 1)) # free-slip bcs1 = DisplacementBoundaryConditions(; no_slip = (left=false, right=false, top=false, bot=false), free_slip = (left=true, right=true, top=true, bot=true), ) flow_bcs!(bcs1, Ux, Uy) @test @views Ux[: , 1] == Ux[:, 2] @test @views Ux[: , end] == Ux[:, end - 1] @test @views Uy[1 , :] == Uy[2, :] @test @views Uy[end, :] == Uy[end - 1, :] @test typeof(bcs1) <: AbstractFlowBoundaryConditions @test typeof(bcs1) <: DisplacementBoundaryConditions # no-slip Ux, Uy = PTArray(backend)(rand(n + 1, n + 2)), PTArray(backend)(rand(n + 2, n + 1)) bcs2 = DisplacementBoundaryConditions(; no_slip = (left=true, right=true, top=true, bot=true), free_slip = (left=false, right=false, top=false, bot=false), ) flow_bcs!(bcs2, Ux, Uy) @test sum(!iszero(Ux[1 , i]) for i in axes(Ux,2)) == 0 @test sum(!iszero(Ux[end, i]) for i in axes(Ux,2)) == 0 @test sum(!iszero(Uy[i, 1]) for i in axes(Uy,1)) == 0 @test sum(!iszero(Uy[i, 1]) for i in axes(Uy,1)) == 0 @test @views Uy[1 , :] == -Uy[2 , :] @test @views Uy[end, :] == -Uy[end - 1, :] @test @views Ux[: , 1] == -Ux[: , 2] @test @views Ux[: , end] == -Ux[: , end - 1] # test with StokesArrays ni = 5, 5 stokes = StokesArrays(backend, ni) stokes.U.Ux .= PTArray(backend)(rand(n + 1, n + 2)) stokes.U.Uy .= PTArray(backend)(rand(n + 2, n + 1)) # free-slip flow_bcs = DisplacementBoundaryConditions(; no_slip = (left=false, right=false, top=false, bot=false), free_slip = (left=true, right=true, top=true, bot=true), ) flow_bcs!(stokes, flow_bcs) @test @views stokes.U.Ux[:, 1] == stokes.U.Ux[:, 2] @test @views stokes.U.Ux[:, end] == stokes.U.Ux[:, end - 1] @test @views stokes.U.Uy[1, :] == stokes.U.Uy[2, :] @test @views stokes.U.Uy[end, :] == stokes.U.Uy[end - 1, :] # no-slip flow_bcs = DisplacementBoundaryConditions(; no_slip = (left=true, right=true, top=true, bot=true), free_slip = (left=false, right=false, top=false, bot=false), ) flow_bcs!(stokes, flow_bcs) @test sum(!iszero(stokes.U.Ux[1 , i]) for i in axes(Ux,2)) == 0 @test sum(!iszero(stokes.U.Ux[end, i]) for i in axes(Ux,2)) == 0 @test sum(!iszero(stokes.U.Uy[i, 1]) for i in axes(Uy,1)) == 0 @test sum(!iszero(stokes.U.Uy[i, 1]) for i in axes(Uy,1)) == 0 @test @views stokes.U.Uy[1 , :] == -stokes.U.Uy[2 , :] @test @views stokes.U.Uy[end, :] == -stokes.U.Uy[end - 1, :] @test @views stokes.U.Ux[: , 1] == -stokes.U.Ux[: , 2] @test @views stokes.U.Ux[: , end] == -stokes.U.Ux[: , end - 1] else @test true === true end end end end
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
9016
@static if ENV["JULIA_JUSTRELAX_BACKEND"] === "AMDGPU" using AMDGPU AMDGPU.allowscalar(true) elseif ENV["JULIA_JUSTRELAX_BACKEND"] === "CUDA" using CUDA CUDA.allowscalar(true) end using JustRelax, JustRelax.JustRelax3D using Test const backend = @static if ENV["JULIA_JUSTRELAX_BACKEND"] === "AMDGPU" AMDGPUBackend elseif ENV["JULIA_JUSTRELAX_BACKEND"] === "CUDA" CUDABackend else CPUBackend end @testset "Boundary Conditions 3D" begin @testset "VelocityBoundaryConditions" begin if backend === CPUBackend # test incompatible boundary conditions @test_throws ErrorException VelocityBoundaryConditions(; no_slip = (left=true, right=true, front=true, back=true, top=true, bot=true), free_slip = (left=false, right=true, front=true, back=true, top=true, bot=true), ) # test with StokesArrays ni = 5, 5, 5 stokes = StokesArrays(backend, ni) stokes.V.Vx .= PTArray(backend)(rand(size(stokes.V.Vx)...)) stokes.V.Vy .= PTArray(backend)(rand(size(stokes.V.Vy)...)) stokes.V.Vz .= PTArray(backend)(rand(size(stokes.V.Vz)...)) # free-slip flow_bcs = VelocityBoundaryConditions(; no_slip = (left=false, right=false, front=false, back=false, top=false, bot=false), free_slip = (left=true, right=true, front=true, back=true, top=true, bot=true), ) flow_bcs!(stokes, flow_bcs) flow_bcs!(stokes, flow_bcs) # just a trick to pass the CI @test @views stokes.V.Vx[ :, :, 1] == stokes.V.Vx[:, :, 2] @test @views stokes.V.Vx[ :, :, end] == stokes.V.Vx[:, :, end - 1] @test @views stokes.V.Vx[ :, 1, :] == stokes.V.Vx[:, 2, :] @test @views stokes.V.Vx[ :, end, :] == stokes.V.Vx[:, end - 1, :] @test @views stokes.V.Vy[ :, :, 1] == stokes.V.Vy[:, :, 2] @test @views stokes.V.Vy[ :, :, end] == stokes.V.Vy[:, :, end - 1] @test @views stokes.V.Vy[ 1, :, :] == stokes.V.Vy[2, :, :] @test @views stokes.V.Vy[end, :, :] == stokes.V.Vy[end - 1, :, :] @test @views stokes.V.Vz[ 1, :, :] == stokes.V.Vz[2, :, :] @test @views stokes.V.Vz[end, :, :] == stokes.V.Vz[end - 1, :, :] @test @views stokes.V.Vz[ :, 1, :] == stokes.V.Vz[:, 2, :] @test @views stokes.V.Vz[ :, end, :] == stokes.V.Vz[:, end - 1, :] # no-slip flow_bcs = VelocityBoundaryConditions(; no_slip = (left=true, right=true, front=true, back=true, top=true, bot=true), free_slip = (left=false, right=false, front=false, back=false, top=false, bot=false), ) flow_bcs!(stokes, flow_bcs) (; Vx, Vy, Vz) = stokes.V @test sum(!iszero(Vx[1 , i, j]) for i in axes(Vx,2), j in axes(Vx,3)) == 0 @test sum(!iszero(Vx[end, i, j]) for i in axes(Vx,2), j in axes(Vx,3)) == 0 @test sum(!iszero(Vy[i, 1, j]) for i in axes(Vy,1), j in axes(Vy,2)) == 0 @test sum(!iszero(Vy[i, end, j]) for i in axes(Vy,1), j in axes(Vy,2)) == 0 @test sum(!iszero(Vz[i, j, 1]) for i in axes(Vz,1), j in axes(Vz,3)) == 0 @test sum(!iszero(Vz[i, j, end]) for i in axes(Vz,1), j in axes(Vz,3)) == 0 @test @views Vx[ :, 1, :] == -Vx[ :, 2, :] @test @views Vx[ :, end, :] == -Vx[ :, end - 1, :] @test @views Vx[ :, :, 1] == -Vx[ :, :, 2] @test @views Vx[ :, :, end] == -Vx[ :, :, end - 1] @test @views Vy[ 1, :, :] == -Vy[ 2, :, :] @test @views Vy[end, :, :] == -Vy[end - 1, :, :] @test @views Vy[ :, :, 1] == -Vy[ :, :, 2] @test @views Vy[ :, :, end] == -Vy[ :, :, end - 1] @test @views Vz[ :, 1, :] == -Vz[ :, 2, :] @test @views Vz[ :, end, :] == -Vz[ :, end - 1, :] @test @views Vz[ 1, :, :] == -Vz[ 2, :, :] @test @views Vz[end, :, :] == -Vz[end - 1, :, :] else @test true === true end end @testset "DisplacementBoundaryConditions" begin if backend === CPUBackend # test incompatible boundary conditions @test_throws ErrorException DisplacementBoundaryConditions(; no_slip = (left=true, right=true, front=true, back=true, top=true, bot=true), free_slip = (left=false, right=true, front=true, back=true, top=true, bot=true), ) # test with StokesArrays ni = 5, 5, 5 stokes = StokesArrays(backend, ni) stokes.U.Ux .= PTArray(backend)(rand(size(stokes.U.Ux)...)) stokes.U.Uy .= PTArray(backend)(rand(size(stokes.U.Uy)...)) stokes.U.Uz .= PTArray(backend)(rand(size(stokes.U.Uz)...)) # free-slip flow_bcs = DisplacementBoundaryConditions(; no_slip = (left=false, right=false, front=false, back=false, top=false, bot=false), free_slip = (left=true, right=true, front=true, back=true, top=true, bot=true), ) flow_bcs!(stokes, flow_bcs) flow_bcs!(stokes, flow_bcs) # just a trick to pass the CI @test @views stokes.U.Ux[ :, :, 1] == stokes.U.Ux[:, :, 2] @test @views stokes.U.Ux[ :, :, end] == stokes.U.Ux[:, :, end - 1] @test @views stokes.U.Ux[ :, 1, :] == stokes.U.Ux[:, 2, :] @test @views stokes.U.Ux[ :, end, :] == stokes.U.Ux[:, end - 1, :] @test @views stokes.U.Uy[ :, :, 1] == stokes.U.Uy[:, :, 2] @test @views stokes.U.Uy[ :, :, end] == stokes.U.Uy[:, :, end - 1] @test @views stokes.U.Uy[ 1, :, :] == stokes.U.Uy[2, :, :] @test @views stokes.U.Uy[end, :, :] == stokes.U.Uy[end - 1, :, :] @test @views stokes.U.Uz[ 1, :, :] == stokes.U.Uz[2, :, :] @test @views stokes.U.Uz[end, :, :] == stokes.U.Uz[end - 1, :, :] @test @views stokes.U.Uz[ :, 1, :] == stokes.U.Uz[:, 2, :] @test @views stokes.U.Uz[ :, end, :] == stokes.U.Uz[:, end - 1, :] # no-slip flow_bcs = DisplacementBoundaryConditions(; no_slip = (left=true, right=true, front=true, back=true, top=true, bot=true), free_slip = (left=false, right=false, front=false, back=false, top=false, bot=false), ) flow_bcs!(stokes, flow_bcs) (; Ux, Uy, Uz) = stokes.U @test sum(!iszero(Ux[1 , i, j]) for i in axes(Ux,2), j in axes(Ux,3)) == 0 @test sum(!iszero(Ux[end, i, j]) for i in axes(Ux,2), j in axes(Ux,3)) == 0 @test sum(!iszero(Uy[i, 1, j]) for i in axes(Uy,1), j in axes(Uy,2)) == 0 @test sum(!iszero(Uy[i, end, j]) for i in axes(Uy,1), j in axes(Uy,2)) == 0 @test sum(!iszero(Uz[i, j, 1]) for i in axes(Uz,1), j in axes(Uz,3)) == 0 @test sum(!iszero(Uz[i, j, end]) for i in axes(Uz,1), j in axes(Uz,3)) == 0 @test @views Ux[ :, 1, :] == -Ux[ :, 2, :] @test @views Ux[ :, end, :] == -Ux[ :, end - 1, :] @test @views Ux[ :, :, 1] == -Ux[ :, :, 2] @test @views Ux[ :, :, end] == -Ux[ :, :, end - 1] @test @views Uy[ 1, :, :] == -Uy[ 2, :, :] @test @views Uy[end, :, :] == -Uy[end - 1, :, :] @test @views Uy[ :, :, 1] == -Uy[ :, :, 2] @test @views Uy[ :, :, end] == -Uy[ :, :, end - 1] @test @views Uz[ :, 1, :] == -Uz[ :, 2, :] @test @views Uz[ :, end, :] == -Uz[ :, end - 1, :] @test @views Uz[ 1, :, :] == -Uz[ 2, :, :] @test @views Uz[end, :, :] == -Uz[end - 1, :, :] else @test true === true end end end
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
4197
push!(LOAD_PATH, "..") @static if ENV["JULIA_JUSTRELAX_BACKEND"] === "AMDGPU" using AMDGPU elseif ENV["JULIA_JUSTRELAX_BACKEND"] === "CUDA" using CUDA end using Test, Suppressor using JustRelax, JustRelax.JustRelax2D using ParallelStencil, ParallelStencil.FiniteDifferences2D const backend_JR = @static if ENV["JULIA_JUSTRELAX_BACKEND"] === "AMDGPU" @init_parallel_stencil(AMDGPU, Float64, 2) AMDGPUBackend elseif ENV["JULIA_JUSTRELAX_BACKEND"] === "CUDA" @init_parallel_stencil(CUDA, Float64, 2) CUDABackend else @init_parallel_stencil(Threads, Float64, 2) CPUBackend end import JustRelax.@cell using GeoParams # HELPER FUNCTIONS --------------------------------------------------------------- @parallel_indices (i, j) function init_T!(T, z) if z[j] == maximum(z) T[i, j] = 300.0 elseif z[j] == minimum(z) T[i, j] = 3500.0 else T[i, j] = z[j] * (1900.0 - 1600.0) / minimum(z) + 1600.0 end return nothing end function elliptical_perturbation!(T, δT, xc, yc, r, xvi) @parallel_indices (i, j) function _elliptical_perturbation!(T, δT, xc, yc, r, x, y) @inbounds if (((x[i]-xc ))^2 + ((y[j] - yc))^2) ≤ r^2 T[i, j] += δT end return nothing end @parallel _elliptical_perturbation!(T, δT, xc, yc, r, xvi...) end # MAIN SCRIPT -------------------------------------------------------------------- function diffusion_2D(; nx=32, ny=32, lx=100e3, ly=100e3, ρ0=3.3e3, Cp0=1.2e3, K0=3.0) kyr = 1e3 * 3600 * 24 * 365.25 Myr = 1e3 * kyr ttot = 1 * Myr # total simulation time dt = 50 * kyr # physical time step init_mpi = JustRelax.MPI.Initialized() ? false : true igg = IGG(init_global_grid(nx, ny, 1; init_MPI = init_mpi)...) # Physical domain ni = (nx, ny) li = (lx, ly) # domain length in x- and y- di = @. li / ni # grid step in x- and -y origin = 0, -ly grid = Geometry(ni, li; origin = origin) (; xci, xvi) = grid # nodes at the center and vertices of the cells # Define the thermal parameters with GeoParams rheology = SetMaterialParams(; Phase = 1, Density = PT_Density(; ρ0=3.1e3, β=0.0, T0=0.0, α = 1.5e-5), HeatCapacity = ConstantHeatCapacity(; Cp=Cp0), Conductivity = ConstantConductivity(; k=K0), ) # fields needed to compute density on the fly P = @zeros(ni...) args = (; P=P, T=@zeros(ni.+1...)) ## Allocate arrays needed for every Thermal Diffusion thermal = ThermalArrays(backend_JR, ni) thermal.H .= 1e-6 # radiogenic heat production # physical parameters ρ = @fill(ρ0, ni...) Cp = @fill(Cp0, ni...) K = @fill(K0, ni...) ρCp = @. Cp * ρ pt_thermal = PTThermalCoeffs(backend_JR, K, ρCp, dt, di, li; CFL = 0.95 / √2.1) thermal_bc = TemperatureBoundaryConditions(; no_flux = (left = true, right = true, top = false, bot = false), ) @parallel (@idx size(thermal.T)) init_T!(thermal.T, xvi[2]) # Add thermal perturbation δT = 100e0 # thermal perturbation r = 10e3 # thermal perturbation radius center_perturbation = lx/2, -ly/2 elliptical_perturbation!(thermal.T, δT, center_perturbation..., r, xvi) temperature2center!(thermal) # Time loop t = 0.0 it = 0 nt = Int(ceil(ttot / dt)) while it < nt heatdiffusion_PT!( thermal, pt_thermal, thermal_bc, rheology, args, dt, di; kwargs = (; verbose = false ), ) t += dt it += 1 end return thermal end @testset "Diffusion_2D" begin @suppress begin nx, ny = 32, 32 thermal = diffusion_2D(; nx = nx, ny = ny) nx_T, ny_T = size(thermal.T) @test Array(thermal.T)[nx_T >>> 1 + 1, ny_T >>> 1 + 1] ≈ 1823.6076461523571 atol=1e-1 @test Array(thermal.Tc)[ nx >>> 1 , nx >>> 1 ] ≈ 1828.3169386441218 atol=1e-1 end end
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
6791
push!(LOAD_PATH, "..") @static if ENV["JULIA_JUSTRELAX_BACKEND"] === "AMDGPU" using AMDGPU elseif ENV["JULIA_JUSTRELAX_BACKEND"] === "CUDA" using CUDA end using Test, Suppressor using GeoParams using JustRelax, JustRelax.JustRelax2D using ParallelStencil const backend_JR = @static if ENV["JULIA_JUSTRELAX_BACKEND"] === "AMDGPU" @init_parallel_stencil(AMDGPU, Float64, 2) AMDGPUBackend elseif ENV["JULIA_JUSTRELAX_BACKEND"] === "CUDA" @init_parallel_stencil(CUDA, Float64, 2) CUDABackend else @init_parallel_stencil(Threads, Float64, 2) CPUBackend end using JustPIC, JustPIC._2D # Threads is the default backend, # to run on a CUDA GPU load CUDA.jl (i.e. "using CUDA") at the beginning of the script, # and to run on an AMD GPU load AMDGPU.jl (i.e. "using AMDGPU") at the beginning of the script. const backend = @static if ENV["JULIA_JUSTRELAX_BACKEND"] === "AMDGPU" JustPIC.AMDGPUBackend elseif ENV["JULIA_JUSTRELAX_BACKEND"] === "CUDA" CUDABackend else JustPIC.CPUBackend end import JustRelax.@cell distance(p1, p2) = mapreduce(x->(x[1]-x[2])^2, +, zip(p1, p2)) |> sqrt @parallel_indices (i, j) function init_T!(T, z) if z[j] == maximum(z) T[i, j] = 300.0 elseif z[j] == minimum(z) T[i, j] = 3500.0 else T[i, j] = z[j] * (1900.0 - 1600.0) / minimum(z) + 1600.0 end return nothing end function elliptical_perturbation!(T, δT, xc, yc, r, xvi) @parallel_indices (i, j) function _elliptical_perturbation!(T, δT, xc, yc, r, x, y) @inbounds if (((x[i]-xc ))^2 + ((y[j] - yc))^2) ≤ r^2 T[i, j] += δT end return nothing end @parallel _elliptical_perturbation!(T, δT, xc, yc, r, xvi...) end function init_phases!(phases, particles, xc, yc, r) ni = size(phases) center = xc, yc @parallel_indices (i, j) function init_phases!(phases, px, py, index, center, r) @inbounds for ip in JustRelax.JustRelax.cellaxes(phases) # quick escape JustRelax.@cell(index[ip, i, j]) == 0 && continue x = JustRelax.@cell px[ip, i, j] y = JustRelax.@cell py[ip, i, j] # plume - rectangular if (((x - center[1] ))^2 + ((y - center[2]))^2) ≤ r^2 JustRelax.@cell phases[ip, i, j] = 2.0 else JustRelax.@cell phases[ip, i, j] = 1.0 end end return nothing end @parallel (@idx ni) init_phases!(phases, particles.coords..., particles.index, center, r) end @parallel_indices (I...) function compute_temperature_source_terms!(H, rheology, phase_ratios, args) args_ij = ntuple_idx(args, I...) H[I...] = fn_ratio(compute_radioactive_heat, rheology, phase_ratios[I...], args_ij) return nothing end function diffusion_2D(; nx=32, ny=32, lx=100e3, ly=100e3, Cp0=1.2e3, K0=3.0) kyr = 1e3 * 3600 * 24 * 365.25 Myr = 1e3 * kyr ttot = 1 * Myr # total simulation time dt = 50 * kyr # physical time step init_mpi = JustRelax.MPI.Initialized() ? false : true igg = IGG(init_global_grid(nx, ny, 1; init_MPI = init_mpi)...) # Physical domain ni = (nx, ny) li = (lx, ly) # domain length in x- and y- di = @. li / ni # grid step in x- and -y grid = Geometry(ni, li; origin = (0, -ly)) (; xci, xvi) = grid # nodes at the center and vertices of the cells # Define the thermal parameters with GeoParams rheology = ( SetMaterialParams(; Phase = 1, Density = PT_Density(; ρ0=3e3, β=0.0, T0=0.0, α = 1.5e-5), HeatCapacity = ConstantHeatCapacity(; Cp=Cp0), Conductivity = ConstantConductivity(; k=K0), RadioactiveHeat = ConstantRadioactiveHeat(1e-6), ), SetMaterialParams(; Phase = 2, Density = PT_Density(; ρ0=3.3e3, β=0.0, T0=0.0, α = 1.5e-5), HeatCapacity = ConstantHeatCapacity(; Cp=Cp0), Conductivity = ConstantConductivity(; k=K0), RadioactiveHeat = ConstantRadioactiveHeat(1e-7), ), ) # fields needed to compute density on the fly P = @zeros(ni...) args = (; P=P) ## Allocate arrays needed for every Thermal Diffusion thermal = ThermalArrays(backend_JR, ni) thermal_bc = TemperatureBoundaryConditions(; no_flux = (left = true, right = true, top = false, bot = false), ) @parallel (@idx size(thermal.T)) init_T!(thermal.T, xvi[2]) # Add thermal perturbation δT = 100e0 # thermal perturbation r = 10e3 # thermal perturbation radius center_perturbation = lx/2, -ly/2 elliptical_perturbation!(thermal.T, δT, center_perturbation..., r, xvi) temperature2center!(thermal) # Initialize particles ------------------------------- nxcell, max_xcell, min_xcell = 40, 40, 1 particles = init_particles( backend, nxcell, max_xcell, min_xcell, xvi... ) # temperature pPhases, = init_cell_arrays(particles, Val(1)) init_phases!(pPhases, particles, center_perturbation..., r) phase_ratios = PhaseRatio(backend_JR, ni, length(rheology)) phase_ratios_center!(phase_ratios, particles, grid, pPhases) # ---------------------------------------------------- @parallel (@idx ni) compute_temperature_source_terms!(thermal.H, rheology, phase_ratios.center, args) # PT coefficients for thermal diffusion args = (; P=P, T=thermal.Tc) pt_thermal = PTThermalCoeffs( backend_JR, rheology, phase_ratios, args, dt, ni, di, li; ϵ=1e-5, CFL=0.95 / √2 ) # Time loop t = 0.0 it = 0 nt = Int(ceil(ttot / dt)) while it < nt heatdiffusion_PT!( thermal, pt_thermal, thermal_bc, rheology, args, dt, di; kwargs = ( phase = phase_ratios, iterMax = 1e3, nout = 10, verbose=false, ) ) it += 1 t += dt end return thermal, phase_ratios end @testset "Diffusion_2D_Multiphase" begin @suppress begin nx=32; ny=32; thermal, phase_ratios = diffusion_2D(; nx = nx, ny = ny) nx_T, ny_T = size(thermal.T) if backend_JR === CPUBackend @test thermal.T[nx_T >>> 1 + 1, ny_T >>> 1 + 1] ≈ 1819.2297931741878 atol=1e-1 @test thermal.Tc[ nx >>> 1 , nx >>> 1 ] ≈ 1824.3532934301472 atol=1e-1 @test nphases(phase_ratios)=== Val{2}() else @test true == true end end end
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
4699
push!(LOAD_PATH, "..") @static if ENV["JULIA_JUSTRELAX_BACKEND"] === "AMDGPU" using AMDGPU elseif ENV["JULIA_JUSTRELAX_BACKEND"] === "CUDA" using CUDA end using Test, Suppressor using GeoParams using JustRelax, JustRelax.JustRelax3D using ParallelStencil @static if ENV["JULIA_JUSTRELAX_BACKEND"] === "AMDGPU" @init_parallel_stencil(AMDGPU, Float64, 3) elseif ENV["JULIA_JUSTRELAX_BACKEND"] === "CUDA" @init_parallel_stencil(CUDA, Float64, 3) else @init_parallel_stencil(Threads, Float64, 3) end const backend = @static if ENV["JULIA_JUSTRELAX_BACKEND"] === "AMDGPU" AMDGPUBackend elseif ENV["JULIA_JUSTRELAX_BACKEND"] === "CUDA" CUDABackend else CPUBackend end # HELPER FUNCTIONS --------------------------------------------------------------- @parallel_indices (i, j, k) function init_T!(T, z) if z[k] == maximum(z) T[i, j, k] = 300.0 elseif z[k] == minimum(z) T[i, j, k] = 3500.0 else T[i, j, k] = z[k] * (1900.0 - 1600.0) / minimum(z) + 1600.0 end return nothing end function elliptical_perturbation!(T, δT, xc, yc, zc, r, xvi) @parallel_indices (i, j, k) function _elliptical_perturbation!(T, x, y, z) @inbounds if (((x[i]-xc))^2 + ((y[j] - yc))^2 + ((z[k] - zc))^2) ≤ r^2 T[i, j, k] += δT end return nothing end @parallel _elliptical_perturbation!(T, xvi...) end function diffusion_3D(; nx = 32, ny = 32, nz = 32, lx = 100e3, ly = 100e3, lz = 100e3, ρ0 = 3.3e3, Cp0 = 1.2e3, K0 = 3.0, init_MPI = JustRelax.MPI.Initialized() ? false : true, finalize_MPI = false, ) kyr = 1e3 * 3600 * 24 * 365.25 Myr = 1e6 * 3600 * 24 * 365.25 ttot = 1 * Myr # total simulation time dt = 50 * kyr # physical time step # Physical domain ni = (nx, ny, nz) li = (lx, ly, lz) # domain length in x- and y- di = @. li / ni # grid step in x- and -y origin = 0, 0, -lz # nodes at the center and vertices of the cells igg = IGG(init_global_grid(nx, ny, nz; init_MPI=init_MPI)...) # init MPI grid = Geometry(ni, li; origin = origin) (; xci, xvi) = grid # nodes at the center and vertices of the cells # Define the thermal parameters with GeoParams rheology = SetMaterialParams(; Phase = 1, Density = PT_Density(; ρ0=3.1e3, β=0.0, T0=0.0, α = 1.5e-5), HeatCapacity = ConstantHeatCapacity(; Cp=Cp0), Conductivity = ConstantConductivity(; k=K0), ) # fields needed to compute density on the fly P = @zeros(ni...) args = (; P=P, T=@zeros(ni.+1...)) ## Allocate arrays needed for every Thermal Diffusion # general thermal arrays thermal = ThermalArrays(backend, ni) thermal.H .= 1e-6 # physical parameters ρ = @fill(ρ0, ni...) Cp = @fill(Cp0, ni...) K = @fill(K0, ni...) ρCp = @. Cp * ρ # Boundary conditions pt_thermal = PTThermalCoeffs(backend, K, ρCp, dt, di, li; CFL = 0.95 / √3.1) thermal_bc = TemperatureBoundaryConditions(; no_flux = (left = true , right = true , top = false, bot = false, front = true , back = true), ) @parallel (@idx size(thermal.T)) init_T!(thermal.T, xvi[3]) # Add thermal perturbation δT = 100e0 # thermal perturbation r = 10e3 # thermal perturbation radius center_perturbation = lx / 2, ly / 2, -lz / 2 elliptical_perturbation!(thermal.T, δT, center_perturbation..., r, xvi) t = 0.0 it = 0 nt = Int(ceil(ttot / dt)) # Physical time loop while it < 10 heatdiffusion_PT!( thermal, pt_thermal, thermal_bc, rheology, args, dt, di; kwargs = (; igg, verbose=false ), ) t += dt it += 1 end finalize_global_grid(; finalize_MPI=finalize_MPI) return thermal end @testset "Diffusion_3D" begin @suppress begin nx=32; ny=32; nz=32; thermal = diffusion_3D(; nx = nx, ny = ny, nz = nz) if backend == CPUBackend @test thermal.T[Int(ceil(nx/2)), Int(ceil(ny/2)), Int(ceil(nz/2))] ≈ 1824.614400703972 rtol=1e-3 @test thermal.Tc[Int(ceil(nx/2)), Int(ceil(ny/2)), Int(ceil(nz/2))] ≈ 1827.002299288895 rtol=1e-3 else @test true ==true end end end
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
7005
push!(LOAD_PATH, "..") @static if ENV["JULIA_JUSTRELAX_BACKEND"] === "AMDGPU" using AMDGPU elseif ENV["JULIA_JUSTRELAX_BACKEND"] === "CUDA" using CUDA end using Test, Suppressor, GeoParams using JustRelax, JustRelax.JustRelax3D using JustRelax using ParallelStencil const backend_JR = @static if ENV["JULIA_JUSTRELAX_BACKEND"] === "AMDGPU" @init_parallel_stencil(AMDGPU, Float64, 3) AMDGPUBackend elseif ENV["JULIA_JUSTRELAX_BACKEND"] === "CUDA" @init_parallel_stencil(CUDA, Float64, 3) CUDABackend else @init_parallel_stencil(Threads, Float64, 3) CPUBackend end using JustPIC using JustPIC._3D # Threads is the default backend, # to run on a CUDA GPU load CUDA.jl (i.e. "using CUDA") at the beginning of the script, # and to run on an AMD GPU load AMDGPU.jl (i.e. "using AMDGPU") at the beginning of the script. const backend = @static if ENV["JULIA_JUSTRELAX_BACKEND"] === "AMDGPU" JustPIC.AMDGPUBackend elseif ENV["JULIA_JUSTRELAX_BACKEND"] === "CUDA" CUDABackend else JustPIC.CPUBackend end import JustRelax.@cell @parallel_indices (i, j, k) function init_T!(T, z) if z[k] == maximum(z) T[i, j, k] = 300.0 elseif z[k] == minimum(z) T[i, j, k] = 3500.0 else T[i, j, k] = z[k] * (1900.0 - 1600.0) / minimum(z) + 1600.0 end return nothing end function elliptical_perturbation!(T, δT, xc, yc, zc, r, xvi) @parallel_indices (i, j, k) function _elliptical_perturbation!(T, x, y, z) @inbounds if (((x[i]-xc))^2 + ((y[j] - yc))^2 + ((z[k] - zc))^2) ≤ r^2 T[i, j, k] += δT end return nothing end @parallel _elliptical_perturbation!(T, xvi...) end function init_phases!(phases, particles, xc, yc, zc, r) ni = size(phases) center = xc, yc, zc @parallel_indices (I...) function init_phases!(phases, px, py, pz, index, center, r) @inbounds for ip in JustRelax.JustRelax.cellaxes(phases) # quick escape @cell(index[ip, I...]) == 0 && continue x = @cell px[ip, I...] y = @cell py[ip, I...] z = @cell pz[ip, I...] # plume - rectangular if (((x - center[1]))^2 + ((y - center[2]))^2 + ((z - center[3]))^2) ≤ r^2 @cell phases[ip, I...] = 2.0 else @cell phases[ip, I...] = 1.0 end end return nothing end @parallel (@idx ni) init_phases!(phases, particles.coords..., particles.index, center, r) end function diffusion_3D(; nx = 32, ny = 32, nz = 32, lx = 100e3, ly = 100e3, lz = 100e3, ρ0 = 3.3e3, Cp0 = 1.2e3, K0 = 3.0, init_MPI = JustRelax.MPI.Initialized() ? false : true, finalize_MPI = false, ) kyr = 1e3 * 3600 * 24 * 365.25 Myr = 1e6 * 3600 * 24 * 365.25 ttot = 1 * Myr # total simulation time dt = 50 * kyr # physical time step # Physical domain ni = (nx, ny, nz) li = (lx, ly, lz) # domain length in x- and y- di = @. li / ni # grid step in x- and -y origin = 0, 0, -lz # nodes at the center and vertices of the cells igg = IGG(init_global_grid(nx, ny, nz; init_MPI=init_MPI)...) # init MPI grid = Geometry(ni, li; origin = origin) (; xci, xvi) = grid # nodes at the center and vertices of the cells # Define the thermal parameters with GeoParams rheology = ( SetMaterialParams(; Phase = 1, Density = PT_Density(; ρ0=3e3, β=0.0, T0=0.0, α = 1.5e-5), HeatCapacity = ConstantHeatCapacity(; Cp=Cp0), Conductivity = ConstantConductivity(; k=K0), RadioactiveHeat = ConstantRadioactiveHeat(1e-6), ), SetMaterialParams(; Phase = 2, Density = PT_Density(; ρ0=3.3e3, β=0.0, T0=0.0, α = 1.5e-5), HeatCapacity = ConstantHeatCapacity(; Cp=Cp0), Conductivity = ConstantConductivity(; k=K0), RadioactiveHeat = ConstantRadioactiveHeat(1e-7), ), ) # fields needed to compute density on the fly P = @zeros(ni...) args = (; P=P) ## Allocate arrays needed for every Thermal Diffusion # general thermal arrays thermal = ThermalArrays(backend_JR, ni) thermal.H .= 1e-6 # physical parameters ρ = @fill(ρ0, ni...) Cp = @fill(Cp0, ni...) K = @fill(K0, ni...) ρCp = @. Cp * ρ # Boundary conditions thermal_bc = TemperatureBoundaryConditions(; no_flux = (left = true , right = true , top = false, bot = false, front = true , back = true), ) @parallel (@idx size(thermal.T)) init_T!(thermal.T, xvi[3]) # Add thermal perturbation δT = 100e0 # thermal perturbation r = 10e3 # thermal perturbation radius center_perturbation = lx/2, ly/2, -lz/2 elliptical_perturbation!(thermal.T, δT, center_perturbation..., r, xvi) # Initialize particles ------------------------------- nxcell, max_xcell, min_xcell = 20, 20, 1 particles = init_particles( backend, nxcell, max_xcell, min_xcell, xvi... ) # temperature pPhases, = init_cell_arrays(particles, Val(1)) phase_ratios = PhaseRatio(backend_JR, ni, length(rheology)) init_phases!(pPhases, particles, center_perturbation..., r) phase_ratios_center!(phase_ratios, particles, grid, pPhases) # ---------------------------------------------------- # PT coefficients for thermal diffusion args = (; P=P, T=thermal.Tc) pt_thermal = PTThermalCoeffs(backend_JR, K, ρCp, dt, di, li; CFL = 0.95 / √3.1) t = 0.0 it = 0 nt = Int(ceil(ttot / dt)) # Physical time loop while it < 10 heatdiffusion_PT!( thermal, pt_thermal, thermal_bc, rheology, args, dt, di; kwargs = (; igg = igg, phase = phase_ratios, iterMax = 10e3, nout = 1e2, verbose = false, ) ) t += dt it += 1 end finalize_global_grid(; finalize_MPI=finalize_MPI) return thermal end @testset "Diffusion_3D_multiphase" begin @suppress begin nx = 32; ny = 32; nz = 32; thermal = diffusion_3D(; nx = nx, ny = ny, nz = nz) if backend_JR == CPUBackend @test thermal.T[Int(ceil(nx/2)), Int(ceil(ny/2)), Int(ceil(nz/2))] ≈ 1825.8463499474844 rtol=1e-3 @test thermal.Tc[Int(ceil(nx/2)), Int(ceil(ny/2)), Int(ceil(nz/2))] ≈ 1828.5932269944233 rtol=1e-3 else @test true == true end end end
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
1398
@static if ENV["JULIA_JUSTRELAX_BACKEND"] === "AMDGPU" using AMDGPU elseif ENV["JULIA_JUSTRELAX_BACKEND"] === "CUDA" using CUDA end using Test, Suppressor, JustRelax, JustRelax.JustRelax2D @testset "Grid2D" begin @suppress begin n = 4 # number of cells nx = n ny = n igg = if !(JustRelax.MPI.Initialized()) # initialize (or not) MPI grid IGG(init_global_grid(nx, ny, 1; init_MPI= true)...) else igg end ly = 1e0 # domain length in y lx = ly # domain length in x ni = nx, ny # number of cells li = lx, ly # domain length in x- and y- dx = lx / nx_g() # grid step in x dy = ly / ny_g() # grid step in y di = dx, dy # grid step in x- and y origin = 0.0, -ly # origin coordinates (15km f sticky air layer) grid = Geometry(ni, li; origin = origin) @test grid.origin == origin for i in 1:2 # test grid at the vertices @test grid.xvi[i][1] == origin[i] # test grid at the cell centers @test grid.xci[i][1] == origin[i] + di[i] / 2 end # test velocity grids @test grid.grid_v[1][2][1] == origin[2] - di[1]/2 @test grid.grid_v[2][1][1] == origin[1] - di[2]/2 end end
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
1521
@static if ENV["JULIA_JUSTRELAX_BACKEND"] === "AMDGPU" using AMDGPU elseif ENV["JULIA_JUSTRELAX_BACKEND"] === "CUDA" using CUDA end using Test, Suppressor, JustRelax, JustRelax.JustRelax3D @testset "Grid3D" begin @suppress begin n = 4 # number of cells nx = ny = nz = n igg = if !(JustRelax.MPI.Initialized()) # initialize (or not) MPI grid IGG(init_global_grid(nx, ny, nz; init_MPI= true)...) else igg end lx = ly = lz = 1e0 # domain length in x ni = nx, ny, nz # number of cells li = lx, ly, lz # domain length in x- and y- dx = lx / nx_g() # grid step in x dy = ly / ny_g() # grid step in y dz = lz / nz_g() # grid step in y di = dx, dy, dz # grid step in x- and y origin = 0.0, 0.0, -lz # origin coordinates (15km f sticky air layer) grid = Geometry(ni, li; origin = origin) @test grid.origin == origin for i in 1:3 # test grid at the vertices @test grid.xvi[i][1] == origin[i] # test grid at the cell centers @test grid.xci[i][1] == origin[i] + di[i] / 2 end # test velocity grids @test grid.grid_v[1][2][1] == origin[2] - di[1]/2 @test grid.grid_v[2][1][1] == origin[1] - di[2]/2 @test grid.grid_v[3][1][1] == origin[1] - di[3]/2 end end
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
6051
push!(LOAD_PATH, "..") @static if ENV["JULIA_JUSTRELAX_BACKEND"] === "AMDGPU" using AMDGPU elseif ENV["JULIA_JUSTRELAX_BACKEND"] === "CUDA" using CUDA end using Test, Suppressor using GeoParams using JustRelax, JustRelax.JustRelax2D using ParallelStencil const backend = @static if ENV["JULIA_JUSTRELAX_BACKEND"] === "AMDGPU" @init_parallel_stencil(AMDGPU, Float64, 2) AMDGPUBackend elseif ENV["JULIA_JUSTRELAX_BACKEND"] === "CUDA" @init_parallel_stencil(CUDA, Float64, 2) CUDABackend else @init_parallel_stencil(Threads, Float64, 2) CPUBackend end # HELPER FUNCTIONS ----------------------------------- ---------------------------- solution(ε, t, G, η) = 2 * ε * η * (1 - exp(-G * t / η)) # Initialize phases on the particles function init_phases!(phase_ratios, xci, radius) ni = size(phase_ratios.center) origin = 0.5, 0.5 @parallel_indices (i, j) function init_phases!(phases, xc, yc, o_x, o_y, radius) x, y = xc[i], yc[j] if ((x-o_x)^2 + (y-o_y)^2) > radius^2 JustRelax.@cell phases[1, i, j] = 1.0 JustRelax.@cell phases[2, i, j] = 0.0 else JustRelax.@cell phases[1, i, j] = 0.0 JustRelax.@cell phases[2, i, j] = 1.0 end return nothing end @parallel (@idx ni) init_phases!(phase_ratios.center, xci..., origin..., radius) end # MAIN SCRIPT -------------------------------------------------------------------- function ShearBand2D() n = 32 nx = n ny = n init_mpi = JustRelax.MPI.Initialized() ? false : true igg = IGG(init_global_grid(nx, ny, 1; init_MPI = init_mpi)...) # Physical domain ------------------------------------ ly = 1e0 # domain length in y lx = ly # domain length in x ni = nx, ny # number of cells li = lx, ly # domain length in x- and y- di = @. li / ni # grid step in x- and -y origin = 0.0, 0.0 # origin coordinates grid = Geometry(ni, li; origin = origin) (; xci, xvi) = grid # nodes at the center and vertices of the cells dt = Inf # Physical properties using GeoParams ---------------- τ_y = 1.6 # yield stress. If do_DP=true, τ_y stand for the cohesion: c*cos(ϕ) ϕ = 30 # friction angle C = τ_y # Cohesion η0 = 1.0 # viscosity G0 = 1.0 # elastic shear modulus Gi = G0/(6.0-4.0) # elastic shear modulus perturbation εbg = 1.0 # background strain-rate η_reg = 8e-3 # regularisation "viscosity" dt = η0/G0/4.0 # assumes Maxwell time of 4 el_bg = ConstantElasticity(; G=G0, Kb=4) el_inc = ConstantElasticity(; G=Gi, Kb=4) visc = LinearViscous(; η=η0) pl = DruckerPrager_regularised(; # non-regularized plasticity C = C, ϕ = ϕ, η_vp = η_reg, Ψ = 0 ) rheology = ( # Low density phase SetMaterialParams(; Phase = 1, Density = ConstantDensity(; ρ = 0.0), Gravity = ConstantGravity(; g = 0.0), CompositeRheology = CompositeRheology((visc, el_bg, pl)), Elasticity = el_bg, ), # High density phase SetMaterialParams(; Density = ConstantDensity(; ρ = 0.0), Gravity = ConstantGravity(; g = 0.0), CompositeRheology = CompositeRheology((visc, el_inc, pl)), Elasticity = el_inc, ), ) # Initialize phase ratios ------------------------------- radius = 0.1 phase_ratios = PhaseRatio(backend, ni, length(rheology)) init_phases!(phase_ratios, xci, radius) # STOKES --------------------------------------------- # Allocate arrays needed for every Stokes problem stokes = StokesArrays(backend, ni) pt_stokes = PTStokesCoeffs(li, di; ϵ=1e-6, CFL = 0.75 / √2.1) # Buoyancy forces ρg = @zeros(ni...), @zeros(ni...) args = (; T = @zeros(ni...), P = stokes.P, dt = dt) # Rheology compute_viscosity!( stokes, phase_ratios, args, rheology, (-Inf, Inf) ) # Boundary conditions flow_bcs = VelocityBoundaryConditions(; free_slip = (left = true, right = true, top = true, bot = true), no_slip = (left = false, right = false, top = false, bot=false), ) stokes.V.Vx .= PTArray(backend)([ x*εbg for x in xvi[1], _ in 1:ny+2]) stokes.V.Vy .= PTArray(backend)([-y*εbg for _ in 1:nx+2, y in xvi[2]]) flow_bcs!(stokes, flow_bcs) # apply boundary conditions update_halo!(@velocity(stokes)...) # Time loop t, it = 0.0, 0 tmax = 3.5 τII = Float64[] sol = Float64[] ttot = Float64[] local iters, τII, sol while t < tmax # Stokes solver ---------------- iters = solve!( stokes, pt_stokes, di, flow_bcs, ρg, phase_ratios, rheology, args, dt, igg; kwargs = ( verbose = false, iterMax = 50e3, nout = 1e2, viscosity_cutoff = (-Inf, Inf) ) ) tensor_invariant!(stokes.ε) push!(τII, maximum(stokes.τ.xx)) it += 1 t += dt push!(sol, solution(εbg, t, G0, η0)) push!(ttot, t) println("it = $it; t = $t \n") end finalize_global_grid(; finalize_MPI = true) return iters, τII, sol end @testset "ShearBand2D" begin @suppress begin iters, τII, sol = ShearBand2D() @test passed = iters.err_evo1[end] < 1e-6 @test τII[end] ≈ 1.41706 atol = 1e-4 @test sol[end] ≈ 1.93960 atol = 1e-4 end end
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
6256
push!(LOAD_PATH, "..") @static if ENV["JULIA_JUSTRELAX_BACKEND"] === "AMDGPU" using AMDGPU elseif ENV["JULIA_JUSTRELAX_BACKEND"] === "CUDA" using CUDA end using Test, Suppressor using GeoParams, CellArrays using JustRelax, JustRelax.JustRelax2D using ParallelStencil const backend = @static if ENV["JULIA_JUSTRELAX_BACKEND"] === "AMDGPU" @init_parallel_stencil(AMDGPU, Float64, 2) AMDGPUBackend elseif ENV["JULIA_JUSTRELAX_BACKEND"] === "CUDA" @init_parallel_stencil(CUDA, Float64, 2) CUDABackend else @init_parallel_stencil(Threads, Float64, 2) CPUBackend end # HELPER FUNCTIONS ----------------------------------- ---------------------------- solution(ε, t, G, η) = 2 * ε * η * (1 - exp(-G * t / η)) # Initialize phases on the particles function init_phases!(phase_ratios, xci, radius) ni = size(phase_ratios.center) origin = 0.5, 0.5 @parallel_indices (i, j) function init_phases!(phases, xc, yc, o_x, o_y, radius) x, y = xc[i], yc[j] if ((x-o_x)^2 + (y-o_y)^2) > radius^2 JustRelax.@cell phases[1, i, j] = 1.0 JustRelax.@cell phases[2, i, j] = 0.0 else JustRelax.@cell phases[1, i, j] = 0.0 JustRelax.@cell phases[2, i, j] = 1.0 end return nothing end @parallel (@idx ni) init_phases!(phase_ratios.center, xci..., origin..., radius) end # MAIN SCRIPT -------------------------------------------------------------------- function ShearBand2D() n = 32 nx = n ny = n init_mpi = JustRelax.MPI.Initialized() ? false : true igg = IGG(init_global_grid(nx, ny, 1; init_MPI = init_mpi)...) # Physical domain ------------------------------------ ly = 1e0 # domain length in y lx = ly # domain length in x ni = nx, ny # number of cells li = lx, ly # domain length in x- and y- di = @. li / ni # grid step in x- and -y origin = 0.0, 0.0 # origin coordinates grid = Geometry(ni, li; origin = origin) (; xci, xvi) = grid # nodes at the center and vertices of the cells dt = Inf # Physical properties using GeoParams ---------------- τ_y = 1.6 # yield stress. If do_DP=true, τ_y stand for the cohesion: c*cos(ϕ) ϕ = 30 # friction angle C = τ_y # Cohesion η0 = 1.0 # viscosity G0 = 1.0 # elastic shear modulus Gi = G0/(6.0-4.0) # elastic shear modulus perturbation εbg = 1.0 # background strain-rate η_reg = 8e-3 # regularisation "viscosity" dt = η0/G0/4.0 # assumes Maxwell time of 4 dt /= 5 el_bg = ConstantElasticity(; G=G0, Kb=4) el_inc = ConstantElasticity(; G=Gi, Kb=4) visc = LinearViscous(; η=η0) # soft_C = LinearSoftening((C/2, C), (0e0, 2e0)) soft_C = NonLinearSoftening(;ξ₀ = C, Δ=C/2) pl = DruckerPrager_regularised(; # non-regularized plasticity C = C, ϕ = ϕ, η_vp = η_reg, Ψ = 0, softening_C = soft_C ) rheology = ( # Low density phase SetMaterialParams(; Phase = 1, Density = ConstantDensity(; ρ = 0.0), Gravity = ConstantGravity(; g = 0.0), CompositeRheology = CompositeRheology((visc, el_bg, pl)), Elasticity = el_bg, ), # High density phase SetMaterialParams(; Density = ConstantDensity(; ρ = 0.0), Gravity = ConstantGravity(; g = 0.0), CompositeRheology = CompositeRheology((visc, el_inc, pl)), Elasticity = el_inc, ), ) # Initialize phase ratios ------------------------------- radius = 0.1 phase_ratios = PhaseRatio(backend, ni, length(rheology)) init_phases!(phase_ratios, xci, radius) # STOKES --------------------------------------------- # Allocate arrays needed for every Stokes problem stokes = StokesArrays(backend, ni) pt_stokes = PTStokesCoeffs(li, di; ϵ=1e-6, CFL = 0.75 / √2.1) # Buoyancy forces ρg = @zeros(ni...), @zeros(ni...) args = (; T = @zeros(ni...), P = stokes.P, dt = dt, ΔTc = @zeros(ni...)) # Rheology compute_viscosity!( stokes, phase_ratios, args, rheology, (-Inf, Inf) ) # Boundary conditions flow_bcs = VelocityBoundaryConditions(; free_slip = (left = true, right = true, top = true, bot = true), no_slip = (left = false, right = false, top = false, bot=false), ) stokes.V.Vx .= PTArray(backend)([ x*εbg for x in xvi[1], _ in 1:ny+2]) stokes.V.Vy .= PTArray(backend)([-y*εbg for _ in 1:nx+2, y in xvi[2]]) flow_bcs!(stokes, flow_bcs) # apply boundary conditions update_halo!(@velocity(stokes)...) # Time loop t, it = 0.0, 0 tmax = 3.5 τII = Float64[] sol = Float64[] ttot = Float64[] local iters, τII, sol while t < tmax # Stokes solver ---------------- iters = solve!( stokes, pt_stokes, di, flow_bcs, ρg, phase_ratios, rheology, args, dt, igg; kwargs = ( verbose = false, iterMax = 50e3, nout = 1e2, viscosity_cutoff = (-Inf, Inf) ) ) tensor_invariant!(stokes.ε) push!(τII, maximum(stokes.τ.xx)) it += 1 t += dt push!(sol, solution(εbg, t, G0, η0)) push!(ttot, t) println("it = $it; t = $t \n") end finalize_global_grid(; finalize_MPI = true) return iters, τII, sol end @testset "NonLinearSoftening_ShearBand2D" begin @suppress begin iters, τII, sol = ShearBand2D() @test passed = iters.err_evo1[end] < 1e-6 @test τII[end] ≈ 1.48348 atol = 1e-4 @test sol[end] ≈ 1.94255 atol = 1e-4 end end
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
9082
push!(LOAD_PATH, "..") using Test, Suppressor @static if ENV["JULIA_JUSTRELAX_BACKEND"] === "AMDGPU" using AMDGPU AMDGPU.allowscalar(true) elseif ENV["JULIA_JUSTRELAX_BACKEND"] === "CUDA" using CUDA CUDA.allowscalar(true) end # Benchmark of Duretz et al. 2014 # http://dx.doi.org/10.1002/2014GL060438 using JustRelax, JustRelax.JustRelax2D using ParallelStencil, ParallelStencil.FiniteDifferences2D const backend_JR = @static if ENV["JULIA_JUSTRELAX_BACKEND"] === "AMDGPU" @init_parallel_stencil(AMDGPU, Float64, 2) AMDGPUBackend elseif ENV["JULIA_JUSTRELAX_BACKEND"] === "CUDA" @init_parallel_stencil(CUDA, Float64, 2) CUDABackend else @init_parallel_stencil(Threads, Float64, 2) CPUBackend end using JustPIC, JustPIC._2D # Threads is the default backend, # to run on a CUDA GPU load CUDA.jl (i.e. "using CUDA") at the beginning of the script, # and to run on an AMD GPU load AMDGPU.jl (i.e. "using AMDGPU") at the beginning of the script. const backend = @static if ENV["JULIA_JUSTRELAX_BACKEND"] === "AMDGPU" JustPIC.AMDGPUBackend elseif ENV["JULIA_JUSTRELAX_BACKEND"] === "CUDA" CUDABackend else JustPIC.CPUBackend end # Load script dependencies using GeoParams # Load file with all the rheology configurations include("../miniapps/benchmarks/stokes2D/shear_heating/Shearheating_rheology.jl") # ## SET OF HELPER FUNCTIONS PARTICULAR FOR THIS SCRIPT -------------------------------- function copyinn_x!(A, B) @parallel function f_x(A, B) @all(A) = @inn_x(B) return nothing end @parallel f_x(A, B) end import ParallelStencil.INDICES const idx_j = INDICES[2] macro all_j(A) return esc(:($A[$idx_j])) end # Initial pressure profile - not accurate @parallel function init_P!(P, ρg, z) @all(P) = abs(@all(ρg) * @all_j(z)) * <(@all_j(z), 0.0) return nothing end ## END OF HELPER FUNCTION ------------------------------------------------------------ ## BEGIN OF MAIN SCRIPT -------------------------------------------------------------- function Shearheating2D(igg; nx=32, ny=32) # Physical domain ------------------------------------ ly = 40e3 # domain length in y lx = 70e3 # domain length in x ni = nx, ny # number of cells li = lx, ly # domain length in x- and y- di = @. li / ni # grid step in x- and -y origin = 0.0, -ly # origin coordinates (15km f sticky air layer) grid = Geometry(ni, li; origin = origin) (; xci, xvi) = grid # nodes at the center and vertices of the cells # ---------------------------------------------------- # Physical properties using GeoParams ---------------- rheology = init_rheologies(; is_TP_Conductivity=false) κ = (4 / (rheology[1].HeatCapacity[1].Cp * rheology[1].Density[1].ρ)) dt = dt_diff = 0.5 * min(di...)^2 / κ / 2.01 # diffusive CFL timestep limiter # ---------------------------------------------------- # Initialize particles ------------------------------- nxcell, max_xcell, min_xcell = 20, 32, 12 particles = init_particles(backend, nxcell, max_xcell, min_xcell, xvi...) # velocity grids grid_vx, grid_vy = velocity_grids(xci, xvi, di) # temperature pT, pPhases = init_cell_arrays(particles, Val(3)) particle_args = (pT, pPhases) # Elliptical temperature anomaly xc_anomaly = lx / 2 # origin of thermal anomaly yc_anomaly = 40e3 # origin of thermal anomaly r_anomaly = 3e3 # radius of perturbation phase_ratios = PhaseRatio(backend_JR, ni, length(rheology)) init_phases!(pPhases, particles, xc_anomaly, yc_anomaly, r_anomaly) phase_ratios_center!(phase_ratios, particles, grid, pPhases) # ---------------------------------------------------- # STOKES --------------------------------------------- # Allocate arrays needed for every Stokes problem stokes = StokesArrays(backend_JR, ni) pt_stokes = PTStokesCoeffs(li, di; ϵ=1e-4, CFL = 0.9 / √2.1) # ---------------------------------------------------- # TEMPERATURE PROFILE -------------------------------- thermal = ThermalArrays(backend_JR, ni) thermal_bc = TemperatureBoundaryConditions(; no_flux = (left = true, right = true, top = false, bot = false), ) # Initialize constant temperature @views thermal.T .= 273.0 + 400 thermal_bcs!(thermal, thermal_bc) temperature2center!(thermal) # ---------------------------------------------------- # Buoyancy forces ρg = @zeros(ni...), @zeros(ni...) compute_ρg!(ρg[2], phase_ratios, rheology, (T=thermal.Tc, P=stokes.P)) @parallel init_P!(stokes.P, ρg[2], xci[2]) # Rheology args = (; T = thermal.Tc, P = stokes.P, dt = Inf) compute_viscosity!(stokes, phase_ratios, args, rheology, (-Inf, Inf)) # PT coefficients for thermal diffusion pt_thermal = PTThermalCoeffs( backend_JR, rheology, phase_ratios, args, dt, ni, di, li; ϵ=1e-5, CFL= 1e-3 / √2.1 ) # Boundary conditions flow_bcs = VelocityBoundaryConditions(; free_slip = (left = true, right=true, top=true, bot=true), ) ## Compression and not extension - fix this εbg = 5e-14 stokes.V.Vx .= PTArray(backend_JR)([ -(x - lx/2) * εbg for x in xvi[1], _ in 1:ny+2]) stokes.V.Vy .= PTArray(backend_JR)([ (ly - abs(y)) * εbg for _ in 1:nx+2, y in xvi[2]]) flow_bcs!(stokes, flow_bcs) # apply boundary conditions update_halo!(@velocity(stokes)...) T_buffer = @zeros(ni.+1) Told_buffer = similar(T_buffer) for (dst, src) in zip((T_buffer, Told_buffer), (thermal.T, thermal.Told)) copyinn_x!(dst, src) end grid2particle!(pT, xvi, T_buffer, particles) # Time loop t, it = 0.0, 0 local iters, thermal while it < 10 # Stokes solver ---------------- iters = solve!( stokes, pt_stokes, di, flow_bcs, ρg, phase_ratios, rheology, args, dt, igg; kwargs = (; iterMax = 75e3, nout=1e3, viscosity_cutoff=(-Inf, Inf) ) ) tensor_invariant!(stokes.ε) dt = compute_dt(stokes, di, dt_diff) # ------------------------------ # interpolate fields from particle to grid vertices particle2grid!(T_buffer, pT, xvi, particles) @views T_buffer[:, end] .= 273.0 + 400 @views thermal.T[2:end-1, :] .= T_buffer temperature2center!(thermal) compute_shear_heating!( thermal, stokes, phase_ratios, rheology, # needs to be a tuple dt, ) # Thermal solver --------------- heatdiffusion_PT!( thermal, pt_thermal, thermal_bc, rheology, args, dt, di; kwargs = (; igg = igg, phase = phase_ratios, iterMax = 10e3, nout = 1e2, verbose = true, ) ) # ------------------------------ # Advection -------------------- # advect particles in space advection!(particles, RungeKutta2(), @velocity(stokes), (grid_vx, grid_vy), dt) # advect particles in memory move_particles!(particles, xvi, particle_args) # interpolate fields from grid vertices to particles for (dst, src) in zip((T_buffer, Told_buffer), (thermal.T, thermal.Told)) copyinn_x!(dst, src) end grid2particle_flip!(pT, xvi, T_buffer, Told_buffer, particles) # check if we need to inject particles inject_particles_phase!(particles, pPhases, (pT,), (T_buffer,), xvi) # update phase ratios phase_ratios_center!(phase_ratios, particles, grid, pPhases) @show it += 1 t += dt end finalize_global_grid(; finalize_MPI=true) return iters, thermal end @testset "Shearheating2D" begin @suppress begin n = 32 nx = n ny = n igg = if !(JustRelax.MPI.Initialized()) IGG(init_global_grid(nx, ny, 1; init_MPI=true)...) else igg end # Initialize iters and thermal to ensure they are defined iters = nothing thermal = nothing try iters, thermal = Shearheating2D(igg; nx=nx, ny=ny) catch e @warn e try iters, thermal = Shearheating2D(igg; nx=nx, ny=ny) catch e2 @warn e2 end end # Ensure iters is defined before running the test @test iters != nothing && iters.err_evo1[end] < 1e-4 end end
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
9141
push!(LOAD_PATH, "..") using Test, Suppressor @static if ENV["JULIA_JUSTRELAX_BACKEND"] === "AMDGPU" using AMDGPU AMDGPU.allowscalar(true) elseif ENV["JULIA_JUSTRELAX_BACKEND"] === "CUDA" using CUDA CUDA.allowscalar(true) end # Benchmark of Duretz et al. 2014 # http://dx.doi.org/10.1002/2014GL060438 using JustRelax, JustRelax.JustRelax3D using ParallelStencil, ParallelStencil.FiniteDifferences3D const backend_JR = @static if ENV["JULIA_JUSTRELAX_BACKEND"] === "AMDGPU" @init_parallel_stencil(AMDGPU, Float64, 3) AMDGPUBackend elseif ENV["JULIA_JUSTRELAX_BACKEND"] === "CUDA" @init_parallel_stencil(CUDA, Float64, 3) CUDABackend else @init_parallel_stencil(Threads, Float64, 3) CPUBackend end using JustPIC using JustPIC._3D # Threads is the default backend, # to run on a CUDA GPU load CUDA.jl (i.e. "using CUDA") at the beginning of the script, # and to run on an AMD GPU load AMDGPU.jl (i.e. "using AMDGPU") at the beginning of the script. const backend = @static if ENV["JULIA_JUSTRELAX_BACKEND"] === "AMDGPU" JustPIC.AMDGPUBackend elseif ENV["JULIA_JUSTRELAX_BACKEND"] === "CUDA" CUDABackend else JustPIC.CPUBackend end import JustRelax.@cell # Load script dependencies using Printf, GeoParams # Load file with all the rheology configurations include("../miniapps/benchmarks/stokes3D/shear_heating/Shearheating_rheology.jl") ## SET OF HELPER FUNCTIONS PARTICULAR FOR THIS SCRIPT -------------------------------- import ParallelStencil.INDICES const idx_k = INDICES[3] macro all_k(A) return esc(:($A[$idx_k])) end # Initial pressure profile - not accurate @parallel function init_P!(P, ρg, z) @all(P) = abs(@all(ρg) * @all_k(z)) * <(@all_k(z), 0.0) return nothing end ## END OF HELPER FUNCTION ------------------------------------------------------------ ## BEGIN OF MAIN SCRIPT -------------------------------------------------------------- function Shearheating3D(igg; nx=16, ny=16, nz=16) # Physical domain ------------------------------------ lx = 70e3 # domain length in x ly = 70e3 # domain length in y lz = 40e3 # domain length in y ni = nx, ny, nz # number of cells li = lx, ly, lz # domain length in x- and y- di = @. li / (nx_g(),ny_g(),nz_g()) # grid step in x- and -y origin = 0.0, 0.0, -lz # origin coordinates (15km f sticky air layer) grid = Geometry(ni, li; origin = origin) (; xci, xvi) = grid # nodes at the center and vertices of the cells # ---------------------------------------------------- # Physical properties using GeoParams ---------------- rheology = init_rheologies(; is_TP_Conductivity=false) κ = (4 / (rheology[1].HeatCapacity[1].Cp * rheology[1].Density[1].ρ)) dt = dt_diff = 0.5 * min(di...)^3 / κ / 3.01 # diffusive CFL timestep limiter # ---------------------------------------------------- # Initialize particles ------------------------------- nxcell, max_xcell, min_xcell = 20, 40, 10 particles = init_particles(backend, nxcell, max_xcell, min_xcell, xvi...) # velocity grids grid_vx, grid_vy, grid_vz = velocity_grids(xci, xvi, di) # temperature pT, pPhases = init_cell_arrays(particles, Val(2)) particle_args = (pT, pPhases) # Elliptical temperature anomaly xc_anomaly = lx/2 # origin of thermal anomaly yc_anomaly = ly/2 # origin of thermal anomaly zc_anomaly = 40e3 # origin of thermal anomaly r_anomaly = 3e3 # radius of perturbation phase_ratios = PhaseRatio(backend_JR, ni, length(rheology)) init_phases!(pPhases, particles, xc_anomaly, yc_anomaly, zc_anomaly, r_anomaly) phase_ratios_center!(phase_ratios, particles, grid, pPhases) # ---------------------------------------------------- # STOKES --------------------------------------------- # Allocate arrays needed for every Stokes problem stokes = StokesArrays(backend_JR, ni) pt_stokes = PTStokesCoeffs(li, di; ϵ=1e-4, CFL = 0.9 / √3.1) # ---------------------------------------------------- # TEMPERATURE PROFILE -------------------------------- thermal = ThermalArrays(backend_JR, ni) thermal_bc = TemperatureBoundaryConditions(; no_flux = (left = true , right = true , top = false, bot = false, front = true , back = true), ) # Initialize constant temperature @views thermal.T .= 273.0 + 400 thermal_bcs!(thermal, thermal_bc) temperature2center!(thermal) # ---------------------------------------------------- # Buoyancy forces ρg = ntuple(_ -> @zeros(ni...), Val(3)) compute_ρg!(ρg[3], phase_ratios, rheology, (T=thermal.Tc, P=stokes.P)) @parallel init_P!(stokes.P, ρg[3], xci[3]) # Rheology args = (; T = thermal.Tc, P = stokes.P, dt = Inf) compute_viscosity!(stokes, phase_ratios, args, rheology, (-Inf, Inf)) # PT coefficients for thermal diffusion pt_thermal = PTThermalCoeffs( backend_JR, rheology, phase_ratios, args, dt, ni, di, li; ϵ=1e-5, CFL=5e-2 / √3 ) # Boundary conditions flow_bcs = VelocityBoundaryConditions(; free_slip = (left = true , right = true , top = true , bot = true , front = true , back = true ), no_slip = (left = false, right = false, top = false, bot = false, front = false, back = false), ) ## Compression and not extension - fix this εbg = 5e-14 stokes.V.Vx .= PTArray(backend_JR)([ -(x - lx/2) * εbg for x in xvi[1], _ in 1:ny+2, _ in 1:nz+2]) stokes.V.Vy .= PTArray(backend_JR)([ -(y - ly/2) * εbg for _ in 1:nx+2, y in xvi[2], _ in 1:nz+2]) stokes.V.Vz .= PTArray(backend_JR)([ (lz - abs(z)) * εbg for _ in 1:nx+2, _ in 1:ny+2, z in xvi[3]]) flow_bcs!(stokes, flow_bcs) # apply boundary conditions update_halo!(@velocity(stokes)...) grid2particle!(pT, xvi, thermal.T, particles) # Time loop t, it = 0.0, 0 local iters while it < 5 # Stokes solver ---------------- iters = solve!( stokes, pt_stokes, di, flow_bcs, ρg, phase_ratios, rheology, args, Inf, igg; kwargs = ( iterMax = 100e3, nout=1e3, viscosity_cutoff=(-Inf, Inf), verbose=false, ) ) tensor_invariant!(stokes.ε) dt = compute_dt(stokes, di, dt_diff) # ------------------------------ # interpolate fields from particle to grid vertices particle2grid!(thermal.T, pT, xvi, particles) temperature2center!(thermal) compute_shear_heating!( thermal, stokes, phase_ratios, rheology, # needs to be a tuple dt, ) # Thermal solver --------------- heatdiffusion_PT!( thermal, pt_thermal, thermal_bc, rheology, args, dt, di; kwargs =( igg = igg, phase = phase_ratios, iterMax = 10e3, nout = 1e2, verbose = false, ) ) # ------------------------------ # Advection -------------------- # advect particles in space advection!( particles, RungeKutta2(), @velocity(stokes), (grid_vx, grid_vy, grid_vz), dt ) # advect particles in memory move_particles!(particles, xvi, particle_args) # interpolate fields from grid vertices to particles grid2particle_flip!(pT, xvi, thermal.T, thermal.Told, particles) # check if we need to inject particles inject_particles_phase!(particles, pPhases, (pT,), (thermal.T,), xvi) # update phase ratios phase_ratios_center!(phase_ratios, particles, grid, pPhases) @show it += 1 t += dt # ------------------------------ end finalize_global_grid(; finalize_MPI=true) return iters, thermal end @testset "Shearheating3D" begin @suppress begin n = 16 nx = n ny = n nz = n igg = if !(JustRelax.MPI.Initialized()) IGG(init_global_grid(nx, ny, nz; init_MPI=true)...) else igg end # Initialize iters and thermal to ensure they are defined iters = nothing thermal = nothing try iters, thermal = Shearheating3D(igg; nx=nx, ny=ny, nz=nz) catch e @warn e try iters, thermal = Shearheating3D(igg; nx=nx, ny=ny, nz=nz) catch e2 @warn e2 end end # Ensure iters is defined before running the test @test iters != nothing && iters.err_evo1[end] < 1e-4 end end
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
6994
push!(LOAD_PATH, "..") @static if ENV["JULIA_JUSTRELAX_BACKEND"] === "AMDGPU" using AMDGPU AMDGPU.allowscalar(true) #used because of velocity2vertex! elseif ENV["JULIA_JUSTRELAX_BACKEND"] === "CUDA" using CUDA CUDA.allowscalar(true) #used because of velocity2vertex! end using Test, Suppressor using JustRelax, JustRelax.JustRelax2D using ParallelStencil, ParallelStencil.FiniteDifferences2D const backend_JR = @static if ENV["JULIA_JUSTRELAX_BACKEND"] === "AMDGPU" @init_parallel_stencil(AMDGPU, Float64, 2) AMDGPUBackend elseif ENV["JULIA_JUSTRELAX_BACKEND"] === "CUDA" @init_parallel_stencil(CUDA, Float64, 2) CUDABackend else @init_parallel_stencil(Threads, Float64, 2) CPUBackend end using JustPIC, JustPIC._2D const backend = @static if ENV["JULIA_JUSTRELAX_BACKEND"] === "AMDGPU" JustPIC.AMDGPUBackend elseif ENV["JULIA_JUSTRELAX_BACKEND"] === "CUDA" CUDABackend else JustPIC.CPUBackend end using GeoParams ## SET OF HELPER FUNCTIONS PARTICULAR FOR THIS SCRIPT -------------------------------- # Thermal rectangular perturbation function rectangular_perturbation!(T, xc, yc, r, xvi) @parallel_indices (i, j) function _rectangular_perturbation!(T, xc, yc, r, x, y) @inbounds if ((x[i]-xc)^2 ≤ r^2) && ((y[j] - yc)^2 ≤ r^2) depth = abs(y[j]) dTdZ = (2047 - 2017) / 50e3 offset = 2017 T[i + 1, j] = (depth - 585e3) * dTdZ + offset end return nothing end ni = length.(xvi) @parallel (@idx ni) _rectangular_perturbation!(T, xc, yc, r, xvi...) return nothing end function init_phases!(phases, particles, xc, yc, r) ni = size(phases) @parallel_indices (i, j) function init_phases!(phases, px, py, index, xc, yc, r) @inbounds for ip in JustRelax.cellaxes(phases) # quick escape JustRelax.@cell(index[ip, i, j]) == 0 && continue x = JustRelax.@cell px[ip, i, j] depth = -(JustRelax.@cell py[ip, i, j]) # plume - rectangular JustRelax.@cell phases[ip, i, j] = if ((x -xc)^2 ≤ r^2) && ((depth - yc)^2 ≤ r^2) 2.0 else 1.0 end end return nothing end @parallel (@idx ni) init_phases!(phases, particles.coords..., particles.index, xc, yc, r) end import ParallelStencil.INDICES const idx_j = INDICES[2] macro all_j(A) esc(:($A[$idx_j])) end @parallel function init_P!(P, ρg, z) @all(P) = @all(ρg)*abs(@all_j(z)) return nothing end # -------------------------------------------------------------------------------- # BEGIN MAIN SCRIPT # -------------------------------------------------------------------------------- function Sinking_Block2D() ar = 1 n = 32 nx = n ny = n init_mpi = JustRelax.MPI.Initialized() ? false : true igg = IGG(init_global_grid(nx, ny, 1; init_MPI = init_mpi)...) # Physical domain ------------------------------------ ly = 500e3 lx = ly * ar origin = 0.0, -ly # origin coordinates ni = nx, ny # number of cells li = lx, ly # domain length in x- and y- di = @. li / (nx_g(), ny_g()) # grid step in x- and -y grid = Geometry(ni, li; origin = origin) (; xci, xvi) = grid # nodes at the center and vertices of the cells # ---------------------------------------------------- # Physical properties using GeoParams ---------------- δρ = 100 rheology = ( SetMaterialParams(; Name = "Mantle", Phase = 1, Density = ConstantDensity(; ρ=3.2e3), CompositeRheology = CompositeRheology((LinearViscous(; η = 1e21), )), Gravity = ConstantGravity(; g=9.81), ), SetMaterialParams(; Name = "Block", Phase = 2, Density = ConstantDensity(; ρ=3.2e3 + δρ), CompositeRheology = CompositeRheology((LinearViscous(; η = 1e23), )), Gravity = ConstantGravity(; g=9.81), ) ) # heat diffusivity dt = 1 # ---------------------------------------------------- # Initialize particles ------------------------------- nxcell, max_xcell, min_xcell = 20, 40, 12 particles = init_particles( backend, nxcell, max_xcell, min_xcell, xvi... ) # temperature pPhases, = init_cell_arrays(particles, Val(1)) particle_args = (pPhases, ) # Rectangular density anomaly xc_anomaly = 250e3 # origin of thermal anomaly yc_anomaly = -(ly-400e3) # origin of thermal anomaly r_anomaly = 50e3 # radius of perturbation phase_ratios = PhaseRatio(backend_JR, ni, length(rheology)) init_phases!(pPhases, particles, xc_anomaly, abs(yc_anomaly), r_anomaly) phase_ratios_center!(phase_ratios, particles, grid, pPhases) # STOKES --------------------------------------------- # Allocate arrays needed for every Stokes problem stokes = StokesArrays(backend_JR, ni) pt_stokes = PTStokesCoeffs(li, di; ϵ=1e-5, CFL = 0.95 / √2.1) # Buoyancy forces ρg = @zeros(ni...), @zeros(ni...) compute_ρg!(ρg[2], phase_ratios, rheology, (T=@ones(ni...), P=stokes.P)) @parallel init_P!(stokes.P, ρg[2], xci[2]) # ---------------------------------------------------- # Viscosity args = (; T = @ones(ni...), P = stokes.P, dt=Inf) η_cutoff = -Inf, Inf compute_viscosity!(stokes, phase_ratios, args, rheology, (-Inf, Inf)) # ---------------------------------------------------- # Boundary conditions flow_bcs = VelocityBoundaryConditions(; free_slip = (left = true, right = true, top = true, bot = true), ) flow_bcs!(stokes, flow_bcs) # apply boundary conditions update_halo!(@velocity(stokes)...) # Stokes solver ---------------- iters = solve!( stokes, pt_stokes, di, flow_bcs, ρg, phase_ratios, rheology, args, dt, igg; kwargs = ( iterMax=150e3, nout=1e3, viscosity_cutoff = η_cutoff, verbose = false, ) ); dt = compute_dt(stokes, di, igg) # ------------------------------ Vx_v = @zeros(ni.+1...) Vy_v = @zeros(ni.+1...) velocity2vertex!(Vx_v, Vy_v, @velocity(stokes)...) velocity = @. √(Vx_v^2 + Vy_v^2 ) finalize_global_grid(; finalize_MPI = true) return iters, velocity end @testset "Sinking_Block2D" begin @suppress begin iters, velocity = Sinking_Block2D() @test passed = iters.err_evo1[end] < 1e-5 @test maximum(velocity) ≈ 4.841885609356093e-10 atol = 1e-6 end end
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
970
push!(LOAD_PATH, "..") @static if ENV["JULIA_JUSTRELAX_BACKEND"] === "AMDGPU" using AMDGPU elseif ENV["JULIA_JUSTRELAX_BACKEND"] === "CUDA" using CUDA end using Test, Suppressor using JustRelax, JustRelax.JustRelax3D using ParallelStencil const backend = @static if ENV["JULIA_JUSTRELAX_BACKEND"] === "AMDGPU" @init_parallel_stencil(AMDGPU, Float64, 3) AMDGPUBackend elseif ENV["JULIA_JUSTRELAX_BACKEND"] === "CUDA" @init_parallel_stencil(CUDA, Float64, 3) CUDABackend else @init_parallel_stencil(Threads, Float64, 3) CPUBackend end include("../miniapps/benchmarks/stokes3D/burstedde/Burstedde.jl") function check_convergence_case1() nx = 16 ny = 16 nz = 16 _, _, iters = burstedde(; nx=nx, ny=ny, nz=nz, init_MPI=true, finalize_MPI=true) tol = 1e-8 passed = iters.err_evo1[end] < tol return passed end @testset "Burstedde" begin @suppress begin @test check_convergence_case1() end end
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
1613
push!(LOAD_PATH, "..") @static if ENV["JULIA_JUSTRELAX_BACKEND"] === "AMDGPU" using AMDGPU elseif ENV["JULIA_JUSTRELAX_BACKEND"] === "CUDA" using CUDA end using Test, Suppressor using JustRelax, JustRelax.JustRelax2D using ParallelStencil, ParallelStencil.FiniteDifferences2D const backend = @static if ENV["JULIA_JUSTRELAX_BACKEND"] === "AMDGPU" @init_parallel_stencil(AMDGPU, Float64, 2) AMDGPUBackend elseif ENV["JULIA_JUSTRELAX_BACKEND"] === "CUDA" @init_parallel_stencil(CUDA, Float64, 2) CUDABackend else @init_parallel_stencil(Threads, Float64, 2) CPUBackend end include("../miniapps/benchmarks/stokes2D/elastic_buildup/Elastic_BuildUp.jl") function check_convergence_case1() # model specific parameters nx, ny = 32, 32 lx, ly = 100e3, 100e3 # length of the domain in meters endtime = 10 # duration of the model in kyrs η0 = 1e21 # viscosity εbg = 1e-14 # background strain rate (pure shear boundary conditions) G = 10e9 # shear modulus # run model init_mpi = JustRelax.MPI.Initialized() ? false : true _, _, av_τyy, sol_τyy, t, = elastic_buildup(; nx=nx, ny=ny, lx=lx, ly=ly, endtime=endtime, η0=η0, εbg=εbg, G=G, init_MPI=init_mpi, finalize_MPI=false, ); err = sum(abs(abs.(av_τyy[i]) - sol_τyy[i]) / sol_τyy[i] for i in eachindex(av_τyy)) / length(av_τyy) println("mean error $err") return err ≤ 5e-3 end @testset "Elastic Build-Up" begin @suppress begin @test check_convergence_case1() end end
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
1014
push!(LOAD_PATH, "..") @static if ENV["JULIA_JUSTRELAX_BACKEND"] === "AMDGPU" using AMDGPU elseif ENV["JULIA_JUSTRELAX_BACKEND"] === "CUDA" using CUDA end using Test, Suppressor using JustRelax, JustRelax.JustRelax2D using ParallelStencil const backend = @static if ENV["JULIA_JUSTRELAX_BACKEND"] === "AMDGPU" @init_parallel_stencil(AMDGPU, Float64, 2) AMDGPUBackend elseif ENV["JULIA_JUSTRELAX_BACKEND"] === "CUDA" @init_parallel_stencil(CUDA, Float64, 2) CUDABackend else @init_parallel_stencil(Threads, Float64, 2) CPUBackend end include("../miniapps/benchmarks/stokes2D/solcx/SolCx.jl") function check_convergence_case1() nx = 64 ny = 64 Δη = 1e6 init_MPI = JustRelax.MPI.Initialized() ? false : true _, _, iters, = solCx(Δη; nx=nx, ny=ny, init_MPI=init_MPI, finalize_MPI=false) tol = 1e-8 passed = iters.err_evo1[end] < tol return passed end @testset "solcx" begin @suppress begin @test check_convergence_case1() end end
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
1001
push!(LOAD_PATH, "..") @static if ENV["JULIA_JUSTRELAX_BACKEND"] === "AMDGPU" using AMDGPU elseif ENV["JULIA_JUSTRELAX_BACKEND"] === "CUDA" using CUDA end using Test, Suppressor using JustRelax, JustRelax.JustRelax2D using ParallelStencil const backend = @static if ENV["JULIA_JUSTRELAX_BACKEND"] === "AMDGPU" @init_parallel_stencil(AMDGPU, Float64, 2) AMDGPUBackend elseif ENV["JULIA_JUSTRELAX_BACKEND"] === "CUDA" @init_parallel_stencil(CUDA, Float64, 2) CUDABackend else @init_parallel_stencil(Threads, Float64, 2) CPUBackend end include("../miniapps/benchmarks/stokes2D/solkz/SolKz.jl") function check_convergence_case1() nx = 64 ny = 64 init_MPI = JustRelax.MPI.Initialized() ? false : true _, _, iters, _ = solKz(; nx=nx, ny=ny, init_MPI=init_MPI, finalize_MPI=false) tol = 1e-8 passed = iters.err_evo1[end] < tol return passed end @testset "solkz" begin @suppress begin @test check_convergence_case1() end end
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git
[ "MIT" ]
0.3.2
400eb2287ceaccfcb37bb7db095ecd914493ce75
code
1448
push!(LOAD_PATH, "..") @static if ENV["JULIA_JUSTRELAX_BACKEND"] === "AMDGPU" using AMDGPU AMDGPU.allowscalar(true) elseif ENV["JULIA_JUSTRELAX_BACKEND"] === "CUDA" using CUDA CUDA.allowscalar(true) end using Test, Suppressor using JustRelax, JustRelax.JustRelax3D using ParallelStencil const backend = @static if ENV["JULIA_JUSTRELAX_BACKEND"] === "AMDGPU" @init_parallel_stencil(AMDGPU, Float64, 3) AMDGPUBackend elseif ENV["JULIA_JUSTRELAX_BACKEND"] === "CUDA" @init_parallel_stencil(CUDA, Float64, 3) CUDABackend else @init_parallel_stencil(Threads, Float64, 3) CPUBackend end include("../miniapps/benchmarks/stokes3D/solvi/SolVi3D.jl") function check_convergence_case1() nx = 16 ny = 16 nz = 16 # model specific parameters Δη = 1e-3 # viscosity ratio between matrix and inclusion rc = 1e0 # radius of the inclusion εbg = 1e0 # background strain rate lx, ly, lz = 1e1, 1e1, 1e1 # domain siye in x and y directions # run model _, _, iters = solVi3D(; Δη=Δη, nx=nx, ny=ny, nz=nz, lx=lx, ly=ly, lz=lz, rc=rc, εbg=εbg, init_MPI=JustRelax.MPI.Initialized() ? false : true, finalize_MPI=false, ) tol = 1e-8 passed = iters.norm_Rx[end] < tol return passed end @testset "solvi3D" begin @suppress begin @test check_convergence_case1() end end
JustRelax
https://github.com/PTsolvers/JustRelax.jl.git