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.1.3 | f4076dd5a103010d48bb6c4e50c5526f6622fa96 | docs | 10044 | ---
title: ODE Solver Multi-Language Wrapper Package Work-Precision Benchmarks (MATLAB, SciPy, Julia, deSolve (R))
author: Chris Rackauckas
---
The following benchmarks demonstrate the performance differences due to using
similar algorithms from wrapper packages in the main scripting languages across
a range of stiff and non-stiff ODEs. It takes into account solver time and
error in order to ensure correctness of interpretations. These were ran with
Julia 1.7, MATLAB 2019B, deSolve 1.3.0, and SciPy 1.6.1.
These benchmarks are generated using the following bindings:
- [MATLABDiffEq.jl](https://github.com/JuliaDiffEq/MATLABDiffEq.jl) (MATLAB)
- [SciPyDiffEq.jl](https://github.com/JuliaDiffEq/SciPyDiffEq.jl) (SciPy)
- [deSolveDiffEq.jl](https://github.com/JuliaDiffEq/deSolveDiffEq.jl) (deSolve)
- [OrdinaryDiffEq.jl](https://github.com/JuliaDiffEq/OrdinaryDiffEq.jl) (OrdinaryDiffEq.jl)
- [Sundials.jl](https://github.com/JuliaDiffEq/Sundials.jl) (Sundials)
- [ODEInterfaceDiffEq.jl](https://github.com/JuliaDiffEq/ODEInterfaceDiffEq.jl) (Hairer and Netlib)
The respective repos verify negligible overhead on interop (MATLAB, ODEInterface,
and Sundials overhead are negligable, SciPy is accelerated 3x over SciPy+Numba
setups due to the Julia JIT on the ODE function, deSolve sees a 3x overhead
over the pure-R version). Error and timing is compared together to ensure
the methods are solving to the same accuracy when compared.
More wrappers will continue to be added as necessary.
## Setup
```julia
using ParameterizedFunctions, MATLABDiffEq, OrdinaryDiffEq,
ODEInterfaceDiffEq, Plots, Sundials, SciPyDiffEq, deSolveDiffEq
using DiffEqDevTools
using LinearAlgebra, StaticArrays
```
#### Non-Stiff Problem 1: Lotka-Volterra
```julia
f = @ode_def_bare LotkaVolterra begin
dx = a*x - b*x*y
dy = -c*y + d*x*y
end a b c d
p = [1.5,1,3,1]
tspan = (0.0,10.0)
u0 = [1.0,1.0]
prob = ODEProblem(f,u0,tspan,p)
staticprob = ODEProblem{false}(f,SVector{2}(u0),tspan,SVector{4}(p))
sol = solve(prob,Vern7(),abstol=1/10^14,reltol=1/10^14)
test_sol = TestSolution(sol)
setups = [
Dict(:alg=>DP5())
Dict(:alg=>Tsit5())
Dict(:alg=>Vern7())
Dict(:prob_choice => 2, :alg=>DP5())
Dict(:prob_choice => 2, :alg=>Tsit5())
Dict(:prob_choice => 2, :alg=>Vern7())
Dict(:alg=>dopri5())
Dict(:alg=>MATLABDiffEq.ode45())
Dict(:alg=>MATLABDiffEq.ode113())
Dict(:alg=>SciPyDiffEq.RK45())
Dict(:alg=>SciPyDiffEq.LSODA())
Dict(:alg=>SciPyDiffEq.odeint())
Dict(:alg=>deSolveDiffEq.lsoda())
Dict(:alg=>deSolveDiffEq.ode45())
Dict(:alg=>CVODE_Adams())
]
labels = [
"Julia: DP5"
"Julia: Tsit5"
"Julia: Vern7"
"Julia: DP5 Static"
"Julia: Tsit5 Static"
"Julia: Vern7 Static"
"Hairer: dopri5"
"MATLAB: ode45"
"MATLAB: ode113"
"SciPy: RK45"
"SciPy: LSODA"
"SciPy: odeint"
"deSolve: lsoda"
"deSolve: ode45"
"Sundials: Adams"
]
abstols = 1.0 ./ 10.0 .^ (6:13)
reltols = 1.0 ./ 10.0 .^ (3:10)
wp = WorkPrecisionSet([prob,staticprob],abstols,reltols,setups;
names = labels,print_names = true,
appxsol=[test_sol,test_sol],dense=false,
save_everystep=false,numruns=100,maxiters=10000000,
timeseries_errors=false,verbose=false)
plot(wp,title="Non-stiff 1: Lotka-Volterra",legend=:outertopleft,
color=permutedims([repeat([:LightGreen],3)...,repeat([:DarkGreen],3)...,
:Red,repeat([:Orange],2)...,repeat([:Yellow],3)...,
repeat([:Blue],2)...,:Purple]),size = (800,350),
xticks = 10.0 .^ (-12:1:5),
yticks = 10.0 .^ (-6:0.5:5),
bottom_margin=5Plots.mm)
```
#### Non-Stiff Problem 2: Rigid Body
```julia
f = @ode_def_bare RigidBodyBench begin
dy1 = -2*y2*y3
dy2 = 1.25*y1*y3
dy3 = -0.5*y1*y2 + 0.25*sin(t)^2
end
u0 = [1.0;0.0;0.9]
prob = ODEProblem(f,u0,(0.0,100.0))
staticprob = ODEProblem{false}(f,SVector{3}(u0),(0.0,100.0))
sol = solve(prob,Vern7(),abstol=1/10^14,reltol=1/10^14)
test_sol = TestSolution(sol)
setups = [Dict(:alg=>DP5())
Dict(:alg=>Tsit5())
Dict(:alg=>Vern7())
Dict(:prob_choice => 2, :alg=>DP5())
Dict(:prob_choice => 2, :alg=>Tsit5())
Dict(:prob_choice => 2, :alg=>Vern7())
Dict(:alg=>dopri5())
Dict(:alg=>MATLABDiffEq.ode45())
Dict(:alg=>MATLABDiffEq.ode113())
Dict(:alg=>SciPyDiffEq.RK45())
Dict(:alg=>SciPyDiffEq.LSODA())
Dict(:alg=>SciPyDiffEq.odeint())
Dict(:alg=>deSolveDiffEq.lsoda())
Dict(:alg=>deSolveDiffEq.ode45())
Dict(:alg=>CVODE_Adams())
]
labels = [
"Julia: DP5"
"Julia: Tsit5"
"Julia: Vern7"
"Julia: DP5 Static"
"Julia: Tsit5 Static"
"Julia: Vern7 Static"
"Hairer: dopri5"
"MATLAB: ode45"
"MATLAB: ode113"
"SciPy: RK45"
"SciPy: LSODA"
"SciPy: odeint"
"deSolve: lsoda"
"deSolve: ode45"
"Sundials: Adams"
]
abstols = 1.0 ./ 10.0 .^ (6:13)
reltols = 1.0 ./ 10.0 .^ (3:10)
wp = WorkPrecisionSet([prob,staticprob],abstols,reltols,setups;
names = labels,print_names = true,
appxsol=[test_sol,test_sol],dense=false,
save_everystep=false,numruns=100,maxiters=10000000,
timeseries_errors=false,verbose=false)
plot(wp,title="Non-stiff 2: Rigid-Body",legend=:outertopleft,
color=permutedims([repeat([:LightGreen],3)...,repeat([:DarkGreen],3)...,
:Red,repeat([:Orange],2)...,repeat([:Yellow],3)...,
repeat([:Blue],2)...,:Purple]),size = (800,350),
xticks = 10.0 .^ (-12:1:5),
yticks = 10.0 .^ (-6:0.5:5),
bottom_margin=5Plots.mm)
```
#### Stiff Problem 1: ROBER
```julia
rober = @ode_def begin
dy₁ = -k₁*y₁+k₃*y₂*y₃
dy₂ = k₁*y₁-k₂*y₂^2-k₃*y₂*y₃
dy₃ = k₂*y₂^2
end k₁ k₂ k₃
u0 = [1.0,0.0,0.0]
p = [0.04,3e7,1e4]
prob = ODEProblem(rober,u0,(0.0,1e5),p)
staticprob = ODEProblem{false}(rober,SVector{3}(u0),(0.0,1e5),SVector{3}(p))
sol = solve(prob,CVODE_BDF(),abstol=1/10^14,reltol=1/10^14)
test_sol = TestSolution(sol)
abstols = 1.0 ./ 10.0 .^ (7:12)
reltols = 1.0 ./ 10.0 .^ (3:8);
setups = [Dict(:alg=>Rosenbrock23())
Dict(:alg=>Rodas4())
Dict(:alg=>Rodas5())
Dict(:prob_choice => 2, :alg=>Rosenbrock23())
Dict(:prob_choice => 2, :alg=>Rodas4())
Dict(:prob_choice => 2, :alg=>Rodas5())
Dict(:alg=>rodas())
Dict(:alg=>radau())
Dict(:alg=>MATLABDiffEq.ode23s())
Dict(:alg=>MATLABDiffEq.ode15s())
Dict(:alg=>SciPyDiffEq.LSODA())
Dict(:alg=>SciPyDiffEq.BDF())
Dict(:alg=>SciPyDiffEq.odeint())
Dict(:alg=>deSolveDiffEq.lsoda())
Dict(:alg=>CVODE_BDF())
]
labels = [
"Julia: Rosenbrock23"
"Julia: Rodas4"
"Julia: Rodas5"
"Julia: Rosenbrock23 Static"
"Julia: Rodas4 Static"
"Julia: Rodas5 Static"
"Hairer: rodas"
"Hairer: radau"
"MATLAB: ode23s"
"MATLAB: ode15s"
"SciPy: LSODA"
"SciPy: BDF"
"SciPy: odeint"
"deSolve: lsoda"
"Sundials: CVODE"
]
wp = WorkPrecisionSet([prob,staticprob],abstols,reltols,setups;
names = labels,print_names = true,
dense=false,verbose = false,
save_everystep=false,appxsol=[test_sol,test_sol],
maxiters=Int(1e5))
plot(wp,title="Stiff 1: ROBER", legend=:outertopleft,
color=permutedims([repeat([:LightGreen],3)...,repeat([:DarkGreen],3)...,
:Red,:Red,repeat([:Orange],2)...,repeat([:Yellow],3)...,
repeat([:Blue],1)...,:Purple]),size = (800,350),
xticks = 10.0 .^ (-12:1:5),
yticks = 10.0 .^ (-6:0.5:5),
bottom_margin=5Plots.mm)
```
#### Stiff Problem 2: HIRES
```julia
f = @ode_def Hires begin
dy1 = -1.71*y1 + 0.43*y2 + 8.32*y3 + 0.0007
dy2 = 1.71*y1 - 8.75*y2
dy3 = -10.03*y3 + 0.43*y4 + 0.035*y5
dy4 = 8.32*y2 + 1.71*y3 - 1.12*y4
dy5 = -1.745*y5 + 0.43*y6 + 0.43*y7
dy6 = -280.0*y6*y8 + 0.69*y4 + 1.71*y5 -
0.43*y6 + 0.69*y7
dy7 = 280.0*y6*y8 - 1.81*y7
dy8 = -280.0*y6*y8 + 1.81*y7
end
u0 = zeros(8)
u0[1] = 1
u0[8] = 0.0057
prob = ODEProblem(f,u0,(0.0,321.8122))
staticprob = ODEProblem{false}(f,SVector{8}(u0),(0.0,321.8122))
sol = solve(prob,Rodas5(),abstol=1/10^14,reltol=1/10^14)
test_sol = TestSolution(sol)
abstols = 1.0 ./ 10.0 .^ (5:10)
reltols = 1.0 ./ 10.0 .^ (1:6);
setups = [Dict(:alg=>Rosenbrock23())
Dict(:alg=>Rodas4())
Dict(:alg=>RadauIIA5())
Dict(:prob_choice => 2, :alg=>Rosenbrock23())
Dict(:prob_choice => 2, :alg=>Rodas4())
Dict(:prob_choice => 2, :alg=>RadauIIA5())
Dict(:alg=>rodas())
Dict(:alg=>radau())
Dict(:alg=>MATLABDiffEq.ode23s())
Dict(:alg=>MATLABDiffEq.ode15s())
Dict(:alg=>SciPyDiffEq.LSODA())
Dict(:alg=>SciPyDiffEq.BDF())
Dict(:alg=>SciPyDiffEq.odeint())
Dict(:alg=>deSolveDiffEq.lsoda())
Dict(:alg=>CVODE_BDF())
]
labels = [
"Julia: Rosenbrock23"
"Julia: Rodas4"
"Julia: radau"
"Julia: Rosenbrock23 Static"
"Julia: Rodas4 Static"
"Julia: radau Static"
"Hairer: rodas"
"Hairer: radau"
"MATLAB: ode23s"
"MATLAB: ode15s"
"SciPy: LSODA"
"SciPy: BDF"
"SciPy: odeint"
"deSolve: lsoda"
"Sundials: CVODE"
]
wp = WorkPrecisionSet([prob,staticprob],abstols,reltols,setups;
names = labels,print_names = true,
dense=false,verbose = false,
save_everystep=false,appxsol=[test_sol,test_sol],
maxiters=Int(1e5),numruns=100)
plot(wp,title="Stiff 2: Hires",legend=:outertopleft,
color=permutedims([repeat([:LightGreen],3)...,repeat([:DarkGreen],3)...,
:Red,:Red,repeat([:Orange],2)...,repeat([:Yellow],3)...,
repeat([:Blue],1)...,:Purple]),size = (800,350),
xticks = 10.0 .^ (-12:1:5),
yticks = 10.0 .^ (-6:0.5:5),
bottom_margin=5Plots.mm)
```
| SciMLBenchmarks | https://github.com/SciML/SciMLBenchmarks.jl.git |
|
[
"MIT"
] | 0.1.3 | f4076dd5a103010d48bb6c4e50c5526f6622fa96 | docs | 1647 | ---
title: Special Multi-Language Differential Equation Solver Comparison Benchmarks
author: Chris Rackauckas
---
The following are extra multi-language benchmarks which are harder to fit into the standard
SciMLBenchmarks format. As such, they are less complete as they generally do not make use
of work-precision diagrams but give information about the general status of the performance
developments.
- [Torchdiffeq vs DifferentialEquations.jl (/ DiffEqFlux.jl) Benchmarks](https://gist.github.com/ChrisRackauckas/cc6ac746e2dfd285c28e0584a2bfd320)
- [torchdiffeq vs Julia DiffEqFlux Neural ODE Training Benchmark](https://gist.github.com/ChrisRackauckas/4a4d526c15cc4170ce37da837bfc32c4)
- [torchsde vs DifferentialEquations.jl / DiffEqFlux.jl](https://gist.github.com/ChrisRackauckas/6a03e7b151c86b32d74b41af54d495c6)
- [JITCODE vs SciPy vs DifferentialEquations.jl on large network dynamics](https://github.com/PIK-ICoN/NetworkDynamicsBenchmarks)
- [DifferentialEquations.jl vs Mujuco and DiffTaichi](https://arxiv.org/abs/2012.06684)
- [DiffEqFlux.jl / DifferentialEquations.jl vs Jax on an epidemic model](https://gist.github.com/ChrisRackauckas/62a063f23cccf3a55a4ac9f6e497739a)
- [DifferentialEquations.jl vs SciPy vs NumbaLSODA on a stiff ODE](https://gist.github.com/ChrisRackauckas/fd62e005c4c86520306338b6bdae6b79)
- [DifferentialEquations.jl vs SciPy vs NumbaLSODA](https://github.com/Nicholaswogan/NumbaLSODA/tree/main/benchmark)
- [Brusselator Stiff Partial Differential Equation Benchmark: Julia DifferentialEquations.jl vs Python SciPy](https://gist.github.com/ChrisRackauckas/0bdbea0079a8a3ce28522e9bc8473bf0)
| SciMLBenchmarks | https://github.com/SciML/SciMLBenchmarks.jl.git |
|
[
"MIT"
] | 0.1.3 | f4076dd5a103010d48bb6c4e50c5526f6622fa96 | docs | 8002 | ---
title: Acceleration function benchmarks
author: Sebastian Micluța-Câmpeanu, Mikhail Vaganov
---
Solving the equations of notions for an N-body problem implies solving a (large)
system of differential equations. In `DifferentialEquations.jl` these are represented
through ODE or SDE problems. To build the problem we need a function that
describe the equations. In the case of N-body problems, this function
gives the accelerations for the particles in the system.
Here we will test the performance of several acceleration functions used
in N-body simulations. The systems that will be used are not necessarily realistic
as we are not solving the problem, we just time how fast is an acceleration
function call.
```julia
using BenchmarkTools, NBodySimulator
using NBodySimulator: gather_bodies_initial_coordinates, gather_accelerations_for_potentials,
gather_simultaneous_acceleration, gather_group_accelerations
using StaticArrays
const SUITE = BenchmarkGroup();
function acceleration(simulation)
(u0, v0, n) = gather_bodies_initial_coordinates(simulation)
acceleration_functions = gather_accelerations_for_potentials(simulation)
simultaneous_acceleration = gather_simultaneous_acceleration(simulation)
function soode_system!(dv, v, u, p, t)
@inbounds for i = 1:n
a = MVector(0.0, 0.0, 0.0)
for acceleration! in acceleration_functions
acceleration!(a, u, v, t, i);
end
dv[:, i] .= a
end
for acceleration! in simultaneous_acceleration
acceleration!(dv, u, v, t);
end
end
return soode_system!
end
```
## Gravitational potential
```julia
let SUITE=SUITE
G = 6.67e-11 # m^3/kg/s^2
N = 200 # number of bodies/particles
m = 1.0 # mass of each of them
v = 10.0 # mean velocity
L = 20.0 # size of the cell side
bodies = generate_bodies_in_cell_nodes(N, m, v, L)
g_parameters = GravitationalParameters(G)
system = PotentialNBodySystem(bodies, Dict(:gravitational => g_parameters))
tspan = (0.0, 1.0)
simulation = NBodySimulation(system, tspan)
f = acceleration(simulation)
u0, v0, n = gather_bodies_initial_coordinates(simulation)
dv = zero(v0)
b = @benchmarkable $f(dv, $v0, $u0, $g_parameters, 0.) setup=(dv=zero($v0)) evals=1
SUITE["gravitational"] = b
end
```
## Coulomb potential
```julia
let SUITE=SUITE
n = 200
bodies = ChargedParticle[]
L = 20.0
m = 1.0
q = 1.0
count = 1
dL = L / (ceil(n^(1 / 3)) + 1)
for x = dL / 2:dL:L, y = dL / 2:dL:L, z = dL / 2:dL:L
if count > n
break
end
r = SVector(x, y, z)
v = SVector(.0, .0, .0)
body = ChargedParticle(r, v, m, q)
push!(bodies, body)
count += 1
end
k = 9e9
τ = 0.01 * dL / sqrt(2 * k * q * q / (dL * m))
t1 = 0.0
t2 = 1000 * τ
potential = ElectrostaticParameters(k, 0.45 * L)
system = PotentialNBodySystem(bodies, Dict(:electrostatic => potential))
pbc = CubicPeriodicBoundaryConditions(L)
simulation = NBodySimulation(system, (t1, t2), pbc)
f = acceleration(simulation)
u0, v0, n = gather_bodies_initial_coordinates(simulation)
dv = zero(v0)
b = @benchmarkable $f(dv, $v0, $u0, $potential, 0.) setup=(dv=zero($v0)) evals=1
SUITE["coulomb"] = b
end
```
## Magnetic dipole potential
```julia
let SUITE=SUITE
n = 200
bodies = MagneticParticle[]
L = 20.0
m = 1.0
count = 1
dL = L / (ceil(n^(1 / 3)) + 1)
for x = dL / 2:dL:L, y = dL / 2:dL:L, z = dL / 2:dL:L
if count > n
break
end
r = SVector(x, y, z)
v = SVector(.0, .0, .0)
mm = rand(SVector{3})
body = MagneticParticle(r, v, m, mm)
push!(bodies, body)
count += 1
end
μ_4π = 1e-7
t1 = 0.0 # s
t2 = 1.0 # s
τ = (t2 - t1) / 100
parameters = MagnetostaticParameters(μ_4π)
system = PotentialNBodySystem(bodies, Dict(:magnetic => parameters))
simulation = NBodySimulation(system, (t1, t2))
f = acceleration(simulation)
u0, v0, n = gather_bodies_initial_coordinates(simulation)
dv = zero(v0)
b = @benchmarkable $f(dv, $v0, $u0, $parameters, 0.) setup=(dv=zero($v0)) evals=1
SUITE["magnetic_dipole"] = b
end
```
## Lennard Jones potential
```julia
let SUITE=SUITE
T = 120.0 # K
T0 = 90.0 # K
kb = 8.3144598e-3 # kJ/(K*mol)
ϵ = T * kb
σ = 0.34 # nm
ρ = 1374/1.6747# Da/nm^3
N = 200
m = 39.95# Da = 216 # number of bodies/particles
L = (m*N/ρ)^(1/3)#10.229σ
R = 0.5*L
v_dev = sqrt(kb * T / m)
bodies = generate_bodies_in_cell_nodes(N, m, v_dev, L)
τ = 0.5e-3 # ps or 1e-12 s
t1 = 0.0
t2 = 2000τ
lj_parameters = LennardJonesParameters(ϵ, σ, R)
lj_system = PotentialNBodySystem(bodies, Dict(:lennard_jones => lj_parameters));
pbc = CubicPeriodicBoundaryConditions(L)
simulation = NBodySimulation(lj_system, (t1, t2), pbc, kb)
f = acceleration(simulation)
u0, v0, n = gather_bodies_initial_coordinates(simulation)
dv = zero(v0)
b = @benchmarkable $f(dv, $v0, $u0, $lj_parameters, 0.) setup=(dv=zero($v0)) evals=1
SUITE["lennard_jones"] = b
end
```
## WaterSPCFw model
```julia
function acceleration(simulation::NBodySimulation{<:WaterSPCFw})
(u0, v0, n) = gather_bodies_initial_coordinates(simulation)
(o_acelerations, h_acelerations) = gather_accelerations_for_potentials(simulation)
group_accelerations = gather_group_accelerations(simulation)
simultaneous_acceleration = gather_simultaneous_acceleration(simulation)
function soode_system!(dv, v, u, p, t)
@inbounds for i = 1:n
a = MVector(0.0, 0.0, 0.0)
for acceleration! in o_acelerations
acceleration!(a, u, v, t, 3 * (i - 1) + 1);
end
dv[:, 3 * (i - 1) + 1] .= a
end
@inbounds for i in 1:n, j in (2, 3)
a = MVector(0.0, 0.0, 0.0)
for acceleration! in h_acelerations
acceleration!(a, u, v, t, 3 * (i - 1) + j);
end
dv[:, 3 * (i - 1) + j] .= a
end
@inbounds for i = 1:n
for acceleration! in group_accelerations
acceleration!(dv, u, v, t, i);
end
end
for acceleration! in simultaneous_acceleration
acceleration!(dv, u, v, t);
end
end
return soode_system!
end
let SUITE=SUITE
T = 370 # K
T0 = 275 # K
kb = 8.3144598e-3 # kJ/(K*mol)
ϵOO = 0.1554253*4.184 # kJ
σOO = 0.3165492 # nm
ρ = 997/1.6747# Da/nm^3
mO = 15.999 # Da
mH = 1.00794 # Da
mH2O = mO+2*mH
N = 200
L = (mH2O*N/ρ)^(1/3)
R = 0.9 # ~3*σOO
Rel = 0.49*L
v_dev = sqrt(kb * T /mH2O)
τ = 0.5e-3 # ps
t1 = 0τ
t2 = 5τ # ps
k_bond = 1059.162*4.184*1e2 # kJ/(mol*nm^2)
k_angle = 75.90*4.184 # kJ/(mol*rad^2)
rOH = 0.1012 # nm
∠HOH = 113.24*pi/180 # rad
qH = 0.41
qO = -0.82
k = 138.935458 #
bodies = generate_bodies_in_cell_nodes(N, mH2O, v_dev, L)
jl_parameters = LennardJonesParameters(ϵOO, σOO, R)
e_parameters = ElectrostaticParameters(k, Rel)
spc_parameters = SPCFwParameters(rOH, ∠HOH, k_bond, k_angle)
pbc = CubicPeriodicBoundaryConditions(L)
water = WaterSPCFw(bodies, mH, mO, qH, qO, jl_parameters, e_parameters, spc_parameters);
simulation = NBodySimulation(water, (t1, t2), pbc, kb);
f = acceleration(simulation)
u0, v0, n = gather_bodies_initial_coordinates(simulation)
dv = zero(v0)
b = @benchmarkable $f(dv, $v0, $u0, $spc_parameters, 0.) setup=(dv=zero($v0)) evals=1
SUITE["water_spcfw"] = b
end
```
Here are the results of the benchmarks
```julia
r = run(SUITE)
minimum(r)
```
and
```julia
memory(r)
```
```julia, echo = false
using SciMLBenchmarks
SciMLBenchmarks.bench_footer(WEAVE_ARGS[:folder],WEAVE_ARGS[:file])
```
| SciMLBenchmarks | https://github.com/SciML/SciMLBenchmarks.jl.git |
|
[
"MIT"
] | 0.1.3 | f4076dd5a103010d48bb6c4e50c5526f6622fa96 | docs | 9598 | ---
title: Liquid argon benchmarks
author: Sebastian Micluța-Câmpeanu, Mikhail Vaganov
---
The purpose of these benchmarks is to compare several integrators for use in
molecular dynamics simulation. We will use a simulation of liquid argon form the
examples of NBodySimulator as test case.
```julia
using ProgressLogging
using NBodySimulator, OrdinaryDiffEq, StaticArrays
using Plots, DataFrames, StatsPlots
function setup(t)
T = 120.0 # K
kb = 1.38e-23 # J/K
ϵ = T * kb # J
σ = 3.4e-10 # m
ρ = 1374 # kg/m^3
m = 39.95 * 1.6747 * 1e-27 # kg
N = 350
L = (m*N/ρ)^(1/3)
R = 3.5σ
v_dev = sqrt(kb * T / m) # m/s
_L = L / σ
_σ = 1.0
_ϵ = 1.0
_m = 1.0
_v = v_dev / sqrt(ϵ / m)
_R = R / σ
bodies = generate_bodies_in_cell_nodes(N, _m, _v, _L)
lj_parameters = LennardJonesParameters(_ϵ, _σ, _R)
pbc = CubicPeriodicBoundaryConditions(_L)
lj_system = PotentialNBodySystem(bodies, Dict(:lennard_jones => lj_parameters));
simulation = NBodySimulation(lj_system, (0.0, t), pbc, _ϵ/T)
return simulation
end
```
In order to compare different integrating methods we will consider a fixed simulation
time and change the timestep (or tolerances in the case of adaptive methods).
```julia
function benchmark(energyerr, rts, bytes, allocs, nt, nf, t, configs)
simulation = setup(t)
prob = SecondOrderODEProblem(simulation)
for config in configs
alg = config.alg
sol, rt, b, gc, memalloc = @timed solve(prob, alg();
save_everystep=false, progress=true, progress_name="$alg", config...)
result = NBodySimulator.SimulationResult(sol, simulation)
ΔE = total_energy(result, t) - total_energy(result, 0)
energyerr[alg] = ΔE
rts[alg] = rt
bytes[alg] = b
allocs[alg] = memalloc
nt[alg] = sol.destats.naccept
nf[alg] = sol.destats.nf + sol.destats.nf2
end
end
function run_benchmark!(results, t, integrators, tol...; c=ones(length(integrators)))
@progress "Benchmark at t=$t" for τ in zip(tol...)
runtime = Dict()
ΔE = Dict()
nt = Dict()
nf = Dict()
b = Dict()
allocs = Dict()
cfg = config(integrators, c, τ...)
GC.gc()
benchmark(ΔE, runtime, b, allocs, nt, nf, t, cfg)
get_tol(idx) = haskey(cfg[idx], :dt) ? cfg[idx].dt : (cfg[idx].abstol, cfg[idx].rtol)
for (idx,i) in enumerate(integrators)
push!(results, [string(i), runtime[i], get_tol(idx)..., abs(ΔE[i]), nt[i], nf[i], c[idx]])
end
end
return results
end
```
We will consider symplectic integrators first
```julia
symplectic_integrators = [
VelocityVerlet,
VerletLeapfrog,
PseudoVerletLeapfrog,
McAte2,
CalvoSanz4,
McAte5,
Yoshida6,
KahanLi8,
SofSpa10
];
```
Since for each method there is a different cost for a timestep, we need to take that
into account when choosing the tolerances (`dt`s or `abstol`&`reltol`) for the
solvers. This cost was estimated using the commented code below and the
results were hardcoded in order to prevent fluctuations in the results
between runs due to differences in callibration times.
The calibration is based on running a simulation with equal tolerances for all
solvers and then computing the cost as the runtime / number of timesteps.
The absolute value of the cost is not very relevant, so the cost was normalized
to the cost of one `VelocityVerlet` step.
```julia
config(integrators, c, τ) = [ (alg=a, dt=τ*cₐ) for (a,cₐ) in zip(integrators, c)]
t = 35.0
τs = 1e-3
# warmup
c_symplectic = ones(length(symplectic_integrators))
benchmark(Dict(), Dict(), Dict(), Dict(), Dict(), Dict(), 10.,
config(symplectic_integrators, c_symplectic, τs))
# results = DataFrame(:integrator=>String[], :runtime=>Float64[], :τ=>Float64[],
# :EnergyError=>Float64[], :timesteps=>Int[], :f_evals=>Int[], :cost=>Float64[]);
# run_benchmark!(results, t, symplectic_integrators, τs)
# c_symplectic .= results[!, :runtime] ./ results[!, :timesteps]
# c_Verlet = c_symplectic[1]
# c_symplectic /= c_Verlet
c_symplectic = [
1.00, # VelocityVerlet
1.05, # VerletLeapfrog
0.98, # PseudoVerletLeapfrog
1.02, # McAte2
2.38, # CalvoSanz4
2.92, # McAte5
3.74, # Yoshida6
8.44, # KahanLi8
15.76 # SofSpa10
]
```
Let us now benchmark the solvers for a fixed simulation time and variable timestep
```julia
t = 40.0
τs = 10 .^range(-4, -3, length=10)
results = DataFrame(:integrator=>String[], :runtime=>Float64[], :τ=>Float64[],
:EnergyError=>Float64[], :timesteps=>Int[], :f_evals=>Int[], :cost=>Float64[]);
run_benchmark!(results, t, symplectic_integrators, τs, c=c_symplectic)
```
The energy error as a function of runtime is given by
```julia
@df results plot(:EnergyError, :runtime, group=:integrator,
xscale=:log10, yscale=:log10, xlabel="Energy error", ylabel="Runtime (s)")
```
Looking at the runtime as a function of timesteps, we can observe that we have
a linear dependency for each method, and the slope is the previously computed
cost per step.
```julia
@df results plot(:timesteps, :runtime, group=:integrator,
xscale=:log10, yscale=:log10, xlabel="Number of timesteps", ylabel="Runtime (s)")
```
We can also look at the energy error history
```julia
function benchmark(energyerr, rts, ts, t, configs)
simulation = setup(t)
prob = SecondOrderODEProblem(simulation)
for config in configs
alg = config.alg
sol, rt = @timed solve(prob, alg(); progress=true, progress_name="$alg", config...)
result = NBodySimulator.SimulationResult(sol, simulation)
ΔE(t) = total_energy(result, t) - total_energy(result, 0)
energyerr[alg] = [ΔE(t) for t in sol.t[2:10^2:end]]
rts[alg] = rt
ts[alg] = sol.t[2:10^2:end]
end
end
ΔE = Dict()
rt = Dict()
ts = Dict()
configs = config(symplectic_integrators, c_symplectic, 2.3e-4)
benchmark(ΔE, rt, ts, 40., configs)
plt = plot(xlabel="Rescaled Time", ylabel="Energy error", legend=:bottomleft);
for c in configs
plot!(plt, ts[c.alg], abs.(ΔE[c.alg]), label="$(c.alg), $(rt[c.alg])s")
end
plt
```
Now, let us compare some adaptive methods
```julia
adaptive_integrators=[
# Non-stiff ODE methods
Tsit5,
Vern7,
Vern9,
# DPRKN
DPRKN6,
DPRKN8,
DPRKN12,
];
```
Similarly to the case of symplectic methods, we will take into account the average cost per timestep
in order to have a fair comparison between the solvers.
```julia
config(integrators, c, at, rt) = [ (alg=a, abstol=at*2^cₐ, rtol=rt*2^cₐ) for (a,cₐ) in zip(integrators, c)]
t = 35.0
ats = 10 .^range(-14, -4, length=10)
rts = 10 .^range(-14, -4, length=10)
# warmup
c_adaptive = ones(length(adaptive_integrators))
benchmark(Dict(), Dict(), Dict(), Dict(), Dict(), Dict(), 10.,
config(adaptive_integrators, 1, ats[1], rts[1]))
# results = DataFrame(:integrator=>String[], :runtime=>Float64[], :abstol=>Float64[],
# :reltol=>Float64[], :EnergyError=>Float64[], :timesteps=>Int[], :f_evals=>Int[], :cost=>Float64[]);
# run_benchmark!(results, t, adaptive_integrators, ats[1], rts[1])
# c_adaptive .= results[!, :runtime] ./ results[!, :timesteps]
# c_adaptive /= c_Verlet
c_adaptive = [
3.55, # Tsit5,
7.84, # Vern7,
11.38, # Vern9
3.56, # DPRKN6,
5.10, # DPRKN8,
8.85 # DPRKN12,
]
```
Let us now benchmark the solvers for a fixed simulation time and variable timestep
```julia
t = 40.0
results = DataFrame(:integrator=>String[], :runtime=>Float64[], :abstol=>Float64[],
:reltol=>Float64[], :EnergyError=>Float64[], :timesteps=>Int[], :f_evals=>Int[], :cost=>Float64[]);
run_benchmark!(results, t, adaptive_integrators, ats, rts, c=c_adaptive)
```
The energy error as a function of runtime is given by
```julia
@df results plot(:EnergyError, :runtime, group=:integrator,
xscale=:log10, yscale=:log10, xlabel="Energy error", ylabel="Runtime (s)")
```
If we consider the number of function evaluations instead, we obtain
```julia
@df results plot(:EnergyError, :f_evals, group=:integrator,
xscale=:log10, yscale=:log10, xlabel="Energy error", ylabel="Number of f evals")
```
We will now compare the best performing solvers
```julia
t = 40.0
symplectic_integrators = [
VelocityVerlet,
VerletLeapfrog,
PseudoVerletLeapfrog,
McAte2,
CalvoSanz4
]
c_symplectic = [
1.00, # VelocityVerlet
1.05, # VerletLeapfrog
0.98, # PseudoVerletLeapfrog
1.02, # McAte2
2.38, # CalvoSanz4
]
results1 = DataFrame(:integrator=>String[], :runtime=>Float64[], :τ=>Float64[],
:EnergyError=>Float64[], :timesteps=>Int[], :f_evals=>Int[], :cost=>Float64[]);
run_benchmark!(results1, t, symplectic_integrators, τs, c=c_symplectic)
adaptive_integrators=[
DPRKN6,
DPRKN8,
DPRKN12,
]
c_adaptive = [
3.56, # DPRKN6,
5.10, # DPRKN8,
8.85 # DPRKN12,
]
results2 = DataFrame(:integrator=>String[], :runtime=>Float64[], :abstol=>Float64[],
:reltol=>Float64[], :EnergyError=>Float64[], :timesteps=>Int[], :f_evals=>Int[], :cost=>Float64[]);
run_benchmark!(results2, t, adaptive_integrators, ats, rts, c=c_adaptive)
append!(results1, results2, cols=:union)
results1
```
The energy error as a function of runtime is given by
```julia
@df results1 plot(:EnergyError, :runtime, group=:integrator,
xscale=:log10, yscale=:log10, xlabel="Energy error", ylabel="Runtime (s)")
```
```julia, echo = false
using SciMLBenchmarks
SciMLBenchmarks.bench_footer(WEAVE_ARGS[:folder],WEAVE_ARGS[:file])
```
| SciMLBenchmarks | https://github.com/SciML/SciMLBenchmarks.jl.git |
|
[
"MIT"
] | 0.1.3 | f4076dd5a103010d48bb6c4e50c5526f6622fa96 | docs | 7220 | ---
title: Liquid argon benchmarks
author: Sebastian Micluța-Câmpeanu, Mikhail Vaganov
---
The purpose of these benchmarks is to compare several integrators for use in
molecular dynamics simulation. We will use a simulation of liquid argon form the
examples of NBodySimulator as test case.
```julia
using ProgressLogging
using NBodySimulator, OrdinaryDiffEq, StaticArrays
using Plots, DataFrames, StatsPlots
function setup(t)
T = 120.0 # K
kb = 1.38e-23 # J/K
ϵ = T * kb # J
σ = 3.4e-10 # m
ρ = 1374 # kg/m^3
m = 39.95 * 1.6747 * 1e-27 # kg
N = 350
L = (m*N/ρ)^(1/3)
R = 3.5σ
v_dev = sqrt(kb * T / m) # m/s
_L = L / σ
_σ = 1.0
_ϵ = 1.0
_m = 1.0
_v = v_dev / sqrt(ϵ / m)
_R = R / σ
bodies = generate_bodies_in_cell_nodes(N, _m, _v, _L)
lj_parameters = LennardJonesParameters(_ϵ, _σ, _R)
pbc = CubicPeriodicBoundaryConditions(_L)
lj_system = PotentialNBodySystem(bodies, Dict(:lennard_jones => lj_parameters));
simulation = NBodySimulation(lj_system, (0.0, t), pbc, _ϵ/T)
return simulation
end
```
In order to compare different integrating methods we will consider a fixed simulation
time and change the timestep (or tolerances in the case of adaptive methods).
```julia
function benchmark(energyerr, rts, bytes, allocs, nt, nf, t, configs)
simulation = setup(t)
prob = SecondOrderODEProblem(simulation)
for config in configs
alg = config.alg
sol, rt, b, gc, memalloc = @timed solve(prob, alg();
save_everystep=false, progress=true, progress_name="$alg", config...)
result = NBodySimulator.SimulationResult(sol, simulation)
ΔE = total_energy(result, t) - total_energy(result, 0)
energyerr[alg] = ΔE
rts[alg] = rt
bytes[alg] = b
allocs[alg] = memalloc
nt[alg] = sol.destats.naccept
nf[alg] = sol.destats.nf + sol.destats.nf2
end
end
function run_benchmark!(results, t, integrators, tol...; c=ones(length(integrators)))
@progress "Benchmark at t=$t" for τ in zip(tol...)
runtime = Dict()
ΔE = Dict()
nt = Dict()
nf = Dict()
b = Dict()
allocs = Dict()
cfg = config(integrators, c, τ...)
GC.gc()
benchmark(ΔE, runtime, b, allocs, nt, nf, t, cfg)
get_tol(idx) = haskey(cfg[idx], :dt) ? cfg[idx].dt : (cfg[idx].abstol, cfg[idx].rtol)
for (idx,i) in enumerate(integrators)
push!(results, [string(i), runtime[i], get_tol(idx)..., abs(ΔE[i]), nt[i], nf[i], c[idx]])
end
end
return results
end
```
We will consider symplectic integrators first
```julia
symplectic_integrators = [
VelocityVerlet,
VerletLeapfrog,
PseudoVerletLeapfrog,
McAte2,
CalvoSanz4,
McAte5,
Yoshida6,
KahanLi8,
SofSpa10
];
```
```julia
config(integrators, c, τ) = [ (alg=a, dt=τ*cₐ) for (a,cₐ) in zip(integrators, c)]
t = 35.0
τs = 1e-3
# warmup
c_symplectic = ones(length(symplectic_integrators))
benchmark(Dict(), Dict(), Dict(), Dict(), Dict(), Dict(), 10.,
config(symplectic_integrators, c_symplectic, τs))
# results = DataFrame(:integrator=>String[], :runtime=>Float64[], :τ=>Float64[],
# :EnergyError=>Float64[], :timesteps=>Int[], :f_evals=>Int[], :cost=>Float64[]);
# run_benchmark!(results, t, symplectic_integrators, τs)
# c_symplectic .= results[!, :runtime] ./ results[!, :timesteps]
# c_Verlet = c_symplectic[1]
# c_symplectic /= c_Verlet
c_symplectic = [
1.00, # VelocityVerlet
1.05, # VerletLeapfrog
0.98, # PseudoVerletLeapfrog
1.02, # McAte2
2.38, # CalvoSanz4
2.92, # McAte5
3.74, # Yoshida6
8.44, # KahanLi8
15.76 # SofSpa10
]
```
We will consider a longer simulation time
```julia
t = 200.0
results = DataFrame(:integrator=>String[], :runtime=>Float64[], :τ=>Float64[],
:EnergyError=>Float64[], :timesteps=>Int[], :f_evals=>Int[], :cost=>Float64[]);
run_benchmark!(results, t, symplectic_integrators, τs, c=c_symplectic)
```
The energy error as a function of runtime is given by
```julia
@df results plot(:EnergyError, :runtime, group=:integrator,
xscale=:log10, yscale=:log10, xlabel="Energy error", ylabel="Runtime (s)")
```
Now, let us compare some adaptive methods
```julia
adaptive_integrators=[
# Non-stiff ODE methods
Tsit5,
Vern7,
Vern9,
# DPRKN
DPRKN6,
DPRKN8,
DPRKN12,
];
```
```julia
config(integrators, c, at, rt) = [ (alg=a, abstol=at*2^cₐ, rtol=rt*2^cₐ) for (a,cₐ) in zip(integrators, c)]
t = 35.0
ats = 10 .^range(-14, -4, length=10)
rts = 10 .^range(-14, -4, length=10)
# warmup
c_adaptive = ones(length(adaptive_integrators))
benchmark(Dict(), Dict(), Dict(), Dict(), Dict(), Dict(), 10.,
config(adaptive_integrators, 1, ats[1], rts[1]))
# results = DataFrame(:integrator=>String[], :runtime=>Float64[], :abstol=>Float64[],
# :reltol=>Float64[], :EnergyError=>Float64[], :timesteps=>Int[], :f_evals=>Int[], :cost=>Float64[]);
# run_benchmark!(results, t, adaptive_integrators, ats[1], rts[1])
# c_adaptive .= results[!, :runtime] ./ results[!, :timesteps]
# c_adaptive /= c_Verlet
c_adaptive = [
3.55, # Tsit5,
7.84, # Vern7,
11.38, # Vern9
3.56, # DPRKN6,
5.10, # DPRKN8,
8.85 # DPRKN12,
]
```
We will consider a longer simulation time
```julia
t = 200.0
results = DataFrame(:integrator=>String[], :runtime=>Float64[], :abstol=>Float64[],
:reltol=>Float64[], :EnergyError=>Float64[], :timesteps=>Int[], :f_evals=>Int[], :cost=>Float64[]);
run_benchmark!(results, t, integrators, ats, rts, c=c_adaptive)
```
The energy error as a function of runtime is given by
```julia
@df results plot(:EnergyError, :runtime, group=:integrator,
xscale=:log10, yscale=:log10, xlabel="Energy error", ylabel="Runtime (s)")
```
We will now compare the best performing solvers
```julia
t = 200.0
symplectic_integrators = [
VelocityVerlet,
VerletLeapfrog,
PseudoVerletLeapfrog,
McAte2,
CalvoSanz4
]
c_symplectic = [
1.00, # VelocityVerlet
1.05, # VerletLeapfrog
0.98, # PseudoVerletLeapfrog
1.02, # McAte2
2.38, # CalvoSanz4
]
results1 = DataFrame(:integrator=>String[], :runtime=>Float64[], :τ=>Float64[],
:EnergyError=>Float64[], :timesteps=>Int[], :f_evals=>Int[], :cost=>Float64[]);
run_benchmark!(results1, t, symplectic_integrators, τs, c=c_symplectic)
adaptive_integrators=[
DPRKN6,
DPRKN8,
DPRKN12,
]
c_adaptive = [
3.56, # DPRKN6,
5.10, # DPRKN8,
8.85 # DPRKN12,
]
results2 = DataFrame(:integrator=>String[], :runtime=>Float64[], :abstol=>Float64[],
:reltol=>Float64[], :EnergyError=>Float64[], :timesteps=>Int[], :f_evals=>Int[], :cost=>Float64[]);
run_benchmark!(results2, t, adaptive_integrators, ats, rts, c=c_adaptive)
append!(results1, results2, cols=:union)
results1
```
The energy error as a function of runtime is given by
```julia
@df results1 plot(:EnergyError, :runtime, group=:integrator,
xscale=:log10, yscale=:log10, xlabel="Energy error", ylabel="Runtime (s)")
```
```julia, echo = false
using SciMLBenchmarks
SciMLBenchmarks.bench_footer(WEAVE_ARGS[:folder],WEAVE_ARGS[:file])
```
| SciMLBenchmarks | https://github.com/SciML/SciMLBenchmarks.jl.git |
|
[
"MIT"
] | 0.1.3 | f4076dd5a103010d48bb6c4e50c5526f6622fa96 | docs | 6056 | ---
title: Mackey and Glass Work-Precision Diagrams
author: David Widmann, Chris Rackauckas
---
# Mackey and Glass
We study algorithms for solving constant delay differential equations with a test problem from W.H. Enright and H. Hayashi, "The evaluation of numerical software for delay differential equations", 1997. It is a model of blood production that was published by M. C. Mackey and L. Glass in "Oscillation and chaos in physiological control systems", 1977, and is given by
```math
\begin{equation}
y'(t) = \frac{0.2y(t-14)}{1 + y(t-14)^{10}} - 0.1y(t)
\end{equation}
```
```julia
using DelayDiffEq, DiffEqDevTools, Plots
using DDEProblemLibrary: prob_dde_DDETST_A1 as prob
gr()
sol = solve(prob, MethodOfSteps(Vern9(); fpsolve = NLFunctional(; max_iter = 1000)); reltol=1e-14, abstol=1e-14)
test_sol = TestSolution(sol)
plot(sol)
```
## Low order RK methods
### High tolerances
First we test final error estimates of continuous RK methods of low order at high tolerances. `OwrenZen4`, `OwrenZen5`, and `RK4` yield the best error estimates.
```julia
abstols = 1.0 ./ 10.0 .^ (4:7)
reltols = 1.0 ./ 10.0 .^ (1:4)
setups = [Dict(:alg=>MethodOfSteps(BS3())),
Dict(:alg=>MethodOfSteps(Tsit5())),
Dict(:alg=>MethodOfSteps(RK4())),
Dict(:alg=>MethodOfSteps(DP5())),
Dict(:alg=>MethodOfSteps(OwrenZen3())),
Dict(:alg=>MethodOfSteps(OwrenZen4())),
Dict(:alg=>MethodOfSteps(OwrenZen5()))]
wp = WorkPrecisionSet(prob,abstols,reltols,setups;
appxsol=test_sol,maxiters=Int(1e5),error_estimate=:final)
plot(wp)
```
Next we test average interpolation errors:
```julia
abstols = 1.0 ./ 10.0 .^ (4:7)
reltols = 1.0 ./ 10.0 .^ (1:4)
setups = [Dict(:alg=>MethodOfSteps(BS3())),
Dict(:alg=>MethodOfSteps(Tsit5())),
Dict(:alg=>MethodOfSteps(RK4())),
Dict(:alg=>MethodOfSteps(DP5())),
Dict(:alg=>MethodOfSteps(OwrenZen3())),
Dict(:alg=>MethodOfSteps(OwrenZen4())),
Dict(:alg=>MethodOfSteps(OwrenZen5()))]
wp = WorkPrecisionSet(prob,abstols,reltols,setups;
appxsol=test_sol,maxiters=Int(1e5),error_estimate=:L2)
plot(wp)
```
As before, `OwrenZen4` and `OwrenZen5` perform well over the whole range of investigated tolerances.
### Low tolerances
We repeat our tests with low tolerances.
```julia
abstols = 1.0 ./ 10.0 .^ (8:11)
reltols = 1.0 ./ 10.0 .^ (5:8)
setups = [Dict(:alg=>MethodOfSteps(BS3())),
Dict(:alg=>MethodOfSteps(Tsit5())),
Dict(:alg=>MethodOfSteps(RK4())),
Dict(:alg=>MethodOfSteps(DP5())),
Dict(:alg=>MethodOfSteps(OwrenZen3())),
Dict(:alg=>MethodOfSteps(OwrenZen4())),
Dict(:alg=>MethodOfSteps(OwrenZen5()))]
wp = WorkPrecisionSet(prob,abstols,reltols,setups;
appxsol=test_sol,maxiters=Int(1e5),error_estimate=:final)
plot(wp)
```
And once again we also test the interpolation errors:
```julia
abstols = 1.0 ./ 10.0 .^ (8:11)
reltols = 1.0 ./ 10.0 .^ (5:8)
setups = [Dict(:alg=>MethodOfSteps(BS3())),
Dict(:alg=>MethodOfSteps(Tsit5())),
Dict(:alg=>MethodOfSteps(RK4())),
Dict(:alg=>MethodOfSteps(DP5())),
Dict(:alg=>MethodOfSteps(OwrenZen3())),
Dict(:alg=>MethodOfSteps(OwrenZen4())),
Dict(:alg=>MethodOfSteps(OwrenZen5()))]
wp = WorkPrecisionSet(prob,abstols,reltols,setups;
appxsol=test_sol,maxiters=Int(1e5),error_estimate=:L2)
plot(wp)
```
Apparently `Tsit5` and `DP5` perform quite well at low tolerances, but only `OwrenZen5`, `OwrenZen4` and `RK4` achieve interpolation errors of around 1e-9.
## Lazy interpolants
### High tolerances
We repeat our tests with the Verner methods which, in contrast to the methods above, use lazy interpolants. As reference we include `OwrenZen4`.
```julia
abstols = 1.0 ./ 10.0 .^ (4:7)
reltols = 1.0 ./ 10.0 .^ (1:4)
setups = [Dict(:alg=>MethodOfSteps(Vern6())),
Dict(:alg=>MethodOfSteps(Vern7())),
Dict(:alg=>MethodOfSteps(Vern8())),
Dict(:alg=>MethodOfSteps(Vern9())),
Dict(:alg=>MethodOfSteps(OwrenZen4()))]
wp = WorkPrecisionSet(prob,abstols,reltols,setups;
appxsol=test_sol,maxiters=Int(1e5),error_estimate=:final)
plot(wp)
```
And we obtain the following interpolation errors:
```julia
abstols = 1.0 ./ 10.0 .^ (4:7)
reltols = 1.0 ./ 10.0 .^ (1:4)
setups = [Dict(:alg=>MethodOfSteps(Vern6())),
Dict(:alg=>MethodOfSteps(Vern7())),
Dict(:alg=>MethodOfSteps(Vern8())),
Dict(:alg=>MethodOfSteps(Vern9())),
Dict(:alg=>MethodOfSteps(OwrenZen4()))]
wp = WorkPrecisionSet(prob,abstols,reltols,setups;
appxsol=test_sol,maxiters=Int(1e5),error_estimate=:L2)
plot(wp)
```
`Vern6`, `Vern7`, and `Vern9` are outperformed by `OwrenZen4`.
### Low tolerances
Again, we repeat our tests at low tolerances.
```julia
abstols = 1.0 ./ 10.0 .^ (8:11)
reltols = 1.0 ./ 10.0 .^ (5:8)
setups = [Dict(:alg=>MethodOfSteps(Vern6())),
Dict(:alg=>MethodOfSteps(Vern7())),
Dict(:alg=>MethodOfSteps(Vern8())),
Dict(:alg=>MethodOfSteps(Vern9())),
Dict(:alg=>MethodOfSteps(OwrenZen4()))]
wp = WorkPrecisionSet(prob,abstols,reltols,setups;
appxsol=test_sol,maxiters=Int(1e5),error_estimate=:final)
plot(wp)
```
```julia
abstols = 1.0 ./ 10.0 .^ (8:11)
reltols = 1.0 ./ 10.0 .^ (5:8)
setups = [Dict(:alg=>MethodOfSteps(Vern6())),
Dict(:alg=>MethodOfSteps(Vern7())),
Dict(:alg=>MethodOfSteps(Vern8())),
Dict(:alg=>MethodOfSteps(Vern9())),
Dict(:alg=>MethodOfSteps(OwrenZen4()))]
wp = WorkPrecisionSet(prob,abstols,reltols,setups;
appxsol=test_sol,maxiters=Int(1e5),error_estimate=:L2)
plot(wp)
```
`Vern6`, `Vern7`, and `Vern9` show similar results at low tolerances, and perform even better than `OwrenZen4`.
```julia, echo = false
using SciMLBenchmarks
SciMLBenchmarks.bench_footer(WEAVE_ARGS[:folder],WEAVE_ARGS[:file])
```
| SciMLBenchmarks | https://github.com/SciML/SciMLBenchmarks.jl.git |
|
[
"MIT"
] | 0.1.3 | f4076dd5a103010d48bb6c4e50c5526f6622fa96 | docs | 6181 | ---
title: Wheldon, Kirk, and Finlay Work-Precision Diagrams
author: David Widmann, Chris Rackauckas
---
# Wheldon, Kirk, and Finlay
We study algorithms for solving constant delay differential equations with a test problem from W.H. Enright and H. Hayashi, "The evaluation of numerical software for delay differential equations", 1997. It is a model of chronic granulocytic leukemia that was published by T. Wheldon, J. Kirk and H. Finlay in "Cyclical granulopoiesis in chronic granulocytic leukemia: A simulation study", 1974, and is given by
```math
\begin{align}
y_1'(t) &= \frac{1.1}{1 + \sqrt{10}y_1(t-20)^{5/4}} - \frac{10y_1(t)}{1 + 40y_2(t)} \\
y_2'(t) &= \frac{100y_1(t)}{1 + 40y_2(t)} - 2.43y_2(t)
\end{align}
```
```julia
using DelayDiffEq, DiffEqDevTools, Plots
using DDEProblemLibrary: prob_dde_DDETST_A2 as prob
gr()
sol = solve(prob, MethodOfSteps(Vern9(); fpsolve = NLFunctional(; max_iter = 1000)); reltol=1e-14, abstol=1e-14)
test_sol = TestSolution(sol)
plot(sol)
```
## Low order RK methods
### High tolerances
First we compare final errors of solutions with low order RK methods at high tolerances.
```julia
abstols = 1.0 ./ 10.0 .^ (4:7)
reltols = 1.0 ./ 10.0 .^ (1:4)
setups = [Dict(:alg=>MethodOfSteps(BS3())),
Dict(:alg=>MethodOfSteps(Tsit5())),
Dict(:alg=>MethodOfSteps(RK4())),
Dict(:alg=>MethodOfSteps(DP5())),
Dict(:alg=>MethodOfSteps(OwrenZen3())),
Dict(:alg=>MethodOfSteps(OwrenZen4())),
Dict(:alg=>MethodOfSteps(OwrenZen5()))]
wp = WorkPrecisionSet(prob,abstols,reltols,setups;
appxsol=test_sol,maxiters=Int(1e5),error_estimate=:final)
plot(wp)
```
Next we test interpolation errors:
```julia
abstols = 1.0 ./ 10.0 .^ (4:7)
reltols = 1.0 ./ 10.0 .^ (1:4)
setups = [Dict(:alg=>MethodOfSteps(BS3())),
Dict(:alg=>MethodOfSteps(Tsit5())),
Dict(:alg=>MethodOfSteps(RK4())),
Dict(:alg=>MethodOfSteps(DP5())),
Dict(:alg=>MethodOfSteps(OwrenZen3())),
Dict(:alg=>MethodOfSteps(OwrenZen4())),
Dict(:alg=>MethodOfSteps(OwrenZen5()))]
wp = WorkPrecisionSet(prob,abstols,reltols,setups;
appxsol=test_sol,maxiters=Int(1e5),error_estimate=:L2)
plot(wp)
```
Both interpolation tests and tests of final error show similar results. `BS3` does quite well but only `OwrenZen4`, `OwrenZen5`, and `RK4` achieve interpolation errors of about 1e-5.
### Low tolerances
We repeat our tests at low tolerances.
```julia
abstols = 1.0 ./ 10.0 .^ (8:11)
reltols = 1.0 ./ 10.0 .^ (5:8)
setups = [Dict(:alg=>MethodOfSteps(BS3())),
Dict(:alg=>MethodOfSteps(Tsit5())),
Dict(:alg=>MethodOfSteps(RK4())),
Dict(:alg=>MethodOfSteps(DP5())),
Dict(:alg=>MethodOfSteps(OwrenZen3())),
Dict(:alg=>MethodOfSteps(OwrenZen4())),
Dict(:alg=>MethodOfSteps(OwrenZen5()))]
wp = WorkPrecisionSet(prob,abstols,reltols,setups;
appxsol=test_sol,maxiters=Int(1e5),error_estimate=:final)
plot(wp)
```
```julia
abstols = 1.0 ./ 10.0 .^ (8:11)
reltols = 1.0 ./ 10.0 .^ (5:8)
setups = [Dict(:alg=>MethodOfSteps(BS3())),
Dict(:alg=>MethodOfSteps(Tsit5())),
Dict(:alg=>MethodOfSteps(RK4())),
Dict(:alg=>MethodOfSteps(DP5())),
Dict(:alg=>MethodOfSteps(OwrenZen3())),
Dict(:alg=>MethodOfSteps(OwrenZen4())),
Dict(:alg=>MethodOfSteps(OwrenZen5()))]
wp = WorkPrecisionSet(prob,abstols,reltols,setups;
appxsol=test_sol,maxiters=Int(1e5),error_estimate=:L2)
plot(wp)
```
Out of the compared methods, `Tsit5`, `DP5`, and `OwrenZen5` seem to be the best methods for this problem at low tolerances, but also `OwrenZen4` performs similarly well. `OwrenZen5` and `OwrenZen4` can even achieve interpolation errors below 1e-9.
## Lazy interpolants
### High tolerances
We compare the Verner methods, which use lazy interpolants, at high tolerances. As reference we include `OwrenZen4`.
```julia
abstols = 1.0 ./ 10.0 .^ (4:7)
reltols = 1.0 ./ 10.0 .^ (1:4)
setups = [Dict(:alg=>MethodOfSteps(Vern6())),
Dict(:alg=>MethodOfSteps(Vern7())),
Dict(:alg=>MethodOfSteps(Vern8())),
Dict(:alg=>MethodOfSteps(Vern9())),
Dict(:alg=>MethodOfSteps(OwrenZen4()))]
wp = WorkPrecisionSet(prob,abstols,reltols,setups;
appxsol=test_sol,maxiters=Int(1e5),error_estimate=:final)
plot(wp)
```
```julia
abstols = 1.0 ./ 10.0 .^ (4:7)
reltols = 1.0 ./ 10.0 .^ (1:4)
setups = [Dict(:alg=>MethodOfSteps(Vern6())),
Dict(:alg=>MethodOfSteps(Vern7())),
Dict(:alg=>MethodOfSteps(Vern8())),
Dict(:alg=>MethodOfSteps(Vern9())),
Dict(:alg=>MethodOfSteps(OwrenZen4()))]
wp = WorkPrecisionSet(prob,abstols,reltols,setups;
appxsol=test_sol,maxiters=Int(1e5),error_estimate=:L2)
plot(wp)
```
### Low tolerances
We repeat these tests and compare the Verner methods also at low tolerances.
```julia
abstols = 1.0 ./ 10.0 .^ (8:11)
reltols = 1.0 ./ 10.0 .^ (5:8)
setups = [Dict(:alg=>MethodOfSteps(Vern6())),
Dict(:alg=>MethodOfSteps(Vern7())),
Dict(:alg=>MethodOfSteps(Vern8())),
Dict(:alg=>MethodOfSteps(Vern9())),
Dict(:alg=>MethodOfSteps(OwrenZen4()))]
wp = WorkPrecisionSet(prob,abstols,reltols,setups;
appxsol=test_sol,maxiters=Int(1e5),error_estimate=:final)
plot(wp)
```
```julia
abstols = 1.0 ./ 10.0 .^ (8:11)
reltols = 1.0 ./ 10.0 .^ (5:8)
setups = [Dict(:alg=>MethodOfSteps(Vern6())),
Dict(:alg=>MethodOfSteps(Vern7())),
Dict(:alg=>MethodOfSteps(Vern8())),
Dict(:alg=>MethodOfSteps(Vern9())),
Dict(:alg=>MethodOfSteps(OwrenZen4()))]
wp = WorkPrecisionSet(prob,abstols,reltols,setups;
appxsol=test_sol,maxiters=Int(1e5),error_estimate=:L2)
plot(wp)
```
It seems `Vern6` and `Vern7` are both well suited for the problem at low tolerances and outperform `OwrenZen4`, whereas at high tolerances `OwrenZen4` is more efficient.
```julia, echo = false
using SciMLBenchmarks
SciMLBenchmarks.bench_footer(WEAVE_ARGS[:folder],WEAVE_ARGS[:file])
```
| SciMLBenchmarks | https://github.com/SciML/SciMLBenchmarks.jl.git |
|
[
"MIT"
] | 0.1.3 | f4076dd5a103010d48bb6c4e50c5526f6622fa96 | docs | 6267 | ---
title: Fitzhugh-Nagumo Work-Precision Diagrams
author: Chris Rackauckas
---
# Fitzhugh-Nagumo
The purpose of this is to see how the errors scale on a standard nonlinear problem.
```julia
using OrdinaryDiffEq, ParameterizedFunctions, ODE, ODEInterface,
ODEInterfaceDiffEq, LSODA, Sundials, DiffEqDevTools,
StaticArrays
using Plots; gr()
f = @ode_def FitzhughNagumo begin
dv = v - v^3/3 -w + l
dw = τinv*(v + a - b*w)
end a b τinv l
p = SA[0.7,0.8,1/12.5,0.5]
prob = ODEProblem{true, SciMLBase.FullSpecialize}(f,[1.0;1.0],(0.0,10.0),p)
probstatic = ODEProblem{false}(f,SA[1.0;1.0],(0.0,10.0),p)
abstols = 1.0 ./ 10.0 .^ (6:13)
reltols = 1.0 ./ 10.0 .^ (3:10);
sol = solve(prob,Vern7(),abstol=1/10^14,reltol=1/10^14)
sol2 = solve(probstatic,Vern7(),abstol=1/10^14,reltol=1/10^14)
probs = [prob,probstatic]
test_sol = [sol,sol2];
```
```julia
plot(sol)
```
## Low Order
```julia
setups = [Dict(:alg=>DP5())
#Dict(:alg=>ode45()) #fails
Dict(:alg=>dopri5())
Dict(:alg=>BS5())
Dict(:alg=>Tsit5())
Dict(:alg=>Vern6())
Dict(:alg=>Tsit5(), :prob_choice => 2)
Dict(:alg=>Vern6(), :prob_choice => 2)
]
wp = WorkPrecisionSet(probs,abstols,reltols,setups;appxsol=test_sol,save_everystep=false,numruns=100,maxiters=1000)
plot(wp)
```
### Interpolation
```julia
setups = [Dict(:alg=>DP5())
#Dict(:alg=>ode45()) # fails
Dict(:alg=>BS5())
Dict(:alg=>Tsit5())
Dict(:alg=>Vern6())
Dict(:alg=>Tsit5(), :prob_choice => 2)
Dict(:alg=>Vern6(), :prob_choice => 2)
]
wp = WorkPrecisionSet(probs,abstols,reltols,setups;appxsol=test_sol,numruns=100,maxiters=10000,error_estimate=:L2,dense_errors=true)
plot(wp)
```
## Higher Order
```julia
setups = [Dict(:alg=>DP8())
Dict(:alg=>dop853())
#Dict(:alg=>ode78()) # fails
Dict(:alg=>Vern6())
Dict(:alg=>Vern7())
Dict(:alg=>Vern8())
Dict(:alg=>Vern9())
Dict(:alg=>Vern6(), :prob_choice => 2)
Dict(:alg=>Vern7(), :prob_choice => 2)
Dict(:alg=>Vern8(), :prob_choice => 2)
Dict(:alg=>Vern9(), :prob_choice => 2)
]
wp = WorkPrecisionSet(probs,abstols,reltols,setups;appxsol=test_sol,save_everystep=false,numruns=100,maxiters=1000)
plot(wp)
```
```julia
setups = [Dict(:alg=>DP8())
Dict(:alg=>Vern7())
Dict(:alg=>Vern7(), :prob_choice => 2)
Dict(:alg=>CVODE_Adams())
Dict(:alg=>ARKODE(Sundials.Explicit(),order=6))
Dict(:alg=>lsoda())
Dict(:alg=>odex())
Dict(:alg=>ddeabm())
]
wp = WorkPrecisionSet(probs,abstols,reltols,setups;appxsol=test_sol,save_everystep=false,numruns=100,maxiters=1000)
plot(wp)
```
### Interpolation
```julia
setups = [Dict(:alg=>DP8())
#Dict(:alg=>ode78()) # fails
Dict(:alg=>Vern6())
Dict(:alg=>Vern7())
Dict(:alg=>Vern8())
Dict(:alg=>Vern9())
Dict(:alg=>Vern6(), :prob_choice => 2)
Dict(:alg=>Vern7(), :prob_choice => 2)
Dict(:alg=>Vern8(), :prob_choice => 2)
Dict(:alg=>Vern9(), :prob_choice => 2)
]
wp = WorkPrecisionSet(probs,abstols,reltols,setups;appxsol=test_sol,numruns=100,maxiters=1000,error_estimate=:L2,dense_errors=true)
plot(wp)
```
## Comparison with Non-RK methods
Now let's test Tsit5 and Vern9 against parallel extrapolation methods and an
Adams-Bashforth-Moulton:
```julia
setups = [Dict(:alg=>Tsit5())
Dict(:alg=>Vern9())
Dict(:alg=>VCABM())
Dict(:alg=>Vern9(), :prob_choice => 2)
Dict(:alg=>VCABM(), :prob_choice => 2)
Dict(:alg=>AitkenNeville(min_order=1, max_order=9, init_order=4, threading=true))
Dict(:alg=>ExtrapolationMidpointDeuflhard(min_order=1, max_order=9, init_order=4, threading=true))
Dict(:alg=>ExtrapolationMidpointHairerWanner(min_order=2, max_order=11, init_order=4, threading=true))]
solnames = ["Tsit5","Vern9","VCABM","Vern9 Static","VCABM Static","AitkenNeville","Midpoint Deuflhard","Midpoint Hairer Wanner"]
wp = WorkPrecisionSet(probs,abstols,reltols,setups;appxsol=test_sol,names=solnames,
save_everystep=false,verbose=false,numruns=100)
plot(wp)
```
```julia
setups = [Dict(:alg=>ExtrapolationMidpointDeuflhard(min_order=1, max_order=9, init_order=9, threading=false))
Dict(:alg=>ExtrapolationMidpointHairerWanner(min_order=2, max_order=11, init_order=4, threading=false))
Dict(:alg=>ExtrapolationMidpointHairerWanner(min_order=2, max_order=11, init_order=4, threading=true))
Dict(:alg=>ExtrapolationMidpointHairerWanner(min_order=2, max_order=11, init_order=4, sequence = :romberg, threading=true))
Dict(:alg=>ExtrapolationMidpointHairerWanner(min_order=2, max_order=11, init_order=4, sequence = :bulirsch, threading=true))]
solnames = ["Deuflhard","No threads","standard","Romberg","Bulirsch"]
wp = WorkPrecisionSet(probs,abstols,reltols,setups;appxsol=test_sol,names=solnames,
save_everystep=false,verbose=false,numruns=100)
plot(wp)
```
```julia
setups = [Dict(:alg=>ExtrapolationMidpointHairerWanner(min_order=2, max_order=11, init_order=10, threading=true))
Dict(:alg=>ExtrapolationMidpointHairerWanner(min_order=2, max_order=11, init_order=4, threading=true))
Dict(:alg=>ExtrapolationMidpointHairerWanner(min_order=5, max_order=11, init_order=10, threading=true))
Dict(:alg=>ExtrapolationMidpointHairerWanner(min_order=2, max_order=15, init_order=10, threading=true))
Dict(:alg=>ExtrapolationMidpointHairerWanner(min_order=5, max_order=7, init_order=6, threading=true))]
solnames = ["1","2","3","4","5"]
wp = WorkPrecisionSet(probs,abstols,reltols,setups;appxsol=test_sol,names=solnames,
save_everystep=false,verbose=false,numruns=100)
plot(wp)
```
## Conclusion
As expected, the algorithms are all pretty matched on time for this problem. However, you can clearly see the OrdinaryDiffEq.jl algorithms solving to a much higher accuracy and still faster, especially when the interpolations are involved.
```julia, echo = false
using SciMLBenchmarks
SciMLBenchmarks.bench_footer(WEAVE_ARGS[:folder],WEAVE_ARGS[:file])
```
| SciMLBenchmarks | https://github.com/SciML/SciMLBenchmarks.jl.git |
|
[
"MIT"
] | 0.1.3 | f4076dd5a103010d48bb6c4e50c5526f6622fa96 | docs | 7059 | ---
title: Lotka-Volterra Work-Precision Diagrams
author: Chris Rackauckas
---
## Lotka-Volterra
The purpose of this problem is to test the performance on easy problems. Since it's periodic, the error is naturally low, and so most of the difference will come down to startup times and, when measuring the interpolations, the algorithm choices.
```julia
using OrdinaryDiffEq, ParameterizedFunctions, ODE, ODEInterfaceDiffEq, LSODA,
Sundials, DiffEqDevTools, StaticArrays
f = @ode_def LotkaVolterra begin
dx = a*x - b*x*y
dy = -c*y + d*x*y
end a b c d
p = SA[1.5,1.0,3.0,1.0]
prob = ODEProblem{true, SciMLBase.FullSpecialize}(f,[1.0;1.0],(0.0,10.0),p)
probstatic = ODEProblem{false}(f,SA[1.0;1.0],(0.0,10.0),p)
abstols = 1.0 ./ 10.0 .^ (6:13)
reltols = 1.0 ./ 10.0 .^ (3:10);
sol = solve(prob,Vern7(),abstol=1/10^14,reltol=1/10^14)
sol2 = solve(probstatic,Vern7(),abstol=1/10^14,reltol=1/10^14)
probs = [prob,probstatic]
test_sol = [sol,sol2];
using Plots; gr()
```
```julia
plot(sol)
```
### Low Order
```julia
setups = [Dict(:alg=>DP5())
#Dict(:alg=>ode45()) # fail
Dict(:alg=>dopri5())
Dict(:alg=>Tsit5())
Dict(:alg=>Vern6())
Dict(:alg=>Tsit5(), :prob_choice => 2)
Dict(:alg=>Vern6(), :prob_choice => 2)
]
wp = WorkPrecisionSet(probs,abstols,reltols,setups;appxsol=test_sol,save_everystep=false,maxiters=10000,numruns=100)
plot(wp)
```
Here we see the OrdinaryDiffEq.jl algorithms once again far in the lead.
### Interpolation Error
Since the problem is periodic, the real measure of error is the error throughout the solution.
```julia
setups = [Dict(:alg=>DP5())
#Dict(:alg=>ode45())
Dict(:alg=>Tsit5())
Dict(:alg=>Vern6())
Dict(:alg=>Tsit5(), :prob_choice => 2)
Dict(:alg=>Vern6(), :prob_choice => 2)
]
wp = WorkPrecisionSet(probs,abstols,reltols,setups;appxsol=test_sol,maxiters=10000,error_estimate=:L2,dense_errors=true,numruns=100)
plot(wp)
```
Here we see the power of algorithm specific interpolations. The ODE.jl algorithm is only able to reach $10^{-7}$ error even at a tolerance of $10^{-13}$, while the DifferentialEquations.jl algorithms are below $10^{-10}$
## Higher Order
```julia
setups = [Dict(:alg=>DP8())
Dict(:alg=>dop853())
#Dict(:alg=>ode78()) # fails
Dict(:alg=>Vern6())
Dict(:alg=>Vern7())
Dict(:alg=>Vern8())
Dict(:alg=>Vern9())
Dict(:alg=>Vern6(), :prob_choice => 2)
Dict(:alg=>Vern7(), :prob_choice => 2)
Dict(:alg=>Vern8(), :prob_choice => 2)
Dict(:alg=>Vern9(), :prob_choice => 2)
]
wp = WorkPrecisionSet(probs,abstols,reltols,setups;appxsol=test_sol,save_everystep=false,maxiters=1000,numruns=100)
plot(wp)
```
```julia
setups = [Dict(:alg=>odex())
Dict(:alg=>ddeabm())
Dict(:alg=>Vern6())
Dict(:alg=>Vern7())
Dict(:alg=>Vern8())
Dict(:alg=>Vern9())
Dict(:alg=>Vern6(), :prob_choice => 2)
Dict(:alg=>Vern7(), :prob_choice => 2)
Dict(:alg=>Vern8(), :prob_choice => 2)
Dict(:alg=>Vern9(), :prob_choice => 2)
Dict(:alg=>CVODE_Adams())
Dict(:alg=>lsoda())
Dict(:alg=>ARKODE(Sundials.Explicit(),order=6))
]
wp = WorkPrecisionSet(probs,abstols,reltols,setups;appxsol=test_sol,save_everystep=false,maxiters=1000,numruns=100)
plot(wp)
```
Again we look at interpolations:
```julia
setups = [Dict(:alg=>DP8())
#Dict(:alg=>ode78())
Dict(:alg=>Vern6())
Dict(:alg=>Vern7())
Dict(:alg=>Vern8())
Dict(:alg=>Vern9())
Dict(:alg=>Vern6(), :prob_choice => 2)
Dict(:alg=>Vern7(), :prob_choice => 2)
Dict(:alg=>Vern8(), :prob_choice => 2)
Dict(:alg=>Vern9(), :prob_choice => 2)
]
wp = WorkPrecisionSet(probs,abstols,reltols,setups;appxsol=test_sol,dense=true,maxiters=1000,error_estimate=:L2,numruns=100)
plot(wp)
```
Again, the ODE.jl algorithms suffer when measuring the interpolations due to relying on an order 3 Hermite polynomial instead of an algorithm-specific order matching interpolation which uses the timesteps.
## Comparison with Non-RK methods
Now let's test Tsit5 and Vern9 against parallel extrapolation methods and an
Adams-Bashforth-Moulton:
```julia
setups = [Dict(:alg=>Tsit5())
Dict(:alg=>Vern9())
Dict(:alg=>VCABM())
Dict(:alg=>Vern9(), :prob_choice => 2)
Dict(:alg=>VCABM(), :prob_choice => 2)
Dict(:alg=>AitkenNeville(min_order=1, max_order=9, init_order=4, threading=true))
Dict(:alg=>ExtrapolationMidpointDeuflhard(min_order=1, max_order=9, init_order=4, threading=true))
Dict(:alg=>ExtrapolationMidpointHairerWanner(min_order=2, max_order=11, init_order=4, threading=true))]
solnames = ["Tsit5","Vern9","VCABM","Vern9 Static","VCABM Static","AitkenNeville","Midpoint Deuflhard","Midpoint Hairer Wanner"]
wp = WorkPrecisionSet(probs,abstols,reltols,setups;appxsol=test_sol,names=solnames,
save_everystep=false,verbose=false,numruns=100)
plot(wp)
```
```julia
setups = [Dict(:alg=>ExtrapolationMidpointDeuflhard(min_order=1, max_order=9, init_order=9, threading=false))
Dict(:alg=>ExtrapolationMidpointHairerWanner(min_order=2, max_order=11, init_order=4, threading=false))
Dict(:alg=>ExtrapolationMidpointHairerWanner(min_order=2, max_order=11, init_order=4, threading=true))
Dict(:alg=>ExtrapolationMidpointHairerWanner(min_order=2, max_order=11, init_order=4, sequence = :romberg, threading=true))
Dict(:alg=>ExtrapolationMidpointHairerWanner(min_order=2, max_order=11, init_order=4, sequence = :bulirsch, threading=true))]
solnames = ["Deuflhard","No threads","standard","Romberg","Bulirsch"]
wp = WorkPrecisionSet(probs,abstols,reltols,setups;appxsol=test_sol,names=solnames,
save_everystep=false,verbose=false,numruns=100)
plot(wp)
```
```julia
setups = [Dict(:alg=>ExtrapolationMidpointHairerWanner(min_order=2, max_order=11, init_order=10, threading=true))
Dict(:alg=>ExtrapolationMidpointHairerWanner(min_order=2, max_order=11, init_order=4, threading=true))
Dict(:alg=>ExtrapolationMidpointHairerWanner(min_order=5, max_order=11, init_order=10, threading=true))
Dict(:alg=>ExtrapolationMidpointHairerWanner(min_order=2, max_order=15, init_order=10, threading=true))
Dict(:alg=>ExtrapolationMidpointHairerWanner(min_order=5, max_order=7, init_order=6, threading=true))]
solnames = ["1","2","3","4","5"]
wp = WorkPrecisionSet(probs,abstols,reltols,setups;appxsol=test_sol,names=solnames,
save_everystep=false,verbose=false,numruns=100)
plot(wp)
```
## Conclusion
The OrdinaryDiffEq.jl are quicker and still solve to a much higher accuracy, especially when the interpolations are involved. ODE.jl errors a lot.
```julia, echo = false
using SciMLBenchmarks
SciMLBenchmarks.bench_footer(WEAVE_ARGS[:folder],WEAVE_ARGS[:file])
```
| SciMLBenchmarks | https://github.com/SciML/SciMLBenchmarks.jl.git |
|
[
"MIT"
] | 0.1.3 | f4076dd5a103010d48bb6c4e50c5526f6622fa96 | docs | 6141 | ---
title: Pleiades Work-Precision Diagrams
author: Chris Rackauckas
---
```julia
using OrdinaryDiffEq, ODE, ODEInterfaceDiffEq, LSODA, Sundials, DiffEqDevTools
f = (du,u,p,t) -> begin
@inbounds begin
x = view(u,1:7) # x
y = view(u,8:14) # y
v = view(u,15:21) # x′
w = view(u,22:28) # y′
du[1:7] .= v
du[8:14].= w
for i in 15:28
du[i] = zero(u[1])
end
for i=1:7,j=1:7
if i != j
r = ((x[i]-x[j])^2 + (y[i] - y[j])^2)^(3/2)
du[14+i] += j*(x[j] - x[i])/r
du[21+i] += j*(y[j] - y[i])/r
end
end
end
end
prob = ODEProblem{true, SciMLBase.FullSpecialize}(f,[3.0,3.0,-1.0,-3.0,2.0,-2.0,2.0,3.0,-3.0,2.0,0,0,-4.0,4.0,0,0,0,0,0,1.75,-1.5,0,0,0,-1.25,1,0,0],(0.0,3.0))
abstols = 1.0 ./ 10.0 .^ (6:9)
reltols = 1.0 ./ 10.0 .^ (3:6);
using Plots; gr()
```
```julia
sol = solve(prob,Vern8(),abstol=1/10^12,reltol=1/10^10,maxiters=1000000)
test_sol = TestSolution(sol);
plot(sol)
```
## Low Order
ODE.jl had to be discarded. The error estimate is off since it throws errors and aborts and so that artificially lowers the error the the time is serverly diminished.
```julia
#setups = [Dict(:alg=>ode45())]
#wp = WorkPrecisionSet(prob,abstols,reltols,setups;appxsol=test_sol,save_everystep=false,numruns=100,maxiters=10000)
#plot(wp)
```
```julia
setups = [Dict(:alg=>DP5())
Dict(:alg=>dopri5())
Dict(:alg=>Tsit5())
Dict(:alg=>Vern6())
]
wp = WorkPrecisionSet(prob,abstols,reltols,setups;appxsol=test_sol,save_everystep=false,numruns=100,maxiters=10000)
plot(wp)
```
### Interpolation
```julia
setups = [Dict(:alg=>DP5())
Dict(:alg=>Tsit5())
Dict(:alg=>Vern6())
]
wp = WorkPrecisionSet(prob,abstols,reltols,setups;appxsol=test_sol,numruns=100,maxiters=10000,error_estimate=:L2,dense_errors=true)
plot(wp)
```
## Higher Order
Once again ODE.jl had to be discarded since it errors.
```julia
#setups = [Dict(:alg=>ode78())]
#wp = WorkPrecisionSet(prob,abstols,reltols,setups;appxsol=test_sol,save_everystep=false,numruns=100,maxiters=1000)
#plot(wp)
```
```julia
setups = [Dict(:alg=>DP8())
Dict(:alg=>Vern6())
Dict(:alg=>Vern7())
Dict(:alg=>Vern8())
Dict(:alg=>Vern9())
Dict(:alg=>dop853())
]
wp = WorkPrecisionSet(prob,abstols,reltols,setups;appxsol=test_sol,save_everystep=false,numruns=100,maxiters=1000)
plot(wp)
```
```julia
setups = [Dict(:alg=>odex())
Dict(:alg=>Vern7())
Dict(:alg=>CVODE_Adams())
Dict(:alg=>lsoda())
Dict(:alg=>Vern6())
Dict(:alg=>Tsit5())
Dict(:alg=>ddeabm())
Dict(:alg=>ARKODE(Sundials.Explicit(),order=6))
]
wp = WorkPrecisionSet(prob,abstols,reltols,setups;appxsol=test_sol,save_everystep=false,numruns=20)
plot(wp)
```
### Interpolations
```julia
setups = [Dict(:alg=>DP8())
Dict(:alg=>Vern6())
Dict(:alg=>Vern7())
Dict(:alg=>Vern8())
Dict(:alg=>Vern9())
]
wp = WorkPrecisionSet(prob,abstols,reltols,setups;appxsol=test_sol,numruns=100,maxiters=1000,error_estimate=:L2,dense_errors=true)
plot(wp)
```
## Comparison with Non-RK methods
Now let's test Tsit5 and Vern9 against parallel extrapolation methods and an
Adams-Bashforth-Moulton:
```julia
setups = [Dict(:alg=>Tsit5())
Dict(:alg=>Vern9())
Dict(:alg=>VCABM())
Dict(:alg=>AitkenNeville(min_order=1, max_order=9, init_order=4, threading=true))
Dict(:alg=>ExtrapolationMidpointDeuflhard(min_order=1, max_order=9, init_order=4, threading=true))
Dict(:alg=>ExtrapolationMidpointHairerWanner(min_order=2, max_order=11, init_order=4, threading=true))]
solnames = ["Tsit5","Vern9","VCABM","AitkenNeville","Midpoint Deuflhard","Midpoint Hairer Wanner"]
wp = WorkPrecisionSet(prob,abstols,reltols,setups;appxsol=test_sol,names=solnames,
save_everystep=false,verbose=false,numruns=100)
plot(wp)
```
```julia
setups = [Dict(:alg=>ExtrapolationMidpointDeuflhard(min_order=1, max_order=9, init_order=9, threading=false))
Dict(:alg=>ExtrapolationMidpointHairerWanner(min_order=2, max_order=11, init_order=4, threading=false))
Dict(:alg=>ExtrapolationMidpointHairerWanner(min_order=2, max_order=11, init_order=4, threading=true))
Dict(:alg=>ExtrapolationMidpointHairerWanner(min_order=2, max_order=11, init_order=4, sequence = :romberg, threading=true))
Dict(:alg=>ExtrapolationMidpointHairerWanner(min_order=2, max_order=11, init_order=4, sequence = :bulirsch, threading=true))]
solnames = ["Deuflhard","No threads","standard","Romberg","Bulirsch"]
wp = WorkPrecisionSet(prob,abstols,reltols,setups;appxsol=test_sol,names=solnames,
save_everystep=false,verbose=false,numruns=100)
plot(wp)
```
```julia
setups = [Dict(:alg=>ExtrapolationMidpointHairerWanner(min_order=2, max_order=11, init_order=10, threading=true))
Dict(:alg=>ExtrapolationMidpointHairerWanner(min_order=2, max_order=11, init_order=4, threading=true))
Dict(:alg=>ExtrapolationMidpointHairerWanner(min_order=5, max_order=11, init_order=10, threading=true))
Dict(:alg=>ExtrapolationMidpointHairerWanner(min_order=2, max_order=15, init_order=10, threading=true))
Dict(:alg=>ExtrapolationMidpointHairerWanner(min_order=5, max_order=7, init_order=6, threading=true))]
solnames = ["1","2","3","4","5"]
wp = WorkPrecisionSet(prob,abstols,reltols,setups;appxsol=test_sol,names=solnames,
save_everystep=false,verbose=false,numruns=100)
plot(wp)
```
## Conclusion
One big conclusion is that, once again, the ODE.jl algorithms fail to run on difficult problems. Its minimum timestep is essentially machine epsilon, and so this shows some fatal flaws in its timestepping algorithm. The OrdinaryDiffEq.jl algorithms come out as faster in each case than the ODEInterface algorithms. Overall, the Verner methods have a really good showing once again. The `CVODE_Adams` method does really well here when the tolerances are higher.
```julia, echo = false
using SciMLBenchmarks
SciMLBenchmarks.bench_footer(WEAVE_ARGS[:folder],WEAVE_ARGS[:file])
```
| SciMLBenchmarks | https://github.com/SciML/SciMLBenchmarks.jl.git |
|
[
"MIT"
] | 0.1.3 | f4076dd5a103010d48bb6c4e50c5526f6622fa96 | docs | 5448 | ---
title: Rigid Body Work-Precision Diagrams
author: Chris Rackauckas
---
```julia
using OrdinaryDiffEq, ParameterizedFunctions, ODE, ODEInterfaceDiffEq, LSODA,
Sundials, DiffEqDevTools, StaticArrays
k(t) = 0.25*sin(t)^2
g = @ode_def RigidBody begin
dy1 = I₁*y2*y3
dy2 = I₂*y1*y3
dy3 = I₃*y1*y2 + k(t)
end I₁ I₂ I₃
p = SA[-2.0,1.25,-0.5]
prob = ODEProblem{true, SciMLBase.FullSpecialize}(g,[1.0;0.0;0.9],(0.0,10.0),p)
probstatic = ODEProblem{false}(g,SA[1.0;0.0;0.9],(0.0,10.0),p)
abstols = 1.0 ./ 10.0 .^ (6:13)
reltols = 1.0 ./ 10.0 .^ (3:10);
sol = solve(prob,Vern7(),abstol=1/10^14,reltol=1/10^14)
sol2 = solve(probstatic,Vern7(),abstol=1/10^14,reltol=1/10^14)
probs = [prob,probstatic]
test_sol = [sol,sol2];
using Plots; gr()
```
```julia
plot(sol)
```
```julia
setups = [Dict(:alg=>DP5())
#Dict(:alg=>ode45()) # fails
Dict(:alg=>dopri5())
Dict(:alg=>Tsit5())
Dict(:alg=>Vern6())
Dict(:alg=>Tsit5(), :prob_choice => 2)
Dict(:alg=>Vern6(), :prob_choice => 2)
]
wp = WorkPrecisionSet(probs,abstols,reltols,setups;appxsol=test_sol,save_everystep=true,numruns=100,maxiters=10000)
plot(wp)
```
The DifferentialEquations.jl algorithms once again pull ahead. This is the first benchmark we've ran where `ode45` doesn't fail. However, it still doesn't do as well as `Tsit5`. One reason why it does so well is that the maximum norm that ODE.jl uses (as opposed to the L2 norm of Sundials, DifferentialEquations, and ODEInterface) seems to do really well on this problem. `dopri5` does surprisingly bad in this test.
## Higher Order
```julia
setups = [Dict(:alg=>DP8())
Dict(:alg=>dop853())
#Dict(:alg=>ode78()) # fails
Dict(:alg=>Vern6())
Dict(:alg=>Vern7())
Dict(:alg=>Vern8())
Dict(:alg=>Vern9())
Dict(:alg=>Vern6(), :prob_choice => 2)
Dict(:alg=>Vern7(), :prob_choice => 2)
Dict(:alg=>Vern8(), :prob_choice => 2)
Dict(:alg=>Vern9(), :prob_choice => 2)
]
wp = WorkPrecisionSet(probs,abstols,reltols,setups;appxsol=test_sol,save_everystep=false,numruns=100,maxiters=1000)
plot(wp)
```
```julia
setups = [Dict(:alg=>Vern7())
Dict(:alg=>Vern8())
Dict(:alg=>Vern7(), :prob_choice => 2)
Dict(:alg=>Vern8(), :prob_choice => 2)
Dict(:alg=>odex())
Dict(:alg=>CVODE_Adams())
Dict(:alg=>lsoda())
Dict(:alg=>ddeabm())
Dict(:alg=>ARKODE(Sundials.Explicit(),order=6))
]
wp = WorkPrecisionSet(probs,abstols,reltols,setups;appxsol=test_sol,save_everystep=false,numruns=100,maxiters=1000)
plot(wp)
```
## Comparison with Non-RK methods
Now let's test Tsit5 and Vern9 against parallel extrapolation methods and an
Adams-Bashforth-Moulton:
```julia
setups = [Dict(:alg=>Tsit5())
Dict(:alg=>Vern9())
Dict(:alg=>VCABM())
Dict(:alg=>Vern9(), :prob_choice => 2)
Dict(:alg=>VCABM(), :prob_choice => 2)
Dict(:alg=>AitkenNeville(min_order=1, max_order=9, init_order=4, threading=true))
Dict(:alg=>ExtrapolationMidpointDeuflhard(min_order=1, max_order=9, init_order=4, threading=true))
Dict(:alg=>ExtrapolationMidpointHairerWanner(min_order=2, max_order=11, init_order=4, threading=true))]
solnames = ["Tsit5","Vern9","VCABM","Vern9 Static","VCABM Static","AitkenNeville","Midpoint Deuflhard","Midpoint Hairer Wanner"]
wp = WorkPrecisionSet(probs,abstols,reltols,setups;appxsol=test_sol,names=solnames,
save_everystep=false,verbose=false,numruns=100)
plot(wp)
```
```julia
setups = [Dict(:alg=>ExtrapolationMidpointDeuflhard(min_order=1, max_order=9, init_order=9, threading=false))
Dict(:alg=>ExtrapolationMidpointHairerWanner(min_order=2, max_order=11, init_order=4, threading=false))
Dict(:alg=>ExtrapolationMidpointHairerWanner(min_order=2, max_order=11, init_order=4, threading=true))
Dict(:alg=>ExtrapolationMidpointHairerWanner(min_order=2, max_order=11, init_order=4, sequence = :romberg, threading=true))
Dict(:alg=>ExtrapolationMidpointHairerWanner(min_order=2, max_order=11, init_order=4, sequence = :bulirsch, threading=true))]
solnames = ["Deuflhard","No threads","standard","Romberg","Bulirsch"]
wp = WorkPrecisionSet(probs,abstols,reltols,setups;appxsol=test_sol,names=solnames,
save_everystep=false,verbose=false,numruns=100)
plot(wp)
```
```julia
setups = [Dict(:alg=>ExtrapolationMidpointHairerWanner(min_order=2, max_order=11, init_order=10, threading=true))
Dict(:alg=>ExtrapolationMidpointHairerWanner(min_order=2, max_order=11, init_order=4, threading=true))
Dict(:alg=>ExtrapolationMidpointHairerWanner(min_order=5, max_order=11, init_order=10, threading=true))
Dict(:alg=>ExtrapolationMidpointHairerWanner(min_order=2, max_order=15, init_order=10, threading=true))
Dict(:alg=>ExtrapolationMidpointHairerWanner(min_order=5, max_order=7, init_order=6, threading=true))]
solnames = ["1","2","3","4","5"]
wp = WorkPrecisionSet(probs,abstols,reltols,setups;appxsol=test_sol,names=solnames,
save_everystep=false,verbose=false,numruns=100)
plot(wp)
```
### Conclusion
Once again, the OrdinaryDiffEq.jl pull far ahead in terms of speed and accuracy.
```julia, echo = false
using SciMLBenchmarks
SciMLBenchmarks.bench_footer(WEAVE_ARGS[:folder],WEAVE_ARGS[:file])
```
| SciMLBenchmarks | https://github.com/SciML/SciMLBenchmarks.jl.git |
|
[
"MIT"
] | 0.1.3 | f4076dd5a103010d48bb6c4e50c5526f6622fa96 | docs | 7989 | ---
title: Three Body Work-Precision Diagrams
author: Chris Rackauckas
---
```julia
using OrdinaryDiffEq, ODE, ODEInterfaceDiffEq, LSODA, Sundials, DiffEqDevTools, StaticArrays
using Plots; gr()
## Define the ThreeBody Problem
const threebody_μ = parse(Float64,"0.012277471")
const threebody_μ′ = 1 - threebody_μ
function f(du,u,p,t)
@inbounds begin
# 1 = y₁
# 2 = y₂
# 3 = y₁'
# 4 = y₂'
D₁ = ((u[1]+threebody_μ)^2 + u[2]^2)^(3/2)
D₂ = ((u[1]-threebody_μ′)^2 + u[2]^2)^(3/2)
du[1] = u[3]
du[2] = u[4]
du[3] = u[1] + 2u[4] - threebody_μ′*(u[1]+threebody_μ)/D₁ - threebody_μ*(u[1]-threebody_μ′)/D₂
du[4] = u[2] - 2u[3] - threebody_μ′*u[2]/D₁ - threebody_μ*u[2]/D₂
end
end
function f(u,p,t)
@inbounds begin
# 1 = y₁
# 2 = y₂
# 3 = y₁'
# 4 = y₂'
D₁ = ((u[1]+threebody_μ)^2 + u[2]^2)^(3/2)
D₂ = ((u[1]-threebody_μ′)^2 + u[2]^2)^(3/2)
du1 = u[3]
du2 = u[4]
du3 = u[1] + 2u[4] - threebody_μ′*(u[1]+threebody_μ)/D₁ - threebody_μ*(u[1]-threebody_μ′)/D₂
du4 = u[2] - 2u[3] - threebody_μ′*u[2]/D₁ - threebody_μ*u[2]/D₂
end
SA[du1,du2,du3,du4]
end
t₀ = 0.0; T = parse(Float64,"17.0652165601579625588917206249")
tspan = (t₀,2T)
prob = ODEProblem{true, SciMLBase.FullSpecialize}(f,[0.994, 0.0, 0.0, parse(Float64,"-2.00158510637908252240537862224")],tspan)
probstatic = ODEProblem{false}(f,SA[0.994, 0.0, 0.0, parse(Float64,"-2.00158510637908252240537862224")],tspan)
sol = solve(prob,Vern7(),abstol=1/10^14,reltol=1/10^14)
sol2 = solve(probstatic,Vern7(),abstol=1/10^14,reltol=1/10^14)
probs = [prob,probstatic]
test_sol = [sol,sol2];
abstols = 1.0 ./ 10.0 .^ (3:13); reltols = 1.0 ./ 10.0 .^ (0:10);
```
See that it's periodic in the chosen timespan:
```julia
sol = solve(prob,Vern9(),abstol=1e-14,reltol=1e-14)
@show sol[1] - sol[end]
@show sol[end] - prob.u0;
```
This three-body problem is known to be a tough problem. Let's see how the algorithms do at standard tolerances.
### 5th Order Runge-Kutta Methods
```julia
setups = [Dict(:alg=>DP5())
#Dict(:alg=>ode45()) #fails
Dict(:alg=>BS5())
Dict(:alg=>Tsit5())
Dict(:alg=>Tsit5(), :prob_choice => 2)
Dict(:alg=>dopri5())];
wp = WorkPrecisionSet(probs,abstols,reltols,setups;appxsol=test_sol,save_everystep=false,numruns=100)
plot(wp)
```
#### Full save, but no dense
```julia
setups = [Dict(:alg=>DP5(),:dense=>false)
#Dict(:alg=>ode45()) # Fails
Dict(:alg=>BS5(),:dense=>false)
Dict(:alg=>Tsit5(),:dense=>false)
Dict(:alg=>Tsit5(),:dense=>false, :prob_choice => 2)
Dict(:alg=>dopri5())];
wp = WorkPrecisionSet(probs,abstols,reltols,setups;appxsol=test_sol,numruns=100)
plot(wp)
```
#### Dense
```julia
setups = [Dict(:alg=>DP5())
#Dict(:alg=>ode45()) #fails
Dict(:alg=>BS5())
Dict(:alg=>Tsit5())
Dict(:alg=>Tsit5(), :prob_choice => 2)
Dict(:alg=>dopri5())];
wp = WorkPrecisionSet(probs,abstols,reltols,setups;appxsol=test_sol,numruns=100)
plot(wp)
```
In these tests we see that most of the algorithms are close,with `BS5` and `DP5` showing much better than `Tsit5`. `ode45` errors.
### Higher Order Algorithms
```julia
setups = [Dict(:alg=>DP5())
Dict(:alg=>TanYam7())
Dict(:alg=>DP8())
Dict(:alg=>dop853())
Dict(:alg=>Vern6())
Dict(:alg=>Vern7())
Dict(:alg=>Vern8())
Dict(:alg=>Vern9())
Dict(:alg=>Vern6(), :prob_choice => 2)
Dict(:alg=>Vern7(), :prob_choice => 2)
Dict(:alg=>Vern8(), :prob_choice => 2)
Dict(:alg=>Vern9(), :prob_choice => 2)];
wp = WorkPrecisionSet(probs,abstols,reltols,setups;appxsol=test_sol,save_everystep=false,numruns=100)
plot(wp)
```
```julia
wp = WorkPrecisionSet(probs,abstols,reltols,setups;appxsol=test_sol,dense=false,numruns=100,verbose=false)
plot(wp)
```
```julia
wp = WorkPrecisionSet(probs,abstols,reltols,setups;appxsol=test_sol,numruns=100)
plot(wp)
```
In this test we see `Vern7` and `Vern8` shine.
### Other Algorithms
Once again we separate ODE.jl because it fails. We also separate Sundials' `CVODE_Adams` since it fails at high tolerances.
```julia
#setups = [Dict(:alg=>ode78())
# Dict(:alg=>VCABM())
# Dict(:alg=>CVODE_Adams())];
#wp = WorkPrecisionSet(prob,abstols,reltols,setups;appxsol=test_sol,dense=false,numruns=100)
```
```julia
setups = [Dict(:alg=>DP5())
Dict(:alg=>lsoda())
Dict(:alg=>Vern8())
Dict(:alg=>Vern8(), :prob_choice => 2)
Dict(:alg=>ddeabm())
Dict(:alg=>odex())
Dict(:alg=>ARKODE(Sundials.Explicit(),order=6))
];
wp = WorkPrecisionSet(probs,abstols,reltols,setups;appxsol=test_sol,save_everystep=false,numruns=100)
plot(wp)
```
Again, on cheap function calculations the Adams methods are shown to not be efficient once the error is sufficiently small. Also, as seen in other places, the extrapolation methods do not fare as well as the Runge-Kutta methods.
## Comparison with Non-RK methods
Now let's test Tsit5 and Vern9 against parallel extrapolation methods and an
Adams-Bashforth-Moulton:
```julia
abstols = 1.0 ./ 10.0 .^ (3:13); reltols = 1.0 ./ 10.0 .^ (0:10);
setups = [Dict(:alg=>Tsit5())
Dict(:alg=>Vern9())
Dict(:alg=>Vern9(), :prob_choice => 2)
Dict(:alg=>AitkenNeville(min_order=1, max_order=9, init_order=4, threading=true))
Dict(:alg=>ExtrapolationMidpointDeuflhard(min_order=1, max_order=9, init_order=4, threading=true))
Dict(:alg=>ExtrapolationMidpointHairerWanner(min_order=2, max_order=11, init_order=4, threading=true))]
solnames = ["Tsit5","Vern9","Vern9 Static","AitkenNeville","Midpoint Deuflhard","Midpoint Hairer Wanner"]
wp = WorkPrecisionSet(probs,abstols,reltols,setups;appxsol=test_sol,names=solnames,
save_everystep=false,verbose=false,numruns=100)
plot(wp)
```
```julia
setups = [Dict(:alg=>ExtrapolationMidpointDeuflhard(min_order=1, max_order=9, init_order=9, threading=false))
Dict(:alg=>ExtrapolationMidpointHairerWanner(min_order=2, max_order=11, init_order=4, threading=false))
Dict(:alg=>ExtrapolationMidpointHairerWanner(min_order=2, max_order=11, init_order=4, threading=true))
Dict(:alg=>ExtrapolationMidpointHairerWanner(min_order=2, max_order=11, init_order=4, sequence = :romberg, threading=true))
Dict(:alg=>ExtrapolationMidpointHairerWanner(min_order=2, max_order=11, init_order=4, sequence = :bulirsch, threading=true))]
solnames = ["Deuflhard","No threads","standard","Romberg","Bulirsch"]
wp = WorkPrecisionSet(probs,abstols,reltols,setups;appxsol=test_sol,names=solnames,
save_everystep=false,verbose=false,numruns=100)
plot(wp)
```
```julia
setups = [Dict(:alg=>ExtrapolationMidpointHairerWanner(min_order=2, max_order=11, init_order=10, threading=true))
Dict(:alg=>ExtrapolationMidpointHairerWanner(min_order=2, max_order=11, init_order=4, threading=true))
Dict(:alg=>ExtrapolationMidpointHairerWanner(min_order=5, max_order=11, init_order=10, threading=true))
Dict(:alg=>ExtrapolationMidpointHairerWanner(min_order=2, max_order=15, init_order=10, threading=true))
Dict(:alg=>ExtrapolationMidpointHairerWanner(min_order=5, max_order=7, init_order=6, threading=true))]
solnames = ["1","2","3","4","5"]
wp = WorkPrecisionSet(probs,abstols,reltols,setups;appxsol=test_sol,names=solnames,
save_everystep=false,verbose=false,numruns=100)
plot(wp)
```
### Conclusion
As in the other tests, the OrdinaryDiffEq.jl algorithms with the Verner Efficient methods are the most efficient solvers at stringent tolerances for most of the tests, while the order 5 methods do well at cruder tolerances. ODE.jl fails to run the test problems without erroring.
```julia, echo = false
using SciMLBenchmarks
SciMLBenchmarks.bench_footer(WEAVE_ARGS[:folder],WEAVE_ARGS[:file])
```
| SciMLBenchmarks | https://github.com/SciML/SciMLBenchmarks.jl.git |
|
[
"MIT"
] | 0.1.3 | f4076dd5a103010d48bb6c4e50c5526f6622fa96 | docs | 10473 | ---
title: 100 Independent Linear Work-Precision Diagrams
author: Chris Rackauckas
---
For these tests we will solve a diagonal 100 independent linear differential
equations. This will demonstrate the efficiency of the implementation of the methods
for handling large systems, since the system is both large enough that array
handling matters, but `f` is cheap enough that it is not simply a game of
calculating `f` as few times as possible. We will be mostly looking at the
efficiency of the work-horse Dormand-Prince Order 4/5 Pairs: one from
DifferentialEquations.jl (`DP5`), one from ODE.jl `rk45`, one from
ODEInterface (Hairer's famous `dopri5`, and one from SUNDIALS' ARKODE suite.
Also included is `Tsit5`. While all other ODE programs have gone with the
traditional choice of using the Dormand-Prince 4/5 pair as the default,
DifferentialEquations.jl uses `Tsit5` as one of the default algorithms. It's a
very new (2011) and not widely known, but the theory and the implimentation
shows it's more efficient than DP5. Thus we include it just to show off how
re-designing a library from the ground up in a language for rapid code and
rapid development has its advantages.
## Setup
```julia
using OrdinaryDiffEq, Sundials, DiffEqDevTools, Plots, ODEInterfaceDiffEq, ODE, LSODA
using Random
Random.seed!(123)
gr()
# 2D Linear ODE
function f(du,u,p,t)
@inbounds for i in eachindex(u)
du[i] = 1.01*u[i]
end
end
function f_analytic(u₀,p,t)
u₀*exp(1.01*t)
end
tspan = (0.0,10.0)
prob = ODEProblem(ODEFunction{true, SciMLBase.FullSpecialize}(f,analytic=f_analytic),rand(100,100),tspan)
abstols = 1.0 ./ 10.0 .^ (3:13)
reltols = 1.0 ./ 10.0 .^ (0:10);
```
### Speed Baseline
First a baseline. These are all testing the same Dormand-Prince order 5/4
algorithm of each package. While all the same Runge-Kutta tableau, they exhibit
different behavior due to different choices of adaptive timestepping algorithms
and tuning. First we will test with all extra saving features are turned off to
put DifferentialEquations.jl in "speed mode".
```julia
setups = [Dict(:alg=>DP5())
Dict(:alg=>ode45())
Dict(:alg=>dopri5())
Dict(:alg=>ARKODE(Sundials.Explicit(),etable=Sundials.DORMAND_PRINCE_7_4_5))
Dict(:alg=>Tsit5())]
solnames = ["OrdinaryDiffEq";"ODE";"ODEInterface";"Sundials ARKODE";"OrdinaryDiffEq Tsit5"]
wp = WorkPrecisionSet(prob,abstols,reltols,setups;names=solnames,save_everystep=false,numruns=100)
plot(wp)
```
### Full Saving
```julia
setups = [Dict(:alg=>DP5(),:dense=>false)
Dict(:alg=>ode45(),:dense=>false)
Dict(:alg=>dopri5()) # dense=false by default: no nonlinear interpolation
Dict(:alg=>ARKODE(Sundials.Explicit(),etable=Sundials.DORMAND_PRINCE_7_4_5),:dense=>false)
Dict(:alg=>Tsit5(),:dense=>false)]
solnames = ["OrdinaryDiffEq";"ODE";"ODEInterface";"Sundials ARKODE";"OrdinaryDiffEq Tsit5"]
wp = WorkPrecisionSet(prob,abstols,reltols,setups;names=solnames,numruns=100)
plot(wp)
```
### Continuous Output
Now we include continuous output. This has a large overhead because at every
timepoint the matrix of rates `k` has to be deep copied.
```julia
setups = [Dict(:alg=>DP5())
Dict(:alg=>ode45())
Dict(:alg=>dopri5())
Dict(:alg=>ARKODE(Sundials.Explicit(),etable=Sundials.DORMAND_PRINCE_7_4_5))
Dict(:alg=>Tsit5())]
solnames = ["OrdinaryDiffEq";"ODE";"ODEInterface";"Sundials ARKODE";"OrdinaryDiffEq Tsit5"]
wp = WorkPrecisionSet(prob,abstols,reltols,setups;names=solnames,numruns=100)
plot(wp)
```
### Other Runge-Kutta Algorithms
Now let's test it against a smattering of other Runge-Kutta algorithms. First
we will test it with all overheads off. Let's do the Order 5 (and the 2/3 pair)
algorithms:
```julia
setups = [Dict(:alg=>DP5())
Dict(:alg=>BS3())
Dict(:alg=>BS5())
Dict(:alg=>Tsit5())]
wp = WorkPrecisionSet(prob,abstols,reltols,setups;save_everystep=false,numruns=100)
plot(wp)
```
## Higher Order
Now let's see how OrdinaryDiffEq.jl fairs with some higher order algorithms:
```julia
setups = [Dict(:alg=>DP5())
Dict(:alg=>Vern6())
Dict(:alg=>TanYam7())
Dict(:alg=>Vern7())
Dict(:alg=>Vern8())
Dict(:alg=>DP8())
Dict(:alg=>Vern9())]
wp = WorkPrecisionSet(prob,abstols,reltols,setups;save_everystep=false,numruns=100)
plot(wp)
```
## Higher Order With Many Packages
Now we test OrdinaryDiffEq against the high order methods of the other packages:
```julia
setups = [Dict(:alg=>DP5())
Dict(:alg=>Vern7())
Dict(:alg=>dop853())
Dict(:alg=>ode78())
Dict(:alg=>odex())
Dict(:alg=>lsoda())
Dict(:alg=>ddeabm())
Dict(:alg=>ARKODE(Sundials.Explicit(),order=8))
Dict(:alg=>CVODE_Adams())]
wp = WorkPrecisionSet(prob,abstols,reltols,setups;save_everystep=false,numruns=100)
plot(wp)
```
## Interpolation Error
Now we will look at the error using an interpolation measurement instead of at
the timestepping points. Since the DifferentialEquations.jl algorithms have
higher order interpolants than the ODE.jl algorithms, one would expect this
would magnify the difference. First the order 4/5 comparison:
```julia
setups = [Dict(:alg=>DP5())
#Dict(:alg=>ode45())
Dict(:alg=>Tsit5())]
wp = WorkPrecisionSet(prob,abstols,reltols,setups;error_estimate=:L2,dense_errors=true,numruns=100)
plot(wp)
```
Note that all of ODE.jl uses a 3rd order Hermite interpolation, while the
DifferentialEquations algorithms interpolations which are specialized to the
algorithm. For example, `DP5` and `Tsit5` both use "free" order 4
interpolations, which are both as fast as the Hermite interpolation while
achieving far less error. At higher order:
```julia
setups = [Dict(:alg=>DP5())
Dict(:alg=>Vern7())
#Dict(:alg=>ode78())
]
wp = WorkPrecisionSet(prob,abstols,reltols,setups;error_estimate=:L2,dense_errors=true,numruns=100)
plot(wp)
```
## Comparison with Fixed Timestep RK4
Let's run the first benchmark but add some fixed timestep RK4 methods to see
the difference:
```julia
abstols = 1.0 ./ 10.0 .^ (3:13)
reltols = 1.0 ./ 10.0 .^ (0:10);
dts = [1,1/2,1/4,1/10,1/20,1/40,1/60,1/80,1/100,1/140,1/240]
setups = [Dict(:alg=>DP5())
Dict(:alg=>ode45())
Dict(:alg=>dopri5())
Dict(:alg=>RK4(),:dts=>dts)
Dict(:alg=>Tsit5())]
solnames = ["DifferentialEquations";"ODE";"ODEInterface";"DifferentialEquations RK4";"DifferentialEquations Tsit5"]
wp = WorkPrecisionSet(prob,abstols,reltols,setups;names=solnames,
save_everystep=false,verbose=false,numruns=100)
plot(wp)
```
## Comparison with Non-RK methods
Now let's test Tsit5 and Vern9 against parallel extrapolation methods and an
Adams-Bashforth-Moulton:
```julia
setups = [Dict(:alg=>Tsit5())
Dict(:alg=>Vern9())
Dict(:alg=>VCABM())
Dict(:alg=>AitkenNeville(min_order=1, max_order=9, init_order=4, threading=true))
Dict(:alg=>ExtrapolationMidpointDeuflhard(min_order=1, max_order=9, init_order=4, threading=true))
Dict(:alg=>ExtrapolationMidpointHairerWanner(min_order=2, max_order=11, init_order=4, threading=true))]
solnames = ["Tsit5","Vern9","VCABM","AitkenNeville","Midpoint Deuflhard","Midpoint Hairer Wanner"]
wp = WorkPrecisionSet(prob,abstols,reltols,setups;names=solnames,
save_everystep=false,verbose=false,numruns=100)
plot(wp)
```
```julia
setups = [Dict(:alg=>ExtrapolationMidpointDeuflhard(min_order=1, max_order=9, init_order=9, threading=false))
Dict(:alg=>ExtrapolationMidpointHairerWanner(min_order=2, max_order=11, init_order=4, threading=false))
Dict(:alg=>ExtrapolationMidpointHairerWanner(min_order=2, max_order=11, init_order=4, threading=true))
Dict(:alg=>ExtrapolationMidpointHairerWanner(min_order=2, max_order=11, init_order=4, sequence = :romberg, threading=true))
Dict(:alg=>ExtrapolationMidpointHairerWanner(min_order=2, max_order=11, init_order=4, sequence = :bulirsch, threading=true))]
solnames = ["Deuflhard","No threads","standard","Romberg","Bulirsch"]
wp = WorkPrecisionSet(prob,abstols,reltols,setups;names=solnames,
save_everystep=false,verbose=false,numruns=100)
plot(wp)
```
```julia
setups = [Dict(:alg=>ExtrapolationMidpointHairerWanner(min_order=2, max_order=11, init_order=10, threading=true))
Dict(:alg=>ExtrapolationMidpointHairerWanner(min_order=2, max_order=11, init_order=4, threading=true))
Dict(:alg=>ExtrapolationMidpointHairerWanner(min_order=5, max_order=11, init_order=10, threading=true))
Dict(:alg=>ExtrapolationMidpointHairerWanner(min_order=2, max_order=15, init_order=10, threading=true))
Dict(:alg=>ExtrapolationMidpointHairerWanner(min_order=5, max_order=7, init_order=6, threading=true))]
solnames = ["1","2","3","4","5"]
wp = WorkPrecisionSet(prob,abstols,reltols,setups;names=solnames,
save_everystep=false,verbose=false,numruns=100)
plot(wp)
```
```julia
abstols = 1.0 ./ 10.0 .^ (12:15)
reltols = 1.0 ./ 10.0 .^ (9:12)
setups = [Dict(:alg=>Tsit5())
Dict(:alg=>Vern9())
Dict(:alg=>VCABM())
#Dict(:alg=>AitkenNeville(threading = OrdinaryDiffEq.PolyesterThreads()))
Dict(:alg=>ExtrapolationMidpointDeuflhard(threading = OrdinaryDiffEq.PolyesterThreads()))
Dict(:alg=>ExtrapolationMidpointHairerWanner(threading = OrdinaryDiffEq.PolyesterThreads()))
Dict(:alg=>odex())
Dict(:alg=>dop853())
Dict(:alg=>CVODE_Adams())
]
wp = WorkPrecisionSet(prob,abstols,reltols,setups;
save_everystep=false,verbose=false,numruns=100)
plot(wp)
```
## Conclusion
DifferentialEquations's default choice of `Tsit5` does well for quick and easy
solving at normal tolerances. However, at low tolerances the higher order
algorithms are faster. In every case, the DifferentialEquations algorithms are
far in the lead, many times an order of magnitude faster than the competitors.
`Vern7` with its included 7th order interpolation looks to be a good workhorse
for scientific computing in floating point range. These along with many other
benchmarks are why these algorithms were chosen as part of the defaults.
```julia, echo = false
using SciMLBenchmarks
SciMLBenchmarks.bench_footer(WEAVE_ARGS[:folder],WEAVE_ARGS[:file])
```
| SciMLBenchmarks | https://github.com/SciML/SciMLBenchmarks.jl.git |
|
[
"MIT"
] | 0.1.3 | f4076dd5a103010d48bb6c4e50c5526f6622fa96 | docs | 9367 | ---
title: SDE Basic Weak Work-Precision Diagrams
author: Chris Rackauckas
---
# SDE Basic Weak Work-Precision Diagrams
In this notebook we will run some benchmarks for the weak error on some simple sample SDEs. The weak error is defined as:
$$E_W = \mathbb{E}[Y_\delta(t)] - \mathbb{E}[Y(t)]$$
and is thus a measure of how close the mean of the numerical solution is to the mean of the true solution. Other moments can be measured as well, but the mean is a good stand-in for other properties. Note that convergence of the mean is calculated on a sample. Thus there's acutally two sources of error. We have not only the error between the numerical and actual results, but we also have the error of the mean to the true mean due to only taking a finite sample. Using the normal confidence interval of the mean due to the Central Limit Theorem, the error due to finite sampling is
$$E_S = V[Y(t)]/\sqrt(N)$$
for $N$ being the number of samples. In practice,
$$E = minimum(E_W,E_S)$$
Thus in each case, we will determine the variance of the true solution and use that to estimate the sample error, and the goal is to thus find the numerical method that achieves the sample error most efficiently.
```julia
using StochasticDiffEq, DiffEqDevTools, ParameterizedFunctions, SDEProblemLibrary
using Plots; gr()
import SDEProblemLibrary: prob_sde_additive,
prob_sde_linear, prob_sde_wave
const N = 1000
```
### Additive Noise Problem
$$dX_{t}=\left(\frac{\beta}{\sqrt{1+t}}-\frac{1}{2\left(1+t\right)}X_{t}\right)dt+\frac{\alpha\beta}{\sqrt{1+t}}dW_{t},\thinspace\thinspace\thinspace X_{0}=\frac{1}{2}$$
where $\alpha=\frac{1}{10}$ and $\beta=\frac{1}{20}$. Actual Solution:
$$X_{t}=\frac{1}{\sqrt{1+t}}X_{0}+\frac{\beta}{\sqrt{1+t}}\left(t+\alpha W_{t}\right).$$
```julia
prob = prob_sde_additive
reltols = 1.0 ./ 10.0 .^ (1:5)
abstols = reltols#[0.0 for i in eachindex(reltols)]
setups = [
Dict(:alg=>EM(),:dts=>1.0./5.0.^((1:length(reltols)) .+ 1))
Dict(:alg=>RKMil(),:dts=>1.0./5.0.^((1:length(reltols)) .+ 1),:adaptive=>false)
Dict(:alg=>SRIW1(),:dts=>1.0./5.0.^((1:length(reltols)) .+ 1),:adaptive=>false)
Dict(:alg=>SRA1(),:dts=>1.0./5.0.^((1:length(reltols)) .+ 1),:adaptive=>false)
Dict(:alg=>SRA1())
Dict(:alg=>SRIW1())
]
wp = WorkPrecisionSet(prob,abstols,reltols,setups;numruns_error=N,
save_everystep = false,
parallel_type = :none,
error_estimate=:weak_final)#
plot(wp)
```
```julia
sample_size = Int[10;1e2;1e3;1e4]
se = get_sample_errors(prob,setups[6],numruns=sample_size,
sample_error_runs = 100_000,solution_runs=100)
```
```julia
times = [wp[i].times for i in 1:length(wp)]
times = [minimum(minimum(t) for t in times),maximum(maximum(t) for t in times)]
plot!([se[end];se[end]],times,color=:red,linestyle=:dash,label="Sample Error: 1000",lw=3)
```
```julia
prob = prob_sde_additive
reltols = 1.0 ./ 10.0 .^ (1:5)
abstols = reltols#[0.0 for i in eachindex(reltols)]
setups = [
Dict(:alg=>SRA1())
Dict(:alg=>SRA2())
Dict(:alg=>SRA3())
Dict(:alg=>SOSRA())
Dict(:alg=>SOSRA2())
]
wp = WorkPrecisionSet(prob,abstols,reltols,setups;numruns_error=N,
save_everystep = false,
maxiters = 1e7,
parallel_type = :none,
error_estimate=:weak_final)
plot(wp)
```
```julia
sample_size = Int[10;1e2;1e3;1e4]
se = get_sample_errors(prob,setups[4],numruns=sample_size,
sample_error_runs = 100_000,solution_runs=100)
```
```julia
times = [wp[i].times for i in 1:length(wp)]
times = [minimum(minimum(t) for t in times),maximum(maximum(t) for t in times)]
plot!([se[end];se[end]],times,color=:red,linestyle=:dash,label="Sample Error: 1000",lw=3)
```
### Scalar Noise
We will use a the linear SDE (also known as the Black-Scholes equation)
$$dX_{t}=\alpha X_{t}dt+\beta X_{t}dW_{t},\thinspace\thinspace\thinspace X_{0}=\frac{1}{2}$$
where $\alpha=\frac{1}{10}$ and $\beta=\frac{1}{20}$. Actual Solution:
$$X_{t}=X_{0}e^{\left(\beta-\frac{\alpha^{2}}{2}\right)t+\alpha W_{t}}.$$
```julia
prob = prob_sde_linear
reltols = 1.0 ./ 10.0 .^ (1:5)
abstols = reltols#[0.0 for i in eachindex(reltols)]
setups = [Dict(:alg=>SRIW1())
Dict(:alg=>EM(),:dts=>1.0./5.0.^((1:length(reltols)) .+ 1))
Dict(:alg=>RKMil(),:dts=>1.0./5.0.^((1:length(reltols)) .+ 1),:adaptive=>false)
Dict(:alg=>SRIW1(),:dts=>1.0./5.0.^((1:length(reltols)) .+ 1),:adaptive=>false)
]
wp = WorkPrecisionSet(prob,abstols,reltols,setups;numruns_error=N,
save_everystep = false,
maxiters = 1e7,
parallel_type = :none,
error_estimate=:weak_final)
plot(wp)
```
```julia
sample_size = Int[10;1e2;1e3;1e4]
se = get_sample_errors(prob,setups[1],numruns=sample_size,
sample_error_runs = 100_000,solution_runs=100)
```
```julia
times = [wp[i].times for i in 1:length(wp)]
times = [minimum(minimum(t) for t in times),maximum(maximum(t) for t in times)]
plot!([se[end];se[end]],times,color=:red,linestyle=:dash,label="Sample Error: 1000",lw=3)
```
```julia
prob = prob_sde_linear
reltols = 1.0 ./ 10.0 .^ (1:5)
abstols = reltols#[0.0 for i in eachindex(reltols)]
setups = [Dict(:alg=>EM(),:dts=>1.0./5.0.^((1:length(reltols)) .+ 2))
Dict(:alg=>RKMil(),:dts=>1.0./5.0.^((1:length(reltols)) .+ 2),:adaptive=>false)
Dict(:alg=>SRI())
Dict(:alg=>SRIW1())
Dict(:alg=>SRIW2())
Dict(:alg=>SOSRI())
Dict(:alg=>SOSRI2())
]
wp = WorkPrecisionSet(prob,abstols,reltols,setups;numruns_error=N,
save_everystep = false,
maxiters = 1e7,
parallel_type = :none,
error_estimate=:weak_final)
plot(wp)
```
```julia
sample_size = Int[10;1e2;1e3;1e4]
se = get_sample_errors(prob,setups[6],numruns=sample_size,
sample_error_runs = 100_000,solution_runs=100)
```
```julia
times = [wp[i].times for i in 1:length(wp)]
times = [minimum(minimum(t) for t in times),maximum(maximum(t) for t in times)]
plot!([se[end];se[end]],times,color=:red,linestyle=:dash,label="Sample Error: 1000",lw=3)
```
## Scalar Wave SDE
$$dX_{t}=-\left(\frac{1}{10}\right)^{2}\sin\left(X_{t}\right)\cos^{3}\left(X_{t}\right)dt+\frac{1}{10}\cos^{2}\left(X_{t}\right)dW_{t},\thinspace\thinspace\thinspace X_{0}=\frac{1}{2}$$
Actual Solution:
$$X_{t}=\arctan\left(\frac{1}{10}W_{t}+\tan\left(X_{0}\right)\right).$$
```julia
prob = prob_sde_wave
reltols = 1.0 ./ 10.0 .^ (1:5)
abstols = reltols#[0.0 for i in eachindex(reltols)]
setups = [
Dict(:alg=>EM(),:dts=>1.0./5.0.^((1:length(reltols)) .+ 1))
Dict(:alg=>RKMil(),:dts=>1.0./5.0.^((1:length(reltols)) .+ 1),:adaptive=>false)
Dict(:alg=>SRIW1(),:dts=>1.0./5.0.^((1:length(reltols)) .+ 1),:adaptive=>false)
Dict(:alg=>SRIW1())
]
wp = WorkPrecisionSet(prob,abstols,reltols,setups;numruns_error=N,
save_everystep = false,
maxiters = 1e7,
parallel_type = :none,
error_estimate=:weak_final)
plot(wp)
```
```julia
sample_size = Int[10;1e2;1e3;1e4]
se = get_sample_errors(prob,setups[4],numruns=sample_size,
sample_error_runs = 100_000,solution_runs=100)
```
```julia
times = [wp[i].times for i in 1:length(wp)]
times = [minimum(minimum(t) for t in times),maximum(maximum(t) for t in times)]
plot!([se[end];se[end]],times,color=:red,linestyle=:dash,label="Sample Error: 1000",lw=3)
```
```julia
prob = prob_sde_wave
reltols = 1.0 ./ 10.0 .^ (1:5)
abstols = reltols#[0.0 for i in eachindex(reltols)]
setups = [Dict(:alg=>EM(),:dts=>1.0./5.0.^((1:length(reltols)) .+ 2))
Dict(:alg=>RKMil(),:dts=>1.0./5.0.^((1:length(reltols)) .+ 2),:adaptive=>false)
Dict(:alg=>SRI())
Dict(:alg=>SRIW1())
Dict(:alg=>SRIW2())
Dict(:alg=>SOSRI())
Dict(:alg=>SOSRI2())
]
wp = WorkPrecisionSet(prob,abstols,reltols,setups;numruns_error=N,
save_everystep = false,
maxiters = 1e7,
parallel_type = :none,
error_estimate=:weak_final)
plot(wp)
```
```julia
sample_size = Int[10;1e2;1e3;1e4]
se = get_sample_errors(prob,setups[6],numruns=sample_size,
sample_error_runs = 100_000,solution_runs=100)
```
```julia
times = [wp[i].times for i in 1:length(wp)]
times = [minimum(minimum(t) for t in times),maximum(maximum(t) for t in times)]
plot!([se[end];se[end]],times,color=:red,linestyle=:dash,label="Sample Error: 1000",lw=3)
```
## Summary
In the additive noise problem, the `EM` and `RKMil` algorithms are not effective at reaching the sample error. In the other two problems, the `EM` and `RKMil` algorithms are as efficient as the higher order methods at achieving the maximal weak error.
```julia, echo = false
using SciMLBenchmarks
SciMLBenchmarks.bench_footer(WEAVE_ARGS[:folder],WEAVE_ARGS[:file])
```
| SciMLBenchmarks | https://github.com/SciML/SciMLBenchmarks.jl.git |
|
[
"MIT"
] | 0.1.3 | f4076dd5a103010d48bb6c4e50c5526f6622fa96 | docs | 9117 | ---
title: SDE Basic Work-Precision Diagrams
author: Chris Rackauckas
---
# SDE Work-Precision Diagrams
In this notebook we will run some simple work-precision diagrams for the SDE integrators. These problems are additive and diagonal noise SDEs which can utilize the specialized Rossler methods. These problems are very well-behaved, meaning that adaptive timestepping should not be a significant advantage (unlike more difficult and realistic problems). Thus these tests will measure both the efficiency gains of the Rossler methods along with the overhead of adaptivity.
```julia
using StochasticDiffEq, Plots, DiffEqDevTools, SDEProblemLibrary
import SDEProblemLibrary: prob_sde_additivesystem,
prob_sde_additive, prob_sde_2Dlinear, prob_sde_linear, prob_sde_wave
gr()
const N = 1000
```
In this notebook, the error that will be measured is the strong error. The strong error is defined as
$$ E = \mathbb{E}[Y_\delta(t) - Y(t)] $$
where $Y_\delta$ is the numerical approximation to $Y$. This is the same as saying, for a given Wiener trajectory $W(t)$, how well does the numerical trajectory match the real trajectory? Note that this is not how well the mean or other moments match the true mean/variance/etc. (that's the weak error), this is how close the trajectory is to the true trajectory which is a stronger notion. In a sense, this is measuring convergence, rather than just convergence in distribution.
### Additive Noise Problem
\begin{equation}
dX_{t}=\left(\frac{\beta}{\sqrt{1+t}}-\frac{1}{2\left(1+t\right)}X_{t}\right)dt+\frac{\alpha\beta}{\sqrt{1+t}}dW_{t},\thinspace\thinspace\thinspace X_{0}=\frac{1}{2}
\end{equation}
where $\alpha=\frac{1}{10}$ and $\beta=\frac{1}{20}$. Actual Solution:
\begin{equation}
X_{t}=\frac{1}{\sqrt{1+t}}X_{0}+\frac{\beta}{\sqrt{1+t}}\left(t+\alpha W_{t}\right).
\end{equation}
First let's solve this using a system of SDEs, repeating this same problem 4 times.
```julia
prob = prob_sde_additivesystem
prob = remake(prob,tspan=(0.0,1.0))
reltols = 1.0 ./ 10.0 .^ (1:5)
abstols = reltols#[0.0 for i in eachindex(reltols)]
setups = [Dict(:alg=>SRIW1())
Dict(:alg=>EM(),:dts=>1.0./5.0.^((1:length(reltols)) .+ 1))
Dict(:alg=>RKMil(),:dts=>1.0./5.0.^((1:length(reltols)) .+ 1),:adaptive=>false)
Dict(:alg=>SRIW1(),:dts=>1.0./5.0.^((1:length(reltols)) .+ 1),:adaptive=>false)
Dict(:alg=>SRA1(),:dts=>1.0./5.0.^((1:length(reltols)) .+ 1),:adaptive=>false)
Dict(:alg=>SRA1())
]
names = ["SRIW1","EM","RKMil","SRIW1 Fixed","SRA1 Fixed","SRA1"]
wp = WorkPrecisionSet(prob,abstols,reltols,setups;numruns=N,names=names,maxiters=1e7,error_estimate=:l2)
plot(wp)
```
```julia
prob = prob_sde_additivesystem
prob = remake(prob,tspan=(0.0,1.0))
reltols = 1.0 ./ 10.0 .^ (1:5)
abstols = reltols#[0.0 for i in eachindex(reltols)]
setups = [
Dict(:alg=>SRA1())
Dict(:alg=>SRA2())
Dict(:alg=>SRA3())
Dict(:alg=>SOSRA())
Dict(:alg=>SOSRA2())
]
wp = WorkPrecisionSet(prob,abstols,reltols,setups;numruns=N,maxiters=1e7,error_estimate=:l2)
plot(wp)
```
Now as a scalar SDE.
```julia
prob = prob_sde_additive
prob = remake(prob,tspan=(0.0,1.0))
reltols = 1.0 ./ 10.0 .^ (1:5)
abstols = reltols#[0.0 for i in eachindex(reltols)]
setups = [Dict(:alg=>SRIW1())
Dict(:alg=>EM(),:dts=>1.0./5.0.^((1:length(reltols)) .+ 1))
Dict(:alg=>RKMil(),:dts=>1.0./5.0.^((1:length(reltols)) .+ 1),:adaptive=>false)
Dict(:alg=>SRIW1(),:dts=>1.0./5.0.^((1:length(reltols)) .+ 1),:adaptive=>false)
Dict(:alg=>SRA1(),:dts=>1.0./5.0.^((1:length(reltols)) .+ 1),:adaptive=>false)
Dict(:alg=>SRA1())
]
names = ["SRIW1","EM","RKMil","SRIW1 Fixed","SRA1 Fixed","SRA1"]
wp = WorkPrecisionSet(prob,abstols,reltols,setups;numruns=N,names=names,maxiters=1e7,error_estimate=:l2)
plot(wp)
```
```julia
prob = prob_sde_additive
prob = remake(prob,tspan=(0.0,1.0))
reltols = 1.0 ./ 10.0 .^ (1:5)
abstols = reltols#[0.0 for i in eachindex(reltols)]
setups = [
Dict(:alg=>SRA1())
Dict(:alg=>SRA2())
Dict(:alg=>SRA3())
Dict(:alg=>SOSRA())
Dict(:alg=>SOSRA2())
]
wp = WorkPrecisionSet(prob,abstols,reltols,setups;numruns=N,error_estimate=:l2)
plot(wp)
```
### Diagonal Noise
We will use a 4x2 matrix of indepdendent linear SDEs (also known as the Black-Scholes equation)
\begin{equation}
dX_{t}=\alpha X_{t}dt+\beta X_{t}dW_{t},\thinspace\thinspace\thinspace X_{0}=\frac{1}{2}
\end{equation}
where $\alpha=\frac{1}{10}$ and $\beta=\frac{1}{20}$. Actual Solution:
\begin{equation}
X_{t}=X_{0}e^{\left(\beta-\frac{\alpha^{2}}{2}\right)t+\alpha W_{t}}.
\end{equation}
```julia
prob = prob_sde_2Dlinear
prob = remake(prob,tspan=(0.0,1.0))
reltols = 1.0 ./ 10.0 .^ (1:5)
abstols = reltols#[0.0 for i in eachindex(reltols)]
setups = [Dict(:alg=>SRIW1())
Dict(:alg=>EM(),:dts=>1.0./5.0.^((1:length(reltols)) .+ 1))
Dict(:alg=>RKMil(),:dts=>1.0./5.0.^((1:length(reltols)) .+ 1),:adaptive=>false)
Dict(:alg=>SRIW1(),:dts=>1.0./5.0.^((1:length(reltols)) .+ 1),:adaptive=>false)
]
names = ["SRIW1","EM","RKMil","SRIW1 Fixed"]
wp = WorkPrecisionSet(prob,abstols,reltols,setups;numruns=N,names=names,maxiters=1e7,error_estimate=:l2)
plot(wp)
```
```julia
prob = prob_sde_2Dlinear
prob = remake(prob,tspan=(0.0,1.0))
reltols = 1.0 ./ 10.0 .^ (1:5)
abstols = reltols#[0.0 for i in eachindex(reltols)]
setups = [Dict(:alg=>EM(),:dts=>1.0./5.0.^((1:length(reltols)) .+ 2))
Dict(:alg=>RKMil(),:dts=>1.0./5.0.^((1:length(reltols)) .+ 2),:adaptive=>false)
Dict(:alg=>SRI())
Dict(:alg=>SRIW1())
Dict(:alg=>SRIW2())
Dict(:alg=>SOSRI())
Dict(:alg=>SOSRI2())
]
wp = WorkPrecisionSet(prob,abstols,reltols,setups;numruns=N,maxiters=1e7,error_estimate=:l2)
plot(wp)
```
Now just the scalar Black-Scholes
```julia
prob = prob_sde_linear
prob = remake(prob,tspan=(0.0,1.0))
reltols = 1.0 ./ 10.0 .^ (1:5)
abstols = reltols#[0.0 for i in eachindex(reltols)]
setups = [Dict(:alg=>SRIW1())
Dict(:alg=>EM(),:dts=>1.0./5.0.^((1:length(reltols)) .+ 1))
Dict(:alg=>RKMil(),:dts=>1.0./5.0.^((1:length(reltols)) .+ 1),:adaptive=>false)
Dict(:alg=>SRIW1(),:dts=>1.0./5.0.^((1:length(reltols)) .+ 1),:adaptive=>false)
]
names = ["SRIW1","EM","RKMil","SRIW1 Fixed"]
wp = WorkPrecisionSet(prob,abstols,reltols,setups;numruns=N,names=names,maxiters=1e7,error_estimate=:l2)
plot(wp)
```
```julia
setups = [Dict(:alg=>EM(),:dts=>1.0./5.0.^((1:length(reltols)) .+ 2))
Dict(:alg=>RKMil(),:dts=>1.0./5.0.^((1:length(reltols)) .+ 2),:adaptive=>false)
Dict(:alg=>SRI())
Dict(:alg=>SRIW1())
Dict(:alg=>SRIW2())
Dict(:alg=>SOSRI())
Dict(:alg=>SOSRI2())
]
wp = WorkPrecisionSet(prob,abstols,reltols,setups;numruns=N,maxiters=1e7,error_estimate=:l2)
plot(wp)
```
Now a scalar wave SDE:
\begin{equation}
dX_{t}=-\left(\frac{1}{10}\right)^{2}\sin\left(X_{t}\right)\cos^{3}\left(X_{t}\right)dt+\frac{1}{10}\cos^{2}\left(X_{t}\right)dW_{t},\thinspace\thinspace\thinspace X_{0}=\frac{1}{2}
\end{equation}
Actual Solution:
\begin{equation}
X_{t}=\arctan\left(\frac{1}{10}W_{t}+\tan\left(X_{0}\right)\right).
\end{equation}
```julia
prob = prob_sde_wave
prob = remake(prob,tspan=(0.0,1.0))
reltols = 1.0 ./ 10.0 .^ (1:5)
abstols = reltols#[0.0 for i in eachindex(reltols)]
setups = [Dict(:alg=>SRIW1())
Dict(:alg=>EM(),:dts=>1.0./5.0.^((1:length(reltols)) .+ 1))
Dict(:alg=>RKMil(),:dts=>1.0./5.0.^((1:length(reltols)) .+ 1),:adaptive=>false)
Dict(:alg=>SRIW1(),:dts=>1.0./5.0.^((1:length(reltols)) .+ 1),:adaptive=>false)
]
names = ["SRIW1","EM","RKMil","SRIW1 Fixed"]
wp = WorkPrecisionSet(prob,abstols,reltols,setups;numruns=N,names=names,maxiters=1e7,error_estimate=:l2)
plot(wp)
```
Note that in this last problem, the adaptivity algorithm accurately detects that the error is already low enough, and does not increase the number of steps as the tolerance drops further.
```julia
setups = [Dict(:alg=>EM(),:dts=>1.0./5.0.^((1:length(reltols)) .+ 2))
Dict(:alg=>RKMil(),:dts=>1.0./5.0.^((1:length(reltols)) .+ 2),:adaptive=>false)
Dict(:alg=>SRI())
Dict(:alg=>SRIW1())
Dict(:alg=>SRIW2())
Dict(:alg=>SOSRI())
Dict(:alg=>SOSRI2())
]
wp = WorkPrecisionSet(prob,abstols,reltols,setups;numruns=N,maxiters=1e7,error_estimate=:l2)
plot(wp)
```
### Conclusion
The RSwM3 adaptivity algorithm does not appear to have any significant overhead even on problems which do not necessitate adaptive timestepping. The tolerance clearly In addition, the Rossler methods are shown to be orders of magnitude more efficient and should be used whenever applicable. The Oval2 tests show that these results are only magnified as the problem difficulty increases.
```julia, echo = false
using SciMLBenchmarks
SciMLBenchmarks.bench_footer(WEAVE_ARGS[:folder],WEAVE_ARGS[:file])
```
| SciMLBenchmarks | https://github.com/SciML/SciMLBenchmarks.jl.git |
|
[
"MIT"
] | 0.1.3 | f4076dd5a103010d48bb6c4e50c5526f6622fa96 | docs | 3719 | ---
title: SDE Lokta-Volterra Work-Precision Diagrams
author: Chris Rackauckas
---
```julia
using StochasticDiffEq, DiffEqDevTools, ParameterizedFunctions
using Plots; gr()
const N = 100
f = @ode_def LotkaVolterraTest begin
dx = a*x - b*x*y
dy = -c*y + d*x*y
end a b c d
p = [1.5,1.0,3.0,1.0]
function g(du,u,p,t)
du .= 0.1u
end
u0 = [1.0;1.0]
tspan = (0.0,10.0)
prob = SDEProblem(f,g,u0,tspan,p);
```
```julia
sol = solve(prob,SRIW1(),abstol=1e-4,reltol=1e-4)
plot(sol)
```
## Strong Error
The starting `dt`s was chosen as the largest in the `1/4^i` which were stable. All larger `dt`s contained trajectories which would veer off to infinity.
```julia
reltols = 1.0 ./ 4.0 .^ (2:4)
abstols = reltols#[0.0 for i in eachindex(reltols)]
setups = [Dict(:alg=>SRIW1())
Dict(:alg=>EM(),:dts=>1.0./12.0.^((1:length(reltols)) .+ 1.5))
Dict(:alg=>RKMil(),:dts=>1.0./12.0.^((1:length(reltols)) .+ 1.5),:adaptive=>false)
Dict(:alg=>SRIW1(),:dts=>1.0./4.0.^((1:length(reltols)) .+ 5),:adaptive=>false)
Dict(:alg=>SRIW2())
Dict(:alg=>SOSRI())
Dict(:alg=>SOSRI2())
]
test_dt = 1/10^2
appxsol_setup = Dict(:alg=>SRIW1(),:abstol=>1e-4,:reltol=>1e-4)
wp = WorkPrecisionSet(prob,abstols,reltols,setups,test_dt;
maxiters = 1e7,
verbose=false,save_everystep=false,
parallel_type = :threads,
appxsol_setup = appxsol_setup,
numruns_error=N,error_estimate=:final)
plot(wp)
```
## Weak Error
```julia
reltols = 1.0 ./ 4.0 .^ (2:4)
abstols = reltols#[0.0 for i in eachindex(reltols)]
setups = [Dict(:alg=>SRIW1())
Dict(:alg=>EM(),:dts=>1.0./12.0.^((1:length(reltols)) .+ 1.5))
Dict(:alg=>RKMil(),:dts=>1.0./12.0.^((1:length(reltols)) .+ 1.5),:adaptive=>false)
Dict(:alg=>SRIW1(),:dts=>1.0./4.0.^((1:length(reltols)) .+ 5),:adaptive=>false)
Dict(:alg=>SRIW2())
Dict(:alg=>SOSRI())
Dict(:alg=>SOSRI2())
]
test_dt = 1e-2
appxsol_setup = Dict(:alg=>SRIW1(),:abstol=>1e-4,:reltol=>1e-4)
wp = WorkPrecisionSet(prob,abstols,reltols,setups,test_dt;
maxiters = 1e7,
verbose=false,save_everystep=false,
parallel_type = :none,
appxsol_setup = appxsol_setup,
numruns_error=N,error_estimate=:weak_final)
plot(wp;legend=:topleft)
```
```julia
sample_size = Int[10;1e2;1e3]
se = get_sample_errors(prob,setups[6],test_dt,numruns=sample_size,
appxsol_setup = appxsol_setup,
sample_error_runs = 100_000,solution_runs=20)
```
```julia
plot(wp;legend=:topleft)
times = [wp[i].times for i in 1:length(wp)]
times = [minimum(minimum(t) for t in times),maximum(maximum(t) for t in times)]
plot!([se[end];se[end]],times,color=:orange,linestyle=:dash,label="Sample Error: 1000",lw=3)
```
## Conclusion
These results show that in both strong and weak error, the high order method is more efficient.
The strong and the weak are track each other well for the methods tested on this problem, with the
strong error slightly higher than the weak error. To reach the sample error for a 100 trajectories,
the higher order method is around 5x faster. To reach the sampling error for 10000 trajectories, the
higher order method is nearly 100x faster.
```julia, echo = false
using SciMLBenchmarks
SciMLBenchmarks.bench_footer(WEAVE_ARGS[:folder],WEAVE_ARGS[:file])
```
| SciMLBenchmarks | https://github.com/SciML/SciMLBenchmarks.jl.git |
|
[
"MIT"
] | 0.1.3 | f4076dd5a103010d48bb6c4e50c5526f6622fa96 | docs | 9061 | ---
title: Allen-Cahn PDE Physics-Informed Neural Network (PINN) Loss Function Error vs Time Benchmarks
author: Kirill Zubov, Zoe McCarthy, Yingbo Ma, Francesco Calisto, Valerio Pagliarino, Simone Azeglio, Luca Bottero, Emmanuel Luján, Valentin Sulzer, Ashutosh Bharambe, Nand Vinchhi, Kaushik Balakrishnan, Devesh Upadhyay, Chris Rackauckas
---
Adapted from [NeuralPDE: Automating Physics-Informed Neural Networks (PINNs) with Error Approximations](https://arxiv.org/abs/2107.09443).
Uses the [NeuralPDE.jl](https://neuralpde.sciml.ai/dev/) library from the
[SciML Scientific Machine Learning Open Source Organization](https://sciml.ai/)
for the implementation of physics-informed neural networks (PINNs) and other
science-guided AI techniques.
## Setup Code
```julia
using NeuralPDE
using Integrals, IntegralsCubature, IntegralsCuba
using OptimizationFlux, ModelingToolkit, Optimization, OptimizationOptimJL
using Lux, Plots
using DelimitedFiles
using QuasiMonteCarlo
import ModelingToolkit: Interval, infimum, supremum
function allen_cahn(strategy, minimizer, maxIters)
## DECLARATIONS
@parameters t x1 x2 x3 x4
@variables u(..)
Dt = Differential(t)
Dxx1 = Differential(x1)^2
Dxx2 = Differential(x2)^2
Dxx3 = Differential(x3)^2
Dxx4 = Differential(x4)^2
# Discretization
tmax = 1.0
x1width = 1.0
x2width = 1.0
x3width = 1.0
x4width = 1.0
tMeshNum = 10
x1MeshNum = 10
x2MeshNum = 10
x3MeshNum = 10
x4MeshNum = 10
dt = tmax / tMeshNum
dx1 = x1width / x1MeshNum
dx2 = x2width / x2MeshNum
dx3 = x3width / x3MeshNum
dx4 = x4width / x4MeshNum
domains = [t ∈ Interval(0.0, tmax),
x1 ∈ Interval(0.0, x1width),
x2 ∈ Interval(0.0, x2width),
x3 ∈ Interval(0.0, x3width),
x4 ∈ Interval(0.0, x4width)]
ts = 0.0:dt:tmax
x1s = 0.0:dx1:x1width
x2s = 0.0:dx2:x2width
x3s = 0.0:dx3:x3width
x4s = 0.0:dx4:x4width
# Operators
Δu = Dxx1(u(t, x1, x2, x3, x4)) + Dxx2(u(t, x1, x2, x3, x4)) + Dxx3(u(t, x1, x2, x3, x4)) + Dxx4(u(t, x1, x2, x3, x4)) # Laplacian
# Equation
eq = Dt(u(t, x1, x2, x3, x4)) - Δu - u(t, x1, x2, x3, x4) + u(t, x1, x2, x3, x4) * u(t, x1, x2, x3, x4) * u(t, x1, x2, x3, x4) ~ 0 #ALLEN CAHN EQUATION
initialCondition = 1 / (2 + 0.4 * (x1 * x1 + x2 * x2 + x3 * x3 + x4 * x4)) # see PNAS paper
bcs = [u(0, x1, x2, x3, x4) ~ initialCondition] #from literature
## NEURAL NETWORK
n = 10 #neuron number
chain = Lux.Chain(Lux.Dense(5, n, tanh), Lux.Dense(n, n, tanh), Lux.Dense(n, 1)) #Neural network from OptimizationFlux library
indvars = [t, x1, x2, x3, x4] #phisically independent variables
depvars = [u(t, x1, x2, x3, x4)] #dependent (target) variable
dim = length(domains)
losses = []
error = []
times = []
dx_err = 0.2
error_strategy = GridTraining(dx_err)
discretization_ = PhysicsInformedNN(chain, error_strategy)
@named pde_system_ = PDESystem(eq, bcs, domains, indvars, depvars)
prob_ = discretize(pde_system_, discretization_)
function loss_function_(θ, p)
return prob_.f.f(θ, nothing)
end
cb_ = function (p, l)
deltaT_s = time_ns() #Start a clock when the callback begins, this will evaluate questo misurerà anche il calcolo degli uniform error
ctime = time_ns() - startTime - timeCounter #This variable is the time to use for the time benchmark plot
append!(times, ctime / 10^9) #Conversion nanosec to seconds
append!(losses, l)
loss_ = loss_function_(p, nothing)
append!(error, loss_)
timeCounter = timeCounter + time_ns() - deltaT_s #timeCounter sums all delays due to the callback functions of the previous iterations
#if (ctime/10^9 > time) #if I exceed the limit time I stop the training
# return true #Stop the minimizer and continue from line 142
#end
return false
end
@named pde_system = PDESystem(eq, bcs, domains, indvars, depvars)
discretization = NeuralPDE.PhysicsInformedNN(chain, strategy)
prob = NeuralPDE.discretize(pde_system, discretization)
timeCounter = 0.0
startTime = time_ns() #Fix initial time (t=0) before starting the training
res = Optimization.solve(prob, minimizer, callback=cb_, maxiters=maxIters)
phi = discretization.phi
params = res.minimizer
# Model prediction
domain = [ts, x1s, x2s, x3s, x4s]
u_predict = [reshape([first(phi([t, x1, x2, x3, x4], res.minimizer)) for x1 in x1s for x2 in x2s for x3 in x3s for x4 in x4s], (length(x1s), length(x2s), length(x3s), length(x4s))) for t in ts] #matrix of model's prediction
return [error, params, domain, times, losses]
end
```
```julia
maxIters = [(1,1,1,1,1,1,1000),(1,1,1,1,300,300,300)] #iters for ADAM/LBFGS
# maxIters = [(1,1,1,1,1,1,10),(1,1,1,3,3,3,3)] #iters for ADAM/LBFGS
strategies = [NeuralPDE.QuadratureTraining(quadrature_alg = CubaCuhre(), reltol = 1e-4, abstol = 1e-4, maxiters = 100),
NeuralPDE.QuadratureTraining(quadrature_alg = HCubatureJL(), reltol = 1e-4, abstol = 1e-4, maxiters = 100, batch = 0),
NeuralPDE.QuadratureTraining(quadrature_alg = CubatureJLh(), reltol = 1e-4, abstol = 1e-4, maxiters = 100),
NeuralPDE.QuadratureTraining(quadrature_alg = CubatureJLp(), reltol = 1e-4, abstol = 1e-4, maxiters = 100),
NeuralPDE.GridTraining(0.2),
NeuralPDE.StochasticTraining(400 ; bcs_points= 50),
NeuralPDE.QuasiRandomTraining(400 ; bcs_points= 50)]
strategies_short_name = ["CubaCuhre",
"HCubatureJL",
"CubatureJLh",
"CubatureJLp",
"GridTraining",
"StochasticTraining",
"QuasiRandomTraining"]
minimizers = [ADAM(0.005),BFGS()]
minimizers_short_name = ["ADAM","BFGS"]
# Run models
error_res = Dict()
domains = Dict()
params_res = Dict() #to use same params for the next run
times = Dict()
losses_res = Dict()
```
## Solve
```julia
## Convergence
for min =1:length(minimizers) # minimizer
for strat=1:length(strategies) # strategy
# println(string(strategies_short_name[strat], " ", minimizers_short_name[min]))
res = allen_cahn(strategies[strat], minimizers[min], maxIters[min][strat])
push!(error_res, string(strat,min) => res[1])
push!(params_res, string(strat,min) => res[2])
push!(domains, string(strat,min) => res[3])
push!(times, string(strat,min) => res[4])
push!(losses_res, string(strat,min) => res[5])
end
end
```
## Results
```julia
print("\n Plotting error vs times")
#Plotting the first strategy with the first minimizer out from the loop to initialize the canvas
current_label = string(strategies_short_name[1], " + " , minimizers_short_name[1])
error = Plots.plot(times["11"], error_res["11"], yaxis=:log10, label = current_label)#, xlims = (0,10))#legend = true)#, size=(1200,700))
plot!(error, times["21"], error_res["21"], yaxis=:log10, label = string(strategies_short_name[2], " + " , minimizers_short_name[1]))
plot!(error, times["31"], error_res["31"], yaxis=:log10, label = string(strategies_short_name[3], " + " , minimizers_short_name[1]))
plot!(error, times["41"], error_res["41"], yaxis=:log10, label = string(strategies_short_name[4], " + " , minimizers_short_name[1]))
plot!(error, times["51"], error_res["51"], yaxis=:log10, label = string(strategies_short_name[5], " + " , minimizers_short_name[1]))
plot!(error, times["61"], error_res["61"], yaxis=:log10, label = string(strategies_short_name[6], " + " , minimizers_short_name[1]))
plot!(error, times["71"], error_res["71"], yaxis=:log10, label = string(strategies_short_name[7], " + " , minimizers_short_name[1]))
plot!(error, times["12"], error_res["12"], yaxis=:log10, label = string(strategies_short_name[1], " + " , minimizers_short_name[2]))
plot!(error, times["22"], error_res["22"], yaxis=:log10, label = string(strategies_short_name[2], " + " , minimizers_short_name[2]))
plot!(error, times["32"], error_res["32"], yaxis=:log10, label = string(strategies_short_name[3], " + " , minimizers_short_name[2]))
plot!(error, times["42"], error_res["42"], yaxis=:log10, label = string(strategies_short_name[4], " + " , minimizers_short_name[2]))
plot!(error, times["52"], error_res["52"], yaxis=:log10, label = string(strategies_short_name[5], " + " , minimizers_short_name[2]))
plot!(error, times["62"], error_res["62"], yaxis=:log10, label = string(strategies_short_name[6], " + " , minimizers_short_name[2]))
plot!(error, times["72"], error_res["72"], yaxis=:log10, title = string("Allen Cahn convergence ADAM/LBFGS"), ylabel = "log(error)",xlabel = "t", label = string(strategies_short_name[7], " + " , minimizers_short_name[2]))
```
```julia, echo = false
using SciMLBenchmarks
SciMLBenchmarks.bench_footer(WEAVE_ARGS[:folder],WEAVE_ARGS[:file])
```
| SciMLBenchmarks | https://github.com/SciML/SciMLBenchmarks.jl.git |
|
[
"MIT"
] | 0.1.3 | f4076dd5a103010d48bb6c4e50c5526f6622fa96 | docs | 7542 | ---
title: Diffusion PDE Physics-Informed Neural Network (PINN) Loss Function Error vs Time Benchmarks
author: Kirill Zubov, Zoe McCarthy, Yingbo Ma, Francesco Calisto, Valerio Pagliarino, Simone Azeglio, Luca Bottero, Emmanuel Luján, Valentin Sulzer, Ashutosh Bharambe, Nand Vinchhi, Kaushik Balakrishnan, Devesh Upadhyay, Chris Rackauckas
---
Adapted from [NeuralPDE: Automating Physics-Informed Neural Networks (PINNs) with Error Approximations](https://arxiv.org/abs/2107.09443).
Uses the [NeuralPDE.jl](https://neuralpde.sciml.ai/dev/) library from the
[SciML Scientific Machine Learning Open Source Organization](https://sciml.ai/)
for the implementation of physics-informed neural networks (PINNs) and other
science-guided AI techniques.
## Setup
```julia
using NeuralPDE
using Integrals, IntegralsCubature, IntegralsCuba
using OptimizationFlux, ModelingToolkit, Optimization, OptimizationOptimJL
using Lux, Plots
using DelimitedFiles
using QuasiMonteCarlo
import ModelingToolkit: Interval, infimum, supremum
```
```julia
function diffusion(strategy, minimizer, maxIters)
## DECLARATIONS
@parameters x t
@variables u(..)
Dt = Differential(t)
Dxx = Differential(x)^2
eq = Dt(u(x,t)) - Dxx(u(x,t)) ~ -exp(-t) * (sin(pi * x) - pi^2 * sin(pi * x))
bcs = [u(x,0) ~ sin(pi*x),
u(-1,t) ~ 0.,
u(1,t) ~ 0.]
domains = [x ∈ Interval(-1.0,1.0),
t ∈ Interval(0.0,1.0)]
dx = 0.2; dt = 0.1
xs,ts = [infimum(domain.domain):dx/10:supremum(domain.domain) for (dx,domain) in zip([dx,dt],domains)]
indvars = [x,t]
depvars = [u(x,t)]
chain = Lux.Chain(Lux.Dense(2,10,tanh),Lux.Dense(10,10,tanh),Lux.Dense(10,1))
losses = []
error = []
times = []
dx_err = [0.2,0.1]
error_strategy = GridTraining(dx_err)
discretization_ = PhysicsInformedNN(chain,error_strategy)
@named pde_system_ = PDESystem(eq, bcs, domains, indvars, depvars)
prob_ = discretize(pde_system_, discretization_)
function loss_function_(θ, p)
return prob_.f.f(θ, nothing)
end
cb_ = function (p,l)
deltaT_s = time_ns() #Start a clock when the callback begins, this will evaluate questo misurerà anche il calcolo degli uniform error
ctime = time_ns() - startTime - timeCounter #This variable is the time to use for the time benchmark plot
append!(times, ctime/10^9) #Conversion nanosec to seconds
append!(losses, l)
loss_ = loss_function_(p,nothing)
append!(error, loss_)
timeCounter = timeCounter + time_ns() - deltaT_s #timeCounter sums all delays due to the callback functions of the previous iterations
return false
end
discretization = PhysicsInformedNN(chain,strategy)
@named pde_system = PDESystem(eq,bcs,domains,indvars,depvars)
prob = discretize(pde_system,discretization)
timeCounter = 0.0
startTime = time_ns() #Fix initial time (t=0) before starting the training
res = Optimization.solve(prob, minimizer; callback=cb_, maxiters=maxIters)
phi = discretization.phi
params = res.minimizer
# Model prediction
domain = [x,t]
u_predict = reshape([first(phi([x,t],res.minimizer)) for x in xs for t in ts],(length(xs),length(ts)))
return [error, params, domain, times, u_predict, losses]
end
```
```julia
maxIters = [(5000,5000,5000,5000,5000,5000),(300,300,300,300,300,300)] #iters for ADAM/LBFGS
# maxIters = [(5,5,5,5,5,5),(3,3,3,3,3,3)] #iters for ADAM/LBFGS
strategies = [#NeuralPDE.QuadratureTraining(quadrature_alg = CubaCuhre(), reltol = 1e-4, abstol = 1e-3, maxiters = 10, batch = 10),
NeuralPDE.QuadratureTraining(quadrature_alg = HCubatureJL(), reltol = 1e-4, abstol=1e-5, maxiters=100, batch = 0),
NeuralPDE.QuadratureTraining(quadrature_alg = CubatureJLh(), reltol = 1e-4, abstol=1e-5, maxiters=100),
NeuralPDE.QuadratureTraining(quadrature_alg = CubatureJLp(), reltol = 1e-4, abstol=1e-5, maxiters=100),
NeuralPDE.GridTraining([0.2,0.1]),
NeuralPDE.StochasticTraining(400 ; bcs_points= 50),
NeuralPDE.QuasiRandomTraining(400 ; bcs_points= 50)]
strategies_short_name = [#"CubaCuhre",
"HCubatureJL",
"CubatureJLh",
"CubatureJLp",
#"CubaVegas",
#"CubaSUAVE"]
"GridTraining",
"StochasticTraining",
"QuasiRandomTraining"]
minimizers = [ADAM(0.001),
#BFGS()]
LBFGS()]
minimizers_short_name = ["ADAM",
"LBFGS"]
# "BFGS"]
# Run models
error_res = Dict()
domains = Dict()
params_res = Dict() #to use same params for the next run
times = Dict()
prediction = Dict()
losses_res = Dict()
```
## Solve
```julia
print("Starting run")
## Convergence
for min =1:length(minimizers) # minimizer
for strat=1:length(strategies) # strategy
# println(string(strategies_short_name[strat], " ", minimizers_short_name[min]))
res = diffusion(strategies[strat], minimizers[min], maxIters[min][strat])
push!(error_res, string(strat,min) => res[1])
push!(params_res, string(strat,min) => res[2])
push!(domains, string(strat,min) => res[3])
push!(times, string(strat,min) => res[4])
push!(prediction, string(strat,min) => res[5])
push!(losses_res, string(strat,min) => res[6])
end
end
```
## Results
```julia
current_label = string(strategies_short_name[1], " + " , minimizers_short_name[1])
error = Plots.plot(times["11"], error_res["11"], yaxis=:log10, label = current_label)#, xlims = (0,100))#legend = true)#, size=(1200,700))
plot!(error, times["21"], error_res["21"], yaxis=:log10, label = string(strategies_short_name[2], " + " , minimizers_short_name[1]))
plot!(error, times["31"], error_res["31"], yaxis=:log10, label = string(strategies_short_name[3], " + " , minimizers_short_name[1]))
plot!(error, times["41"], error_res["41"], yaxis=:log10, label = string(strategies_short_name[4], " + " , minimizers_short_name[1]))
plot!(error, times["51"], error_res["51"], yaxis=:log10, label = string(strategies_short_name[5], " + " , minimizers_short_name[1]))
plot!(error, times["61"], error_res["61"], yaxis=:log10, label = string(strategies_short_name[6], " + " , minimizers_short_name[1]))
plot!(error, times["12"], error_res["12"], yaxis=:log10, label = string(strategies_short_name[1], " + " , minimizers_short_name[2]))
plot!(error, times["22"], error_res["22"], yaxis=:log10, label = string(strategies_short_name[2], " + " , minimizers_short_name[2]))
plot!(error, times["32"], error_res["32"], yaxis=:log10, label = string(strategies_short_name[3], " + " , minimizers_short_name[2]))
plot!(error, times["42"], error_res["42"], yaxis=:log10, label = string(strategies_short_name[4], " + " , minimizers_short_name[2]))
plot!(error, times["52"], error_res["52"], yaxis=:log10, label = string(strategies_short_name[5], " + " , minimizers_short_name[2]))
plot!(error, times["62"], error_res["62"], yaxis=:log10, title = string("Diffusion convergence ADAM/LBFGS"), ylabel = "log(error)",xlabel = "t", label = string(strategies_short_name[6], " + " , minimizers_short_name[2]))
```
```julia, echo = false
using SciMLBenchmarks
SciMLBenchmarks.bench_footer(WEAVE_ARGS[:folder],WEAVE_ARGS[:file])
```
| SciMLBenchmarks | https://github.com/SciML/SciMLBenchmarks.jl.git |
|
[
"MIT"
] | 0.1.3 | f4076dd5a103010d48bb6c4e50c5526f6622fa96 | docs | 9168 | ---
title: Hamilton-Jacobi PDE Physics-Informed Neural Network (PINN) Loss Function Error vs Time Benchmarks
author: Kirill Zubov, Zoe McCarthy, Yingbo Ma, Francesco Calisto, Valerio Pagliarino, Simone Azeglio, Luca Bottero, Emmanuel Luján, Valentin Sulzer, Ashutosh Bharambe, Nand Vinchhi, Kaushik Balakrishnan, Devesh Upadhyay, Chris Rackauckas
---
Adapted from [NeuralPDE: Automating Physics-Informed Neural Networks (PINNs) with Error Approximations](https://arxiv.org/abs/2107.09443).
Uses the [NeuralPDE.jl](https://neuralpde.sciml.ai/dev/) library from the
[SciML Scientific Machine Learning Open Source Organization](https://sciml.ai/)
for the implementation of physics-informed neural networks (PINNs) and other
science-guided AI techniques.
```julia
using NeuralPDE
using Integrals, IntegralsCubature, IntegralsCuba
using OptimizationFlux, ModelingToolkit, Optimization, OptimizationOptimJL
using Lux, Plots
using DelimitedFiles
using QuasiMonteCarlo
import ModelingToolkit: Interval, infimum, supremum
```
```julia
function hamilton_jacobi(strategy, minimizer, maxIters)
## DECLARATIONS
@parameters t x1 x2 x3 x4
@variables u(..)
Dt = Differential(t)
Dx1 = Differential(x1)
Dx2 = Differential(x2)
Dx3 = Differential(x3)
Dx4 = Differential(x4)
Dxx1 = Differential(x1)^2
Dxx2 = Differential(x2)^2
Dxx3 = Differential(x3)^2
Dxx4 = Differential(x4)^2
# Discretization
tmax = 1.0
x1width = 1.0
x2width = 1.0
x3width = 1.0
x4width = 1.0
tMeshNum = 10
x1MeshNum = 10
x2MeshNum = 10
x3MeshNum = 10
x4MeshNum = 10
dt = tmax / tMeshNum
dx1 = x1width / x1MeshNum
dx2 = x2width / x2MeshNum
dx3 = x3width / x3MeshNum
dx4 = x4width / x4MeshNum
domains = [t ∈ Interval(0.0, tmax),
x1 ∈ Interval(0.0, x1width),
x2 ∈ Interval(0.0, x2width),
x3 ∈ Interval(0.0, x3width),
x4 ∈ Interval(0.0, x4width)]
ts = 0.0:dt:tmax
x1s = 0.0:dx1:x1width
x2s = 0.0:dx2:x2width
x3s = 0.0:dx3:x3width
x4s = 0.0:dx4:x4width
λ = 1.0f0
# Operators
Δu = Dxx1(u(t, x1, x2, x3, x4)) + Dxx2(u(t, x1, x2, x3, x4)) + Dxx3(u(t, x1, x2, x3, x4)) + Dxx4(u(t, x1, x2, x3, x4)) # Laplacian
∇u = [Dx1(u(t, x1, x2, x3, x4)), Dx2(u(t, x1, x2, x3, x4)), Dx3(u(t, x1, x2, x3, x4)), Dx4(u(t, x1, x2, x3, x4))]
# Equation
eq = Dt(u(t, x1, x2, x3, x4)) + Δu - λ * sum(∇u .^ 2) ~ 0 #HAMILTON-JACOBI-BELLMAN EQUATION
terminalCondition = log((1 + x1 * x1 + x2 * x2 + x3 * x3 + x4 * x4) / 2) # see PNAS paper
bcs = [u(tmax, x1, x2, x3, x4) ~ terminalCondition] #PNAS paper again
## NEURAL NETWORK
n = 10 #neuron number
chain = Lux.Chain(Lux.Dense(5, n, tanh), Lux.Dense(n, n, tanh), Lux.Dense(n, 1)) #Neural network from OptimizationFlux library
indvars = [t, x1, x2, x3, x4] #phisically independent variables
depvars = [u(t, x1, x2, x3, x4)] #dependent (target) variable
dim = length(domains)
losses = []
error = []
times = []
dx_err = 0.2
error_strategy = GridTraining(dx_err)
discretization_ = PhysicsInformedNN(chain, error_strategy)
@named pde_system_ = PDESystem(eq, bcs, domains, indvars, depvars)
prob_ = discretize(pde_system_, discretization_)
function loss_function_(θ, p)
return prob_.f.f(θ, nothing)
end
cb_ = function (p, l)
deltaT_s = time_ns() #Start a clock when the callback begins, this will evaluate questo misurerà anche il calcolo degli uniform error
ctime = time_ns() - startTime - timeCounter #This variable is the time to use for the time benchmark plot
append!(times, ctime / 10^9) #Conversion nanosec to seconds
append!(losses, l)
loss_ = loss_function_(p, nothing)
append!(error, loss_)
timeCounter = timeCounter + time_ns() - deltaT_s #timeCounter sums all delays due to the callback functions of the previous iterations
return false
end
@named pde_system = PDESystem(eq, bcs, domains, indvars, depvars)
discretization = NeuralPDE.PhysicsInformedNN(chain, strategy)
prob = NeuralPDE.discretize(pde_system, discretization)
timeCounter = 0.0
startTime = time_ns() #Fix initial time (t=0) before starting the training
res = Optimization.solve(prob, minimizer, callback=cb_, maxiters=maxIters)
phi = discretization.phi
params = res.minimizer
# Model prediction
domain = [ts, x1s, x2s, x3s, x4s]
u_predict = [reshape([first(phi([t, x1, x2, x3, x4], res.minimizer)) for x1 in x1s for x2 in x2s for x3 in x3s for x4 in x4s], (length(x1s), length(x2s), length(x3s), length(x4s))) for t in ts] #matrix of model's prediction
return [error, params, domain, times, losses]
end
maxIters = [(1,1,1,1000,1000,1000,1000),(1,1,1,300,300,300,300)] #iters for ADAM/LBFGS
# maxIters = [(1,1,1,1,1,2,2),(1,1,1,3,3,3,3)] #iters for ADAM/LBFGS
strategies = [NeuralPDE.QuadratureTraining(quadrature_alg = CubaCuhre(), reltol = 1e-4, abstol = 1e-4, maxiters = 100),
NeuralPDE.QuadratureTraining(quadrature_alg = HCubatureJL(), reltol = 1e-4, abstol = 1e-4, maxiters = 100, batch = 0),
NeuralPDE.QuadratureTraining(quadrature_alg = CubatureJLh(), reltol = 1e-4, abstol = 1e-4, maxiters = 100),
NeuralPDE.QuadratureTraining(quadrature_alg = CubatureJLp(), reltol = 1e-4, abstol = 1e-4, maxiters = 100),
NeuralPDE.GridTraining(0.2),
NeuralPDE.StochasticTraining(400 ; bcs_points= 50),
NeuralPDE.QuasiRandomTraining(400 ; bcs_points= 50)]
strategies_short_name = ["CubaCuhre",
"HCubatureJL",
"CubatureJLh",
"CubatureJLp",
"GridTraining",
"StochasticTraining",
"QuasiRandomTraining"]
minimizers = [ADAM(0.005),
#BFGS()]
LBFGS()]
minimizers_short_name = ["ADAM",
"LBFGS"]
#"BFGS"]
# Run models
error_res = Dict()
domains = Dict()
params_res = Dict() #to use same params for the next run
times = Dict()
losses_res = Dict()
```
## Solve
```julia
print("Starting run")
## Convergence
for min =1:length(minimizers) # minimizer
for strat=1:length(strategies) # strategy
# println(string(strategies_short_name[strat], " ", minimizers_short_name[min]))
res = hamilton_jacobi(strategies[strat], minimizers[min], maxIters[min][strat])
push!(error_res, string(strat,min) => res[1])
push!(params_res, string(strat,min) => res[2])
push!(domains, string(strat,min) => res[3])
push!(times, string(strat,min) => res[4])
push!(losses_res, string(strat,min) => res[5])
end
end
```
```julia
#Plotting the first strategy with the first minimizer out from the loop to initialize the canvas
current_label = string(strategies_short_name[1], " + " , minimizers_short_name[1])
error = Plots.plot(times["11"], error_res["11"], yaxis=:log10, label = current_label)#, xlims = (0,10))#legend = true)#, size=(1200,700))
plot!(error, times["21"], error_res["21"], yaxis=:log10, label = string(strategies_short_name[2], " + " , minimizers_short_name[1]))
plot!(error, times["31"], error_res["31"], yaxis=:log10, label = string(strategies_short_name[3], " + " , minimizers_short_name[1]))
plot!(error, times["41"], error_res["41"], yaxis=:log10, label = string(strategies_short_name[4], " + " , minimizers_short_name[1]))
plot!(error, times["51"], error_res["51"], yaxis=:log10, label = string(strategies_short_name[5], " + " , minimizers_short_name[1]))
plot!(error, times["61"], error_res["61"], yaxis=:log10, label = string(strategies_short_name[6], " + " , minimizers_short_name[1]))
plot!(error, times["71"], error_res["71"], yaxis=:log10, label = string(strategies_short_name[7], " + " , minimizers_short_name[1]))
plot!(error, times["12"], error_res["12"], yaxis=:log10, label = string(strategies_short_name[1], " + " , minimizers_short_name[2]))
plot!(error, times["22"], error_res["22"], yaxis=:log10, label = string(strategies_short_name[2], " + " , minimizers_short_name[2]))
plot!(error, times["32"], error_res["32"], yaxis=:log10, label = string(strategies_short_name[3], " + " , minimizers_short_name[2]))
plot!(error, times["42"], error_res["42"], yaxis=:log10, label = string(strategies_short_name[4], " + " , minimizers_short_name[2]))
plot!(error, times["52"], error_res["52"], yaxis=:log10, label = string(strategies_short_name[5], " + " , minimizers_short_name[2]))
plot!(error, times["62"], error_res["62"], yaxis=:log10, label = string(strategies_short_name[6], " + " , minimizers_short_name[2]))
plot!(error, times["72"], error_res["72"], yaxis=:log10, title = string("Hamilton Jacobi convergence ADAM/LBFGS"), ylabel = "log(error)",xlabel = "t", label = string(strategies_short_name[7], " + " , minimizers_short_name[2]))
```
```julia, echo = false
using SciMLBenchmarks
SciMLBenchmarks.bench_footer(WEAVE_ARGS[:folder],WEAVE_ARGS[:file])
```
| SciMLBenchmarks | https://github.com/SciML/SciMLBenchmarks.jl.git |
|
[
"MIT"
] | 0.1.3 | f4076dd5a103010d48bb6c4e50c5526f6622fa96 | docs | 8939 | ---
title: Level Set PDE Physics-Informed Neural Network (PINN) Loss Function Error vs Time Benchmarks
author: Kirill Zubov, Zoe McCarthy, Yingbo Ma, Francesco Calisto, Valerio Pagliarino, Simone Azeglio, Luca Bottero, Emmanuel Luján, Valentin Sulzer, Ashutosh Bharambe, Nand Vinchhi, Kaushik Balakrishnan, Devesh Upadhyay, Chris Rackauckas
---
Adapted from [NeuralPDE: Automating Physics-Informed Neural Networks (PINNs) with Error Approximations](https://arxiv.org/abs/2107.09443).
Uses the [NeuralPDE.jl](https://neuralpde.sciml.ai/dev/) library from the
[SciML Scientific Machine Learning Open Source Organization](https://sciml.ai/)
for the implementation of physics-informed neural networks (PINNs) and other
science-guided AI techniques.
## Setup
```julia
using NeuralPDE
using Integrals, IntegralsCubature, IntegralsCuba
using OptimizationFlux, ModelingToolkit, Optimization, OptimizationOptimJL
using Lux, Plots
using DelimitedFiles
using QuasiMonteCarlo
import ModelingToolkit: Interval, infimum, supremum
```
```julia
function level_set(strategy, minimizer, maxIters)
## DECLARATIONS
@parameters t x y
@variables u(..)
Dt = Differential(t)
Dx = Differential(x)
Dy = Differential(y)
# Discretization
xwidth = 1.0 #ft
ywidth = 1.0
tmax = 1.0 #min
xScale = 1.0
yScale = 1.0
xMeshNum = 10
yMeshNum = 10
tMeshNum = 10
dx = xwidth / xMeshNum
dy = ywidth / yMeshNum
dt = tmax / tMeshNum
domains = [t ∈ Interval(0.0, tmax),
x ∈ Interval(0.0, xwidth),
y ∈ Interval(0.0, ywidth)]
xs = 0.0:dx:xwidth
ys = 0.0:dy:ywidth
ts = 0.0:dt:tmax
# Definitions
x0 = 0.5
y0 = 0.5
Uwind = [0.0, 2.0] #wind vector
# Operators
gn = (Dx(u(t, x, y))^2 + Dy(u(t, x, y))^2)^0.5 #gradient's norm
∇u = [Dx(u(t, x, y)), Dy(u(t, x, y))]
n = ∇u / gn #normal versor
#U = ((Uwind[1]*n[1] + Uwind[2]*n[2])^2)^0.5 #inner product between wind and normal vector
R0 = 0.112471
ϕw = 0#0.156927*max((0.44*U)^0.04086,1.447799)
ϕs = 0
S = R0 * (1 + ϕw + ϕs)
# Equation
eq = Dt(u(t, x, y)) + S * gn ~ 0 #LEVEL SET EQUATION
initialCondition = (xScale * (x - x0)^2 + (yScale * (y - y0)^2))^0.5 - 0.2 #Distance from ignition
bcs = [u(0, x, y) ~ initialCondition] #from literature
## NEURAL NETWORK
n = 10 #neuron number
chain = Lux.Chain(Lux.Dense(3, n, tanh), Lux.Dense(n, n, tanh), Lux.Dense(n, 1)) #Neural network from OptimizationFlux library
indvars = [t, x, y] #phisically independent variables
depvars = [u(t, x, y)] #dependent (target) variable
dim = length(domains)
losses = []
error = []
times = []
dx_err = 0.1
error_strategy = GridTraining(dx_err)
discretization_ = PhysicsInformedNN(chain, error_strategy)
@named pde_system_ = PDESystem(eq, bcs, domains, indvars, depvars)
prob_ = discretize(pde_system_, discretization_)
function loss_function_(θ, p)
return prob_.f.f(θ, nothing)
end
cb_ = function (p, l)
deltaT_s = time_ns() #Start a clock when the callback begins, this will evaluate questo misurerà anche il calcolo degli uniform error
ctime = time_ns() - startTime - timeCounter #This variable is the time to use for the time benchmark plot
append!(times, ctime / 10^9) #Conversion nanosec to seconds
append!(losses, l)
loss_ = loss_function_(p, nothing)
append!(error, loss_)
timeCounter = timeCounter + time_ns() - deltaT_s #timeCounter sums all delays due to the callback functions of the previous iterations
return false
end
@named pde_system = PDESystem(eq, bcs, domains, indvars, depvars)
discretization = NeuralPDE.PhysicsInformedNN(chain, strategy)
prob = NeuralPDE.discretize(pde_system, discretization)
timeCounter = 0.0
startTime = time_ns() #Fix initial time (t=0) before starting the training
res = Optimization.solve(prob, minimizer, callback=cb_, maxiters=maxIters)
phi = discretization.phi
params = res.minimizer
# Model prediction
domain = [ts, xs, ys]
u_predict = [reshape([first(phi([t, x, y], res.minimizer)) for x in xs for y in ys], (length(xs), length(ys))) for t in ts] #matrix of model's prediction
return [error, params, domain, times, losses] #add numeric solution
end
#level_set(NeuralPDE.QuadratureTraining(algorithm = CubaCuhre(), reltol = 1e-8, abstol = 1e-8, maxiters = 100), ADAM(0.01), 500)
maxIters = [(1,1,1,1000,1000,1000,1000),(1,1,1,500,500,500,500)] #iters for ADAM/LBFGS
# maxIters = [(1,1,1,2,2,2,2),(1,1,1,2,2,2,2)] #iters for ADAM/LBFGS
strategies = [NeuralPDE.QuadratureTraining(quadrature_alg = CubaCuhre(), reltol = 1e-4, abstol = 1e-4, maxiters = 100),
NeuralPDE.QuadratureTraining(quadrature_alg = HCubatureJL(), reltol = 1e-4, abstol = 1e-4, maxiters = 100, batch = 0),
NeuralPDE.QuadratureTraining(quadrature_alg = CubatureJLh(), reltol = 1e-4, abstol = 1e-4, maxiters = 100),
NeuralPDE.QuadratureTraining(quadrature_alg = CubatureJLp(), reltol = 1e-4, abstol = 1e-4, maxiters = 100),
NeuralPDE.GridTraining(0.1),
NeuralPDE.StochasticTraining(400 ; bcs_points= 50),
NeuralPDE.QuasiRandomTraining(400 ; bcs_points= 50)]
strategies_short_name = ["CubaCuhre",
"HCubatureJL",
"CubatureJLh",
"CubatureJLp",
"GridTraining",
"StochasticTraining",
"QuasiRandomTraining"]
minimizers = [ADAM(0.005),
#BFGS()]
LBFGS()]
minimizers_short_name = ["ADAM",
"LBFGS"]
# "BFGS"]
# Run models
prediction_res = Dict()
error_res = Dict()
domains = Dict()
params_res = Dict() #to use same params for the next run
times = Dict()
losses_res = Dict()
```
## Solve
```julia
## Convergence
for min =1:length(minimizers) # minimizer
for strat=1:length(strategies) # strategy
# println(string(strategies_short_name[strat], " ", minimizers_short_name[min]))
res = level_set(strategies[strat], minimizers[min], maxIters[min][strat])
push!(error_res, string(strat,min) => res[1])
push!(params_res, string(strat,min) => res[2])
push!(domains, string(strat,min) => res[3])
push!(times, string(strat,min) => res[4])
push!(losses_res, string(strat,min) => res[5])
end
end
```
## Results
```julia
#Plotting the first strategy with the first minimizer out from the loop to initialize the canvas
current_label = string(strategies_short_name[1], " + " , minimizers_short_name[1])
error = Plots.plot(times["11"], error_res["11"], yaxis=:log10, label = current_label)# xlims = (0,10))#legend = true)#, size=(1200,700))
plot!(error, times["21"], error_res["21"], yaxis=:log10, label = string(strategies_short_name[2], " + " , minimizers_short_name[1]))
plot!(error, times["31"], error_res["31"], yaxis=:log10, label = string(strategies_short_name[3], " + " , minimizers_short_name[1]))
plot!(error, times["41"], error_res["41"], yaxis=:log10, label = string(strategies_short_name[4], " + " , minimizers_short_name[1]))
plot!(error, times["51"], error_res["51"], yaxis=:log10, label = string(strategies_short_name[5], " + " , minimizers_short_name[1]))
plot!(error, times["61"], error_res["61"], yaxis=:log10, label = string(strategies_short_name[6], " + " , minimizers_short_name[1]))
plot!(error, times["71"], error_res["71"], yaxis=:log10, label = string(strategies_short_name[7], " + " , minimizers_short_name[1]))
plot!(error, times["12"], error_res["12"], yaxis=:log10, label = string(strategies_short_name[1], " + " , minimizers_short_name[2]))
plot!(error, times["22"], error_res["22"], yaxis=:log10, label = string(strategies_short_name[2], " + " , minimizers_short_name[2]))
plot!(error, times["32"], error_res["32"], yaxis=:log10, label = string(strategies_short_name[3], " + " , minimizers_short_name[2]))
plot!(error, times["42"], error_res["42"], yaxis=:log10, label = string(strategies_short_name[4], " + " , minimizers_short_name[2]))
plot!(error, times["52"], error_res["52"], yaxis=:log10, label = string(strategies_short_name[5], " + " , minimizers_short_name[2]))
plot!(error, times["62"], error_res["62"], yaxis=:log10, label = string(strategies_short_name[6], " + " , minimizers_short_name[2]))
plot!(error, times["72"], error_res["72"], yaxis=:log10, title = string("Level Set convergence ADAM/LBFGS"), ylabel = "log(error)", xlabel = "t", label = string(strategies_short_name[7], " + " , minimizers_short_name[2]))
```
```julia, echo = false
using SciMLBenchmarks
SciMLBenchmarks.bench_footer(WEAVE_ARGS[:folder],WEAVE_ARGS[:file])
```
| SciMLBenchmarks | https://github.com/SciML/SciMLBenchmarks.jl.git |
|
[
"MIT"
] | 0.1.3 | f4076dd5a103010d48bb6c4e50c5526f6622fa96 | docs | 8627 | ---
title: Nernst-Planck PDE Physics-Informed Neural Network (PINN) Loss Function Error vs Time Benchmarks
author: Kirill Zubov, Zoe McCarthy, Yingbo Ma, Francesco Calisto, Valerio Pagliarino, Simone Azeglio, Luca Bottero, Emmanuel Luján, Valentin Sulzer, Ashutosh Bharambe, Nand Vinchhi, Kaushik Balakrishnan, Devesh Upadhyay, Chris Rackauckas
---
Adapted from [NeuralPDE: Automating Physics-Informed Neural Networks (PINNs) with Error Approximations](https://arxiv.org/abs/2107.09443).
Uses the [NeuralPDE.jl](https://neuralpde.sciml.ai/dev/) library from the
[SciML Scientific Machine Learning Open Source Organization](https://sciml.ai/)
for the implementation of physics-informed neural networks (PINNs) and other
science-guided AI techniques.
## Setup
```julia
using NeuralPDE
using Integrals, IntegralsCubature, IntegralsCuba
using OptimizationFlux, ModelingToolkit, Optimization, OptimizationOptimJL
using Lux, Plots
using DelimitedFiles
using QuasiMonteCarlo
import ModelingToolkit: Interval, infimum, supremum
```
```julia
function nernst_planck(strategy, minimizer, maxIters)
## DECLARATIONS
@parameters t x y z
@variables c(..)
Dt = Differential(t)
Dx = Differential(x)
Dy = Differential(y)
Dz = Differential(z)
Dxx = Differential(x)^2
Dyy = Differential(y)^2
Dzz = Differential(z)^2
## DOMAINS AND OPERATORS
# Discretization
xwidth = 1.0
ywidth = 1.0
zwidth = 1.0
tmax = 1.0
xMeshNum = 10
yMeshNum = 10
zMeshNum = 10
tMeshNum = 10
dx = xwidth/xMeshNum
dy = ywidth/yMeshNum
dz = zwidth/zMeshNum
dt = tmax/tMeshNum
domains = [t ∈ Interval(0.0,tmax),
x ∈ Interval(0.0,xwidth),
y ∈ Interval(0.0,ywidth),
z ∈ Interval(0.0,zwidth)]
xs = 0.0 : dx : xwidth
ys = 0.0 : dy : ywidth
zs = 0.0 : dz : zwidth
ts = 0.0 : dt : tmax
# Constants
D = 1 #dummy
ux = 10 #dummy
uy = 10 #dummy
uz = 10 #dummy
# Operators
div = - D*(Dxx(c(t,x,y,z)) + Dyy(c(t,x,y,z)) + Dzz(c(t,x,y,z))) +
(ux*Dx(c(t,x,y,z)) + uy*Dy(c(t,x,y,z)) + uz*Dz(c(t,x,y,z)))
# Equation
eq = Dt(c(t,x,y,z)) + div ~ 0 #NERNST-PLANCK EQUATION
# Boundary conditions
bcs = [c(0,x,y,z) ~ 0]
## NEURAL NETWORK
n = 16 #neuron number
chain = Lux.Chain(Lux.Dense(4,n,tanh),Lux.Dense(n,n,tanh),Lux.Dense(n,1)) #Neural network from OptimizationFlux library
indvars = [t,x,y,z] #independent variables
depvars = [c(t,x,y,z)] #dependent (target) variable
dim = length(domains)
losses = []
error = []
times = []
dx_err = 0.2
error_strategy = GridTraining(dx_err)
discretization_ = PhysicsInformedNN(chain, error_strategy)
@named pde_system_ = PDESystem(eq, bcs, domains, indvars, depvars)
prob_ = discretize(pde_system_, discretization_)
function loss_function_(θ, p)
return prob_.f.f(θ, nothing)
end
cb_ = function (p,l)
deltaT_s = time_ns() #Start a clock when the callback begins, this will evaluate questo misurerà anche il calcolo degli uniform error
ctime = time_ns() - startTime - timeCounter #This variable is the time to use for the time benchmark plot
append!(times, ctime/10^9) #Conversion nanosec to seconds
append!(losses, l)
loss_ = loss_function_(p,nothing)
append!(error, loss_)
timeCounter = timeCounter + time_ns() - deltaT_s #timeCounter sums all delays due to the callback functions of the previous iterations
return false
end
@named pde_system = PDESystem(eq, bcs, domains, indvars, depvars)
discretization = NeuralPDE.PhysicsInformedNN(chain,strategy)
prob = NeuralPDE.discretize(pde_system,discretization)
timeCounter = 0.0
startTime = time_ns() #Fix initial time (t=0) before starting the training
res = Optimization.solve(prob, minimizer, callback = cb_, maxiters=maxIters)
phi = discretization.phi
params = res.minimizer
# Model prediction
domain = [ts, xs, ys, zs]
u_predict = [reshape([phi([t,x,y,z],res.minimizer) for x in xs for y in ys for z in zs],
(length(xs),length(ys),length(zs))) for t in ts]
return [error, params, domain, times]
end
maxIters = [(1,1,1,1000,1000,1000,1000),(1,1,1,300,300,300,300)] #iters for ADAM/LBFGS
# maxIters = [(1,1,1,10,10,10,10),(1,1,1,3,3,3,3)] #iters for ADAM/LBFGS
strategies = [NeuralPDE.QuadratureTraining(quadrature_alg = CubaCuhre(), reltol = 1e-4, abstol = 1e-4, maxiters = 50),
NeuralPDE.QuadratureTraining(quadrature_alg = HCubatureJL(), reltol = 1e-4, abstol = 1e-4, maxiters = 50, batch = 0),
NeuralPDE.QuadratureTraining(quadrature_alg = CubatureJLh(), reltol = 1e-4, abstol = 1e-4, maxiters = 50),
NeuralPDE.QuadratureTraining(quadrature_alg = CubatureJLp(), reltol = 1e-4, abstol = 1e-4, maxiters = 50),
NeuralPDE.GridTraining(0.2),
NeuralPDE.StochasticTraining(400 ; bcs_points= 50),
NeuralPDE.QuasiRandomTraining(400 ; bcs_points= 50)]
strategies_short_name = ["CubaCuhre",
"HCubatureJL",
"CubatureJLh",
"CubatureJLp",
"GridTraining",
"StochasticTraining",
"QuasiRandomTraining"]
minimizers = [ADAM(0.005),
#BFGS()]
LBFGS()]
minimizers_short_name = ["ADAM",
"LBFGS"]
# "BFGS"]
# Run models
error_res = Dict()
domains = Dict()
params_res = Dict() #to use same params for the next run
times = Dict()
```
## Solve
```julia
## Convergence
for strat=1:length(strategies) # strategy
for min =1:length(minimizers) # minimizer
# println(string(strategies_short_name[strat], " ", minimizers_short_name[min]))
res = nernst_planck(strategies[strat], minimizers[min], maxIters[min][strat])
push!(error_res, string(strat,min) => res[1])
push!(params_res, string(strat,min) => res[2])
push!(domains, string(strat,min) => res[3])
push!(times, string(strat,min) => res[4])
end
end
```
## Results
```julia
#Plotting the first strategy with the first minimizer out from the loop to initialize the canvas
current_label = string(strategies_short_name[1], " + " , minimizers_short_name[1])
error = Plots.plot(times["11"], error_res["11"], yaxis=:log10, label = current_label)#, xlims = (0,10))#legend = true)#, size=(1200,700))
plot!(error, times["21"], error_res["21"], yaxis=:log10, label = string(strategies_short_name[2], " + " , minimizers_short_name[1]))
plot!(error, times["31"], error_res["31"], yaxis=:log10, label = string(strategies_short_name[3], " + " , minimizers_short_name[1]))
plot!(error, times["41"], error_res["41"], yaxis=:log10, label = string(strategies_short_name[4], " + " , minimizers_short_name[1]))
plot!(error, times["51"], error_res["51"], yaxis=:log10, label = string(strategies_short_name[5], " + " , minimizers_short_name[1]))
plot!(error, times["61"], error_res["61"], yaxis=:log10, label = string(strategies_short_name[6], " + " , minimizers_short_name[1]))
plot!(error, times["71"], error_res["71"], yaxis=:log10, label = string(strategies_short_name[7], " + " , minimizers_short_name[1]))
plot!(error, times["12"], error_res["12"], yaxis=:log10, label = string(strategies_short_name[1], " + " , minimizers_short_name[2]))
plot!(error, times["22"], error_res["22"], yaxis=:log10, label = string(strategies_short_name[2], " + " , minimizers_short_name[2]))
plot!(error, times["32"], error_res["32"], yaxis=:log10, label = string(strategies_short_name[3], " + " , minimizers_short_name[2]))
plot!(error, times["42"], error_res["42"], yaxis=:log10, label = string(strategies_short_name[4], " + " , minimizers_short_name[2]))
plot!(error, times["52"], error_res["52"], yaxis=:log10, label = string(strategies_short_name[5], " + " , minimizers_short_name[2]))
plot!(error, times["62"], error_res["62"], yaxis=:log10, label = string(strategies_short_name[6], " + " , minimizers_short_name[2]))
plot!(error, times["72"], error_res["72"], yaxis=:log10, title = string("Nernst Planck convergence ADAM/LBFGS"), ylabel = "log(error)", xlabel = "t",label = string(strategies_short_name[7], " + " , minimizers_short_name[2]))
```
```julia, echo = false
using SciMLBenchmarks
SciMLBenchmarks.bench_footer(WEAVE_ARGS[:folder],WEAVE_ARGS[:file])
```
| SciMLBenchmarks | https://github.com/SciML/SciMLBenchmarks.jl.git |
|
[
"MIT"
] | 0.1.3 | f4076dd5a103010d48bb6c4e50c5526f6622fa96 | docs | 4109 | ---
title: Diffusion Equation Physics-Informed Neural Network (PINN) Optimizer Benchmarks
author: Kirill Zubov, Zoe McCarthy, Yingbo Ma, Francesco Calisto, Valerio Pagliarino, Simone Azeglio, Luca Bottero, Emmanuel Luján, Valentin Sulzer, Ashutosh Bharambe, Nand Vinchhi, Kaushik Balakrishnan, Devesh Upadhyay, Chris Rackauckas
---
Adapted from [NeuralPDE: Automating Physics-Informed Neural Networks (PINNs) with Error Approximations](https://arxiv.org/abs/2107.09443).
Uses the [NeuralPDE.jl](https://neuralpde.sciml.ai/dev/) library from the
[SciML Scientific Machine Learning Open Source Organization](https://sciml.ai/)
for the implementation of physics-informed neural networks (PINNs) and other
science-guided AI techniques.
## Setup
```julia
using NeuralPDE, OptimizationFlux, ModelingToolkit, Optimization, OptimizationOptimJL
using Lux, Plots
import ModelingToolkit: Interval, infimum, supremum
```
```julia
function solve(opt)
strategy = QuadratureTraining()
@parameters x t
@variables u(..)
Dt = Differential(t)
Dxx = Differential(x)^2
eq = Dt(u(x,t)) - Dxx(u(x,t)) ~ -exp(-t) * (sin(pi * x) - pi^2 * sin(pi * x))
bcs = [u(x,0) ~ sin(pi*x),
u(-1,t) ~ 0.,
u(1,t) ~ 0.]
domains = [x ∈ Interval(-1.0,1.0),
t ∈ Interval(0.0,1.0)]
chain = Lux.Chain(Lux.Dense(2,18,tanh),Lux.Dense(18,18,tanh),Lux.Dense(18,1))
discretization = PhysicsInformedNN(chain,strategy)
indvars = [x, t] #phisically independent variables
depvars = [u(x,t)] #dependent (target) variable
loss = []
initial_time = nothing
times = []
cb_ = function (p,l)
if initial_time == nothing
initial_time = time()
end
push!(times, time() - initial_time)
#println("Current loss for $opt is: $l")
push!(loss, l)
# println(l )
# println(time() - initial_time)
return false
end
@named pde_system = PDESystem(eq, bcs, domains, indvars, depvars)
prob = discretize(pde_system, discretization)
if opt == "both"
res = Optimization.solve(prob, ADAM(); callback = cb_, maxiters=50)
prob = remake(prob,u0=res.minimizer)
res = Optimization.solve(prob, BFGS(); callback = cb_, maxiters=150)
else
res = Optimization.solve(prob, opt; callback = cb_, maxiters=200)
end
times[1] = 0.01
return loss, times #add numeric solution
end
```
```julia
opt1 = ADAM()
opt2 = ADAM(0.005)
opt3 = ADAM(0.05)
opt4 = RMSProp()
opt5 = RMSProp(0.005)
opt6 = RMSProp(0.05)
opt7 = OptimizationOptimJL.BFGS()
opt8 = OptimizationOptimJL.LBFGS()
```
## Solve
```julia
loss_1, times_1 = solve(opt1)
loss_2, times_2 = solve(opt2)
loss_3, times_3 = solve(opt3)
loss_4, times_4 = solve(opt4)
loss_5, times_5 = solve(opt5)
loss_6, times_6 = solve(opt6)
loss_7, times_7 = solve(opt7)
loss_8, times_8 = solve(opt8)
loss_9, times_9 = solve("both")
```
## Results
```julia
p = plot([times_1, times_2, times_3, times_4, times_5, times_6, times_7, times_8, times_9], [loss_1, loss_2, loss_3, loss_4, loss_5, loss_6, loss_7, loss_8, loss_9],xlabel="time (s)", ylabel="loss", xscale=:log10, yscale=:log10, labels=["ADAM(0.001)" "ADAM(0.005)" "ADAM(0.05)" "RMSProp(0.001)" "RMSProp(0.005)" "RMSProp(0.05)" "BFGS()" "LBFGS()" "ADAM + BFGS"], legend=:bottomleft, linecolor=["#2660A4" "#4CD0F4" "#FEC32F" "#F763CD" "#44BD79" "#831894" "#A6ED18" "#980000" "#FF912B"])
```
```julia
p = plot([loss_1, loss_2, loss_3, loss_4, loss_5, loss_6, loss_7, loss_8, loss_9], xlabel="iterations", ylabel="loss", yscale=:log10, labels=["ADAM(0.001)" "ADAM(0.005)" "ADAM(0.05)" "RMSProp(0.001)" "RMSProp(0.005)" "RMSProp(0.05)" "BFGS()" "LBFGS()" "ADAM + BFGS"], legend=:bottomleft, linecolor=["#2660A4" "#4CD0F4" "#FEC32F" "#F763CD" "#44BD79" "#831894" "#A6ED18" "#980000" "#FF912B"])
```
```julia
@show loss_1[end], loss_2[end], loss_3[end], loss_4[end], loss_5[end], loss_6[end], loss_7[end], loss_8[end], loss_9[end]
```
```julia, echo = false
using SciMLBenchmarks
SciMLBenchmarks.bench_footer(WEAVE_ARGS[:folder],WEAVE_ARGS[:file])
```
| SciMLBenchmarks | https://github.com/SciML/SciMLBenchmarks.jl.git |
|
[
"MIT"
] | 0.1.3 | f4076dd5a103010d48bb6c4e50c5526f6622fa96 | docs | 6717 | ---
title: Nernst-Planck Equation Physics-Informed Neural Network (PINN) Optimizer Benchmarks
author: Kirill Zubov, Zoe McCarthy, Yingbo Ma, Francesco Calisto, Valerio Pagliarino, Simone Azeglio, Luca Bottero, Emmanuel Luján, Valentin Sulzer, Ashutosh Bharambe, Nand Vinchhi, Kaushik Balakrishnan, Devesh Upadhyay, Chris Rackauckas
---
Adapted from [NeuralPDE: Automating Physics-Informed Neural Networks (PINNs) with Error Approximations](https://arxiv.org/abs/2107.09443).
Uses the [NeuralPDE.jl](https://neuralpde.sciml.ai/dev/) library from the
[SciML Scientific Machine Learning Open Source Organization](https://sciml.ai/)
for the implementation of physics-informed neural networks (PINNs) and other
science-guided AI techniques.
## Setup
```julia
using NeuralPDE, OptimizationFlux, ModelingToolkit, Optimization, OptimizationOptimJL
using Lux, Plots
import ModelingToolkit: Interval, infimum, supremum
```
```julia
t_ref = 1.0 # s
x_ref = 0.38 # dm
C_ref = 0.16 # mol/dm^3
Phi_ref = 1.0 # V
epsilon = 78.5 # K
F = 96485.3415 # A s mol^-1
R = 831.0 # kg dm^2 s^-2 K^-1 mol^-1
T = 298.0 # K
z_Na = 1.0 # non-dim
z_Cl = -1.0 # non-dim
D_Na = 0.89e-7 # dm^2 s^−1
D_Cl = 1.36e-7 # dm^2 s^−1
u_Na = D_Na * abs(z_Na) * F / (R * T)
u_Cl = D_Cl * abs(z_Cl) * F / (R * T)
t_max = 0.01 / t_ref # non-dim
x_max = 0.38 / x_ref # non-dim
Na_0 = 0.16 / C_ref # non-dim
Cl_0 = 0.16 / C_ref # non-dim
Phi_0 = 4.0 / Phi_ref # non-dim
Na_anode = 0.0 # non-dim
Na_cathode = 2.0 * Na_0 # non-dim
Cl_anode = 1.37 * Cl_0 # non-dim
Cl_cathode = 0.0 # non-dim
Pe_Na = x_ref^2 / ( t_ref * D_Na ) # non-dim
Pe_Cl = x_ref^2 / ( t_ref * D_Cl ) # non-dim
M_Na = x_ref^2 / ( t_ref * Phi_ref * u_Na ) # non-dim
M_Cl = x_ref^2 / ( t_ref * Phi_ref * u_Cl ) # non-dim
Po_1 = (epsilon * Phi_ref) / (F * x_ref * C_ref) # non-dim
dx = 0.01 # non-dim
```
```julia
function solve(opt)
strategy = QuadratureTraining()
@parameters t,x
@variables Phi(..),Na(..),Cl(..)
Dt = Differential(t)
Dx = Differential(x)
Dxx = Differential(x)^2
eqs = [
( Dxx(Phi(t,x)) ~ ( 1.0 / Po_1 ) *
( z_Na * Na(t,x) + z_Cl * Cl(t,x) ) )
,
( Dt(Na(t,x)) ~ ( 1.0 / Pe_Na ) * Dxx(Na(t,x))
+ z_Na / ( abs(z_Na) * M_Na )
* ( Dx(Na(t,x)) * Dx(Phi(t,x)) + Na(t,x) * Dxx(Phi(t,x)) ) )
,
( Dt(Cl(t,x)) ~ ( 1.0 / Pe_Cl ) * Dxx(Cl(t,x))
+ z_Cl / ( abs(z_Cl) * M_Cl )
* ( Dx(Cl(t,x)) * Dx(Phi(t,x)) + Cl(t,x) * Dxx(Phi(t,x)) ) )
]
bcs = [
Phi(t,0.0) ~ Phi_0,
Phi(t,x_max) ~ 0.0
,
Na(0.0,x) ~ Na_0,
Na(t,0.0) ~ Na_anode,
Na(t,x_max) ~ Na_cathode
,
Cl(0.0,x) ~ Cl_0,
Cl(t,0.0) ~ Cl_anode,
Cl(t,x_max) ~ Cl_cathode
]
# Space and time domains ###################################################
domains = [
t ∈ Interval(0.0, t_max),
x ∈ Interval(0.0, x_max)
]
# Neural network, Discretization ###########################################
dim = length(domains)
output = length(eqs)
neurons = 16
chain1 = Lux.Chain( Lux.Dense(dim, neurons, tanh),
Lux.Dense(neurons, neurons, tanh),
Lux.Dense(neurons, neurons, tanh),
Lux.Dense(neurons, 1))
chain2 = Lux.Chain( Lux.Dense(dim, neurons, tanh),
Lux.Dense(neurons, neurons, tanh),
Lux.Dense(neurons, neurons, tanh),
Lux.Dense(neurons, 1))
chain3 = Lux.Chain( Lux.Dense(dim, neurons, tanh),
Lux.Dense(neurons, neurons, tanh),
Lux.Dense(neurons, neurons, tanh),
Lux.Dense(neurons, 1))
discretization = PhysicsInformedNN([chain1, chain2, chain3], strategy)
indvars = [t, x] #phisically independent variables
depvars = [Phi, Na, Cl] #dependent (target) variable
loss = []
initial_time = 0
times = []
cb = function (p,l)
if initial_time == 0
initial_time = time()
end
push!(times, time() - initial_time)
#println("Current loss for $opt is: $l")
push!(loss, l)
return false
end
@named pde_system = PDESystem(eqs, bcs, domains, indvars, depvars)
prob = discretize(pde_system, discretization)
if opt == "both"
res = Optimization.solve(prob, ADAM(); callback = cb, maxiters=50)
prob = remake(prob,u0=res.minimizer)
res = Optimization.solve(prob, BFGS(); callback = cb, maxiters=150)
else
res = Optimization.solve(prob, opt; callback = cb, maxiters=200)
end
times[1] = 0.001
return loss, times #add numeric solution
end
```
```julia
opt1 = ADAM()
opt2 = ADAM(0.005)
opt3 = ADAM(0.05)
opt4 = RMSProp()
opt5 = RMSProp(0.005)
opt6 = RMSProp(0.05)
opt7 = OptimizationOptimJL.BFGS()
opt8 = OptimizationOptimJL.LBFGS()
```
## Solve
```julia
loss_1, times_1 = solve(opt1)
loss_2, times_2 = solve(opt2)
loss_3, times_3 = solve(opt3)
loss_4, times_4 = solve(opt4)
loss_5, times_5 = solve(opt5)
loss_6, times_6 = solve(opt6)
loss_7, times_7 = solve(opt7)
loss_8, times_8 = solve(opt8)
loss_9, times_9 = solve("both")
```
## Results
```julia
p = plot([times_1, times_2, times_3, times_4, times_5, times_6, times_7, times_8, times_9], [loss_1, loss_2, loss_3, loss_4, loss_5, loss_6, loss_7, loss_8, loss_9],xlabel="time (s)", ylabel="loss", xscale=:log10, yscale=:log10, labels=["ADAM(0.001)" "ADAM(0.005)" "ADAM(0.05)" "RMSProp(0.001)" "RMSProp(0.005)" "RMSProp(0.05)" "BFGS()" "LBFGS()" "ADAM + BFGS"], legend=:bottomleft, linecolor=["#2660A4" "#4CD0F4" "#FEC32F" "#F763CD" "#44BD79" "#831894" "#A6ED18" "#980000" "#FF912B"])
```
```julia
p = plot([loss_1, loss_2, loss_3, loss_4, loss_5, loss_6, loss_7, loss_8, loss_9[2:end]], xlabel="iterations", ylabel="loss", yscale=:log10, labels=["ADAM(0.001)" "ADAM(0.005)" "ADAM(0.05)" "RMSProp(0.001)" "RMSProp(0.005)" "RMSProp(0.05)" "BFGS()" "LBFGS()" "ADAM + BFGS"], legend=:bottomleft, linecolor=["#2660A4" "#4CD0F4" "#FEC32F" "#F763CD" "#44BD79" "#831894" "#A6ED18" "#980000" "#FF912B"])
```
```julia
@show loss_1[end], loss_2[end], loss_3[end], loss_4[end], loss_5[end], loss_6[end], loss_7[end], loss_8[end], loss_9[end]
```
```julia, echo = false
using SciMLBenchmarks
SciMLBenchmarks.bench_footer(WEAVE_ARGS[:folder],WEAVE_ARGS[:file])
```
| SciMLBenchmarks | https://github.com/SciML/SciMLBenchmarks.jl.git |
|
[
"MIT"
] | 0.1.3 | f4076dd5a103010d48bb6c4e50c5526f6622fa96 | docs | 5197 | ---
title: Allen-Cahn Equation Physics-Informed Neural Network (PINN) Optimizer Benchmarks
author: Kirill Zubov, Zoe McCarthy, Yingbo Ma, Francesco Calisto, Valerio Pagliarino, Simone Azeglio, Luca Bottero, Emmanuel Luján, Valentin Sulzer, Ashutosh Bharambe, Nand Vinchhi, Kaushik Balakrishnan, Devesh Upadhyay, Chris Rackauckas
---
Adapted from [NeuralPDE: Automating Physics-Informed Neural Networks (PINNs) with Error Approximations](https://arxiv.org/abs/2107.09443).
Uses the [NeuralPDE.jl](https://neuralpde.sciml.ai/dev/) library from the
[SciML Scientific Machine Learning Open Source Organization](https://sciml.ai/)
for the implementation of physics-informed neural networks (PINNs) and other
science-guided AI techniques.
## Setup
```julia
using NeuralPDE, OptimizationFlux, ModelingToolkit, Optimization, OptimizationOptimJL
using Lux, Plots
import ModelingToolkit: Interval, infimum, supremum
```
```julia
function solve(opt)
strategy = QuadratureTraining()
@parameters t x1 x2 x3 x4
@variables u(..)
Dt = Differential(t)
Dxx1 = Differential(x1)^2
Dxx2 = Differential(x2)^2
Dxx3 = Differential(x3)^2
Dxx4 = Differential(x4)^2
# Discretization
tmax = 1.0
x1width = 1.0
x2width = 1.0
x3width = 1.0
x4width = 1.0
tMeshNum = 10
x1MeshNum = 10
x2MeshNum = 10
x3MeshNum = 10
x4MeshNum = 10
dt = tmax/tMeshNum
dx1 = x1width/x1MeshNum
dx2 = x2width/x2MeshNum
dx3 = x3width/x3MeshNum
dx4 = x4width/x4MeshNum
domains = [t ∈ Interval(0.0,tmax),
x1 ∈ Interval(0.0,x1width),
x2 ∈ Interval(0.0,x2width),
x3 ∈ Interval(0.0,x3width),
x4 ∈ Interval(0.0,x4width)]
ts = 0.0 : dt : tmax
x1s = 0.0 : dx1 : x1width
x2s = 0.0 : dx2 : x2width
x3s = 0.0 : dx3 : x3width
x4s = 0.0 : dx4 : x4width
# Operators
Δu = Dxx1(u(t,x1,x2,x3,x4)) + Dxx2(u(t,x1,x2,x3,x4)) + Dxx3(u(t,x1,x2,x3,x4)) + Dxx4(u(t,x1,x2,x3,x4)) # Laplacian
# Equation
eq = Dt(u(t,x1,x2,x3,x4)) - Δu - u(t,x1,x2,x3,x4) + u(t,x1,x2,x3,x4)*u(t,x1,x2,x3,x4)*u(t,x1,x2,x3,x4) ~ 0 #ALLEN CAHN EQUATION
initialCondition = 1/(2 + 0.4 * (x1*x1 + x2*x2 + x3*x3 + x4*x4)) # see PNAS paper
bcs = [u(0,x1,x2,x3,x4) ~ initialCondition] #from literature
## NEURAL NETWORK
n = 20 #neuron number
chain = Lux.Chain(Lux.Dense(5,n,tanh),Lux.Dense(n,n,tanh),Lux.Dense(n,1)) #Neural network from OptimizationFlux library
discretization = PhysicsInformedNN(chain, strategy)
indvars = [t,x1,x2,x3,x4] #phisically independent variables
depvars = [u] #dependent (target) variable
loss = []
initial_time = 0
times = []
cb = function (p,l)
if initial_time == 0
initial_time = time()
end
push!(times, time() - initial_time)
#println("Current loss for $opt is: $l")
push!(loss, l)
return false
end
@named pde_system = PDESystem(eq, bcs, domains, indvars, depvars)
prob = discretize(pde_system, discretization)
if opt == "both"
res = Optimization.solve(prob, ADAM(); callback = cb, maxiters=50)
prob = remake(prob,u0=res.minimizer)
res = Optimization.solve(prob, BFGS(); callback = cb, maxiters=150)
else
res = Optimization.solve(prob, opt; callback = cb, maxiters=200)
end
times[1] = 0.001
return loss, times #add numeric solution
end
```
```julia
opt1 = ADAM()
opt2 = ADAM(0.005)
opt3 = ADAM(0.05)
opt4 = RMSProp()
opt5 = RMSProp(0.005)
opt6 = RMSProp(0.05)
opt7 = OptimizationOptimJL.BFGS()
opt8 = OptimizationOptimJL.LBFGS()
```
## Solve
```julia
loss_1, times_1 = solve(opt1)
loss_2, times_2 = solve(opt2)
loss_3, times_3 = solve(opt3)
loss_4, times_4 = solve(opt4)
loss_5, times_5 = solve(opt5)
loss_6, times_6 = solve(opt6)
loss_7, times_7 = solve(opt7)
loss_8, times_8 = solve(opt8)
loss_9, times_9 = solve("both")
```
## Results
```julia
p = plot([times_1, times_2, times_3, times_4, times_5, times_6, times_7, times_8, times_9], [loss_1, loss_2, loss_3, loss_4, loss_5, loss_6, loss_7, loss_8, loss_9],xlabel="time (s)", ylabel="loss", xscale=:log10, yscale=:log10, labels=["ADAM(0.001)" "ADAM(0.005)" "ADAM(0.05)" "RMSProp(0.001)" "RMSProp(0.005)" "RMSProp(0.05)" "BFGS()" "LBFGS()" "ADAM + BFGS"], legend=:bottomleft, linecolor=["#2660A4" "#4CD0F4" "#FEC32F" "#F763CD" "#44BD79" "#831894" "#A6ED18" "#980000" "#FF912B"])
```
```julia
p = plot([loss_1, loss_2, loss_3, loss_4, loss_5, loss_6, loss_7, loss_8, loss_9[2:end]], xlabel="iterations", ylabel="loss", yscale=:log10, labels=["ADAM(0.001)" "ADAM(0.005)" "ADAM(0.05)" "RMSProp(0.001)" "RMSProp(0.005)" "RMSProp(0.05)" "BFGS()" "LBFGS()" "ADAM + BFGS"], legend=:bottomleft, linecolor=["#2660A4" "#4CD0F4" "#FEC32F" "#F763CD" "#44BD79" "#831894" "#A6ED18" "#980000" "#FF912B"])
```
```julia
@show loss_1[end], loss_2[end], loss_3[end], loss_4[end], loss_5[end], loss_6[end], loss_7[end], loss_8[end], loss_9[end]
```
```julia, echo = false
using SciMLBenchmarks
SciMLBenchmarks.bench_footer(WEAVE_ARGS[:folder],WEAVE_ARGS[:file])
```
| SciMLBenchmarks | https://github.com/SciML/SciMLBenchmarks.jl.git |
|
[
"MIT"
] | 0.1.3 | f4076dd5a103010d48bb6c4e50c5526f6622fa96 | docs | 9728 | ---
title: Berger's Equation Physics-Informed Neural Network (PINN) Optimizer Benchmarks
author: Kirill Zubov, Zoe McCarthy, Yingbo Ma, Francesco Calisto, Valerio Pagliarino, Simone Azeglio, Luca Bottero, Emmanuel Luján, Valentin Sulzer, Ashutosh Bharambe, Nand Vinchhi, Kaushik Balakrishnan, Devesh Upadhyay, Chris Rackauckas
---
Adapted from [NeuralPDE: Automating Physics-Informed Neural Networks (PINNs) with Error Approximations](https://arxiv.org/abs/2107.09443).
Uses the [NeuralPDE.jl](https://neuralpde.sciml.ai/dev/) library from the
[SciML Scientific Machine Learning Open Source Organization](https://sciml.ai/)
for the implementation of physics-informed neural networks (PINNs) and other
science-guided AI techniques.
## Setup
```julia
using NeuralPDE, OptimizationFlux, ModelingToolkit, Optimization, OptimizationOptimJL
using Lux, Plots
import ModelingToolkit: Interval, infimum, supremum
```
```julia
# Physical and numerical parameters (fixed)
nu = 0.07
nx = 10001 #101
x_max = 2.0 * pi
dx = x_max / (nx - 1.0)
nt = 2 #10
dt = dx * nu
t_max = dt * nt
# Analytic function
analytic_sol_func(t, x) = -2*nu*(-(-8*t + 2*x)*exp(-(-4*t + x)^2/(4*nu*(t + 1)))/
(4*nu*(t + 1)) - (-8*t + 2*x - 12.5663706143592)*
exp(-(-4*t + x - 6.28318530717959)^2/(4*nu*(t + 1)))/
(4*nu*(t + 1)))/(exp(-(-4*t + x - 6.28318530717959)^2/
(4*nu*(t + 1))) + exp(-(-4*t + x)^2/(4*nu*(t + 1)))) + 4
```
```julia
function burgers(strategy, minimizer)
@parameters x t
@variables u(..)
Dt = Differential(t)
Dx = Differential(x)
Dxx = Differential(x)^2
eq = Dt(u(x, t)) + u(x, t) * Dx(u(x, t)) ~ nu * Dxx(u(x, t))
bcs = [u(x, 0.0) ~ analytic_sol_func(x, 0.0),
u(0.0, t) ~ u(x_max, t)]
domains = [x ∈ Interval(0.0, x_max),
t ∈ Interval(0.0, t_max)]
chain = Lux.Chain(Lux.Dense(2, 16, tanh), Lux.Dense(16, 16, tanh), Lux.Dense(16, 1))
discretization = PhysicsInformedNN(chain, strategy)
indvars = [x, t] #physically independent variables
depvars = [u] #dependent (target) variable
dim = length(domains)
losses = []
error = []
times = []
dx_err = 0.00005
error_strategy = GridTraining(dx_err)
discretization_ = PhysicsInformedNN(chain, error_strategy)
@named pde_system_ = PDESystem(eq, bcs, domains, indvars, depvars)
prob_ = discretize(pde_system_, discretization_)
function loss_function__(θ)
return prob_.f.f(θ, nothing)
end
cb = function (p, l)
timeCounter = 0.0
deltaT_s = time_ns() #Start a clock when the callback begins, this will evaluate questo misurerà anche il calcolo degli uniform error
ctime = time_ns() - startTime - timeCounter #This variable is the time to use for the time benchmark plot
append!(times, ctime / 10^9) #Conversion nanosec to seconds
append!(losses, l)
append!(error, loss_function__(p))
#println(length(losses), " Current loss is: ", l, " uniform error is, ", loss_function__(p))
timeCounter = timeCounter + time_ns() - deltaT_s #timeCounter sums all delays due to the callback functions of the previous iterations
return false
end
@named pde_system = PDESystem(eq, bcs, domains, indvars, depvars)
discretization = NeuralPDE.PhysicsInformedNN(chain, strategy)
prob = NeuralPDE.discretize(pde_system, discretization)
startTime = time_ns() #Fix initial time (t=0) before starting the training
if minimizer == "both"
res = Optimization.solve(prob, ADAM(); callback=cb, maxiters=5)
prob = remake(prob, u0=res.minimizer)
res = Optimization.solve(prob, BFGS(); callback=cb, maxiters=15)
else
res = Optimization.solve(prob, minimizer; callback=cb, maxiters=500)
end
phi = discretization.phi
params = res.minimizer
return [error, params, times, losses]
end
```
## Solve
```julia
# Settings:
#maxIters = [(0,0,0,0,0,0,20000),(300,300,300,300,300,300,300)] #iters
strategies = [NeuralPDE.QuadratureTraining()]
strategies_short_name = ["QuadratureTraining"]
minimizers = [ADAM(),
ADAM(0.000005),
ADAM(0.0005),
RMSProp(),
RMSProp(0.00005),
RMSProp(0.05),
BFGS(),
LBFGS()]
minimizers_short_name = ["ADAM",
"ADAM(0.000005)",
"ADAM(0.0005)",
"RMS",
"RMS(0.00005)",
"RMS(0.05)",
"BFGS",
"LBFGS"]
```
```julia
# Run models
error_res = Dict()
params_res = Dict()
times = Dict()
losses_res = Dict()
print("Starting run \n")
for min in 1:length(minimizers) # minimizer
for strat in 1:length(strategies) # strategy
#println(string(strategies_short_name[1], " ", minimizers_short_name[min]))
res = burgers(strategies[strat], minimizers[min])
push!(error_res, string(strat,min) => res[1])
push!(params_res, string(strat,min) => res[2])
push!(times, string(strat,min) => res[3])
push!(losses_res, string(strat,min) => res[4])
end
end
```
## Results
```julia
#PLOT ERROR VS ITER: to compare to compare between minimizers, keeping the same strategy (easily adjustable to compare between strategies)
error_iter = Plots.plot(1:length(error_res["11"]), error_res["11"], yaxis=:log10, title = string("Burger error vs iter"), ylabel = "Error", label = string(minimizers_short_name[1]), ylims = (0.0001,1))
plot!(error_iter, 1:length(error_res["12"]), error_res["12"], yaxis=:log10, label = string(minimizers_short_name[2]))
plot!(error_iter, 1:length(error_res["13"]), error_res["13"], yaxis=:log10, label = string(minimizers_short_name[3]))
plot!(error_iter, 1:length(error_res["14"]), error_res["14"], yaxis=:log10, label = string(minimizers_short_name[4]))
plot!(error_iter, 1:length(error_res["15"]), error_res["15"], yaxis=:log10, label = string(minimizers_short_name[5]))
plot!(error_iter, 1:length(error_res["16"]), error_res["16"], yaxis=:log10, label = string(minimizers_short_name[6]))
plot!(error_iter, 1:length(error_res["17"]), error_res["17"], yaxis=:log10, label = string(minimizers_short_name[7]))
plot!(error_iter, 1:length(error_res["18"]), error_res["18"], yaxis=:log10, label = string(minimizers_short_name[8]))
Plots.plot(error_iter)
```
```julia
#Use after having modified the analysis setting correctly --> Error vs iter: to compare different strategies, keeping the same minimizer
#error_iter = Plots.plot(1:length(error_res["11"]), error_res["11"], yaxis=:log10, title = string("Burger error vs iter"), ylabel = "Error", label = string(strategies_short_name[1]), ylims = (0.0001,1))
#plot!(error_iter, 1:length(error_res["21"]), error_res["21"], yaxis=:log10, label = string(strategies_short_name[2]))
#plot!(error_iter, 1:length(error_res["31"]), error_res["31"], yaxis=:log10, label = string(strategies_short_name[3]))
#plot!(error_iter, 1:length(error_res["41"]), error_res["41"], yaxis=:log10, label = string(strategies_short_name[4]))
#plot!(error_iter, 1:length(error_res["51"]), error_res["51"], yaxis=:log10, label = string(strategies_short_name[5]))
#plot!(error_iter, 1:length(error_res["61"]), error_res["61"], yaxis=:log10, label = string(strategies_short_name[6]))
#plot!(error_iter, 1:length(error_res["71"]), error_res["71"], yaxis=:log10, label = string(strategies_short_name[7]))
```
```julia
#PLOT ERROR VS TIME: to compare to compare between minimizers, keeping the same strategy
error_time = plot(times["11"], error_res["11"], yaxis=:log10, label = string(minimizers_short_name[1]),title = string("Burger error vs time"), ylabel = "Error", size = (1500,500))
plot!(error_time, times["12"], error_res["12"], yaxis=:log10, label = string(minimizers_short_name[2]))
plot!(error_time, times["13"], error_res["13"], yaxis=:log10, label = string(minimizers_short_name[3]))
plot!(error_time, times["14"], error_res["14"], yaxis=:log10, label = string(minimizers_short_name[4]))
plot!(error_time, times["15"], error_res["15"], yaxis=:log10, label = string(minimizers_short_name[5]))
plot!(error_time, times["16"], error_res["16"], yaxis=:log10, label = string(minimizers_short_name[6]))
plot!(error_time, times["17"], error_res["17"], yaxis=:log10, label = string(minimizers_short_name[7]))
plot!(error_time, times["18"], error_res["18"], yaxis=:log10, label = string(minimizers_short_name[7]))
Plots.plot(error_time)
```
```julia
#Use after having modified the analysis setting correctly --> Error vs time: to compare different strategies, keeping the same minimizer
#error_time = plot(times["11"], error_res["11"], yaxis=:log10, label = string(strategies_short_name[1]),title = string("Burger error vs time"), ylabel = "Error", size = (1500,500))
#plot!(error_time, times["21"], error_res["21"], yaxis=:log10, label = string(strategies_short_name[2]))
#plot!(error_time, times["31"], error_res["31"], yaxis=:log10, label = string(strategies_short_name[3]))
#plot!(error_time, times["41"], error_res["41"], yaxis=:log10, label = string(strategies_short_name[4]))
#plot!(error_time, times["51"], error_res["51"], yaxis=:log10, label = string(strategies_short_name[5]))
#plot!(error_time, times["61"], error_res["61"], yaxis=:log10, label = string(strategies_short_name[6]))
#plot!(error_time, times["71"], error_res["71"], yaxis=:log10, label = string(strategies_short_name[7]))
```
```julia, echo = false
using SciMLBenchmarks
SciMLBenchmarks.bench_footer(WEAVE_ARGS[:folder],WEAVE_ARGS[:file])
```
| SciMLBenchmarks | https://github.com/SciML/SciMLBenchmarks.jl.git |
|
[
"MIT"
] | 0.1.3 | f4076dd5a103010d48bb6c4e50c5526f6622fa96 | docs | 5393 | ---
title: Hamilton-Jacobi PDE Physics-Informed Neural Network (PINN) Optimizer Benchmarks
author: Kirill Zubov, Zoe McCarthy, Yingbo Ma, Francesco Calisto, Valerio Pagliarino, Simone Azeglio, Luca Bottero, Emmanuel Luján, Valentin Sulzer, Ashutosh Bharambe, Nand Vinchhi, Kaushik Balakrishnan, Devesh Upadhyay, Chris Rackauckas
---
Adapted from [NeuralPDE: Automating Physics-Informed Neural Networks (PINNs) with Error Approximations](https://arxiv.org/abs/2107.09443).
Uses the [NeuralPDE.jl](https://neuralpde.sciml.ai/dev/) library from the
[SciML Scientific Machine Learning Open Source Organization](https://sciml.ai/)
for the implementation of physics-informed neural networks (PINNs) and other
science-guided AI techniques.
## Setup
```julia
using NeuralPDE, OptimizationFlux, ModelingToolkit, Optimization, OptimizationOptimJL
using Lux, Plots
import ModelingToolkit: Interval, infimum, supremum
```
```julia
function solve(opt)
strategy = QuadratureTraining()
## DECLARATIONS
@parameters t x1 x2 x3 x4
@variables u(..)
Dt = Differential(t)
Dx1 = Differential(x1)
Dx2 = Differential(x2)
Dx3 = Differential(x3)
Dx4 = Differential(x4)
Dxx1 = Differential(x1)^2
Dxx2 = Differential(x2)^2
Dxx3 = Differential(x3)^2
Dxx4 = Differential(x4)^2
# Discretization
tmax = 1.0
x1width = 1.0
x2width = 1.0
x3width = 1.0
x4width = 1.0
tMeshNum = 10
x1MeshNum = 10
x2MeshNum = 10
x3MeshNum = 10
x4MeshNum = 10
dt = tmax/tMeshNum
dx1 = x1width/x1MeshNum
dx2 = x2width/x2MeshNum
dx3 = x3width/x3MeshNum
dx4 = x4width/x4MeshNum
domains = [t ∈ Interval(0.0,tmax),
x1 ∈ Interval(0.0,x1width),
x2 ∈ Interval(0.0,x2width),
x3 ∈ Interval(0.0,x3width),
x4 ∈ Interval(0.0,x4width)]
ts = 0.0 : dt : tmax
x1s = 0.0 : dx1 : x1width
x2s = 0.0 : dx2 : x2width
x3s = 0.0 : dx3 : x3width
x4s = 0.0 : dx4 : x4width
λ = 1.0f0
# Operators
Δu = Dxx1(u(t,x1,x2,x3,x4)) + Dxx2(u(t,x1,x2,x3,x4)) + Dxx3(u(t,x1,x2,x3,x4)) + Dxx4(u(t,x1,x2,x3,x4)) # Laplacian
∇u = [Dx1(u(t,x1,x2,x3,x4)), Dx2(u(t,x1,x2,x3,x4)),Dx3(u(t,x1,x2,x3,x4)),Dx4(u(t,x1,x2,x3,x4))]
# Equation
eq = Dt(u(t,x1,x2,x3,x4)) + Δu - λ*sum(∇u.^2) ~ 0 #HAMILTON-JACOBI-BELLMAN EQUATION
terminalCondition = log((1 + x1*x1 + x2*x2 + x3*x3 + x4*x4)/2) # see PNAS paper
bcs = [u(tmax,x1,x2,x3,x4) ~ terminalCondition] #PNAS paper again
## NEURAL NETWORK
n = 20 #neuron number
chain = Lux.Chain(Lux.Dense(5,n,tanh),Lux.Dense(n,n,tanh),Lux.Dense(n,1)) #Neural network from OptimizationFlux library
discretization = PhysicsInformedNN(chain, strategy)
indvars = [t,x1,x2,x3,x4] #phisically independent variables
depvars = [u] #dependent (target) variable
loss = []
initial_time = 0
times = []
cb = function (p,l)
if initial_time == 0
initial_time = time()
end
push!(times, time() - initial_time)
#println("Current loss for $opt is: $l")
push!(loss, l)
return false
end
@named pde_system = PDESystem(eq, bcs, domains, indvars, depvars)
prob = discretize(pde_system, discretization)
if opt == "both"
res = Optimization.solve(prob, ADAM(); callback = cb, maxiters=50)
prob = remake(prob,u0=res.minimizer)
res = Optimization.solve(prob, BFGS(); callback = cb, maxiters=150)
else
res = Optimization.solve(prob, opt; callback = cb, maxiters=200)
end
times[1] = 0.001
return loss, times #add numeric solution
end
```
```julia
opt1 = ADAM()
opt2 = ADAM(0.005)
opt3 = ADAM(0.05)
opt4 = RMSProp()
opt5 = RMSProp(0.005)
opt6 = RMSProp(0.05)
opt7 = OptimizationOptimJL.BFGS()
opt8 = OptimizationOptimJL.LBFGS()
```
## Solve
```julia
loss_1, times_1 = solve(opt1)
loss_2, times_2 = solve(opt2)
loss_3, times_3 = solve(opt3)
loss_4, times_4 = solve(opt4)
loss_5, times_5 = solve(opt5)
loss_6, times_6 = solve(opt6)
loss_7, times_7 = solve(opt7)
loss_8, times_8 = solve(opt8)
loss_9, times_9 = solve("both")
```
## Results
```julia
p = plot([times_1, times_2, times_3, times_4, times_5, times_6, times_7, times_8, times_9], [loss_1, loss_2, loss_3, loss_4, loss_5, loss_6, loss_7, loss_8, loss_9],xlabel="time (s)", ylabel="loss", xscale=:log10, yscale=:log10, labels=["ADAM(0.001)" "ADAM(0.005)" "ADAM(0.05)" "RMSProp(0.001)" "RMSProp(0.005)" "RMSProp(0.05)" "BFGS()" "LBFGS()" "ADAM + BFGS"], legend=:bottomleft, linecolor=["#2660A4" "#4CD0F4" "#FEC32F" "#F763CD" "#44BD79" "#831894" "#A6ED18" "#980000" "#FF912B"])
```
```julia
p = plot([loss_1, loss_2, loss_3, loss_4, loss_5, loss_6, loss_7, loss_8, loss_9], xlabel="iterations", ylabel="loss", yscale=:log10, labels=["ADAM(0.001)" "ADAM(0.005)" "ADAM(0.05)" "RMSProp(0.001)" "RMSProp(0.005)" "RMSProp(0.05)" "BFGS()" "LBFGS()" "ADAM + BFGS"], legend=:bottomleft, linecolor=["#2660A4" "#4CD0F4" "#FEC32F" "#F763CD" "#44BD79" "#831894" "#A6ED18" "#980000" "#FF912B"])
```
```julia
@show loss_1[end], loss_2[end], loss_3[end], loss_4[end], loss_5[end], loss_6[end], loss_7[end], loss_8[end], loss_9[end]
```
```julia, echo = false
using SciMLBenchmarks
SciMLBenchmarks.bench_footer(WEAVE_ARGS[:folder],WEAVE_ARGS[:file])
```
| SciMLBenchmarks | https://github.com/SciML/SciMLBenchmarks.jl.git |
|
[
"MIT"
] | 0.1.3 | f4076dd5a103010d48bb6c4e50c5526f6622fa96 | docs | 4181 | ---
title: Poisson PDE Physics-Informed Neural Network (PINN) Optimizer Benchmarks
author: Kirill Zubov, Zoe McCarthy, Yingbo Ma, Francesco Calisto, Valerio Pagliarino, Simone Azeglio, Luca Bottero, Emmanuel Luján, Valentin Sulzer, Ashutosh Bharambe, Nand Vinchhi, Kaushik Balakrishnan, Devesh Upadhyay, Chris Rackauckas
---
Adapted from [NeuralPDE: Automating Physics-Informed Neural Networks (PINNs) with Error Approximations](https://arxiv.org/abs/2107.09443).
Uses the [NeuralPDE.jl](https://neuralpde.sciml.ai/dev/) library from the
[SciML Scientific Machine Learning Open Source Organization](https://sciml.ai/)
for the implementation of physics-informed neural networks (PINNs) and other
science-guided AI techniques.
## Setup Code
```julia
using NeuralPDE, OptimizationFlux, ModelingToolkit, Optimization, OptimizationOptimJL
using Lux, Plots
import ModelingToolkit: Interval, infimum, supremum
```
```julia
function solve(opt)
strategy = QuadratureTraining()
@parameters x y
@variables u(..)
Dxx = Differential(x)^2
Dyy = Differential(y)^2
# 2D PDE
eq = Dxx(u(x,y)) + Dyy(u(x,y)) ~ -sin(pi*x)*sin(pi*y)
# Boundary conditions
bcs = [u(0,y) ~ 0.f0, u(1,y) ~ -sin(pi*1)*sin(pi*y),
u(x,0) ~ 0.f0, u(x,1) ~ -sin(pi*x)*sin(pi*1)]
# Space and time domains
domains = [x ∈ Interval(0.0,1.0),
y ∈ Interval(0.0,1.0)]
# Neural network
dim = 2 # number of dimensions
chain = Lux.Chain(Lux.Dense(dim,16,tanh),Lux.Dense(16,16,tanh),Lux.Dense(16,1))
discretization = PhysicsInformedNN(chain,strategy)
indvars = [x, y] #phisically independent variables
depvars = [u(x,y)] #dependent (target) variable
loss = []
initial_time = nothing
times = []
cb = function (p,l)
if initial_time == nothing
initial_time = time()
end
push!(times, time() - initial_time)
#println("Current loss for $opt is: $l")
push!(loss, l)
return false
end
@named pde_system = PDESystem(eq, bcs, domains, indvars, depvars)
prob = discretize(pde_system, discretization)
if opt == "both"
res = Optimization.solve(prob, ADAM(); callback = cb, maxiters=50)
prob = remake(prob,u0=res.minimizer)
res = Optimization.solve(prob, BFGS(); callback = cb, maxiters=150)
else
res = Optimization.solve(prob, opt; callback = cb, maxiters=200)
end
times[1] = 0.001
return loss, times #add numeric solution
end
```
```julia
opt1 = ADAM()
opt2 = ADAM(0.005)
opt3 = ADAM(0.05)
opt4 = RMSProp()
opt5 = RMSProp(0.005)
opt6 = RMSProp(0.05)
opt7 = OptimizationOptimJL.BFGS()
opt8 = OptimizationOptimJL.LBFGS()
```
## Solve
```julia
loss_1, times_1 = solve(opt1)
loss_2, times_2 = solve(opt2)
loss_3, times_3 = solve(opt3)
loss_4, times_4 = solve(opt4)
loss_5, times_5 = solve(opt5)
loss_6, times_6 = solve(opt6)
loss_7, times_7 = solve(opt7)
loss_8, times_8 = solve(opt8)
loss_9, times_9 = solve("both")
```
## Results
```julia
p = plot([times_1, times_2, times_3, times_4, times_5, times_6, times_7, times_8, times_9], [loss_1, loss_2, loss_3, loss_4, loss_5, loss_6, loss_7, loss_8, loss_9],xlabel="time (s)", ylabel="loss", xscale=:log10, yscale=:log10, labels=["ADAM(0.001)" "ADAM(0.005)" "ADAM(0.05)" "RMSProp(0.001)" "RMSProp(0.005)" "RMSProp(0.05)" "BFGS()" "LBFGS()" "ADAM + BFGS"], legend=:bottomleft, linecolor=["#2660A4" "#4CD0F4" "#FEC32F" "#F763CD" "#44BD79" "#831894" "#A6ED18" "#980000" "#FF912B"])
```
```julia
p = plot([loss_1, loss_2, loss_3, loss_4, loss_5, loss_6, loss_7, loss_8, loss_9], xlabel="iterations", ylabel="loss", yscale=:log10, labels=["ADAM(0.001)" "ADAM(0.005)" "ADAM(0.05)" "RMSProp(0.001)" "RMSProp(0.005)" "RMSProp(0.05)" "BFGS()" "LBFGS()" "ADAM + BFGS"], legend=:bottomleft, linecolor=["#2660A4" "#4CD0F4" "#FEC32F" "#F763CD" "#44BD79" "#831894" "#A6ED18" "#980000" "#FF912B"])
```
```julia
@show loss_1[end], loss_2[end], loss_3[end], loss_4[end], loss_5[end], loss_6[end], loss_7[end], loss_8[end], loss_9[end]
```
```julia, echo = false
using SciMLBenchmarks
SciMLBenchmarks.bench_footer(WEAVE_ARGS[:folder],WEAVE_ARGS[:file])
```
| SciMLBenchmarks | https://github.com/SciML/SciMLBenchmarks.jl.git |
|
[
"MIT"
] | 0.1.3 | f4076dd5a103010d48bb6c4e50c5526f6622fa96 | docs | 9813 | ---
title: FitzHugh-Nagumo Parameter Estimation Benchmarks
author: Vaibhav Dixit, Chris Rackauckas
---
# Parameter estimation of FitzHugh-Nagumo model using optimisation methods
```julia
using ParameterizedFunctions, OrdinaryDiffEq, DiffEqParamEstim
using BlackBoxOptim, NLopt, Plots,QuadDIRECT
gr(fmt=:png)
```
```julia
loc_bounds = Tuple{Float64,Float64}[(0, 1), (0, 1), (0, 1), (0, 1)]
glo_bounds = Tuple{Float64,Float64}[(0, 5), (0, 5), (0, 5), (0, 5)]
loc_init = [0.5,0.5,0.5,0.5]
glo_init = [2.5,2.5,2.5,2.5]
```
```julia
fitz = @ode_def FitzhughNagumo begin
dv = v - v^3/3 -w + l
dw = τinv*(v + a - b*w)
end a b τinv l
```
```julia
p = [0.7,0.8,0.08,0.5] # Parameters used to construct the dataset
r0 = [1.0; 1.0] # initial value
tspan = (0.0, 30.0) # sample of 3000 observations over the (0,30) timespan
prob = ODEProblem(fitz, r0, tspan,p)
tspan2 = (0.0, 3.0) # sample of 300 observations with a timestep of 0.01
prob_short = ODEProblem(fitz, r0, tspan2,p)
```
```julia
dt = 30.0/3000
tf = 30.0
tinterval = 0:dt:tf
t = collect(tinterval)
```
```julia
h = 0.01
M = 300
tstart = 0.0
tstop = tstart + M * h
tinterval_short = 0:h:tstop
t_short = collect(tinterval_short)
```
```julia
#Generate Data
data_sol_short = solve(prob_short,Vern9(),saveat=t_short,reltol=1e-9,abstol=1e-9)
data_short = convert(Array, data_sol_short) # This operation produces column major dataset obs as columns, equations as rows
data_sol = solve(prob,Vern9(),saveat=t,reltol=1e-9,abstol=1e-9)
data = convert(Array, data_sol)
```
#### Plot of the solution
##### Short Solution
```julia
plot(data_sol_short)
```
##### Longer Solution
```julia
plot(data_sol)
```
## Local Solution from the short data set
```julia
obj_short = build_loss_objective(prob_short,Tsit5(),L2Loss(t_short,data_short),tstops=t_short)
res1 = bboptimize(obj_short;SearchRange = glo_bounds, MaxSteps = 7e3)
# Lower tolerance could lead to smaller fitness (more accuracy)
```
```julia
obj_short = build_loss_objective(prob_short,Tsit5(),L2Loss(t_short,data_short),tstops=t_short,reltol=1e-9)
res1 = bboptimize(obj_short;SearchRange = glo_bounds, MaxSteps = 7e3)
# Change in tolerance makes it worse
```
```julia
obj_short = build_loss_objective(prob_short,Vern9(),L2Loss(t_short,data_short),tstops=t_short,reltol=1e-9,abstol=1e-9)
res1 = bboptimize(obj_short;SearchRange = glo_bounds, MaxSteps = 7e3)
# using the moe accurate Vern9() reduces the fitness marginally and leads to some increase in time taken
```
## Using NLopt
#### Global Optimisation
```julia
obj_short = build_loss_objective(prob_short,Vern9(),L2Loss(t_short,data_short),tstops=t_short,reltol=1e-9,abstol=1e-9)
```
```julia
opt = Opt(:GN_ORIG_DIRECT_L, 4)
lower_bounds!(opt,[0.0,0.0,0.0,0.0])
upper_bounds!(opt,[5.0,5.0,5.0,5.0])
min_objective!(opt, obj_short.cost_function2)
xtol_rel!(opt,1e-12)
maxeval!(opt, 10000)
@time (minf,minx,ret) = NLopt.optimize(opt,glo_init)
```
```julia
opt = Opt(:GN_CRS2_LM, 4)
lower_bounds!(opt,[0.0,0.0,0.0,0.0])
upper_bounds!(opt,[5.0,5.0,5.0,5.0])
min_objective!(opt, obj_short.cost_function2)
xtol_rel!(opt,1e-12)
maxeval!(opt, 10000)
@time (minf,minx,ret) = NLopt.optimize(opt,glo_init)
```
```julia
opt = Opt(:GN_ISRES, 4)
lower_bounds!(opt,[0.0,0.0,0.0,0.0])
upper_bounds!(opt,[5.0,5.0,5.0,5.0])
min_objective!(opt, obj_short.cost_function2)
xtol_rel!(opt,1e-12)
maxeval!(opt, 10000)
@time (minf,minx,ret) = NLopt.optimize(opt,glo_init)
```
```julia
opt = Opt(:GN_ESCH, 4)
lower_bounds!(opt,[0.0,0.0,0.0,0.0])
upper_bounds!(opt,[5.0,5.0,5.0,5.0])
min_objective!(opt, obj_short.cost_function2)
xtol_rel!(opt,1e-12)
maxeval!(opt, 10000)
@time (minf,minx,ret) = NLopt.optimize(opt,glo_init)
```
Now local optimization algorithms are used to check the global ones, these use the local constraints, different intial values and time step
```julia
opt = Opt(:LN_BOBYQA, 4)
lower_bounds!(opt,[0.0,0.0,0.0,0.0])
upper_bounds!(opt,[1.0,1.0,1.0,1.0])
min_objective!(opt, obj_short.cost_function2)
xtol_rel!(opt,1e-12)
maxeval!(opt, 10000)
@time (minf,minx,ret) = NLopt.optimize(opt,loc_init)
```
```julia
opt = Opt(:LN_NELDERMEAD, 4)
lower_bounds!(opt,[0.0,0.0,0.0,0.0])
upper_bounds!(opt,[1.0,1.0,1.0,1.0])
min_objective!(opt, obj_short.cost_function2)
xtol_rel!(opt,1e-12)
maxeval!(opt, 10000)
@time (minf,minx,ret) = NLopt.optimize(opt,loc_init)
```
```julia
opt = Opt(:LD_SLSQP, 4)
lower_bounds!(opt,[0.0,0.0,0.0,0.0])
upper_bounds!(opt,[1.0,1.0,1.0,1.0])
min_objective!(opt, obj_short.cost_function2)
xtol_rel!(opt,1e-12)
maxeval!(opt, 10000)
@time (minf,minx,ret) = NLopt.optimize(opt,loc_init)
```
```julia
opt = Opt(:LN_COBYLA, 4)
lower_bounds!(opt,[0.0,0.0,0.0,0.0])
upper_bounds!(opt,[1.0,1.0,1.0,1.0])
min_objective!(opt, obj_short.cost_function2)
xtol_rel!(opt,1e-12)
maxeval!(opt, 10000)
@time (minf,minx,ret) = NLopt.optimize(opt,loc_init)
```
```julia
opt = Opt(:LN_NEWUOA_BOUND, 4)
lower_bounds!(opt,[0.0,0.0,0.0,0.0])
upper_bounds!(opt,[1.0,1.0,1.0,1.0])
min_objective!(opt, obj_short.cost_function2)
xtol_rel!(opt,1e-12)
maxeval!(opt, 10000)
@time (minf,minx,ret) = NLopt.optimize(opt,loc_init)
```
```julia
opt = Opt(:LN_PRAXIS, 4)
lower_bounds!(opt,[0.0,0.0,0.0,0.0])
upper_bounds!(opt,[1.0,1.0,1.0,1.0])
min_objective!(opt, obj_short.cost_function2)
xtol_rel!(opt,1e-12)
maxeval!(opt, 10000)
@time (minf,minx,ret) = NLopt.optimize(opt,loc_init)
```
```julia
opt = Opt(:LN_SBPLX, 4)
lower_bounds!(opt,[0.0,0.0,0.0,0.0])
upper_bounds!(opt,[1.0,1.0,1.0,1.0])
min_objective!(opt, obj_short.cost_function2)
xtol_rel!(opt,1e-12)
maxeval!(opt, 10000)
@time (minf,minx,ret) = NLopt.optimize(opt,loc_init)
```
```julia
opt = Opt(:LD_MMA, 4)
lower_bounds!(opt,[0.0,0.0,0.0,0.0])
upper_bounds!(opt,[1.0,1.0,1.0,1.0])
min_objective!(opt, obj_short.cost_function2)
xtol_rel!(opt,1e-12)
maxeval!(opt, 10000)
@time (minf,minx,ret) = NLopt.optimize(opt,loc_init)
```
### Now the longer problem is solved for a global solution
Vern9 solver with reltol=1e-9 and abstol=1e-9 is used and the dataset is increased to 3000 observations per variable with the same integration time step of 0.01.
```julia
obj = build_loss_objective(prob,Vern9(),L2Loss(t,data),tstops=t,reltol=1e-9,abstol=1e-9)
res1 = bboptimize(obj;SearchRange = glo_bounds, MaxSteps = 4e3)
```
```julia
opt = Opt(:GN_ORIG_DIRECT_L, 4)
lower_bounds!(opt,[0.0,0.0,0.0,0.0])
upper_bounds!(opt,[5.0,5.0,5.0,5.0])
min_objective!(opt, obj.cost_function2)
xtol_rel!(opt,1e-12)
maxeval!(opt, 10000)
@time (minf,minx,ret) = NLopt.optimize(opt,glo_init)
```
```julia
opt = Opt(:GN_CRS2_LM, 4)
lower_bounds!(opt,[0.0,0.0,0.0,0.0])
upper_bounds!(opt,[5.0,5.0,5.0,5.0])
min_objective!(opt, obj.cost_function2)
xtol_rel!(opt,1e-12)
maxeval!(opt, 20000)
@time (minf,minx,ret) = NLopt.optimize(opt,glo_init)
```
```julia
opt = Opt(:GN_ISRES, 4)
lower_bounds!(opt,[0.0,0.0,0.0,0.0])
upper_bounds!(opt,[5.0,5.0,5.0,5.0])
min_objective!(opt, obj.cost_function2)
xtol_rel!(opt,1e-12)
maxeval!(opt, 50000)
@time (minf,minx,ret) = NLopt.optimize(opt,glo_init)
```
```julia
opt = Opt(:GN_ESCH, 4)
lower_bounds!(opt,[0.0,0.0,0.0,0.0])
upper_bounds!(opt,[5.0,5.0,5.0,5.0])
min_objective!(opt, obj.cost_function2)
xtol_rel!(opt,1e-12)
maxeval!(opt, 20000)
@time (minf,minx,ret) = NLopt.optimize(opt,glo_init)
```
```julia
opt = Opt(:LN_BOBYQA, 4)
lower_bounds!(opt,[0.0,0.0,0.0,0.0])
upper_bounds!(opt,[1.0,1.0,1.0,1.0])
min_objective!(opt, obj.cost_function2)
xtol_rel!(opt,1e-12)
maxeval!(opt, 10000)
@time (minf,minx,ret) = NLopt.optimize(opt,loc_init)
```
```julia
opt = Opt(:LN_NELDERMEAD, 4)
lower_bounds!(opt,[0.0,0.0,0.0,0.0])
upper_bounds!(opt,[1.0,1.0,1.0,1.0])
min_objective!(opt, obj.cost_function2)
xtol_rel!(opt,1e-9)
maxeval!(opt, 10000)
@time (minf,minx,ret) = NLopt.optimize(opt,loc_init)
```
```julia
opt = Opt(:LD_SLSQP, 4)
lower_bounds!(opt,[0.0,0.0,0.0,0.0])
upper_bounds!(opt,[1.0,1.0,1.0,1.0])
min_objective!(opt, obj.cost_function2)
xtol_rel!(opt,1e-12)
maxeval!(opt, 10000)
@time (minf,minx,ret) = NLopt.optimize(opt,loc_init)
```
As expected from other problems the longer sample proves to be extremely challenging for some of the global optimizers. A few give the accurate values, while others seem to struggle with accuracy a lot.
#### Using QuadDIRECT
```julia
obj_short = build_loss_objective(prob_short,Tsit5(),L2Loss(t_short,data_short),tstops=t_short)
lower = [0,0,0,0]
upper = [1,1,1,1]
splits = ([0,0.3,0.7],[0,0.3,0.7],[0,0.3,0.7],[0,0.3,0.7])
@time root, x0 = analyze(obj_short,splits,lower,upper)
```
```julia
minimum(root)
```
```julia
obj = build_loss_objective(prob,Vern9(),L2Loss(t,data),tstops=t,reltol=1e-9,abstol=1e-9)
lower = [0,0,0,0]
upper = [5,5,5,5]
splits = ([0,0.5,1],[0,0.5,1],[0,0.5,1],[0,0.5,1])
@time root, x0 = analyze(obj_short,splits,lower,upper)
```
```julia
minimum(root)
```
# Conclusion
It is observed that lower tolerance lead to higher accuracy but too low tolerance could affect the convergance time drastically. Also fitting a shorter timespan seems to be easier in comparision (quite intutively). NLOpt methods seem to give great accuracy in the shorter problem with a lot of the algorithms giving 0 fitness, BBO performs very well on it with marginal change with tol values. In case of global optimization of the longer problem there is some difference in the perfomance amongst the algorithms with :LN_BOBYQA giving accurate results for the local optimization and :GN_ISRES :GN_CRS2_LM in case of the global give the highest accuracy. BBO also fails to perform too well in the case of the longer problem. QuadDIRECT performs well in case of the shorter problem but fails to give good results in the longer version.
```julia, echo = false
using SciMLBenchmarks
SciMLBenchmarks.bench_footer(WEAVE_ARGS[:folder],WEAVE_ARGS[:file])
```
| SciMLBenchmarks | https://github.com/SciML/SciMLBenchmarks.jl.git |
|
[
"MIT"
] | 0.1.3 | f4076dd5a103010d48bb6c4e50c5526f6622fa96 | docs | 14845 | ---
title: Lorenz Parameter Estimation Benchmarks
author: finmod, Chris Rackauckas, Vaibhav Dixit
---
# Estimate the parameters of the Lorenz system from the dataset
Note: If data is generated with a fixed time step method and then is tested against with the same time step, there is a biased introduced since it's no longer about hitting the true solution, rather it's just about retreiving the same values that the ODE was first generated by! Thus this version uses adaptive timestepping for all portions so that way tests are against the true solution.
```julia
using ParameterizedFunctions, OrdinaryDiffEq, DiffEqParamEstim
using BlackBoxOptim, NLopt, Plots, QuadDIRECT
gr(fmt=:png)
```
```julia
Xiang2015Bounds = Tuple{Float64, Float64}[(9, 11), (20, 30), (2, 3)] # for local optimizations
xlow_bounds = [9.0,20.0,2.0]
xhigh_bounds = [11.0,30.0,3.0]
LooserBounds = Tuple{Float64, Float64}[(0, 22), (0, 60), (0, 6)] # for global optimization
GloIniPar = [0.0, 0.5, 0.1] # for global optimizations
LocIniPar = [9.0, 20.0, 2.0] # for local optimization
```
```julia
g1 = @ode_def LorenzExample begin
dx = σ*(y-x)
dy = x*(ρ-z) - y
dz = x*y - β*z
end σ ρ β
p = [10.0,28.0,2.66] # Parameters used to construct the dataset
r0 = [1.0; 0.0; 0.0] #[-11.8,-5.1,37.5] PODES Initial values of the system in space # [0.1, 0.0, 0.0]
tspan = (0.0, 30.0) # PODES sample of 3000 observations over the (0,30) timespan
prob = ODEProblem(g1, r0, tspan,p)
tspan2 = (0.0, 3.0) # Xiang test sample of 300 observations with a timestep of 0.01
prob_short = ODEProblem(g1, r0, tspan2,p)
```
```julia
dt = 30.0/3000
tf = 30.0
tinterval = 0:dt:tf
t = collect(tinterval)
```
```julia
h = 0.01
M = 300
tstart = 0.0
tstop = tstart + M * h
tinterval_short = 0:h:tstop
t_short = collect(tinterval_short)
```
```julia
# Generate Data
data_sol_short = solve(prob_short,Vern9(),saveat=t_short,reltol=1e-9,abstol=1e-9)
data_short = convert(Array, data_sol_short) # This operation produces column major dataset obs as columns, equations as rows
data_sol = solve(prob,Vern9(),saveat=t,reltol=1e-9,abstol=1e-9)
data = convert(Array, data_sol)
```
Plot the data
```julia
plot(data_sol_short,vars=(1,2,3)) # the short solution
plot(data_sol,vars=(1,2,3)) # the longer solution
interpolation_sol = solve(prob,Vern7(),saveat=t,reltol=1e-12,abstol=1e-12)
plot(interpolation_sol,vars=(1,2,3))
```
```julia
xyzt = plot(data_sol_short, plotdensity=10000,lw=1.5)
xy = plot(data_sol_short, plotdensity=10000, vars=(1,2))
xz = plot(data_sol_short, plotdensity=10000, vars=(1,3))
yz = plot(data_sol_short, plotdensity=10000, vars=(2,3))
xyz = plot(data_sol_short, plotdensity=10000, vars=(1,2,3))
plot(plot(xyzt,xyz),plot(xy, xz, yz, layout=(1,3),w=1), layout=(2,1), size=(800,600))
```
```julia
xyzt = plot(data_sol, plotdensity=10000,lw=1.5)
xy = plot(data_sol, plotdensity=10000, vars=(1,2))
xz = plot(data_sol, plotdensity=10000, vars=(1,3))
yz = plot(data_sol, plotdensity=10000, vars=(2,3))
xyz = plot(data_sol, plotdensity=10000, vars=(1,2,3))
plot(plot(xyzt,xyz),plot(xy, xz, yz, layout=(1,3),w=1), layout=(2,1), size=(800,600))
```
## Find a local solution for the three parameters from a short data set
```julia
obj_short = build_loss_objective(prob_short,Tsit5(),L2Loss(t_short,data_short),tstops=t_short)
res1 = bboptimize(obj_short;SearchRange = LooserBounds, MaxSteps = 7e3)
# Tolernace is still too high to get close enough
```
```julia
obj_short = build_loss_objective(prob_short,Tsit5(),L2Loss(t_short,data_short),tstops=t_short,reltol=1e-9)
res1 = bboptimize(obj_short;SearchRange = LooserBounds, MaxSteps = 7e3)
# With the tolerance lower, it achieves the correct solution in 3.5 seconds.
```
```julia
obj_short = build_loss_objective(prob_short,Vern9(),L2Loss(t_short,data_short),tstops=t_short,reltol=1e-9,abstol=1e-9)
res1 = bboptimize(obj_short;SearchRange = LooserBounds, MaxSteps = 7e3)
# With the more accurate solver Vern9 in the solution of the ODE, the convergence is less efficient!
# Fastest BlackBoxOptim: 3.5 seconds
```
# Using NLopt
First, the global optimization algorithms
```julia
obj_short = build_loss_objective(prob_short,Vern9(),L2Loss(t_short,data_short),tstops=t_short,reltol=1e-9,abstol=1e-9)
```
```julia
opt = Opt(:GN_ORIG_DIRECT_L, 3)
lower_bounds!(opt,[0.0,0.0,0.0])
upper_bounds!(opt,[22.0,60.0,6.0])
min_objective!(opt, obj_short.cost_function2)
xtol_rel!(opt,1e-12)
maxeval!(opt, 10000)
@time (minf,minx,ret) = NLopt.optimize(opt,GloIniPar) # Accurate 3.2 seconds
```
```julia
opt = Opt(:GN_CRS2_LM, 3)
lower_bounds!(opt,[0.0,0.0,0.0])
upper_bounds!(opt,[22.0,60.0,6.0])
min_objective!(opt, obj_short.cost_function2)
xtol_rel!(opt,1e-12)
maxeval!(opt, 10000)
@time (minf,minx,ret) = NLopt.optimize(opt,GloIniPar) # Accurate 3.0 seconds
```
```julia
opt = Opt(:GN_ISRES, 3)
lower_bounds!(opt,[0.0,0.0,0.0])
upper_bounds!(opt,[22.0,60.0,6.0])
min_objective!(opt, obj_short.cost_function2)
xtol_rel!(opt,1e-12)
maxeval!(opt, 10000)
@time (minf,minx,ret) = NLopt.optimize(opt,GloIniPar) # Accurate to single precision 8.2 seconds
```
```julia
opt = Opt(:GN_ESCH, 3)
lower_bounds!(opt,[0.0,0.0,0.0])
upper_bounds!(opt,[22.0,60.0,6.0])
min_objective!(opt, obj_short.cost_function2)
xtol_rel!(opt,1e-12)
maxeval!(opt, 10000)
@time (minf,minx,ret) = NLopt.optimize(opt,GloIniPar) # Approximatively accurate, good starting values for local optimization
```
Next, the local optimization algorithms that could be used after the global algorithms as a check on the solution and its precision. All the local optimizers are started from LocIniPar and with the narrow bounds of the Xiang2015Paper.
```julia
opt = Opt(:LN_BOBYQA, 3)
lower_bounds!(opt,[9.0,20.0,2.0])
upper_bounds!(opt,[11.0,30.0,3.0])
min_objective!(opt, obj_short.cost_function2)
xtol_rel!(opt,1e-12)
maxeval!(opt, 10000)
@time (minf,minx,ret) = NLopt.optimize(opt,LocIniPar) # 0.1 seconds
```
```julia
opt = Opt(:LN_NELDERMEAD, 3)
lower_bounds!(opt,[9.0,20.0,2.0])
upper_bounds!(opt,[11.0,30.0,3.0])
min_objective!(opt, obj_short.cost_function2)
xtol_rel!(opt,1e-12)
maxeval!(opt, 10000)
@time (minf,minx,ret) = NLopt.optimize(opt,LocIniPar) # Accurate 0.29 sec
```
```julia
opt = Opt(:LD_SLSQP, 3)
lower_bounds!(opt,[9.0,20.0,2.0])
upper_bounds!(opt,[11.0,30.0,3.0])
min_objective!(opt, obj_short.cost_function2)
xtol_rel!(opt,1e-12)
maxeval!(opt, 10000)
@time (minf,minx,ret) = NLopt.optimize(opt,LocIniPar) # Accurate 0.21 sec
```
```julia
opt = Opt(:LN_COBYLA, 3)
lower_bounds!(opt,[9.0,20.0,2.0])
upper_bounds!(opt,[11.0,30.0,3.0])
min_objective!(opt, obj_short.cost_function2)
xtol_rel!(opt,1e-12)
maxeval!(opt, 10000)
@time (minf,minx,ret) = NLopt.optimize(opt,LocIniPar) # Accurate 1.84 sec
```
```julia
opt = Opt(:LN_NEWUOA_BOUND, 3)
lower_bounds!(opt,[9.0,20.0,2.0])
upper_bounds!(opt,[11.0,30.0,3.0])
min_objective!(opt, obj_short.cost_function2)
xtol_rel!(opt,1e-12)
maxeval!(opt, 10000)
@time (minf,minx,ret) = NLopt.optimize(opt,LocIniPar) # Accurate 0.18 sec ROUNDOFF LIMITED
```
```julia
opt = Opt(:LN_PRAXIS, 3)
lower_bounds!(opt,[9.0,20.0,2.0])
upper_bounds!(opt,[11.0,30.0,3.0])
min_objective!(opt, obj_short.cost_function2)
xtol_rel!(opt,1e-12)
maxeval!(opt, 10000)
@time (minf,minx,ret) = NLopt.optimize(opt,LocIniPar) # Accurate 0.18 sec
```
```julia
opt = Opt(:LN_SBPLX, 3)
lower_bounds!(opt,[9.0,20.0,2.0])
upper_bounds!(opt,[11.0,30.0,3.0])
min_objective!(opt, obj_short.cost_function2)
xtol_rel!(opt,1e-12)
maxeval!(opt, 10000)
@time (minf,minx,ret) = NLopt.optimize(opt,LocIniPar) # Accurate 0.65 sec
```
```julia
opt = Opt(:LD_MMA, 3)
lower_bounds!(opt,[9.0,20.0,2.0])
upper_bounds!(opt,[11.0,30.0,3.0])
min_objective!(opt, obj_short.cost_function2)
xtol_rel!(opt,1e-12)
maxeval!(opt, 10000)
@time (minf,minx,ret) = NLopt.optimize(opt,LocIniPar) # Accurate 0.7 sec
```
```julia
opt = Opt(:LD_LBFGS, 3)
lower_bounds!(opt,[9.0,20.0,2.0])
upper_bounds!(opt,[11.0,30.0,3.0])
min_objective!(opt, obj_short.cost_function2)
xtol_rel!(opt,1e-12)
maxeval!(opt, 10000)
@time (minf,minx,ret) = NLopt.optimize(opt,LocIniPar) # Accurate 0.12 sec
```
```julia
opt = Opt(:LD_TNEWTON_PRECOND_RESTART, 3)
lower_bounds!(opt,[9.0,20.0,2.0])
upper_bounds!(opt,[11.0,30.0,3.0])
min_objective!(opt, obj_short.cost_function2)
xtol_rel!(opt,1e-12)
maxeval!(opt, 10000)
@time (minf,minx,ret) = NLopt.optimize(opt,LocIniPar) # Accurate 0.15 sec
```
## Now let's solve the longer version for a global solution
Notice from the plotting above that this ODE problem is chaotic and tends to diverge over time. In the longer version of parameter estimation, the dataset is increased to 3000 observations per variable with the same integration time step of 0.01.
Vern9 solver with reltol=1e-9 and abstol=1e-9 has been established to be accurate on the time interval [0,50]
```julia
# BB with Vern9 converges very slowly. The final values are within the NarrowBounds.
obj = build_loss_objective(prob,Vern9(),L2Loss(t,data),tstops=t,reltol=1e-9,abstol=1e-9)
res1 = bboptimize(obj;SearchRange = LooserBounds, MaxSteps = 4e3) # Default adaptive_de_rand_1_bin_radiuslimited 33 sec [10.2183, 24.6711, 2.28969]
#res1 = bboptimize(obj;SearchRange = LooserBounds, Method = :adaptive_de_rand_1_bin, MaxSteps = 4e3) # Method 32 sec [13.2222, 25.8589, 2.56176]
#res1 = bboptimize(obj;SearchRange = LooserBounds, Method = :dxnes, MaxSteps = 2e3) # Method dxnes 119 sec [16.8648, 24.393, 2.29119]
#res1 = bboptimize(obj;SearchRange = LooserBounds, Method = :xnes, MaxSteps = 2e3) # Method xnes 304 sec [19.1647, 24.9479, 2.39467]
#res1 = bboptimize(obj;SearchRange = LooserBounds, Method = :de_rand_1_bin_radiuslimited, MaxSteps = 2e3) # Method 44 sec [13.805, 24.6054, 2.37274]
#res1 = bboptimize(obj;SearchRange = LooserBounds, Method = :generating_set_search, MaxSteps = 2e3) # Method 195 sec [19.1847, 24.9492, 2.39412]
```
```julia
# using Evolutionary
# N = 3
# @time result, fitness, cnt = cmaes(obj, N; μ = 3, λ = 12, iterations = 1000) # cmaes( rastrigin, N; μ = 15, λ = P, tol = 1e-8)
```
```julia
opt = Opt(:GN_ORIG_DIRECT_L, 3)
lower_bounds!(opt,[0.0,0.0,0.0])
upper_bounds!(opt,[22.0,60.0,6.0])
min_objective!(opt, obj.cost_function2)
xtol_rel!(opt,1e-12)
maxeval!(opt, 10000)
@time (minf,minx,ret) = NLopt.optimize(opt,GloIniPar) # Fail to converge
```
```julia
opt = Opt(:GN_CRS2_LM, 3)
lower_bounds!(opt,[0.0,0.0,0.0])
upper_bounds!(opt,[22.0,60.0,6.0])
min_objective!(opt, obj.cost_function2)
xtol_rel!(opt,1e-12)
maxeval!(opt, 20000)
@time (minf,minx,ret) = NLopt.optimize(opt,GloIniPar) # Hit and miss. converge approximately accurate values for local opt.91 seconds
```
```julia
opt = Opt(:GN_ISRES, 3)
lower_bounds!(opt,[0.0,0.0,0.0])
upper_bounds!(opt,[22.0,60.0,6.0])
min_objective!(opt, obj.cost_function2)
xtol_rel!(opt,1e-12)
maxeval!(opt, 50000)
@time (minf,minx,ret) = NLopt.optimize(opt,GloIniPar) # Approximately accurate within local bounds
```
```julia
opt = Opt(:GN_ESCH, 3)
lower_bounds!(opt,[0.0,0.0,0.0])
upper_bounds!(opt,[22.0,60.0,6.0])
min_objective!(opt, obj.cost_function2)
xtol_rel!(opt,1e-12)
maxeval!(opt, 20000)
@time (minf,minx,ret) = NLopt.optimize(opt,GloIniPar) # Approximately accurate
```
This parameter estimation on the longer sample proves to be extremely challenging for the global optimizers. BlackBoxOptim is best in optimizing the objective function. All of the global algorithms produces final parameter estimates that could be used as starting values for further refinement with the local optimization algorithms.
```julia
opt = Opt(:LN_BOBYQA, 3)
lower_bounds!(opt,[9.0,20.0,2.0])
upper_bounds!(opt,[11.0,30.0,3.0])
min_objective!(opt, obj.cost_function2)
xtol_rel!(opt,1e-12)
maxeval!(opt, 10000)
@time (minf,minx,ret) = NLopt.optimize(opt,LocIniPar) # Claims SUCCESS but does not iterate to the true values.
```
```julia
opt = Opt(:LN_NELDERMEAD, 3)
lower_bounds!(opt,[9.0,20.0,2.0])
upper_bounds!(opt,[11.0,30.0,3.0])
min_objective!(opt, obj.cost_function2)
xtol_rel!(opt,1e-9)
maxeval!(opt, 10000)
@time (minf,minx,ret) = NLopt.optimize(opt,LocIniPar) # Inaccurate final values
```
```julia
opt = Opt(:LD_SLSQP, 3)
lower_bounds!(opt,[9.0,20.0,2.0])
upper_bounds!(opt,[11.0,30.0,3.0])
min_objective!(opt, obj.cost_function2)
xtol_rel!(opt,1e-12)
maxeval!(opt, 10000)
@time (minf,minx,ret) = NLopt.optimize(opt,LocIniPar) # Inaccurate final values
```
No local optimizer can improve the global solution to the true values.
#### Using QuadDIRECT
```julia
obj_short = build_loss_objective(prob_short,Tsit5(),L2Loss(t_short,data_short),tstops=t_short)
lower = [0.0,0.0,0.0]
upper = [50.0,50.0,50.0]
splits = ([1.0,5.0,15.0],[0,10,20],[0,10,20])
@time root, x0 = analyze(obj_short,splits,lower,upper)
```
```julia
minimum(root)
```
```julia
obj = build_loss_objective(prob,Vern9(),L2Loss(t,data),tstops=t,reltol=1e-9,abstol=1e-9)
lower = [0.0,0.0,0.0]
upper = [50.0,50.0,50.0]
splits = ([0,5.0,15.0],[0,15,30],[0,2,5])
@time root, x0 = analyze(obj,splits,lower,upper)
```
```julia
minimum(root)
```
# Conclusion:
1) As expected the Lorenz system is extremely sensitive to initial space values. Starting the integration from `r0 = [0.1,0.0,0.0]` produces convergence with the short sample of 300 observations. This can be achieved by all the global optimizers as well as most of the local optimizers. Instead starting from `r0= [-11.8,-5.1,37.5]`, as in PODES, with the shorter sample shrinks the number of successful algorithms to 3: `BBO`, `:GN_CRS2_LM `and `:LD_SLSQP`. For the longer sample, all the algorithms fail.
2) When trying to hit the real data, having a low enough tolerance on the numerical solution is key. If the numerical solution is too rough, then we can never actually hone in on the true parameters since even with the true parameters we will erroneously induce numerical error. Maybe this could be adaptive?
3) Excessively low tolerance in the numerical solution is inefficient and delays the convergence of the estimation.
4) The estimation method and the global versus local optimization make a huge difference in the timings. Here, BBO always find the correct solution for a global optimization setup. For local optimization, most methods in NLopt, like :LN_BOBYQA, solve the problem in <0.05 seconds. This is an algorithm that can scale a local optimization but we are aiming to scale a global optimization.
5) QuadDIRECT performs very well on the shorter problem but doesn't give very great results for the longer in the Lorenz case, more can be read about the algorithm [here](https://github.com/timholy/QuadDIRECT.jl).
6) Fitting shorter timespans is easier... maybe this can lead to determining a minimal sample size for the optimizers and the estimator to succeed.
```julia, echo = false
using SciMLBenchmarks
SciMLBenchmarks.bench_footer(WEAVE_ARGS[:folder],WEAVE_ARGS[:file])
```
| SciMLBenchmarks | https://github.com/SciML/SciMLBenchmarks.jl.git |
|
[
"MIT"
] | 0.1.3 | f4076dd5a103010d48bb6c4e50c5526f6622fa96 | docs | 10124 | ---
title: Lotka-Volterra Parameter Estimation Benchmarks
author: Vaibhav Dixit, Chris Rackauckas
---
# Parameter estimation of Lotka Volterra model using optimisation methods
```julia
using ParameterizedFunctions, OrdinaryDiffEq, DiffEqParamEstim
using BlackBoxOptim, NLopt, Plots, RecursiveArrayTools, QuadDIRECT
gr(fmt=:png)
```
```julia
loc_bounds = Tuple{Float64, Float64}[(0, 5), (0, 5), (0, 5), (0, 5)]
glo_bounds = Tuple{Float64, Float64}[(0, 10), (0, 10), (0, 10), (0, 10)]
loc_init = [1,0.5,3.5,1.5]
glo_init = [5,5,5,5]
```
```julia
f = @ode_def LotkaVolterraTest begin
dx = a*x - b*x*y
dy = -c*y + d*x*y
end a b c d
```
```julia
u0 = [1.0,1.0] #initial values
tspan = (0.0,10.0)
p = [1.5,1.0,3.0,1,0] #parameters used, these need to be estimated from the data
tspan = (0.0, 30.0) # sample of 3000 observations over the (0,30) timespan
prob = ODEProblem(f, u0, tspan,p)
tspan2 = (0.0, 3.0) # sample of 3000 observations over the (0,30) timespan
prob_short = ODEProblem(f, u0, tspan2,p)
```
```julia
dt = 30.0/3000
tf = 30.0
tinterval = 0:dt:tf
t = collect(tinterval)
```
```julia
h = 0.01
M = 300
tstart = 0.0
tstop = tstart + M * h
tinterval_short = 0:h:tstop
t_short = collect(tinterval_short)
```
```julia
#Generate Data
data_sol_short = solve(prob_short,Tsit5(),saveat=t_short,reltol=1e-9,abstol=1e-9)
data_short = convert(Array, data_sol_short)
data_sol = solve(prob,Tsit5(),saveat=t,reltol=1e-9,abstol=1e-9)
data = convert(Array, data_sol)
```
#### Plot of the solution
##### Short Solution
```julia
p1 = plot(data_sol_short)
```
##### Longer Solution
```julia
p2 = plot(data_sol)
```
### Local Solution from the short data set
```julia
obj_short = build_loss_objective(prob_short,Tsit5(),L2Loss(t_short,data_short),tstops=t_short)
res1 = bboptimize(obj_short;SearchRange = glo_bounds, MaxSteps = 7e3)
# Lower tolerance could lead to smaller fitness (more accuracy)
```
```julia
obj_short = build_loss_objective(prob_short,Tsit5(),L2Loss(t_short,data_short),tstops=t_short,reltol=1e-9)
res1 = bboptimize(obj_short;SearchRange = glo_bounds, MaxSteps = 7e3)
# Change in tolerance makes it worse
```
```julia
obj_short = build_loss_objective(prob_short,Vern9(),L2Loss(t_short,data_short),tstops=t_short,reltol=1e-9,abstol=1e-9)
res1 = bboptimize(obj_short;SearchRange = glo_bounds, MaxSteps = 7e3)
# using the moe accurate Vern9() reduces the fitness marginally and leads to some increase in time taken
```
# Using NLopt
#### Global Optimisation first
```julia
obj_short = build_loss_objective(prob_short,Vern9(),L2Loss(t_short,data_short),tstops=t_short,reltol=1e-9,abstol=1e-9)
```
```julia
opt = Opt(:GN_ORIG_DIRECT_L, 4)
lower_bounds!(opt,[0.0,0.0,0.0,0.0])
upper_bounds!(opt,[10.0,10.0,10.0,10.0])
min_objective!(opt, obj_short.cost_function2)
xtol_rel!(opt,1e-12)
maxeval!(opt, 10000)
@time (minf,minx,ret) = NLopt.optimize(opt,glo_init)
```
```julia
opt = Opt(:GN_CRS2_LM, 4)
lower_bounds!(opt,[0.0,0.0,0.0,0.0])
upper_bounds!(opt,[10.0,10.0,10.0,10.0])
min_objective!(opt, obj_short.cost_function2)
xtol_rel!(opt,1e-12)
maxeval!(opt, 10000)
@time (minf,minx,ret) = NLopt.optimize(opt,glo_init)
```
```julia
opt = Opt(:GN_ISRES, 4)
lower_bounds!(opt,[0.0,0.0,0.0,0.0])
upper_bounds!(opt,[10.0,10.0,10.0,10.0])
min_objective!(opt, obj_short.cost_function2)
xtol_rel!(opt,1e-12)
maxeval!(opt, 10000)
@time (minf,minx,ret) = NLopt.optimize(opt,glo_init)
```
```julia
opt = Opt(:GN_ESCH, 4)
lower_bounds!(opt,[0.0,0.0,0.0,0.0])
upper_bounds!(opt,[10.0,10.0,10.0,10.0])
min_objective!(opt, obj_short.cost_function2)
xtol_rel!(opt,1e-12)
maxeval!(opt, 10000)
@time (minf,minx,ret) = NLopt.optimize(opt,glo_init)
```
Now local optimization algorithms are used to check the global ones, these use the local constraints, different intial values and time step
```julia
opt = Opt(:LN_BOBYQA, 4)
lower_bounds!(opt,[0.0,0.0,0.0,0.0])
upper_bounds!(opt,[5.0,5.0,5.0,5.0])
min_objective!(opt, obj_short.cost_function2)
xtol_rel!(opt,1e-12)
maxeval!(opt, 10000)
@time (minf,minx,ret) = NLopt.optimize(opt,loc_init)
```
```julia
opt = Opt(:LN_NELDERMEAD, 4)
lower_bounds!(opt,[0.0,0.0,0.0,0.0])
upper_bounds!(opt,[5.0,5.0,5.0,5.0])
min_objective!(opt, obj_short.cost_function2)
xtol_rel!(opt,1e-12)
maxeval!(opt, 10000)
@time (minf,minx,ret) = NLopt.optimize(opt,loc_init)
```
```julia
opt = Opt(:LD_SLSQP, 4)
lower_bounds!(opt,[0.0,0.0,0.0,0.0])
upper_bounds!(opt,[5.0,5.0,5.0,5.0])
min_objective!(opt, obj_short.cost_function2)
xtol_rel!(opt,1e-12)
maxeval!(opt, 10000)
@time (minf,minx,ret) = NLopt.optimize(opt,loc_init)
```
```julia
opt = Opt(:LN_COBYLA, 4)
lower_bounds!(opt,[0.0,0.0,0.0,0.0])
upper_bounds!(opt,[5.0,5.0,5.0,5.0])
min_objective!(opt, obj_short.cost_function2)
xtol_rel!(opt,1e-12)
maxeval!(opt, 10000)
@time (minf,minx,ret) = NLopt.optimize(opt,loc_init)
```
```julia
opt = Opt(:LN_NEWUOA_BOUND, 4)
lower_bounds!(opt,[0.0,0.0,0.0,0.0])
upper_bounds!(opt,[5.0,5.0,5.0,5.0])
min_objective!(opt, obj_short.cost_function2)
xtol_rel!(opt,1e-12)
maxeval!(opt, 10000)
@time (minf,minx,ret) = NLopt.optimize(opt,loc_init)
```
```julia
opt = Opt(:LN_PRAXIS, 4)
lower_bounds!(opt,[0.0,0.0,0.0,0.0])
upper_bounds!(opt,[5.0,5.0,5.0,5.0])
min_objective!(opt, obj_short.cost_function2)
xtol_rel!(opt,1e-12)
maxeval!(opt, 10000)
@time (minf,minx,ret) = NLopt.optimize(opt,loc_init)
```
```julia
opt = Opt(:LN_SBPLX, 4)
lower_bounds!(opt,[0.0,0.0,0.0,0.0])
upper_bounds!(opt,[5.0,5.0,5.0,5.0])
min_objective!(opt, obj_short.cost_function2)
xtol_rel!(opt,1e-12)
maxeval!(opt, 10000)
@time (minf,minx,ret) = NLopt.optimize(opt,loc_init)
```
```julia
opt = Opt(:LD_MMA, 4)
lower_bounds!(opt,[0.0,0.0,0.0,0.0])
upper_bounds!(opt,[5.0,5.0,5.0,5.0])
min_objective!(opt, obj_short.cost_function2)
xtol_rel!(opt,1e-12)
maxeval!(opt, 10000)
@time (minf,minx,ret) = NLopt.optimize(opt,loc_init)
```
```julia
opt = Opt(:LD_TNEWTON_PRECOND_RESTART, 4)
lower_bounds!(opt,[0.0,0.0,0.0,0.0])
upper_bounds!(opt,[5.0,5.0,5.0,5.0])
min_objective!(opt, obj_short.cost_function2)
xtol_rel!(opt,1e-12)
maxeval!(opt, 10000)
@time (minf,minx,ret) = NLopt.optimize(opt,loc_init)
```
## Now the longer problem is solved for a global solution
Vern9 solver with reltol=1e-9 and abstol=1e-9 is used and the dataset is increased to 3000 observations per variable with the same integration time step of 0.01.
```julia
obj = build_loss_objective(prob,Vern9(),L2Loss(t,data),tstops=t,reltol=1e-9,abstol=1e-9)
res1 = bboptimize(obj;SearchRange = glo_bounds, MaxSteps = 4e3)
```
```julia
opt = Opt(:GN_ORIG_DIRECT_L, 4)
lower_bounds!(opt,[0.0,0.0,0.0,0.0])
upper_bounds!(opt,[10.0,10.0,10.0,10.0])
min_objective!(opt, obj.cost_function2)
xtol_rel!(opt,1e-12)
maxeval!(opt, 10000)
@time (minf,minx,ret) = NLopt.optimize(opt,glo_init)
```
```julia
opt = Opt(:GN_CRS2_LM, 4)
lower_bounds!(opt,[0.0,0.0,0.0,0.0])
upper_bounds!(opt,[10.0,10.0,10.0,10.0])
min_objective!(opt, obj.cost_function2)
xtol_rel!(opt,1e-12)
maxeval!(opt, 20000)
@time (minf,minx,ret) = NLopt.optimize(opt,glo_init)
```
```julia
opt = Opt(:GN_ISRES, 4)
lower_bounds!(opt,[0.0,0.0,0.0,0.0])
upper_bounds!(opt,[10.0,10.0,10.0,10.0])
min_objective!(opt, obj.cost_function2)
xtol_rel!(opt,1e-12)
maxeval!(opt, 50000)
@time (minf,minx,ret) = NLopt.optimize(opt,glo_init)
```
```julia
opt = Opt(:GN_ESCH, 4)
lower_bounds!(opt,[0.0,0.0,0.0,0.0])
upper_bounds!(opt,[10.0,10.0,10.0,10.0])
min_objective!(opt, obj.cost_function2)
xtol_rel!(opt,1e-12)
maxeval!(opt, 20000)
@time (minf,minx,ret) = NLopt.optimize(opt,glo_init)
```
```julia
opt = Opt(:LN_BOBYQA, 4)
lower_bounds!(opt,[0.0,0.0,0.0,0.0])
upper_bounds!(opt,[5.0,5.0,5.0,5.0])
min_objective!(opt, obj.cost_function2)
xtol_rel!(opt,1e-12)
maxeval!(opt, 10000)
@time (minf,minx,ret) = NLopt.optimize(opt,loc_init)
```
```julia
opt = Opt(:LN_NELDERMEAD, 4)
lower_bounds!(opt,[0.0,0.0,0.0,0.0])
upper_bounds!(opt,[5.0,5.0,5.0,5.0])
min_objective!(opt, obj.cost_function2)
xtol_rel!(opt,1e-9)
maxeval!(opt, 10000)
@time (minf,minx,ret) = NLopt.optimize(opt,loc_init)
```
```julia
opt = Opt(:LD_SLSQP, 4)
lower_bounds!(opt,[0.0,0.0,0.0,0.0])
upper_bounds!(opt,[5.0,5.0,5.0,5.0])
min_objective!(opt, obj.cost_function2)
xtol_rel!(opt,1e-12)
maxeval!(opt, 10000)
@time (minf,minx,ret) = NLopt.optimize(opt,loc_init)
```
#### Using QuadDIRECT
```julia
obj_short = build_loss_objective(prob_short,Tsit5(),L2Loss(t_short,data_short),tstops=t_short)
lower = [0.0,0.0,0.0,0.0]
upper = [5.0,5.0,5.0,5.0]
splits = ([0.0,1.0,3.0],[0.0,1.0,3.0],[0.0,1.0,3.0],[0.0,1.0,3.0])
root, x0 = analyze(obj_short,splits,lower,upper)
```
```julia
minimum(root)
```
```julia
obj = build_loss_objective(prob,Vern9(),L2Loss(t,data),tstops=t,reltol=1e-9,abstol=1e-9)
lower = [0.0,0.0,0.0,0.0]
upper = [10.0,10.0,10.0,10.0]
splits = ([0.0,3.0,6.0],[0.0,3.0,6.0],[0.0,3.0,6.0],[0.0,3.0,6.0])
root, x0 = analyze(obj,splits,lower,upper)
```
```julia
minimum(root)
```
#### Parameter estimation on the longer sample proves to be extremely challenging for some of the global optimizers. A few give the accurate values, BlacBoxOptim also performs quite well while others seem to struggle with accuracy a lot.
# Conclusion
In general we observe that lower tolerance lead to higher accuracy but too low tolerance could affect the convergance time drastically. Also fitting a shorter timespan seems to be easier in comparision (quite intutively). NLOpt methods seem to give great accuracy in the shorter problem with a lot of the algorithms giving 0 fitness, BBO performs very well on it with marginal change with `tol` values. In case of global optimization of the longer problem there is some difference in the perfomance amongst the algorithms with `LD_SLSQP` `GN_ESCH` `GN_ISRES` `GN_ORIG_DIRECT_L` performing among the worse, BBO also gives a bit high fitness in comparison. QuadDIRECT gives accurate results in the case of the shorter problem but doesn't perform very well in the longer problem case.
```julia, echo = false
using SciMLBenchmarks
SciMLBenchmarks.bench_footer(WEAVE_ARGS[:folder],WEAVE_ARGS[:file])
```
| SciMLBenchmarks | https://github.com/SciML/SciMLBenchmarks.jl.git |
|
[
"MIT"
] | 0.1.3 | f4076dd5a103010d48bb6c4e50c5526f6622fa96 | docs | 10127 | ---
title: Quorum Sensing Work-Precision Diagrams
author: David Widmann, Chris Rackauckas
---
# Quorum Sensing
Here we test a model of quorum sensing of Pseudomonas putida IsoF in continuous cultures with constant
delay which was published by K. Buddrus-Schiemann et al. in "Analysis of N-Acylhomoserine Lactone Dynamics in Continuous
Cultures of Pseudomonas Putida IsoF By Use of ELISA and UHPLC/qTOF-MS-derived Measurements
and Mathematical Models", Analytical and Bioanalytical Chemistry, 2014.
```julia
using DelayDiffEq, DiffEqDevTools, DDEProblemLibrary, Plots
import DDEProblemLibrary: prob_dde_qs
gr()
sol = solve(prob_dde_qs, MethodOfSteps(Vern9(); fpsolve = NLFunctional(; max_iter = 1000)); reltol=1e-14, abstol=1e-14)
plot(sol)
```
Particularly, we are interested in the third, low-level component of the system:
```julia
sol = solve(prob_dde_qs, MethodOfSteps(Vern9(); fpsolve = NLFunctional(; max_iter = 1000)); reltol=1e-14, abstol=1e-14, save_idxs=3)
test_sol = TestSolution(sol)
plot(sol)
```
## Qualitative comparisons
First we compare the quality of the solution's third component for different algorithms, using the default tolerances.
### RK methods
```julia
sol = solve(prob_dde_qs, MethodOfSteps(BS3()); reltol=1e-3, abstol=1e-6, save_idxs=3)
p = plot(sol);
scatter!(p,sol.t, sol.u)
p
```
```julia
sol = solve(prob_dde_qs, MethodOfSteps(Tsit5()); reltol=1e-3, abstol=1e-6, save_idxs=3)
p = plot(sol);
scatter!(p,sol.t, sol.u)
p
```
```julia
sol = solve(prob_dde_qs, MethodOfSteps(RK4()); reltol=1e-3, abstol=1e-6, save_idxs=3)
p = plot(sol);
scatter!(p,sol.t, sol.u)
p
```
```julia
sol = solve(prob_dde_qs, MethodOfSteps(DP5()); reltol=1e-3, abstol=1e-6, save_idxs=3)
p = plot(sol);
scatter!(p,sol.t, sol.u)
p
```
```julia
sol = solve(prob_dde_qs, MethodOfSteps(DP8()); reltol=1e-3, abstol=1e-6, save_idxs=3)
p = plot(sol);
scatter!(p,sol.t, sol.u)
p
```
```julia
sol = solve(prob_dde_qs, MethodOfSteps(OwrenZen3()); reltol=1e-3, abstol=1e-6, save_idxs=3)
p = plot(sol);
scatter!(p,sol.t, sol.u)
p
```
```julia
sol = solve(prob_dde_qs, MethodOfSteps(OwrenZen4()); reltol=1e-3, abstol=1e-6, save_idxs=3)
p = plot(sol);
scatter!(p,sol.t, sol.u)
p
```
```julia
sol = solve(prob_dde_qs, MethodOfSteps(OwrenZen5()); reltol=1e-3, abstol=1e-6, save_idxs=3)
p = plot(sol);
scatter!(p,sol.t, sol.u)
p
```
### Rosenbrock methods
```julia
sol = solve(prob_dde_qs, MethodOfSteps(Rosenbrock23()); reltol=1e-3, abstol=1e-6, save_idxs=3)
p = plot(sol);
scatter!(p,sol.t, sol.u)
p
```
```julia
sol = solve(prob_dde_qs, MethodOfSteps(Rosenbrock32()); reltol=1e-3, abstol=1e-6, save_idxs=3)
p = plot(sol);
scatter!(p,sol.t, sol.u)
p
```
```julia
sol = solve(prob_dde_qs, MethodOfSteps(Rodas4()); reltol=1e-3, abstol=1e-6, save_idxs=3)
p = plot(sol);
scatter!(p,sol.t, sol.u)
p
```
```julia
sol = solve(prob_dde_qs, MethodOfSteps(Rodas5()); reltol=1e-4, abstol=1e-6, save_idxs=3)
p = plot(sol);
scatter!(p,sol.t, sol.u)
p
```
### Lazy interpolants
```julia
sol = solve(prob_dde_qs, MethodOfSteps(Vern7()); reltol=1e-3, abstol=1e-6, save_idxs=3)
p = plot(sol);
scatter!(p,sol.t, sol.u)
p
```
```julia
sol = solve(prob_dde_qs, MethodOfSteps(Vern9()); reltol=1e-3, abstol=1e-6, save_idxs=3)
p = plot(sol);
scatter!(p,sol.t, sol.u)
p
```
## Qualitative comparisons
Now we compare these methods quantitatively.
### High tolerances
#### RK methods
We start with RK methods at high tolerances.
```julia
abstols = 1.0 ./ 10.0 .^ (4:7)
reltols = 1.0 ./ 10.0 .^ (1:4)
setups = [Dict(:alg=>MethodOfSteps(BS3())),
Dict(:alg=>MethodOfSteps(Tsit5())),
Dict(:alg=>MethodOfSteps(RK4())),
Dict(:alg=>MethodOfSteps(DP5())),
Dict(:alg=>MethodOfSteps(OwrenZen3())),
Dict(:alg=>MethodOfSteps(OwrenZen4())),
Dict(:alg=>MethodOfSteps(OwrenZen5()))]
wp = WorkPrecisionSet(prob_dde_qs,abstols,reltols,setups;
save_idxs=3,appxsol=test_sol,maxiters=Int(1e5),error_estimate=:final)
plot(wp)
```
We also compare interpolation errors:
```julia
abstols = 1.0 ./ 10.0 .^ (4:7)
reltols = 1.0 ./ 10.0 .^ (1:4)
setups = [Dict(:alg=>MethodOfSteps(BS3())),
Dict(:alg=>MethodOfSteps(Tsit5())),
Dict(:alg=>MethodOfSteps(RK4())),
Dict(:alg=>MethodOfSteps(DP5())),
Dict(:alg=>MethodOfSteps(OwrenZen3())),
Dict(:alg=>MethodOfSteps(OwrenZen4())),
Dict(:alg=>MethodOfSteps(OwrenZen5()))]
wp = WorkPrecisionSet(prob_dde_qs,abstols,reltols,setups;
save_idxs=3,appxsol=test_sol,maxiters=Int(1e5),error_estimate=:L2)
plot(wp)
```
And the maximal interpolation error:
```julia
abstols = 1.0 ./ 10.0 .^ (4:7)
reltols = 1.0 ./ 10.0 .^ (1:4)
setups = [Dict(:alg=>MethodOfSteps(BS3())),
Dict(:alg=>MethodOfSteps(Tsit5())),
Dict(:alg=>MethodOfSteps(RK4())),
Dict(:alg=>MethodOfSteps(DP5())),
Dict(:alg=>MethodOfSteps(OwrenZen3())),
Dict(:alg=>MethodOfSteps(OwrenZen4())),
Dict(:alg=>MethodOfSteps(OwrenZen5()))]
wp = WorkPrecisionSet(prob_dde_qs,abstols,reltols,setups;
save_idxs=3,appxsol=test_sol,maxiters=Int(1e5),error_estimate=:L∞)
plot(wp)
```
Since the correct solution is in the range of 1e-7, we see that most solutions, even at the lower end of tested tolerances, always lead to relative maximal interpolation errors of at least 1e-1 (and usually worse). `RK4` performs slightly better with relative maximal errors of at least 1e-2. This matches our qualitative analysis above.
#### Rosenbrock methods
We repeat these tests with Rosenbrock methods, and include `RK4` as reference.
```julia
abstols = 1.0 ./ 10.0 .^ (4:7)
reltols = 1.0 ./ 10.0 .^ (1:4)
setups = [Dict(:alg=>MethodOfSteps(Rosenbrock23())),
Dict(:alg=>MethodOfSteps(Rosenbrock32())),
Dict(:alg=>MethodOfSteps(Rodas4())),
Dict(:alg=>MethodOfSteps(RK4()))]
wp = WorkPrecisionSet(prob_dde_qs,abstols,reltols,setups;
save_idxs=3,appxsol=test_sol,maxiters=Int(1e5),error_estimate=:final)
plot(wp)
```
```julia
abstols = 1.0 ./ 10.0 .^ (4:7)
reltols = 1.0 ./ 10.0 .^ (1:4)
setups = [Dict(:alg=>MethodOfSteps(Rosenbrock23())),
Dict(:alg=>MethodOfSteps(Rosenbrock32())),
Dict(:alg=>MethodOfSteps(Rodas4())),
Dict(:alg=>MethodOfSteps(RK4()))]
wp = WorkPrecisionSet(prob_dde_qs,abstols,reltols,setups;
save_idxs=3,appxsol=test_sol,maxiters=Int(1e5),error_estimate=:L2)
plot(wp)
```
```julia
abstols = 1.0 ./ 10.0 .^ (4:7)
reltols = 1.0 ./ 10.0 .^ (1:4)
setups = [Dict(:alg=>MethodOfSteps(Rosenbrock23())),
Dict(:alg=>MethodOfSteps(Rosenbrock32())),
Dict(:alg=>MethodOfSteps(Rodas4())),
Dict(:alg=>MethodOfSteps(RK4()))]
wp = WorkPrecisionSet(prob_dde_qs,abstols,reltols,setups;
save_idxs=3,appxsol=test_sol,maxiters=Int(1e5),error_estimate=:L∞)
plot(wp)
```
Out of the tested Rosenbrock methods `Rodas4` and `Rosenbrock23` perform best at high tolerances.
#### Lazy interpolants
Finally we test the Verner methods with lazy interpolants, and include `Rosenbrock23` as reference.
```julia
abstols = 1.0 ./ 10.0 .^ (4:7)
reltols = 1.0 ./ 10.0 .^ (1:4)
setups = [Dict(:alg=>MethodOfSteps(Vern6())),
Dict(:alg=>MethodOfSteps(Vern7())),
Dict(:alg=>MethodOfSteps(Vern8())),
Dict(:alg=>MethodOfSteps(Vern9())),
Dict(:alg=>MethodOfSteps(Rosenbrock23()))]
wp = WorkPrecisionSet(prob_dde_qs,abstols,reltols,setups;
save_idxs=3,appxsol=test_sol,maxiters=Int(1e5),error_estimate=:final)
plot(wp)
```
```julia
abstols = 1.0 ./ 10.0 .^ (4:7)
reltols = 1.0 ./ 10.0 .^ (1:4)
setups = [Dict(:alg=>MethodOfSteps(Vern6())),
Dict(:alg=>MethodOfSteps(Vern7())),
Dict(:alg=>MethodOfSteps(Vern8())),
Dict(:alg=>MethodOfSteps(Vern9())),
Dict(:alg=>MethodOfSteps(Rosenbrock23()))]
wp = WorkPrecisionSet(prob_dde_qs,abstols,reltols,setups;
save_idxs=3,appxsol=test_sol,maxiters=Int(1e5),error_estimate=:L2)
plot(wp)
```
```julia
abstols = 1.0 ./ 10.0 .^ (4:7)
reltols = 1.0 ./ 10.0 .^ (1:4)
setups = [Dict(:alg=>MethodOfSteps(Vern6())),
Dict(:alg=>MethodOfSteps(Vern7())),
Dict(:alg=>MethodOfSteps(Vern8())),
Dict(:alg=>MethodOfSteps(Vern9())),
Dict(:alg=>MethodOfSteps(Rosenbrock23()))]
wp = WorkPrecisionSet(prob_dde_qs,abstols,reltols,setups;
save_idxs=3,appxsol=test_sol,maxiters=Int(1e5),error_estimate=:L∞)
plot(wp)
```
All in all, at high tolerances `Rodas5` and `Rosenbrock23` are the best methods for solving this stiff DDE.
### Low tolerances
#### Rosenbrock methods
We repeat our tests of Rosenbrock methods `Rosenbrock23` and `Rodas5` at low tolerances:
```julia
abstols = 1.0 ./ 10.0 .^ (8:11)
reltols = 1.0 ./ 10.0 .^ (5:8)
setups = [Dict(:alg=>MethodOfSteps(Rosenbrock23())),
Dict(:alg=>MethodOfSteps(Rodas4())),
Dict(:alg=>MethodOfSteps(Rodas5()))]
wp = WorkPrecisionSet(prob_dde_qs,abstols,reltols,setups;
save_idxs=3,appxsol=test_sol,maxiters=Int(1e5),error_estimate=:final)
plot(wp)
```
```julia
abstols = 1.0 ./ 10.0 .^ (8:11)
reltols = 1.0 ./ 10.0 .^ (5:8)
setups = [Dict(:alg=>MethodOfSteps(Rosenbrock23())),
Dict(:alg=>MethodOfSteps(Rodas4())),
Dict(:alg=>MethodOfSteps(Rodas5()))]
wp = WorkPrecisionSet(prob_dde_qs,abstols,reltols,setups;
save_idxs=3,appxsol=test_sol,maxiters=Int(1e5),error_estimate=:L2)
plot(wp)
```
```julia
abstols = 1.0 ./ 10.0 .^ (8:11)
reltols = 1.0 ./ 10.0 .^ (5:8)
setups = [Dict(:alg=>MethodOfSteps(Rosenbrock23())),
Dict(:alg=>MethodOfSteps(Rodas4())),
Dict(:alg=>MethodOfSteps(Rodas5()))]
wp = WorkPrecisionSet(prob_dde_qs,abstols,reltols,setups;
save_idxs=3,appxsol=test_sol,maxiters=Int(1e5),error_estimate=:L∞)
plot(wp)
```
Thus at low tolerances `Rodas5` outperforms `Rosenbrock23`.
```julia, echo = false
using SciMLBenchmarks
SciMLBenchmarks.bench_footer(WEAVE_ARGS[:folder],WEAVE_ARGS[:file])
```
| SciMLBenchmarks | https://github.com/SciML/SciMLBenchmarks.jl.git |
|
[
"MIT"
] | 0.1.3 | f4076dd5a103010d48bb6c4e50c5526f6622fa96 | docs | 17152 | ---
title: Brusselator Work-Precision Diagrams
author: Chris Rackauckas and Utkarsh
---
```julia
using OrdinaryDiffEq, DiffEqDevTools, Sundials, ParameterizedFunctions, Plots,
ODEInterfaceDiffEq, LSODA, SparseArrays, LinearSolve,
LinearAlgebra, IncompleteLU, AlgebraicMultigrid, Symbolics, ModelingToolkit
gr()
const N = 8
xyd_brusselator = range(0,stop=1,length=N)
brusselator_f(x, y, t) = (((x-0.3)^2 + (y-0.6)^2) <= 0.1^2) * (t >= 1.1) * 5.
limit(a, N) = a == N+1 ? 1 : a == 0 ? N : a
function brusselator_2d_loop(du, u, p, t)
A, B, alpha, dx = p
alpha = alpha/dx^2
@inbounds for I in CartesianIndices((N, N))
i, j = Tuple(I)
x, y = xyd_brusselator[I[1]], xyd_brusselator[I[2]]
ip1, im1, jp1, jm1 = limit(i+1, N), limit(i-1, N), limit(j+1, N), limit(j-1, N)
du[i,j,1] = alpha*(u[im1,j,1] + u[ip1,j,1] + u[i,jp1,1] + u[i,jm1,1] - 4u[i,j,1]) +
B + u[i,j,1]^2*u[i,j,2] - (A + 1)*u[i,j,1] + brusselator_f(x, y, t)
du[i,j,2] = alpha*(u[im1,j,2] + u[ip1,j,2] + u[i,jp1,2] + u[i,jm1,2] - 4u[i,j,2]) +
A*u[i,j,1] - u[i,j,1]^2*u[i,j,2]
end
end
p = (3.4, 1., 10., step(xyd_brusselator))
input = rand(N,N,2)
output = similar(input)
sparsity_pattern = Symbolics.jacobian_sparsity(brusselator_2d_loop,output,input,p,0.0)
jac_sparsity = Float64.(sparse(sparsity_pattern))
f = ODEFunction{true, SciMLBase.FullSpecialize}(brusselator_2d_loop;jac_prototype=jac_sparsity)
function init_brusselator_2d(xyd)
N = length(xyd)
u = zeros(N, N, 2)
for I in CartesianIndices((N, N))
x = xyd[I[1]]
y = xyd[I[2]]
u[I,1] = 22*(y*(1-y))^(3/2)
u[I,2] = 27*(x*(1-x))^(3/2)
end
u
end
u0 = init_brusselator_2d(xyd_brusselator)
prob = ODEProblem(f,u0,(0.,11.5),p);
```
```julia
prob_mtk = ODEProblem(modelingtoolkitize(prob),[],(0.0,11.5),jac=true,sparse=true);
```
Also comparing with MethodOfLines.jl:
```julia
using MethodOfLines, DomainSets
@parameters x y t
@variables u(..) v(..)
Dt = Differential(t)
Dx = Differential(x)
Dy = Differential(y)
Dxx = Differential(x)^2
Dyy = Differential(y)^2
∇²(u) = Dxx(u) + Dyy(u)
brusselator_f(x, y, t) = (((x-0.3)^2 + (y-0.6)^2) <= 0.1^2) * (t >= 1.1) * 5.
x_min = y_min = t_min = 0.0
x_max = y_max = 1.0
t_max = 11.5
α = 10.
u0_mol(x,y,t) = 22(y*(1-y))^(3/2)
v0_mol(x,y,t) = 27(x*(1-x))^(3/2)
eq = [Dt(u(x,y,t)) ~ 1. + v(x,y,t)*u(x,y,t)^2 - 4.4*u(x,y,t) + α*∇²(u(x,y,t)) + brusselator_f(x, y, t),
Dt(v(x,y,t)) ~ 3.4*u(x,y,t) - v(x,y,t)*u(x,y,t)^2 + α*∇²(v(x,y,t))]
domains = [x ∈ Interval(x_min, x_max),
y ∈ Interval(y_min, y_max),
t ∈ Interval(t_min, t_max)]
bcs = [u(x,y,0) ~ u0_mol(x,y,0),
u(0,y,t) ~ u(1,y,t),
u(x,0,t) ~ u(x,1,t),
v(x,y,0) ~ v0_mol(x,y,0),
v(0,y,t) ~ v(1,y,t),
v(x,0,t) ~ v(x,1,t)]
@named pdesys = PDESystem(eq,bcs,domains,[x,y,t],[u(x,y,t),v(x,y,t)])
# Method of lines discretization
dx = 1/N
dy = 1/N
order = 2
discretization = MOLFiniteDifference([x=>dx, y=>dy], t; approx_order = order, jac = true, sparse = true, wrap = Val(false))
# Convert the PDE system into an ODE problem
prob_mol = discretize(pdesys,discretization)
```
```julia
using Base.Experimental: Const, @aliasscope
macro vp(expr)
nodes = (Symbol("llvm.loop.vectorize.predicate.enable"), 1)
if expr.head != :for
error("Syntax error: loopinfo needs a for loop")
end
push!(expr.args[2].args, Expr(:loopinfo, nodes))
return esc(expr)
end
struct Brusselator2DLoop <: Function
N::Int
s::Float64
end
function (b::Brusselator2DLoop)(du, unc, p, t)
N = b.N
s = b.s
A, B, alpha, dx = p
alpha = alpha/abs2(dx)
u = Base.Experimental.Const(unc)
Base.Experimental.@aliasscope begin
@inbounds @fastmath begin
b = ((abs2(-0.3) + abs2(-0.6)) <= abs2(0.1)) * (t >= 1.1) * 5.0
du1 = alpha*(u[N,1,1] + u[2,1,1] + u[1,2,1] + u[1,N,1] - 4u[1,1,1]) +
B + abs2(u[1,1,1])*u[1,1,2] - (A + 1)*u[1,1,1] + b
du2 = alpha*(u[N,1,2] + u[2,1,2] + u[1,2,2] + u[1,N,2] - 4u[1,1,2]) +
A*u[1,1,1] - abs2(u[1,1,1])*u[1,1,2]
du[1,1,1] = du1
du[1,1,2] = du2
@vp for i = 2:N-1
x = (i-1)*s
ip1 = i+1
im1 = i-1
b = ((abs2(x-0.3) + abs2(-0.6)) <= abs2(0.1)) * (t >= 1.1) * 5.0
du1 = alpha*(u[im1,1,1] + u[ip1,1,1] + u[i,2,1] + u[i,N,1] - 4u[i,1,1]) +
B + abs2(u[i,1,1])*u[i,1,2] - (A + 1)*u[i,1,1] + b
du2 = alpha*(u[im1,1,2] + u[ip1,1,2] + u[i,2,2] + u[i,N,2] - 4u[i,1,2]) +
A*u[i,1,1] - abs2(u[i,1,1])*u[i,1,2]
du[i,1,1] = du1
du[i,1,2] = du2
end
b = ((abs2(0.7) + abs2(-0.6)) <= abs2(0.1)) * (t >= 1.1) * 5.0
du1 = alpha*(u[N-1,1,1] + u[1,1,1] + u[N,2,1] + u[N,N,1] - 4u[N,1,1]) +
B + abs2(u[N,1,1])*u[N,1,2] - (A + 1)*u[N,1,1] + b
du2 = alpha*(u[N-1,1,2] + u[1,1,2] + u[N,2,2] + u[N,N,2] - 4u[N,1,2]) +
A*u[N,1,1] - abs2(u[N,1,1])*u[N,1,2]
du[N,1,1] = du1
du[N,1,2] = du2
for j = 2:N-1
y = (j-1)*s
jp1 = j+1
jm1 = j-1
b0 = ((abs2(-0.3) + abs2(y-0.6)) <= abs2(0.1)) * (t >= 1.1) * 5.0
du[1,j,1] = alpha*(u[N,j,1] + u[2,j,1] + u[1,jp1,1] + u[1,jm1,1] - 4u[1,j,1]) +
B + abs2(u[1,j,1])*u[1,j,2] - (A + 1)*u[1,j,1] + b0
du[1,j,2] = alpha*(u[N,j,2] + u[2,j,2] + u[1,jp1,2] + u[1,jm1,2] - 4u[1,j,2]) +
A*u[1,j,1] - abs2(u[1,j,1])*u[1,j,2]
@vp for i = 2:N-1
x = (i-1)*s
b = ((abs2(x-0.3) + abs2(y-0.6)) <= abs2(0.1)) * (t >= 1.1) * 5.0
du1 = alpha*(u[i-1,j,1] + u[i+1,j,1] + u[i,jp1,1] + u[i,jm1,1] - 4u[i,j,1]) +
B + abs2(u[i,j,1])*u[i,j,2] - (A + 1)*u[i,j,1] + b
du2 = alpha*(u[i-1,j,2] + u[i+1,j,2] + u[i,jp1,2] + u[i,jm1,2] - 4u[i,j,2]) +
A*u[i,j,1] - abs2(u[i,j,1])*u[i,j,2]
du[i,j,1] = du1
du[i,j,2] = du2
end
bN = ((abs2(0.7) + abs2(y-0.6)) <= abs2(0.1)) * (t >= 1.1) * 5.0
du[N,j,1] = alpha*(u[N-1,j,1] + u[1,j,1] + u[N,jp1,1] + u[N,jm1,1] - 4u[N,j,1]) +
B + abs2(u[N,j,1])*u[N,j,2] - (A + 1)*u[N,j,1] + bN
du[N,j,2] = alpha*(u[N-1,j,2] + u[1,j,2] + u[N,jp1,2] + u[N,jm1,2] - 4u[N,j,2]) +
A*u[N,j,1] - abs2(u[N,j,1])*u[N,j,2]
end
b = ((abs2(-0.3) + abs2(0.4)) <= abs2(0.1)) * (t >= 1.1) * 5.0
du1 = alpha*(u[N,N,1] + u[2,N,1] + u[1,1,1] + u[1,N-1,1] - 4u[1,N,1]) +
B + abs2(u[1,N,1])*u[1,N,2] - (A + 1)*u[1,N,1] + b
du2 = alpha*(u[N,N,2] + u[2,N,2] + u[1,1,2] + u[1,N-1,2] - 4u[1,N,2]) +
A*u[1,N,1] - abs2(u[1,N,1])*u[1,N,2]
du[1,N,1] = du1
du[1,N,2] = du2
@vp for i = 2:N-1
x = (i-1)*s
ip1 = i+1
im1 = i-1
b = ((abs2(x-0.3) + abs2(0.4)) <= abs2(0.1)) * (t >= 1.1) * 5.0
du1 = alpha*(u[im1,N,1] + u[ip1,N,1] + u[i,1,1] + u[i,N-1,1] - 4u[i,N,1]) +
B + abs2(u[i,N,1])*u[i,N,2] - (A + 1)*u[i,N,1] + b
du2 = alpha*(u[im1,N,2] + u[ip1,N,2] + u[i,1,2] + u[i,N-1,2] - 4u[i,N,2]) +
A*u[i,N,1] - abs2(u[i,N,1])*u[i,N,2]
du[i,N,1] = du1
du[i,N,2] = du2
end
b = ((abs2(0.7) + abs2(0.4)) <= abs2(0.1)) * (t >= 1.1) * 5.0
du1 = alpha*(u[N-1,N,1] + u[1,N,1] + u[N,1,1] + u[N,N-1,1] - 4u[N,N,1]) +
B + abs2(u[N,N,1])*u[N,N,2] - (A + 1)*u[N,N,1] + b
du2 = alpha*(u[N-1,N,2] + u[1,N,2] + u[N,1,2] + u[N,N-1,2] - 4u[N,N,2]) +
A*u[N,N,1] - abs2(u[N,N,1])*u[N,N,2]
du[N,N,1] = du1
du[N,N,2] = du2
end
end
end
function fast_bruss(N)
xyd_brusselator = range(0,stop=1,length=N)
brusselator_2d_loop = Brusselator2DLoop(N,Float64(step(xyd_brusselator)))
p = (3.4, 1., 10., step(xyd_brusselator))
input = rand(N,N,2)
output = similar(input)
sparsity_pattern = Symbolics.jacobian_sparsity(brusselator_2d_loop,output,input,p,0.0)
jac_sparsity = Float64.(sparse(sparsity_pattern))
f = ODEFunction(brusselator_2d_loop;jac_prototype=jac_sparsity)
u0 = zeros(N, N, 2)
@inbounds for I in CartesianIndices((N, N))
x = xyd_brusselator[I[1]]
y = xyd_brusselator[I[2]]
u0[I,1] = 22*(y*(1-y))^(3/2)
u0[I,2] = 27*(x*(1-x))^(3/2)
end
return ODEProblem(f,u0,(0.,11.5),p)
end
fastprob = fast_bruss(N)
```
```julia
sol = solve(prob,CVODE_BDF(),abstol=1/10^14,reltol=1/10^14)
sol2 = solve(prob_mtk,CVODE_BDF(linear_solver = :KLU),abstol=1/10^14,reltol=1/10^14)
sol3 = solve(prob_mol,CVODE_BDF(linear_solver = :KLU),abstol=1/10^14,reltol=1/10^14,wrap=Val(false))
```
```julia
test_sol = [sol,sol2,sol,sol3]
probs = [prob,prob_mtk,fastprob,prob_mol];
```
```julia
plot(sol,vars = 1)
```
```julia
plot(sol,vars = 10)
```
## Setup Preconditioners
### OrdinaryDiffEq
```julia
function incompletelu(W,du,u,p,t,newW,Plprev,Prprev,solverdata)
if newW === nothing || newW
Pl = ilu(convert(AbstractMatrix,W), τ = 50.0)
else
Pl = Plprev
end
Pl,nothing
end
function algebraicmultigrid(W,du,u,p,t,newW,Plprev,Prprev,solverdata)
if newW === nothing || newW
Pl = aspreconditioner(ruge_stuben(convert(AbstractMatrix,W)))
else
Pl = Plprev
end
Pl,nothing
end
```
### Sundials
```julia
const jaccache = prob_mtk.f.jac(prob.u0,prob.p,0.0)
const W = I - 1.0*jaccache
prectmp = ilu(W, τ = 50.0)
const preccache = Ref(prectmp)
function psetupilu(p, t, u, du, jok, jcurPtr, gamma)
if !jok
prob_mtk.f.jac(jaccache,u,p,t)
jcurPtr[] = true
# W = I - gamma*J
@. W = -gamma*jaccache
idxs = diagind(W)
@. @view(W[idxs]) = @view(W[idxs]) + 1
# Build preconditioner on W
preccache[] = ilu(W, τ = 5.0)
end
end
function precilu(z,r,p,t,y,fy,gamma,delta,lr)
ldiv!(z,preccache[],r)
end
prectmp2 = aspreconditioner(ruge_stuben(W, presmoother = AlgebraicMultigrid.Jacobi(rand(size(W,1))), postsmoother = AlgebraicMultigrid.Jacobi(rand(size(W,1)))))
const preccache2 = Ref(prectmp2)
function psetupamg(p, t, u, du, jok, jcurPtr, gamma)
if !jok
prob_mtk.f.jac(jaccache,u,p,t)
jcurPtr[] = true
# W = I - gamma*J
@. W = -gamma*jaccache
idxs = diagind(W)
@. @view(W[idxs]) = @view(W[idxs]) + 1
# Build preconditioner on W
preccache2[] = aspreconditioner(ruge_stuben(W, presmoother = AlgebraicMultigrid.Jacobi(rand(size(W,1))), postsmoother = AlgebraicMultigrid.Jacobi(rand(size(W,1)))))
end
end
function precamg(z,r,p,t,y,fy,gamma,delta,lr)
ldiv!(z,preccache2[],r)
end
```
## Compare Problem Implementations
```julia
abstols = 1.0 ./ 10.0 .^ (5:8)
reltols = 1.0 ./ 10.0 .^ (1:4);
setups = [
Dict(:alg => KenCarp47(linsolve=KLUFactorization())),
Dict(:alg => KenCarp47(linsolve=KLUFactorization()), :prob_choice => 2),
Dict(:alg => KenCarp47(linsolve=KLUFactorization()), :prob_choice => 3),
Dict(:alg => KenCarp47(linsolve=KLUFactorization()), :prob_choice => 4),
Dict(:alg => KenCarp47(linsolve=KrylovJL_GMRES())),
Dict(:alg => KenCarp47(linsolve=KrylovJL_GMRES()), :prob_choice => 2),
Dict(:alg => KenCarp47(linsolve=KrylovJL_GMRES()), :prob_choice => 3),
Dict(:alg => KenCarp47(linsolve=KrylovJL_GMRES()), :prob_choice => 4),]
names = ["KenCarp47 KLU","KenCarp47 KLU MTK","KenCarp47 KLU FastBruss", "KenCarp47 KLU MOL",
"KenCarp47 GMRES", "KenCarp47 GMRES MTK", "KenCarp47 GMRES FastBruss", "KenCarp47 GMRES MOL"];
wp = WorkPrecisionSet(probs,abstols,reltols,setups;names = names,
save_everystep=false,appxsol=test_sol,maxiters=Int(1e5),numruns=10,wrap=Val(false))
plot(wp)
```
## High Tolerances
This is the speed when you just want the answer.
```julia
abstols = 1.0 ./ 10.0 .^ (5:8)
reltols = 1.0 ./ 10.0 .^ (1:4);
setups = [
Dict(:alg=>CVODE_BDF(linear_solver = :KLU), :prob_choice => 2),
Dict(:alg=>CVODE_BDF(linear_solver = :GMRES)),
Dict(:alg=>CVODE_BDF(linear_solver = :GMRES), :prob_choice => 2),
Dict(:alg=>CVODE_BDF(linear_solver=:GMRES,prec=precilu,psetup=psetupilu,prec_side=1)),
Dict(:alg=>CVODE_BDF(linear_solver=:GMRES,prec=precamg,psetup=psetupamg,prec_side=1)),
Dict(:alg=>CVODE_BDF(linear_solver=:GMRES,prec=precilu,psetup=psetupilu,prec_side=1), :prob_choice => 2),
Dict(:alg=>CVODE_BDF(linear_solver=:GMRES,prec=precamg,psetup=psetupamg,prec_side=1), :prob_choice => 2),
]
names = ["CVODE MTK KLU","CVODE GMRES","CVODE MTK GMRES", "CVODE iLU GMRES", "CVODE AMG GMRES", "CVODE iLU MTK GMRES", "CVODE AMG MTK GMRES"];
wp = WorkPrecisionSet(probs,abstols,reltols,setups;names=names,
save_everystep=false,appxsol=test_sol,maxiters=Int(1e5),numruns=10)
plot(wp)
```
```julia
setups = [
Dict(:alg=>KenCarp47(linsolve=KLUFactorization())),
Dict(:alg=>KenCarp47(linsolve=KLUFactorization()), :prob_choice => 2),
Dict(:alg=>KenCarp47(linsolve=UMFPACKFactorization())),
Dict(:alg=>KenCarp47(linsolve=UMFPACKFactorization()), :prob_choice => 2),
Dict(:alg=>KenCarp47(linsolve=KrylovJL_GMRES())),
Dict(:alg=>KenCarp47(linsolve=KrylovJL_GMRES()), :prob_choice => 2),
Dict(:alg=>KenCarp47(linsolve=KrylovJL_GMRES(),precs=incompletelu,concrete_jac=true)),
Dict(:alg=>KenCarp47(linsolve=KrylovJL_GMRES(),precs=incompletelu,concrete_jac=true), :prob_choice => 2),
Dict(:alg=>KenCarp47(linsolve=KrylovJL_GMRES(),precs=algebraicmultigrid,concrete_jac=true)),
Dict(:alg=>KenCarp47(linsolve=KrylovJL_GMRES(),precs=algebraicmultigrid,concrete_jac=true), :prob_choice => 2),
]
names = ["KenCarp47 KLU","KenCarp47 KLU MTK","KenCarp47 UMFPACK", "KenCarp47 UMFPACK MTK", "KenCarp47 GMRES",
"KenCarp47 GMRES MTK", "KenCarp47 iLU GMRES", "KenCarp47 iLU GMRES MTK", "KenCarp47 AMG GMRES",
"KenCarp47 AMG GMRES MTK"];
wp = WorkPrecisionSet(probs,abstols,reltols,setups;names = names,
save_everystep=false,appxsol=test_sol,maxiters=Int(1e5),numruns=10)
plot(wp)
```
```julia
setups = [
Dict(:alg=>TRBDF2()),
Dict(:alg=>KenCarp4()),
Dict(:alg=>KenCarp47()),
# Dict(:alg=>QNDF()), # bad
Dict(:alg=>FBDF()),
]
wp = WorkPrecisionSet(probs,abstols,reltols,setups;
save_everystep=false,appxsol=test_sol,maxiters=Int(1e5),numruns=10)
plot(wp)
```
```julia
setups = [
Dict(:alg=>KenCarp47(linsolve=KLUFactorization()), :prob_choice => 2),
Dict(:alg=>KenCarp47(linsolve=KrylovJL_GMRES()), :prob_choice => 2),
Dict(:alg=>FBDF(linsolve=KLUFactorization()), :prob_choice => 2),
Dict(:alg=>FBDF(linsolve=KrylovJL_GMRES()), :prob_choice => 2),
Dict(:alg=>CVODE_BDF(linear_solver = :KLU), :prob_choice => 2),
Dict(:alg=>CVODE_BDF(linear_solver=:GMRES,prec=precilu,psetup=psetupilu,prec_side=1), :prob_choice => 2),
]
names = ["KenCarp47 KLU MTK", "KenCarp47 GMRES MTK",
"FBDF KLU MTK", "FBDF GMRES MTK",
"CVODE MTK KLU", "CVODE iLU MTK GMRES"
];
wp = WorkPrecisionSet(probs,abstols,reltols,setups;names = names,
save_everystep=false,appxsol=test_sol,maxiters=Int(1e5),numruns=10)
plot(wp)
```
### Low Tolerances
This is the speed at lower tolerances, measuring what's good when accuracy is needed.
```julia
abstols = 1.0 ./ 10.0 .^ (7:12)
reltols = 1.0 ./ 10.0 .^ (4:9)
setups = [
Dict(:alg=>CVODE_BDF(linear_solver = :KLU), :prob_choice => 2),
Dict(:alg=>CVODE_BDF(linear_solver = :GMRES)),
Dict(:alg=>CVODE_BDF(linear_solver = :GMRES), :prob_choice => 2),
Dict(:alg=>CVODE_BDF(linear_solver=:GMRES,prec=precilu,psetup=psetupilu,prec_side=1)),
Dict(:alg=>CVODE_BDF(linear_solver=:GMRES,prec=precamg,psetup=psetupamg,prec_side=1)),
Dict(:alg=>CVODE_BDF(linear_solver=:GMRES,prec=precilu,psetup=psetupilu,prec_side=1), :prob_choice => 2),
Dict(:alg=>CVODE_BDF(linear_solver=:GMRES,prec=precamg,psetup=psetupamg,prec_side=1), :prob_choice => 2),
]
names = ["CVODE MTK KLU","CVODE GMRES","CVODE MTK GMRES", "CVODE iLU GMRES", "CVODE AMG GMRES", "CVODE iLU MTK GMRES", "CVODE AMG MTK GMRES"];
wp = WorkPrecisionSet(probs,abstols,reltols,setups;names = names,
save_everystep=false,appxsol=test_sol,maxiters=Int(1e5),numruns=10)
plot(wp)
```
```julia
setups = [
Dict(:alg=>KenCarp47(linsolve=KLUFactorization()), :prob_choice => 2),
Dict(:alg=>KenCarp47(linsolve=KrylovJL_GMRES()), :prob_choice => 2),
Dict(:alg=>FBDF(linsolve=KLUFactorization()), :prob_choice => 2),
Dict(:alg=>FBDF(linsolve=KrylovJL_GMRES()), :prob_choice => 2),
Dict(:alg=>Rodas5P(linsolve=KrylovJL_GMRES()), :prob_choice => 2),
Dict(:alg=>CVODE_BDF(linear_solver = :KLU), :prob_choice => 2),
Dict(:alg=>CVODE_BDF(linear_solver=:GMRES,prec=precilu,psetup=psetupilu,prec_side=1), :prob_choice => 2),
]
names = ["KenCarp47 KLU MTK", "KenCarp47 GMRES MTK",
"FBDF KLU MTK", "FBDF GMRES MTK",
"Rodas5P GMRES MTK",
"CVODE MTK KLU", "CVODE iLU MTK GMRES"
];
wp = WorkPrecisionSet(probs,abstols,reltols,setups;names = names,
save_everystep=false,appxsol=test_sol,maxiters=Int(1e5),numruns=10)
plot(wp)
```
```julia, echo = false
using SciMLBenchmarks
SciMLBenchmarks.bench_footer(WEAVE_ARGS[:folder],WEAVE_ARGS[:file])
```
| SciMLBenchmarks | https://github.com/SciML/SciMLBenchmarks.jl.git |
|
[
"MIT"
] | 0.1.3 | f4076dd5a103010d48bb6c4e50c5526f6622fa96 | docs | 10640 | ---
title: HIRES Work-Precision Diagrams
author: Chris Rackauckas
---
```julia
using OrdinaryDiffEq, ParameterizedFunctions, Plots, ODE, ODEInterfaceDiffEq, LSODA, DiffEqDevTools, Sundials
using LinearAlgebra, StaticArrays
gr() #gr(fmt=:png)
f = @ode_def Hires begin
dy1 = -1.71*y1 + 0.43*y2 + 8.32*y3 + 0.0007
dy2 = 1.71*y1 - 8.75*y2
dy3 = -10.03*y3 + 0.43*y4 + 0.035*y5
dy4 = 8.32*y2 + 1.71*y3 - 1.12*y4
dy5 = -1.745*y5 + 0.43*y6 + 0.43*y7
dy6 = -280.0*y6*y8 + 0.69*y4 + 1.71*y5 -
0.43*y6 + 0.69*y7
dy7 = 280.0*y6*y8 - 1.81*y7
dy8 = -280.0*y6*y8 + 1.81*y7
end
u0 = zeros(8)
u0[1] = 1
u0[8] = 0.0057
prob = ODEProblem{true, SciMLBase.FullSpecialize}(f,u0,(0.0,321.8122))
probstatic = ODEProblem{false}(f,SVector{8}(u0),(0.0,321.8122))
sol = solve(prob,CVODE_BDF(),abstol=1/10^14,reltol=1/10^14)
sol2 = solve(probstatic,Rodas5P(),abstol=1/10^14,reltol=1/10^14)
probs = [prob,probstatic]
test_sol = [sol,sol2];
abstols = 1.0 ./ 10.0 .^ (4:11)
reltols = 1.0 ./ 10.0 .^ (1:8);
```
```julia
plot(sol)
```
```julia
plot(sol,tspan=(0.0,5.0))
```
## Omissions
The following were omitted from the tests due to convergence failures. ODE.jl's
adaptivity is not able to stabilize its algorithms, while
GeometricIntegratorsDiffEq has not upgraded to Julia 1.0.
GeometricIntegrators.jl's methods used to be either fail to converge at
comparable dts (or on some computers errors due to type conversions).
```julia
#sol = solve(prob,ode23s()); println("Total ODE.jl steps: $(length(sol))")
#using GeometricIntegratorsDiffEq
#try
# sol = solve(prob,GIRadIIA3(),dt=1/10)
#catch e
# println(e)
#end
```
The stabilized explicit methods are not stable enough to handle this problem
well. While they don't diverge, they are really slow.
```julia
setups = [
#Dict(:alg=>ROCK2()),
#Dict(:alg=>ROCK4())
#Dict(:alg=>ESERK5())
]
```
## High Tolerances
This is the speed when you just want the answer.
```julia
abstols = 1.0 ./ 10.0 .^ (5:8)
reltols = 1.0 ./ 10.0 .^ (1:4);
setups = [Dict(:alg=>Rosenbrock23()),
Dict(:alg=>Rosenbrock23(), :prob_choice => 2),
Dict(:alg=>FBDF()),
Dict(:alg=>QNDF()),
Dict(:alg=>TRBDF2()),
Dict(:alg=>CVODE_BDF()),
Dict(:alg=>rodas()),
Dict(:alg=>radau()),
Dict(:alg=>RadauIIA5()),
Dict(:alg=>ROS34PW1a()),
Dict(:alg=>lsoda()),
]
wp = WorkPrecisionSet(probs,abstols,reltols,setups;
save_everystep=false,appxsol=test_sol,maxiters=Int(1e5),numruns=10)
plot(wp)
```
```julia
wp = WorkPrecisionSet(probs,abstols,reltols,setups;dense = false,verbose=false,
appxsol=test_sol,maxiters=Int(1e5),error_estimate=:l2)
plot(wp)
```
```julia
wp = WorkPrecisionSet(probs,abstols,reltols,setups;
appxsol=test_sol,maxiters=Int(1e5),error_estimate=:L2)
plot(wp)
```
```julia
setups = [Dict(:alg=>Rosenbrock23()),
Dict(:alg=>Rosenbrock23(), :prob_choice => 2),
Dict(:alg=>Kvaerno3()),
Dict(:alg=>CVODE_BDF()),
Dict(:alg=>KenCarp4()),
Dict(:alg=>TRBDF2()),
Dict(:alg=>KenCarp3()),
# Dict(:alg=>SDIRK2()), # Removed because it's bad
Dict(:alg=>radau())]
wp = WorkPrecisionSet(probs,abstols,reltols,setups;
save_everystep=false,appxsol=test_sol,maxiters=Int(1e5))
plot(wp)
```
```julia
wp = WorkPrecisionSet(probs,abstols,reltols,setups;dense = false,verbose=false,
appxsol=test_sol,maxiters=Int(1e5),error_estimate=:l2)
plot(wp)
```
```julia
wp = WorkPrecisionSet(probs,abstols,reltols,setups;
appxsol=test_sol,maxiters=Int(1e5),error_estimate=:L2)
plot(wp)
```
```julia
setups = [Dict(:alg=>Rosenbrock23()),
Dict(:alg=>Rosenbrock23(), :prob_choice => 2),
Dict(:alg=>KenCarp5()),
Dict(:alg=>KenCarp4()),
Dict(:alg=>KenCarp4(), :prob_choice => 2),
Dict(:alg=>KenCarp3()),
Dict(:alg=>ARKODE(order=5)),
Dict(:alg=>ARKODE()),
Dict(:alg=>ARKODE(order=3))]
names = ["Rosenbrock23" "Rosenbrock23 Static" "KenCarp5" "KenCarp4" "KenCarp3" "ARKODE5" "ARKODE4" "ARKODE3"]
wp = WorkPrecisionSet(probs,abstols,reltols,setups;
names=names,save_everystep=false,appxsol=test_sol,maxiters=Int(1e5))
plot(wp)
```
```julia
wp = WorkPrecisionSet(probs,abstols,reltols,setups;dense = false,verbose=false,
appxsol=test_sol,maxiters=Int(1e5),error_estimate=:l2)
plot(wp)
```
```julia
setups = [Dict(:alg=>Rosenbrock23()),
Dict(:alg=>Rosenbrock23(), :prob_choice => 2),
Dict(:alg=>TRBDF2()),
Dict(:alg=>ImplicitEulerExtrapolation()),
Dict(:alg=>ImplicitEulerBarycentricExtrapolation()),
Dict(:alg=>ImplicitHairerWannerExtrapolation()),
Dict(:alg=>ABDF2()),
Dict(:alg=>FBDF()),
Dict(:alg=>QNDF()),
Dict(:alg=>Exprb43()),
Dict(:alg=>Exprb32()),
]
wp = WorkPrecisionSet(probs,abstols,reltols,setups;
save_everystep=false,appxsol=test_sol,maxiters=Int(1e5))
plot(wp)
```
### Low Tolerances
This is the speed at lower tolerances, measuring what's good when accuracy is needed.
```julia
abstols = 1.0 ./ 10.0 .^ (7:13)
reltols = 1.0 ./ 10.0 .^ (4:10)
setups = [
Dict(:alg=>FBDF()),
Dict(:alg=>QNDF()),
Dict(:alg=>Rodas4()),
Dict(:alg=>Rodas4(), :prob_choice => 2),
Dict(:alg=>CVODE_BDF()),
Dict(:alg=>ddebdf()),
Dict(:alg=>Rodas5()),
Dict(:alg=>Rodas5P()),
Dict(:alg=>Rodas5P(), :prob_choice => 2),
Dict(:alg=>rodas()),
Dict(:alg=>radau()),
Dict(:alg=>lsoda()),
Dict(:alg=>RadauIIA5()),
]
wp = WorkPrecisionSet(probs,abstols,reltols,setups;
save_everystep=false,appxsol=test_sol,maxiters=Int(1e5))
plot(wp)
```
```julia
wp = WorkPrecisionSet(probs,abstols,reltols,setups;verbose=false,
dense=false,appxsol=test_sol,maxiters=Int(1e5),error_estimate=:l2)
plot(wp)
```
```julia
wp = WorkPrecisionSet(probs,abstols,reltols,setups;
appxsol=test_sol,maxiters=Int(1e5),error_estimate=:L2)
plot(wp)
```
```julia
setups = [Dict(:alg=>GRK4A()),
Dict(:alg=>Rodas5()),
Dict(:alg=>Rodas5P()),
Dict(:alg=>Rodas5P(), :prob_choice => 2),
Dict(:alg=>Kvaerno5()),
Dict(:alg=>CVODE_BDF()),
Dict(:alg=>lsoda()),
Dict(:alg=>KenCarp4()),
Dict(:alg=>Rodas4()),
Dict(:alg=>radau()),
Dict(:alg=>ImplicitEulerExtrapolation()),
Dict(:alg=>ImplicitEulerBarycentricExtrapolation()),
Dict(:alg=>ImplicitHairerWannerExtrapolation()),
]
wp = WorkPrecisionSet(probs,abstols,reltols,setups;
save_everystep=false,appxsol=test_sol,maxiters=Int(1e5))
plot(wp)
```
```julia
wp = WorkPrecisionSet(probs,abstols,reltols,setups;verbose=false,
dense=false,appxsol=test_sol,maxiters=Int(1e5),error_estimate=:l2)
plot(wp)
```
```julia
wp = WorkPrecisionSet(probs,abstols,reltols,setups;
appxsol=test_sol,maxiters=Int(1e5),error_estimate=:L2)
plot(wp)
```
```julia
setups = [Dict(:alg=>Rodas5()),
Dict(:alg=>Rodas5(), :prob_choice => 2),
Dict(:alg=>KenCarp5()),
Dict(:alg=>KenCarp4()),
Dict(:alg=>KenCarp4(), :prob_choice => 2),
Dict(:alg=>KenCarp3()),
Dict(:alg=>ARKODE(order=5)),
Dict(:alg=>ARKODE()),
Dict(:alg=>ARKODE(order=3))]
names = ["Rodas5" "Rodas5 Static" "KenCarp5" "KenCarp4" "KenCarp4 Static" "KenCarp3" "ARKODE5" "ARKODE4" "ARKODE3"]
wp = WorkPrecisionSet(probs,abstols,reltols,setups;
names=names,save_everystep=false,appxsol=test_sol,maxiters=Int(1e5))
plot(wp)
```
```julia
wp = WorkPrecisionSet(probs,abstols,reltols,setups;verbose=false,
dense=false,appxsol=test_sol,maxiters=Int(1e5),error_estimate=:l2)
plot(wp)
```
The following algorithms were removed since they failed.
```julia
#setups = [#Dict(:alg=>Hairer4()),
#Dict(:alg=>Hairer42()),
#Dict(:alg=>Rodas3()),
#Dict(:alg=>Kvaerno4()),
#Dict(:alg=>KenCarp5()),
#Dict(:alg=>Cash4())
#]
#wp = WorkPrecisionSet(probs,abstols,reltols,setups;
# save_everystep=false,appxsol=test_sol,maxiters=Int(1e5))
#plot(wp)
```
Multithreading with Parallel Extrapolation Methods
```julia
#Setting BLAS to one thread to measure gains
LinearAlgebra.BLAS.set_num_threads(1)
abstols = 1.0 ./ 10.0 .^ (10:12)
reltols = 1.0 ./ 10.0 .^ (7:9)
setups = [
Dict(:alg=>CVODE_BDF()),
Dict(:alg=>KenCarp4()),
Dict(:alg=>Rodas4()),
Dict(:alg=>Rodas4(), :prob_choice => 2),
Dict(:alg=>Rodas5P()),
Dict(:alg=>Rodas5P(), :prob_choice => 2),
Dict(:alg=>QNDF()),
Dict(:alg=>lsoda()),
Dict(:alg=>radau()),
Dict(:alg=>seulex()),
Dict(:alg=>ImplicitEulerExtrapolation(min_order = 4, init_order = 7,threading = OrdinaryDiffEq.PolyesterThreads())),
Dict(:alg=>ImplicitEulerExtrapolation(min_order = 4, init_order = 7,threading = false)),
Dict(:alg=>ImplicitEulerBarycentricExtrapolation(min_order = 4, init_order = 7, threading = OrdinaryDiffEq.PolyesterThreads())),
Dict(:alg=>ImplicitEulerBarycentricExtrapolation(min_order = 4, init_order = 7, threading = false)),
Dict(:alg=>ImplicitHairerWannerExtrapolation(min_order = 3, init_order = 6,threading = OrdinaryDiffEq.PolyesterThreads())),
Dict(:alg=>ImplicitHairerWannerExtrapolation(min_order = 3, init_order = 6,threading = false)),
]
solnames = ["CVODE_BDF","KenCarp4","Rodas4","Rodas4 Static","Rodas5P","Rodas5P Static","QNDF","lsoda","radau","seulex","ImplEulerExtpl (threaded)", "ImplEulerExtpl (non-threaded)",
"ImplEulerBaryExtpl (threaded)","ImplEulerBaryExtpl (non-threaded)","ImplHWExtpl (threaded)","ImplHWExtpl (non-threaded)"]
wp = WorkPrecisionSet(probs,abstols,reltols,setups;
names = solnames,save_everystep=false,appxsol=test_sol,maxiters=Int(1e5),numruns=10)
plot(wp, title = "Implicit Methods: HIRES",legend=:outertopleft,size = (1000,500),
xticks = 10.0 .^ (-15:1:1),
yticks = 10.0 .^ (-6:0.3:5),
bottom_margin= 5Plots.mm)
```
```julia, echo = false
using SciMLBenchmarks
SciMLBenchmarks.bench_footer(WEAVE_ARGS[:folder],WEAVE_ARGS[:file])
```
| SciMLBenchmarks | https://github.com/SciML/SciMLBenchmarks.jl.git |
|
[
"MIT"
] | 0.1.3 | f4076dd5a103010d48bb6c4e50c5526f6622fa96 | docs | 10359 | ---
title: OREGO Work-Precision Diagrams
author: Chris Rackauckas
---
```julia
using OrdinaryDiffEq, DiffEqDevTools, ParameterizedFunctions, Plots, ODE, ODEInterfaceDiffEq, LSODA, Sundials
gr() #gr(fmt=:png)
using LinearAlgebra, StaticArrays
f = @ode_def Orego begin
dy1 = p1*(y2+y1*(1-p2*y1-y2))
dy2 = (y3-(1+y1)*y2)/p1
dy3 = p3*(y1-y3)
end p1 p2 p3
p = SA[77.27,8.375e-6,0.161]
prob = ODEProblem{true, SciMLBase.FullSpecialize}(f,[1.0,2.0,3.0],(0.0,30.0),p)
probstatic = ODEProblem{false}(f,SA[1.0,2.0,3.0],(0.0,30.0),p)
sol = solve(prob,CVODE_BDF(),abstol=1/10^14,reltol=1/10^14)
sol2 = solve(probstatic,Rodas5P(),abstol=1/10^14,reltol=1/10^14)
probs = [prob,probstatic]
test_sol = [sol,sol2];
abstols = 1.0 ./ 10.0 .^ (4:11)
reltols = 1.0 ./ 10.0 .^ (1:8);
```
```julia
plot_prob = ODEProblem(f,[1.0,2.0,3.0],(0.0,400.0),p)
sol = solve(plot_prob,CVODE_BDF())
plot(sol,yscale=:log10)
```
## Omissions and Tweaking
The following were omitted from the tests due to convergence failures. ODE.jl's
adaptivity is not able to stabilize its algorithms, while
GeometricIntegratorsDiffEq has not upgraded to Julia 1.0.
GeometricIntegrators.jl's methods used to be either fail to converge at
comparable dts (or on some computers errors due to type conversions).
```julia
#sol = solve(prob,ode23s()); println("Total ODE.jl steps: $(length(sol))")
#using GeometricIntegratorsDiffEq
#try
# sol = solve(prob,GIRadIIA3(),dt=1/10)
#catch e
# println(e)
#end
```
```julia
sol = solve(prob,ARKODE(),abstol=1e-5,reltol=1e-1);
```
```julia
sol = solve(prob,ARKODE(nonlinear_convergence_coefficient = 1e-3),abstol=1e-5,reltol=1e-1);
```
```julia
sol = solve(prob,ARKODE(order=3),abstol=1e-5,reltol=1e-1);
```
```julia
sol = solve(prob,ARKODE(order=3,nonlinear_convergence_coefficient = 1e-5),abstol=1e-5,reltol=1e-1);
```
```julia
sol = solve(prob,ARKODE(order=5),abstol=1e-5,reltol=1e-1);
```
The stabilized explicit methods are not stable enough to handle this problem
well. While they don't diverge, they are really slow.
```julia
setups = [
#Dict(:alg=>ROCK2()) #Unstable
#Dict(:alg=>ROCK4()) #needs more iterations
#Dict(:alg=>ESERK5()),
]
```
The EPIRK and exponential methods also fail:
```julia
sol = solve(prob,EXPRB53s3(),dt=2.0^(-8));
sol = solve(prob,EPIRK4s3B(),dt=2.0^(-8));
sol = solve(prob,EPIRK5P2(),dt=2.0^(-8));
```
PDIRK44 also fails
```julia
sol = solve(prob,PDIRK44(),dt=2.0^(-8));
```
## High Tolerances
This is the speed when you just want the answer.
```julia
abstols = 1.0 ./ 10.0 .^ (5:8)
reltols = 1.0 ./ 10.0 .^ (1:4);
setups = [Dict(:alg=>Rosenbrock23()),
Dict(:alg=>Rosenbrock23(), :prob_choice => 2),
Dict(:alg=>FBDF()),
Dict(:alg=>QNDF()),
Dict(:alg=>TRBDF2()),
Dict(:alg=>CVODE_BDF()),
Dict(:alg=>rodas()),
Dict(:alg=>radau()),
Dict(:alg=>RadauIIA5()),
Dict(:alg=>ROS34PW1a()),
Dict(:alg=>lsoda()),
]
wp = WorkPrecisionSet(probs,abstols,reltols,setups;
save_everystep=false,appxsol=test_sol,maxiters=Int(1e5),numruns=10)
plot(wp)
```
```julia
wp = WorkPrecisionSet(probs,abstols,reltols,setups;dense = false,verbose=false,
appxsol=test_sol,maxiters=Int(1e5),error_estimate=:l2,numruns=10)
plot(wp)
```
```julia
wp = WorkPrecisionSet(probs,abstols,reltols,setups;
appxsol=test_sol,maxiters=Int(1e5),error_estimate=:L2,numruns=10)
plot(wp)
```
```julia
setups = [Dict(:alg=>Rosenbrock23()),
Dict(:alg=>Rosenbrock23(), :prob_choice => 2),
Dict(:alg=>Kvaerno3()),
Dict(:alg=>CVODE_BDF()),
Dict(:alg=>KenCarp4()),
Dict(:alg=>TRBDF2()),
Dict(:alg=>KenCarp3()),
Dict(:alg=>lsoda()),
# Dict(:alg=>SDIRK2()), # Removed because it's bad
Dict(:alg=>radau())]
wp = WorkPrecisionSet(probs,abstols,reltols,setups;
save_everystep=false,appxsol=test_sol,maxiters=Int(1e5),numruns=10)
plot(wp)
```
```julia
wp = WorkPrecisionSet(probs,abstols,reltols,setups;dense = false,verbose = false,
appxsol=test_sol,maxiters=Int(1e5),error_estimate=:l2,numruns=10)
plot(wp)
```
```julia
wp = WorkPrecisionSet(probs,abstols,reltols,setups;
appxsol=test_sol,maxiters=Int(1e5),error_estimate=:L2,numruns=10)
plot(wp)
```
```julia
setups = [Dict(:alg=>Rosenbrock23()),
Dict(:alg=>Rosenbrock23(), :prob_choice => 2),
Dict(:alg=>KenCarp5()),
Dict(:alg=>KenCarp4()),
Dict(:alg=>KenCarp4(), :prob_choice => 2),
Dict(:alg=>KenCarp3()),
Dict(:alg=>ARKODE(order=5)),
Dict(:alg=>ARKODE(nonlinear_convergence_coefficient = 1e-6)),
Dict(:alg=>ARKODE(nonlinear_convergence_coefficient = 1e-5,order=3))
]
names = ["Rosenbrock23" "Rosenbrock23 Static" "KenCarp5" "KenCarp4" "KenCarp4 Static" "KenCarp3" "ARKODE5" "ARKODE4" "ARKODE3"]
wp = WorkPrecisionSet(probs,abstols,reltols,setups;
names=names,
save_everystep=false,appxsol=test_sol,maxiters=Int(1e5),numruns=10)
plot(wp)
```
### Low Tolerances
This is the speed at lower tolerances, measuring what's good when accuracy is needed.
```julia
abstols = 1.0 ./ 10.0 .^ (7:13)
reltols = 1.0 ./ 10.0 .^ (4:10)
setups = [
Dict(:alg=>FBDF()),
Dict(:alg=>QNDF()),
Dict(:alg=>Rodas4P()),
Dict(:alg=>CVODE_BDF()),
Dict(:alg=>ddebdf()),
Dict(:alg=>Rodas4()),
Dict(:alg=>Rodas4(), :prob_choice => 2),
Dict(:alg=>Rodas5P()),
Dict(:alg=>Rodas5P(), :prob_choice => 2),
Dict(:alg=>rodas()),
Dict(:alg=>radau()),
Dict(:alg=>RadauIIA5()),
Dict(:alg=>lsoda()),
]
wp = WorkPrecisionSet(probs,abstols,reltols,setups;
save_everystep=false,appxsol=test_sol,maxiters=Int(1e5),numruns=10)
plot(wp)
```
```julia
wp = WorkPrecisionSet(probs,abstols,reltols,setups;verbose=false,
dense=false,appxsol=test_sol,maxiters=Int(1e5),error_estimate=:l2,numruns=10)
plot(wp)
```
```julia
wp = WorkPrecisionSet(probs,abstols,reltols,setups;
appxsol=test_sol,maxiters=Int(1e5),error_estimate=:L2,numruns=10)
plot(wp)
```
```julia
setups = [Dict(:alg=>GRK4A()),
Dict(:alg=>Rodas5()),
Dict(:alg=>Rodas5P()),
Dict(:alg=>Rodas5P(), :prob_choice => 2),
Dict(:alg=>Kvaerno5()),
Dict(:alg=>CVODE_BDF()),
Dict(:alg=>KenCarp4()),
Dict(:alg=>KenCarp4(), :prob_choice => 2),
Dict(:alg=>KenCarp5()),
Dict(:alg=>Rodas4()),
Dict(:alg=>Rodas4(), :prob_choice => 2),
Dict(:alg=>lsoda()),
Dict(:alg=>radau()),
Dict(:alg=>ImplicitEulerExtrapolation()),
Dict(:alg=>ImplicitEulerBarycentricExtrapolation()),
Dict(:alg=>ImplicitHairerWannerExtrapolation()),
]
wp = WorkPrecisionSet(probs,abstols,reltols,setups;
save_everystep=false,appxsol=test_sol,maxiters=Int(1e5),numruns=10)
plot(wp)
```
```julia
wp = WorkPrecisionSet(probs,abstols,reltols,setups;verbose=false,
dense=false,appxsol=test_sol,maxiters=Int(1e5),error_estimate=:l2,numruns=10)
plot(wp)
```
```julia
wp = WorkPrecisionSet(probs,abstols,reltols,setups;
appxsol=test_sol,maxiters=Int(1e5),error_estimate=:L2,numruns=10)
plot(wp)
```
The following algorithms were removed since they failed.
```julia
#setups = [Dict(:alg=>Hairer4()),
#Dict(:alg=>Hairer42()),
#Dict(:alg=>Rodas3()),
#Dict(:alg=>Kvaerno4()),
#Dict(:alg=>Cash4())
#]
#wp = WorkPrecisionSet(probs,abstols,reltols,setups;
# save_everystep=false,appxsol=test_sol,maxiters=Int(1e5),numruns=10)
#plot(wp)
```
Multithreading benchmarks with Parallel Extrapolation Methods
```julia
#Checking for threading
print(Threads.nthreads())
```
```julia
#Setting BLAS to one thread to measure gains
LinearAlgebra.BLAS.set_num_threads(1)
abstols = 1.0 ./ 10.0 .^ (10:12)
reltols = 1.0 ./ 10.0 .^ (7:9)
setups = [
Dict(:alg=>CVODE_BDF()),
Dict(:alg=>KenCarp4()),
Dict(:alg=>Rodas4()),
Dict(:alg=>Rodas4(), :prob_choice => 2),
Dict(:alg=>Rodas5P()),
Dict(:alg=>Rodas5P(), :prob_choice => 2),
Dict(:alg=>QNDF()),
Dict(:alg=>lsoda()),
Dict(:alg=>radau()),
Dict(:alg=>seulex()),
Dict(:alg=>ImplicitEulerExtrapolation(init_order = 4,threading = OrdinaryDiffEq.PolyesterThreads())),
Dict(:alg=>ImplicitEulerExtrapolation(init_order = 4,threading = false)),
Dict(:alg=>ImplicitEulerBarycentricExtrapolation(init_order = 4, threading = OrdinaryDiffEq.PolyesterThreads())),
Dict(:alg=>ImplicitEulerBarycentricExtrapolation(init_order = 4, threading = false)),
Dict(:alg=>ImplicitHairerWannerExtrapolation(init_order = 5,threading = OrdinaryDiffEq.PolyesterThreads())),
Dict(:alg=>ImplicitHairerWannerExtrapolation(init_order = 5,threading = false)),
]
solnames = ["CVODE_BDF","KenCarp4","Rodas4","Rodas4 Static","Rodas%P","Rodas5P Static","QNDF","lsoda","radau","seulex","ImplEulerExtpl (threaded)", "ImplEulerExtpl (non-threaded)",
"ImplEulerBaryExtpl (threaded)","ImplEulerBaryExtpl (non-threaded)","ImplHWExtpl (threaded)","ImplHWExtpl (non-threaded)"]
wp = WorkPrecisionSet(probs,abstols,reltols,setups;
names = solnames,save_everystep=false,appxsol=test_sol,maxiters=Int(1e5),numruns=10)
plot(wp, title = "Implicit Methods: OREGO",legend=:outertopleft,size = (1000,500),
xticks = 10.0 .^ (-15:1:1),
yticks = 10.0 .^ (-6:0.3:5),
bottom_margin= 5Plots.mm)
```
### Conclusion
At high tolerances, `Rosenbrock23` hits the the error estimates and is fast. At lower tolerances and normal user tolerances, `Rodas4` and `Rodas5` are extremely fast. When you get down to `reltol=1e-9` `radau` begins to become as efficient as `Rodas4`, and it continues to do well below that.
```julia, echo = false
using SciMLBenchmarks
SciMLBenchmarks.bench_footer(WEAVE_ARGS[:folder],WEAVE_ARGS[:file])
```
| SciMLBenchmarks | https://github.com/SciML/SciMLBenchmarks.jl.git |
|
[
"MIT"
] | 0.1.3 | f4076dd5a103010d48bb6c4e50c5526f6622fa96 | docs | 13605 | ---
title: POLLU Work-Precision Diagrams
author: Chris Rackauckas
---
```julia
using OrdinaryDiffEq, DiffEqDevTools, Sundials, ParameterizedFunctions, Plots, ODE, ODEInterfaceDiffEq, LSODA, LinearSolve
using ProfileSVG, BenchmarkTools, Profile
gr() # gr(fmt=:png)
using LinearAlgebra
const k1=.35e0
const k2=.266e2
const k3=.123e5
const k4=.86e-3
const k5=.82e-3
const k6=.15e5
const k7=.13e-3
const k8=.24e5
const k9=.165e5
const k10=.9e4
const k11=.22e-1
const k12=.12e5
const k13=.188e1
const k14=.163e5
const k15=.48e7
const k16=.35e-3
const k17=.175e-1
const k18=.1e9
const k19=.444e12
const k20=.124e4
const k21=.21e1
const k22=.578e1
const k23=.474e-1
const k24=.178e4
const k25=.312e1
function f(dy,y,p,t)
r1 = k1 *y[1]
r2 = k2 *y[2]*y[4]
r3 = k3 *y[5]*y[2]
r4 = k4 *y[7]
r5 = k5 *y[7]
r6 = k6 *y[7]*y[6]
r7 = k7 *y[9]
r8 = k8 *y[9]*y[6]
r9 = k9 *y[11]*y[2]
r10 = k10*y[11]*y[1]
r11 = k11*y[13]
r12 = k12*y[10]*y[2]
r13 = k13*y[14]
r14 = k14*y[1]*y[6]
r15 = k15*y[3]
r16 = k16*y[4]
r17 = k17*y[4]
r18 = k18*y[16]
r19 = k19*y[16]
r20 = k20*y[17]*y[6]
r21 = k21*y[19]
r22 = k22*y[19]
r23 = k23*y[1]*y[4]
r24 = k24*y[19]*y[1]
r25 = k25*y[20]
dy[1] = -r1-r10-r14-r23-r24+
r2+r3+r9+r11+r12+r22+r25
dy[2] = -r2-r3-r9-r12+r1+r21
dy[3] = -r15+r1+r17+r19+r22
dy[4] = -r2-r16-r17-r23+r15
dy[5] = -r3+r4+r4+r6+r7+r13+r20
dy[6] = -r6-r8-r14-r20+r3+r18+r18
dy[7] = -r4-r5-r6+r13
dy[8] = r4+r5+r6+r7
dy[9] = -r7-r8
dy[10] = -r12+r7+r9
dy[11] = -r9-r10+r8+r11
dy[12] = r9
dy[13] = -r11+r10
dy[14] = -r13+r12
dy[15] = r14
dy[16] = -r18-r19+r16
dy[17] = -r20
dy[18] = r20
dy[19] = -r21-r22-r24+r23+r25
dy[20] = -r25+r24
end
function fjac(J,y,p,t)
J .= 0.0
J[1,1] = -k1-k10*y[11]-k14*y[6]-k23*y[4]-k24*y[19]
J[1,11] = -k10*y[1]+k9*y[2]
J[1,6] = -k14*y[1]
J[1,4] = -k23*y[1]+k2*y[2]
J[1,19] = -k24*y[1]+k22
J[1,2] = k2*y[4]+k9*y[11]+k3*y[5]+k12*y[10]
J[1,13] = k11
J[1,20] = k25
J[1,5] = k3*y[2]
J[1,10] = k12*y[2]
J[2,4] = -k2*y[2]
J[2,5] = -k3*y[2]
J[2,11] = -k9*y[2]
J[2,10] = -k12*y[2]
J[2,19] = k21
J[2,1] = k1
J[2,2] = -k2*y[4]-k3*y[5]-k9*y[11]-k12*y[10]
J[3,1] = k1
J[3,4] = k17
J[3,16] = k19
J[3,19] = k22
J[3,3] = -k15
J[4,4] = -k2*y[2]-k16-k17-k23*y[1]
J[4,2] = -k2*y[4]
J[4,1] = -k23*y[4]
J[4,3] = k15
J[5,5] = -k3*y[2]
J[5,2] = -k3*y[5]
J[5,7] = 2k4+k6*y[6]
J[5,6] = k6*y[7]+k20*y[17]
J[5,9] = k7
J[5,14] = k13
J[5,17] = k20*y[6]
J[6,6] = -k6*y[7]-k8*y[9]-k14*y[1]-k20*y[17]
J[6,7] = -k6*y[6]
J[6,9] = -k8*y[6]
J[6,1] = -k14*y[6]
J[6,17] = -k20*y[6]
J[6,2] = k3*y[5]
J[6,5] = k3*y[2]
J[6,16] = 2k18
J[7,7] = -k4-k5-k6*y[6]
J[7,6] = -k6*y[7]
J[7,14] = k13
J[8,7] = k4+k5+k6*y[6]
J[8,6] = k6*y[7]
J[8,9] = k7
J[9,9] = -k7-k8*y[6]
J[9,6] = -k8*y[9]
J[10,10] = -k12*y[2]
J[10,2] = -k12*y[10]+k9*y[11]
J[10,9] = k7
J[10,11] = k9*y[2]
J[11,11] = -k9*y[2]-k10*y[1]
J[11,2] = -k9*y[11]
J[11,1] = -k10*y[11]
J[11,9] = k8*y[6]
J[11,6] = k8*y[9]
J[11,13] = k11
J[12,11] = k9*y[2]
J[12,2] = k9*y[11]
J[13,13] = -k11
J[13,11] = k10*y[1]
J[13,1] = k10*y[11]
J[14,14] = -k13
J[14,10] = k12*y[2]
J[14,2] = k12*y[10]
J[15,1] = k14*y[6]
J[15,6] = k14*y[1]
J[16,16] = -k18-k19
J[16,4] = k16
J[17,17] = -k20*y[6]
J[17,6] = -k20*y[17]
J[18,17] = k20*y[6]
J[18,6] = k20*y[17]
J[19,19] = -k21-k22-k24*y[1]
J[19,1] = -k24*y[19]+k23*y[4]
J[19,4] = k23*y[1]
J[19,20] = k25
J[20,20] = -k25
J[20,1] = k24*y[19]
J[20,19] = k24*y[1]
return
end
u0 = zeros(20)
u0[2] = 0.2
u0[4] = 0.04
u0[7] = 0.1
u0[8] = 0.3
u0[9] = 0.01
u0[17] = 0.007
prob = ODEProblem(ODEFunction{true, SciMLBase.FullSpecialize}(f, jac=fjac),u0,(0.0,60.0))
sol = solve(prob,Rodas5(),abstol=1/10^14,reltol=1/10^14)
test_sol = TestSolution(sol)
abstols = 1.0 ./ 10.0 .^ (4:11)
reltols = 1.0 ./ 10.0 .^ (1:8);
```
```julia
plot(sol)
```
```julia
plot(sol,tspan=(0.0,5.0))
```
## Omissions
The following were omitted from the tests due to convergence failures. ODE.jl's
adaptivity is not able to stabilize its algorithms, while
GeometricIntegratorsDiffEq has not upgraded to Julia 1.0.
GeometricIntegrators.jl's methods used to be either fail to converge at
comparable dts (or on some computers errors due to type conversions).
```julia
#sol = solve(prob,ode23s()); println("Total ODE.jl steps: $(length(sol))")
#using GeometricIntegratorsDiffEq
#try
# sol = solve(prob,GIRadIIA3(),dt=1/10)
#catch e
# println(e)
#end
```
The stabilized explicit methods fail.
```julia
setups = [
#Dict(:alg=>ROCK2()),
#Dict(:alg=>ROCK4())
#Dict(:alg=>ESERK5())
]
```
The EPIRK and exponential methods also fail:
```julia
sol = solve(prob,EXPRB53s3(),dt=2.0^(-8));
sol = solve(prob,EPIRK4s3B(),dt=2.0^(-8));
sol = solve(prob,EPIRK5P2(),dt=2.0^(-8));
```
## High Tolerances
This is the speed when you just want the answer.
```julia
abstols = 1.0 ./ 10.0 .^ (5:8)
reltols = 1.0 ./ 10.0 .^ (1:4);
setups = [Dict(:alg=>Rosenbrock23()),
Dict(:alg=>FBDF()),
Dict(:alg=>QNDF()),
Dict(:alg=>TRBDF2()),
Dict(:alg=>CVODE_BDF()),
Dict(:alg=>rodas()),
Dict(:alg=>radau()),
Dict(:alg=>lsoda()),
Dict(:alg=>RadauIIA5()),
]
wp = WorkPrecisionSet(prob,abstols,reltols,setups;verbose=false,
save_everystep=false,appxsol=test_sol,maxiters=Int(1e5),numruns=10)
plot(wp)
```
```julia
wp = WorkPrecisionSet(prob,abstols,reltols,setups;dense = false,verbose = false,
appxsol=test_sol,maxiters=Int(1e5),error_estimate=:l2,numruns=10)
plot(wp)
```
```julia
wp = WorkPrecisionSet(prob,abstols,reltols,setups;verbose=false,
appxsol=test_sol,maxiters=Int(1e5),error_estimate=:L2,numruns=10)
plot(wp)
```
```julia
setups = [Dict(:alg=>Rosenbrock23()),
Dict(:alg=>Kvaerno3()),
Dict(:alg=>CVODE_BDF()),
Dict(:alg=>KenCarp4()),
Dict(:alg=>TRBDF2()),
Dict(:alg=>KenCarp3()),
Dict(:alg=>Rodas4()),
Dict(:alg=>lsoda()),
Dict(:alg=>radau())]
wp = WorkPrecisionSet(prob,abstols,reltols,setups;
save_everystep=false,appxsol=test_sol,maxiters=Int(1e5),numruns=10)
plot(wp)
```
```julia
wp = WorkPrecisionSet(prob,abstols,reltols,setups;dense = false,verbose = false,
appxsol=test_sol,maxiters=Int(1e5),error_estimate=:l2,numruns=10)
plot(wp)
```
```julia
wp = WorkPrecisionSet(prob,abstols,reltols,setups;
appxsol=test_sol,maxiters=Int(1e5),error_estimate=:L2,numruns=10)
plot(wp)
```
```julia
setups = [Dict(:alg=>Rosenbrock23()),
Dict(:alg=>KenCarp5()),
Dict(:alg=>KenCarp4()),
Dict(:alg=>KenCarp3()),
Dict(:alg=>ARKODE(order=5)),
Dict(:alg=>ARKODE()),
Dict(:alg=>ARKODE(order=3))]
names = ["Rosenbrock23" "KenCarp5" "KenCarp4" "KenCarp3" "ARKODE5" "ARKODE4" "ARKODE3"]
wp = WorkPrecisionSet(prob,abstols,reltols,setups;
names=names,save_everystep=false,appxsol=test_sol,maxiters=Int(1e5),numruns=10)
plot(wp)
```
```julia
setups = [Dict(:alg=>Rosenbrock23()),
Dict(:alg=>TRBDF2()),
Dict(:alg=>ImplicitEulerExtrapolation()),
Dict(:alg=>ImplicitEulerExtrapolation()),
Dict(:alg=>ImplicitEulerBarycentricExtrapolation()),
Dict(:alg=>ImplicitHairerWannerExtrapolation()),
Dict(:alg=>ABDF2()),
Dict(:alg=>FBDF()),
#Dict(:alg=>QNDF()),
#Dict(:alg=>Exprb43()), #matrix contains Infs or NaNs
#Dict(:alg=>Exprb32()), #matrix contains Infs or NaNs
]
wp = WorkPrecisionSet(prob,abstols,reltols,setups;
save_everystep=false,appxsol=test_sol,maxiters=Int(1e5))
plot(wp)
```
```julia
setups = [Dict(:alg=>Rosenbrock23()),
Dict(:alg=>TRBDF2()),
Dict(:alg=>ImplicitEulerExtrapolation(linsolve = RFLUFactorization())),
Dict(:alg=>ImplicitEulerBarycentricExtrapolation(linsolve = RFLUFactorization())),
Dict(:alg=>ImplicitHairerWannerExtrapolation(linsolve = RFLUFactorization())),
Dict(:alg=>ABDF2()),
Dict(:alg=>FBDF()),
#Dict(:alg=>QNDF()),
#Dict(:alg=>Exprb43()), #matrix contains Infs or NaNs
#Dict(:alg=>Exprb32()), #matrix contains Infs or NaNs
]
wp = WorkPrecisionSet(prob,abstols,reltols,setups;
save_everystep=false,appxsol=test_sol,maxiters=Int(1e5))
plot(wp)
```
### Low Tolerances
This is the speed at lower tolerances, measuring what's good when accuracy is needed.
```julia
abstols = 1.0 ./ 10.0 .^ (7:13)
reltols = 1.0 ./ 10.0 .^ (4:10)
setups = [
Dict(:alg=>FBDF()),
Dict(:alg=>QNDF()),
Dict(:alg=>Rodas4P()),
Dict(:alg=>CVODE_BDF()),
Dict(:alg=>ddebdf()),
Dict(:alg=>Rodas4()),
Dict(:alg=>Rodas5P()),
Dict(:alg=>rodas()),
Dict(:alg=>radau()),
Dict(:alg=>lsoda())
]
wp = WorkPrecisionSet(prob,abstols,reltols,setups;verbose=false,
save_everystep=false,appxsol=test_sol,maxiters=Int(1e5),numruns=10)
plot(wp)
```
```julia
wp = WorkPrecisionSet(prob,abstols,reltols,setups;verbose=false,
dense=false,appxsol=test_sol,maxiters=Int(1e5),error_estimate=:l2,numruns=10)
plot(wp)
```
```julia
wp = WorkPrecisionSet(prob,abstols,reltols,setups;verbose=false,
appxsol=test_sol,maxiters=Int(1e5),error_estimate=:L2,numruns=10)
plot(wp)
```
```julia
setups = [Dict(:alg=>GRK4A()),
Dict(:alg=>Rodas5()),
Dict(:alg=>Kvaerno4()),
Dict(:alg=>Kvaerno5()),
Dict(:alg=>CVODE_BDF()),
Dict(:alg=>KenCarp4()),
Dict(:alg=>KenCarp5()),
Dict(:alg=>Rodas4()),
Dict(:alg=>Rodas5P()),
Dict(:alg=>radau()),
Dict(:alg=>ImplicitEulerExtrapolation(min_order = 3)),
Dict(:alg=>ImplicitEulerBarycentricExtrapolation()),
Dict(:alg=>ImplicitHairerWannerExtrapolation()),
]
wp = WorkPrecisionSet(prob,abstols,reltols,setups;
save_everystep=false,appxsol=test_sol,maxiters=Int(1e5),numruns=10)
plot(wp)
```
```julia
wp = WorkPrecisionSet(prob,abstols,reltols,setups;verbose=false,
dense=false,appxsol=test_sol,maxiters=Int(1e5),error_estimate=:l2,numruns=10)
plot(wp)
```
```julia
wp = WorkPrecisionSet(prob,abstols,reltols,setups;
appxsol=test_sol,maxiters=Int(1e5),error_estimate=:L2,numruns=10)
plot(wp)
```
The following algorithms were removed since they failed.
```julia
#setups = [#Dict(:alg=>Hairer4()),
#Dict(:alg=>Hairer42()),
#Dict(:alg=>Rodas3()),
#Dict(:alg=>Cash4())
#]
#wp = WorkPrecisionSet(prob,abstols,reltols,setups;
# save_everystep=false,appxsol=test_sol,maxiters=Int(1e5),numruns=10)
#plot(wp)
```
Multithreading benchmarks with Parallel Extrapolation Methods
```julia
#Setting BLAS to one thread to measure gains
LinearAlgebra.BLAS.set_num_threads(1)
abstols = 1.0 ./ 10.0 .^ (11:13)
reltols = 1.0 ./ 10.0 .^ (8:10)
setups = [
Dict(:alg=>CVODE_BDF()),
Dict(:alg=>KenCarp4()),
Dict(:alg=>Rodas4()),
Dict(:alg=>Rodas5()),
Dict(:alg=>Rodas5P()),
Dict(:alg=>QNDF()),
Dict(:alg=>lsoda()),
Dict(:alg=>radau()),
Dict(:alg=>seulex()),
Dict(:alg=>ImplicitEulerExtrapolation(min_order = 5, init_order = 3,threading = OrdinaryDiffEq.PolyesterThreads())),
Dict(:alg=>ImplicitEulerExtrapolation(min_order = 5, init_order = 3,threading = false)),
Dict(:alg=>ImplicitEulerBarycentricExtrapolation(min_order = 5, threading = OrdinaryDiffEq.PolyesterThreads())),
Dict(:alg=>ImplicitEulerBarycentricExtrapolation(min_order = 5, threading = false)),
Dict(:alg=>ImplicitHairerWannerExtrapolation(threading = OrdinaryDiffEq.PolyesterThreads())),
Dict(:alg=>ImplicitHairerWannerExtrapolation(threading = false)),
]
solnames = ["CVODE_BDF","KenCarp4","Rodas4","Rodas5","Rodas5P","QNDF","lsoda","radau","seulex","ImplEulerExtpl (threaded)", "ImplEulerExtpl (non-threaded)",
"ImplEulerBaryExtpl (threaded)","ImplEulerBaryExtpl (non-threaded)","ImplHWExtpl (threaded)","ImplHWExtpl (non-threaded)"]
wp = WorkPrecisionSet(prob,abstols,reltols,setups;
names = solnames,save_everystep=false,appxsol=test_sol,maxiters=Int(1e5),numruns=10)
plot(wp, title = "Implicit Methods: POLLUTION",legend=:outertopleft,size = (1000,500),
xticks = 10.0 .^ (-15:1:1),
yticks = 10.0 .^ (-6:0.3:5),
bottom_margin= 5Plots.mm)
```
### Conclusion
Sundials `CVODE_BDF` the best here. `lsoda` does well at high tolerances but then grows fast when tolerances get too low. `KenCarp4` or `Rodas5` is a decent substitute when necessary.
```julia, echo = false
using SciMLBenchmarks
SciMLBenchmarks.bench_footer(WEAVE_ARGS[:folder],WEAVE_ARGS[:file])
```
| SciMLBenchmarks | https://github.com/SciML/SciMLBenchmarks.jl.git |
|
[
"MIT"
] | 0.1.3 | f4076dd5a103010d48bb6c4e50c5526f6622fa96 | docs | 12290 | ---
title: ROBER Work-Precision Diagrams
author: Chris Rackauckas
---
```julia
using OrdinaryDiffEq, DiffEqDevTools, Sundials, ParameterizedFunctions, Plots, ODE, ODEInterfaceDiffEq, LSODA
gr()
using LinearAlgebra, StaticArrays
rober = @ode_def begin
dy₁ = -k₁*y₁+k₃*y₂*y₃
dy₂ = k₁*y₁-k₂*y₂^2-k₃*y₂*y₃
dy₃ = k₂*y₂^2
end k₁ k₂ k₃
prob = ODEProblem{true, SciMLBase.FullSpecialize}(rober,[1.0,0.0,0.0],(0.0,1e5),(0.04,3e7,1e4))
probstatic = ODEProblem{false}(rober,SA[1.0,0.0,0.0],(0.0,1e5),(0.04,3e7,1e4))
sol = solve(prob,CVODE_BDF(),abstol=1/10^14,reltol=1/10^14)
sol2 = solve(probstatic,Rodas5P(),abstol=1/10^14,reltol=1/10^14)
probs = [prob,probstatic]
test_sol = [sol,sol2];
abstols = 1.0 ./ 10.0 .^ (4:11)
reltols = 1.0 ./ 10.0 .^ (1:8);
```
```julia
plot(sol,labels=["y1","y2","y3"])
```
## Omissions And Tweaking
The following were omitted from the tests due to convergence failures. ODE.jl's
adaptivity is not able to stabilize its algorithms, while
GeometricIntegratorsDiffEq has not upgraded to Julia 1.0.
GeometricIntegrators.jl's methods used to be either fail to converge at
comparable dts (or on some computers errors due to type conversions).
```julia
#sol = solve(prob,ode23s()); println("Total ODE.jl steps: $(length(sol))")
#using GeometricIntegratorsDiffEq
#try
# sol = solve(prob,GIRadIIA3(),dt=1/10)
#catch e
# println(e)
#end
```
`ARKODE` needs a lower `nonlinear_convergence_coefficient` in order to not diverge.
```julia
#sol = solve(prob,ARKODE(nonlinear_convergence_coefficient = 1e-6),abstol=1e-5,reltol=1e-1); # Noisy, output omitted
```
```julia
sol = solve(prob,ARKODE(nonlinear_convergence_coefficient = 1e-7),abstol=1e-5,reltol=1e-1);
```
Note that `1e-7` matches the value from the Sundials manual which was required for their example to converge on this problem. The default is `1e-1`.
```julia
#sol = solve(prob,ARKODE(order=3),abstol=1e-4,reltol=1e-1); # Fails to diverge but doesn't finish
```
```julia
#sol = solve(prob,ARKODE(order=5),abstol=1e-4,reltol=1e-1); # Noisy, output omitted
```
```julia
#sol = solve(prob,ARKODE(order=5,nonlinear_convergence_coefficient = 1e-9),abstol=1e-5,reltol=1e-1); # Noisy, output omitted
```
Additionally, the ROCK methods do not perform well on this benchmark.
```julia
setups = [
#Dict(:alg=>ROCK2()) #Unstable
#Dict(:alg=>ROCK4()) #needs more iterations
]
```
Some of the bad Rosenbrocks fail:
```julia
setups = [
#Dict(:alg=>Hairer4()),
#Dict(:alg=>Hairer42()),
#Dict(:alg=>Cash4()),
]
```
The EPIRK and exponential methods also fail:
```julia
sol = solve(prob,EXPRB53s3(),dt=2.0^(-8));
sol = solve(prob,EPIRK4s3B(),dt=2.0^(-8));
sol = solve(prob,EPIRK5P2(),dt=2.0^(-8));
```
PDIRK44 also fails
```julia
sol = solve(prob,PDIRK44(),dt=2.0^(-8));
```
In fact, all non-adaptive methods fail on this problem.
## High Tolerances
This is the speed when you just want the answer. `ode23s` from ODE.jl was removed since it fails. Note that at high tolerances Sundials' `CVODE_BDF` fails as well so it's excluded from this test.
```julia
abstols = 1.0 ./ 10.0 .^ (5:8)
reltols = 1.0 ./ 10.0 .^ (1:4);
setups = [Dict(:alg=>Rosenbrock23()),
Dict(:alg=>Rosenbrock23(), :prob_choice => 2),
Dict(:alg=>FBDF()),
Dict(:alg=>QNDF()),
Dict(:alg=>TRBDF2()),
Dict(:alg=>rodas()),
Dict(:alg=>lsoda()),
Dict(:alg=>radau()),
Dict(:alg=>RadauIIA5()),
Dict(:alg=>ROS34PW1a()),
]
gr()
wp = WorkPrecisionSet(probs,abstols,reltols,setups;
save_everystep=false,appxsol=test_sol,maxiters=Int(1e5),numruns=10)
plot(wp)
```
```julia
setups = [Dict(:alg=>Rosenbrock23()),
Dict(:alg=>Rosenbrock23(), :prob_choice => 2),
Dict(:alg=>Kvaerno3()),
Dict(:alg=>KenCarp4()),
Dict(:alg=>TRBDF2()),
Dict(:alg=>KenCarp3()),
Dict(:alg=>lsoda()),
# Dict(:alg=>SDIRK2()), # Removed because it's bad
Dict(:alg=>radau())]
names = ["Rosenbrock23" "Rosenbrock23 Static" "Kvaerno3" "KenCarp4" "TRBDF2" "KenCarp3" "lsoda" "radau"]
wp = WorkPrecisionSet(probs,abstols,reltols,setups;names=names,
save_everystep=false,appxsol=test_sol,maxiters=Int(1e5),numruns=10)
plot(wp)
```
```julia
setups = [Dict(:alg=>Rosenbrock23()),
Dict(:alg=>Rosenbrock23(), :prob_choice => 2),
Dict(:alg=>KenCarp5()),
Dict(:alg=>KenCarp4()),
Dict(:alg=>KenCarp4(), :prob_choice => 2),
Dict(:alg=>KenCarp3()),
Dict(:alg=>ARKODE(nonlinear_convergence_coefficient = 1e-9,order=5)),
Dict(:alg=>ARKODE(nonlinear_convergence_coefficient = 1e-8)),
Dict(:alg=>ARKODE(nonlinear_convergence_coefficient = 1e-7,order=3))
]
names = ["Rosenbrock23" "Rosenbrock23 Static" "KenCarp5" "KenCarp4" "KenCarp4 Static" "KenCarp3" "ARKODE5" "ARKODE4" "ARKODE3"]
wp = WorkPrecisionSet(probs,abstols,reltols,setups;
names=names,
save_everystep=false,appxsol=test_sol,maxiters=Int(1e5),numruns=10)
plot(wp)
```
```julia
setups = [Dict(:alg=>Rosenbrock23()),
Dict(:alg=>Rosenbrock23(), :prob_choice => 2),
Dict(:alg=>TRBDF2()),
Dict(:alg=>ImplicitEulerExtrapolation()),
Dict(:alg=>ImplicitEulerExtrapolation()),
Dict(:alg=>ImplicitEulerBarycentricExtrapolation()),
Dict(:alg=>ImplicitHairerWannerExtrapolation()),
#Dict(:alg=>ABDF2()), # Maxiters
Dict(:alg=>FBDF()),
Dict(:alg=>QNDF()),
#Dict(:alg=>Exprb43()), #SingularException
#Dict(:alg=>Exprb32()), #SingularException
]
wp = WorkPrecisionSet(probs,abstols,reltols,setups;
save_everystep=false,appxsol=test_sol,maxiters=Int(1e5),numruns=10)
plot(wp)
```
### Timeseries Errors
```julia
abstols = 1.0 ./ 10.0 .^ (5:8)
reltols = 1.0 ./ 10.0 .^ (1:4);
setups = [Dict(:alg=>Rosenbrock23()),
Dict(:alg=>Rosenbrock23(), :prob_choice => 2),
Dict(:alg=>FBDF()),
Dict(:alg=>QNDF()),
Dict(:alg=>TRBDF2()),
Dict(:alg=>rodas()),
Dict(:alg=>lsoda()),
Dict(:alg=>radau()),
Dict(:alg=>RadauIIA5()),
Dict(:alg=>ROS34PW1a()),
]
gr()
wp = WorkPrecisionSet(probs,abstols,reltols,setups;error_estimate=:l2,
save_everystep=false,appxsol=test_sol,maxiters=Int(1e5),numruns=10)
plot(wp)
```
```julia
setups = [Dict(:alg=>Rosenbrock23()),
Dict(:alg=>Rosenbrock23(), :prob_choice => 2),
Dict(:alg=>Kvaerno3()),
Dict(:alg=>KenCarp4()),
Dict(:alg=>TRBDF2()),
Dict(:alg=>KenCarp3()),
# Dict(:alg=>SDIRK2()), # Removed because it's bad
Dict(:alg=>radau())]
names = ["Rosenbrock23" "Rosenbrock23 Static" "Kvaerno3" "KenCarp4" "TRBDF2" "KenCarp3" "radau"]
wp = WorkPrecisionSet(probs,abstols,reltols,setups;names=names,
appxsol=test_sol,maxiters=Int(1e5),error_estimate=:l2,numruns=10)
plot(wp)
```
```julia
setups = [Dict(:alg=>Rosenbrock23()),
Dict(:alg=>Rosenbrock23(), :prob_choice => 2),
Dict(:alg=>TRBDF2()),
Dict(:alg=>ImplicitEulerExtrapolation()),
Dict(:alg=>ImplicitEulerExtrapolation()),
Dict(:alg=>ImplicitEulerBarycentricExtrapolation()),
Dict(:alg=>ImplicitHairerWannerExtrapolation()),
#Dict(:alg=>ABDF2()), # Maxiters
Dict(:alg=>FBDF()),
Dict(:alg=>QNDF()),
#Dict(:alg=>Exprb43()), #SingularException
#Dict(:alg=>Exprb32()), #SingularException
]
wp = WorkPrecisionSet(probs,abstols,reltols,setups;verbose=false,error_estimate=:l2,
save_everystep=false,appxsol=test_sol,maxiters=Int(1e5),numruns=10)
plot(wp)
```
### Low Tolerances
This is the speed at lower tolerances, measuring what's good when accuracy is needed.
```julia
abstols = 1.0 ./ 10.0 .^ (7:12)
reltols = 1.0 ./ 10.0 .^ (4:9)
setups = [#Dict(:alg=>Rodas5()),
Dict(:alg=>FBDF()),
Dict(:alg=>QNDF()),
Dict(:alg=>CVODE_BDF()),
Dict(:alg=>ddebdf()),
Dict(:alg=>Rodas4()),
Dict(:alg=>Rodas4(), :prob_choice => 2),
#Dict(:alg=>Rodas5P()),
Dict(:alg=>rodas()),
Dict(:alg=>lsoda()),
Dict(:alg=>radau()),
Dict(:alg=>RadauIIA5()),
]
wp = WorkPrecisionSet(probs,abstols,reltols,setups;
save_everystep=false,appxsol=test_sol,maxiters=Int(1e5),numruns=10)
plot(wp)
```
```julia
setups = [Dict(:alg=>Kvaerno4()),
Dict(:alg=>Kvaerno5()),
Dict(:alg=>CVODE_BDF()),
Dict(:alg=>KenCarp4()),
Dict(:alg=>KenCarp47()),
Dict(:alg=>KenCarp47(), :prob_choice => 2),
Dict(:alg=>KenCarp5()),
Dict(:alg=>Rodas4()),
Dict(:alg=>Rodas4(), :prob_choice => 2),
#Dict(:alg=>Rodas5P()),
#Dict(:alg=>Rodas5()),
Dict(:alg=>lsoda()),
Dict(:alg=>radau()),
Dict(:alg=>ImplicitEulerExtrapolation()),
Dict(:alg=>ImplicitEulerBarycentricExtrapolation()),
Dict(:alg=>ImplicitHairerWannerExtrapolation()),
]
wp = WorkPrecisionSet(probs,abstols,reltols,setups;
save_everystep=false,appxsol=test_sol,maxiters=Int(1e5),numruns=10)
plot(wp)
```
```julia
abstols = 1.0 ./ 10.0 .^ (10:12)
reltols = 1.0 ./ 10.0 .^ (7:9)
setups = [Dict(:alg=>Rodas4())
Dict(:alg=>Rodas4(), :prob_choice => 2)
Dict(:alg=>Rodas5())
Dict(:alg=>Rodas5(), :prob_choice => 2)
Dict(:alg=>Rodas5P())
Dict(:alg=>Rodas5P(), :prob_choice => 2)]
names = ["Rodas4" "Rodas4 Static" "Rodas5" "Rodas5 Static" "Rodas5P" "Rodas5P Static"]
wp = WorkPrecisionSet(probs,abstols,reltols,setups;names=names,
save_everystep=false,appxsol=test_sol,maxiters=Int(1e5),numruns=10)
plot(wp)
```
Multithreading benchmarks with Parallel Extrapolation Methods
```julia
#Setting BLAS to one thread to measure gains
LinearAlgebra.BLAS.set_num_threads(1)
abstols = 1.0 ./ 10.0 .^ (10:12)
reltols = 1.0 ./ 10.0 .^ (7:9)
setups = [
Dict(:alg=>CVODE_BDF()),
Dict(:alg=>KenCarp4()),
Dict(:alg=>Rodas4()),
Dict(:alg=>Rodas4(), :prob_choice => 2),
Dict(:alg=>Rodas5P()),
Dict(:alg=>Rodas5P(), :prob_choice => 2),
Dict(:alg=>QNDF()),
Dict(:alg=>lsoda()),
Dict(:alg=>radau()),
Dict(:alg=>seulex()),
Dict(:alg=>ImplicitEulerExtrapolation(threading = OrdinaryDiffEq.PolyesterThreads())),
Dict(:alg=>ImplicitEulerExtrapolation(threading = false)),
Dict(:alg=>ImplicitEulerBarycentricExtrapolation(min_order = 4, threading = OrdinaryDiffEq.PolyesterThreads())),
Dict(:alg=>ImplicitEulerBarycentricExtrapolation(min_order = 4, threading = false)),
Dict(:alg=>ImplicitHairerWannerExtrapolation(threading = OrdinaryDiffEq.PolyesterThreads())),
Dict(:alg=>ImplicitHairerWannerExtrapolation(threading = false)),
]
solnames = ["CVODE_BDF","KenCarp4","Rodas4","Rodas4 Static","Rodas5P","Rodas5P Static","QNDF","lsoda","radau","seulex","ImplEulerExtpl (threaded)", "ImplEulerExtpl (non-threaded)",
"ImplEulerBaryExtpl (threaded)","ImplEulerBaryExtpl (non-threaded)","ImplHWExtpl (threaded)","ImplHWExtpl (non-threaded)"]
wp = WorkPrecisionSet(probs,abstols,reltols,setups;
names = solnames,save_everystep=false,appxsol=test_sol,maxiters=Int(1e5),numruns=10)
plot(wp, title = "Implicit Methods: ROBER",legend=:outertopleft,size = (1000,500),
xticks = 10.0 .^ (-15:1:1),
yticks = 10.0 .^ (-6:0.3:5),
bottom_margin= 5Plots.mm)
```
### Conclusion
At high tolerances, `Rosenbrock23` and `lsoda` hit the the error estimates and are fast. At lower tolerances and normal user tolerances, `Rodas4` and `Rodas5` are extremely fast. `lsoda` does quite well across both ends. When you get down to `reltol=1e-9` `radau` begins to become as efficient as `Rodas4`, and it continues to do well below that.
```julia, echo = false
using SciMLBenchmarks
SciMLBenchmarks.bench_footer(WEAVE_ARGS[:folder],WEAVE_ARGS[:file])
```
| SciMLBenchmarks | https://github.com/SciML/SciMLBenchmarks.jl.git |
|
[
"MIT"
] | 0.1.3 | f4076dd5a103010d48bb6c4e50c5526f6622fa96 | docs | 13583 | ---
title: VanDerPol Work-Precision Diagrams
author: Chris Rackauckas
---
```julia
using OrdinaryDiffEq, DiffEqDevTools, Sundials, ParameterizedFunctions, Plots, ODE, ODEInterfaceDiffEq, LSODA
gr()
using LinearAlgebra, StaticArrays
van = @ode_def begin
dy = μ*((1-x^2)*y - x)
dx = 1*y
end μ
abstols = 1.0 ./ 10.0 .^ (5:9)
reltols = 1.0 ./ 10.0 .^ (2:6)
prob = ODEProblem{true, SciMLBase.FullSpecialize}(van,[1.0;1.0],(0.0,6.3),1e6)
probstatic = ODEProblem{false}(van,SA[0;2.],(0.0,6.3),1e6)
sol = solve(prob,CVODE_BDF(),abstol=1/10^14,reltol=1/10^14)
sol2 = solve(probstatic,Rodas5P(),abstol=1/10^14,reltol=1/10^14)
probs = [prob,probstatic]
test_sol = [sol,sol2];
```
### Plot Test
```julia
plot(sol,ylim=[-4;4])
```
```julia
plot(sol)
```
## Omissions And Tweaking
The following were omitted from the tests due to convergence failures. ODE.jl's
adaptivity is not able to stabilize its algorithms, while
GeometricIntegratorsDiffEq has not upgraded to Julia 1.0.
GeometricIntegrators.jl's methods used to be either fail to converge at
comparable dts (or on some computers errors due to type conversions).
```julia
#sol = solve(prob,ode23s()); println("Total ODE.jl steps: $(length(sol))")
#using GeometricIntegratorsDiffEq
#try
# sol = solve(prob,GIRadIIA3(),dt=1/1000)
#catch e
# println(e)
#end
```
`ARKODE` needs a lower `nonlinear_convergence_coefficient` in order to not diverge.
```julia
sol = solve(prob,ARKODE(),abstol=1e-4,reltol=1e-2);
```
```julia
sol = solve(prob,ARKODE(nonlinear_convergence_coefficient = 1e-6),abstol=1e-4,reltol=1e-1);
```
```julia
sol = solve(prob,ARKODE(order=3),abstol=1e-4,reltol=1e-1);
```
```julia
sol = solve(prob,ARKODE(nonlinear_convergence_coefficient = 1e-6,order=3),abstol=1e-4,reltol=1e-1);
```
```julia
sol = solve(prob,ARKODE(order=5,nonlinear_convergence_coefficient = 1e-3),abstol=1e-4,reltol=1e-1);
```
```julia
sol = solve(prob,ARKODE(order=5,nonlinear_convergence_coefficient = 1e-4),abstol=1e-4,reltol=1e-1);
```
Additionally, the ROCK methods do not perform well on this benchmark.
```julia
setups = [
#Dict(:alg=>ROCK2()) #Unstable
#Dict(:alg=>ROCK4()) #needs more iterations
#Dict(:alg=>ESERK5()),
]
```
Some of the bad Rosenbrocks fail:
```julia
setups = [
#Dict(:alg=>Hairer4()),
#Dict(:alg=>Hairer42()),
#Dict(:alg=>Cash4()),
]
```
The EPIRK and exponential methods also fail:
```julia
sol = solve(prob,EXPRB53s3(),dt=2.0^(-8));
sol = solve(prob,EPIRK4s3B(),dt=2.0^(-8));
sol = solve(prob,EPIRK5P2(),dt=2.0^(-8));
```
## Low Order and High Tolerance
This tests the case where accuracy is not needed as much and quick robust solutions are necessary. Note that `ARKODE`'s convergence coefficient must be lowered to `1e-7` in order to converge.
#### Final timepoint error
This measures the efficiency to get the value at the endpoint correct.
```julia
abstols = 1.0 ./ 10.0 .^ (4:7)
reltols = 1.0 ./ 10.0 .^ (1:4)
setups = [Dict(:alg=>Rosenbrock23()),
Dict(:alg=>Rosenbrock23(), :prob_choice => 2),
Dict(:alg=>FBDF()),
Dict(:alg=>QNDF()),
Dict(:alg=>CVODE_BDF()),
Dict(:alg=>TRBDF2()),
Dict(:alg=>ddebdf()),
Dict(:alg=>rodas()),
Dict(:alg=>lsoda()),
Dict(:alg=>radau())]
wp = WorkPrecisionSet(probs,abstols,reltols,setups;
save_everystep=false,appxsol=test_sol,maxiters=Int(1e5),seconds=5)
plot(wp)
```
```julia
setups = [Dict(:alg=>Rosenbrock23()),
Dict(:alg=>Rosenbrock23(), :prob_choice => 2),
Dict(:alg=>Rodas3()),
Dict(:alg=>TRBDF2()),
Dict(:alg=>rodas()),
Dict(:alg=>lsoda()),
Dict(:alg=>radau()),
Dict(:alg=>RadauIIA5()),
Dict(:alg=>ROS34PW1a()),
]
gr()
wp = WorkPrecisionSet(probs,abstols,reltols,setups;
save_everystep=false,appxsol=test_sol,maxiters=Int(1e5),numruns=10)
plot(wp)
```
```julia
setups = [Dict(:alg=>Rosenbrock23()),
Dict(:alg=>Rosenbrock23(), :prob_choice => 2),
Dict(:alg=>Kvaerno3()),
Dict(:alg=>KenCarp4()),
Dict(:alg=>TRBDF2()),
Dict(:alg=>KenCarp3()),
Dict(:alg=>ARKODE(nonlinear_convergence_coefficient = 1e-6)),
Dict(:alg=>SDIRK2()),
Dict(:alg=>radau())]
names = ["Rosenbrock23" "Rosenbrock23 Static" "Kvaerno3" "KenCarp4" "TRBDF2" "KenCarp3" "ARKODE" "SDIRK2" "radau"]
wp = WorkPrecisionSet(probs,abstols,reltols,setups;
names=names,save_everystep=false,appxsol=test_sol,maxiters=Int(1e5),seconds=5)
plot(wp)
```
```julia
setups = [Dict(:alg=>Rosenbrock23()),
Dict(:alg=>Rosenbrock23(), :prob_choice => 2),
Dict(:alg=>KenCarp5()),
Dict(:alg=>KenCarp4()),
Dict(:alg=>KenCarp4(), :prob_choice => 2),
Dict(:alg=>KenCarp3()),
Dict(:alg=>ARKODE(order=5,nonlinear_convergence_coefficient = 1e-4)),
Dict(:alg=>ARKODE(nonlinear_convergence_coefficient = 1e-6)),
Dict(:alg=>ARKODE(nonlinear_convergence_coefficient = 1e-6,order=3))]
names = ["Rosenbrock23" "Rosenbrock23 Static" "KenCarp5" "KenCarp4" "KenCarp4 Static" "KenCarp3" "ARKODE5" "ARKODE4" "ARKODE3"]
wp = WorkPrecisionSet(probs,abstols,reltols,setups;
names=names,save_everystep=false,appxsol=test_sol,maxiters=Int(1e5),seconds=5)
plot(wp)
```
```julia
setups = [Dict(:alg=>Rosenbrock23()),
Dict(:alg=>TRBDF2()),
Dict(:alg=>ImplicitEulerExtrapolation()),
Dict(:alg=>ImplicitEulerExtrapolation()),
Dict(:alg=>ImplicitEulerBarycentricExtrapolation()),
Dict(:alg=>ImplicitHairerWannerExtrapolation()),
Dict(:alg=>ABDF2()),
Dict(:alg=>FBDF()),
#Dict(:alg=>QNDF()), # ???
#Dict(:alg=>Exprb43()), # Diverges
#Dict(:alg=>Exprb32()), # SingularException
]
wp = WorkPrecisionSet(probs,abstols,reltols,setups;
save_everystep=false,appxsol=test_sol,maxiters=Int(1e5),numruns=10)
plot(wp)
```
Notice that `KenCarp4` is the same overarching algorithm as `ARKODE` here (with major differences to stage predictors and adaptivity though). In this case, `KenCarp4` is more robust and more efficient than `ARKODE`. `CVODE_BDF` does quite well here, which is unusual for it on small equations. You can see that the low-order Rosenbrock methods `Rosenbrock23` and `Rodas3` dominate this test.
#### Timeseries error
Now we measure the average error of the timeseries.
```julia
abstols = 1.0 ./ 10.0 .^ (4:7)
reltols = 1.0 ./ 10.0 .^ (1:4)
setups = [Dict(:alg=>Rosenbrock23()),
Dict(:alg=>Rosenbrock23(), :prob_choice => 2),
Dict(:alg=>FBDF()),
#Dict(:alg=>QNDF()),
Dict(:alg=>CVODE_BDF()),
Dict(:alg=>TRBDF2()),
Dict(:alg=>ddebdf()),
Dict(:alg=>rodas()),
Dict(:alg=>lsoda()),
Dict(:alg=>radau())]
wp = WorkPrecisionSet(probs,abstols,reltols,setups;
error_estimate=:l2,appxsol=test_sol,maxiters=Int(1e5),seconds=5)
plot(wp)
```
```julia
setups = [Dict(:alg=>Rosenbrock23()),
Dict(:alg=>Rosenbrock23(), :prob_choice => 2),
Dict(:alg=>Rodas3()),
Dict(:alg=>TRBDF2()),
Dict(:alg=>rodas()),
Dict(:alg=>lsoda()),
Dict(:alg=>radau()),
Dict(:alg=>RadauIIA5()),
Dict(:alg=>ROS34PW1a()),
]
gr()
wp = WorkPrecisionSet(probs,abstols,reltols,setups;error_estimate=:l2,
save_everystep=false,appxsol=test_sol,maxiters=Int(1e5),numruns=10)
plot(wp)
```
### Higher accuracy tests
Now we transition to higher accracy tests. In this domain higher order methods are stable and much more efficient.
```julia
abstols = 1.0 ./ 10.0 .^ (7:11)
reltols = 1.0 ./ 10.0 .^ (4:8)
setups = [Dict(:alg=>Rodas3()),
#Dict(:alg=>FBDF()), #Diverges
#Dict(:alg=>QNDF()),
Dict(:alg=>Rodas4P()),
Dict(:alg=>Rodas5P()),
Dict(:alg=>Rodas5P(), :prob_choice => 2),
Dict(:alg=>CVODE_BDF()),
Dict(:alg=>Rodas4()),
Dict(:alg=>Rodas4(), :prob_choice => 2),
Dict(:alg=>rodas()),
Dict(:alg=>radau()),
Dict(:alg=>lsoda()),
Dict(:alg=>RadauIIA5()),
Dict(:alg=>Rodas5()),
Dict(:alg=>ImplicitEulerExtrapolation()),
Dict(:alg=>ImplicitEulerBarycentricExtrapolation()),
Dict(:alg=>ImplicitHairerWannerExtrapolation()),
]
wp = WorkPrecisionSet(probs,abstols,reltols,setups;
save_everystep=false,appxsol=test_sol,maxiters=Int(1e6),seconds=5)
plot(wp)
```
```julia
abstols = 1.0 ./ 10.0 .^ (7:11)
reltols = 1.0 ./ 10.0 .^ (4:8)
setups = [Dict(:alg=>Rodas3()),
Dict(:alg=>Kvaerno4()),
Dict(:alg=>Kvaerno5()),
Dict(:alg=>CVODE_BDF()),
Dict(:alg=>KenCarp4()),
Dict(:alg=>KenCarp5()),
Dict(:alg=>ARKODE()),
Dict(:alg=>Rodas4()),
Dict(:alg=>Rodas5P()),
Dict(:alg=>Rodas5P(), :prob_choice => 2),
Dict(:alg=>radau()),
Dict(:alg=>Rodas5())]
names = ["Rodas3" "Kvaerno4" "Kvaerno5" "CVODE_BDF" "KenCarp4" "KenCarp5" "ARKODE" "Rodas4" "Rodas5P" "Rodas5P Static" "radau" "Rodas5"]
wp = WorkPrecisionSet(probs,abstols,reltols,setups;
names=names,save_everystep=false,appxsol=test_sol,maxiters=Int(1e6),seconds=5)
plot(wp)
```
```julia
setups = [Dict(:alg=>Rodas3()),
Dict(:alg=>CVODE_BDF()),
Dict(:alg=>Rodas4()),
Dict(:alg=>radau()),
Dict(:alg=>Rodas5()),
Dict(:alg=>Rodas5P()),
Dict(:alg=>Rodas5P(), :prob_choice => 2)]
wp = WorkPrecisionSet(probs,abstols,reltols,setups;
save_everystep=false,appxsol=test_sol,maxiters=Int(1e6),seconds=5)
plot(wp)
```
#### Timeseries Errors
```julia
abstols = 1.0 ./ 10.0 .^ (7:11)
reltols = 1.0 ./ 10.0 .^ (4:8)
setups = [Dict(:alg=>Rodas3()),
#Dict(:alg=>FBDF()), #Diverges
#Dict(:alg=>QNDF()),
Dict(:alg=>Rodas4P()),
Dict(:alg=>Rodas5P(), :prob_choice => 2),
Dict(:alg=>CVODE_BDF()),
Dict(:alg=>Rodas4()),
Dict(:alg=>Rodas4(), :prob_choice => 2),
Dict(:alg=>rodas()),
Dict(:alg=>radau()),
Dict(:alg=>lsoda()),
Dict(:alg=>RadauIIA5()),
Dict(:alg=>Rodas5())]
wp = WorkPrecisionSet(probs,abstols,reltols,setups;error_estimate=:l2,
save_everystep=false,appxsol=test_sol,maxiters=Int(1e6),seconds=5)
plot(wp)
```
```julia
setups = [Dict(:alg=>Rodas3()),
Dict(:alg=>Kvaerno4()),
Dict(:alg=>Kvaerno5()),
Dict(:alg=>CVODE_BDF()),
Dict(:alg=>KenCarp4()),
Dict(:alg=>KenCarp5()),
Dict(:alg=>Rodas4()),
Dict(:alg=>radau()),
Dict(:alg=>Rodas5()),
Dict(:alg=>Rodas5P()),
Dict(:alg=>Rodas5P(), :prob_choice => 2)]
names = ["Rodas3" "Kvaerno4" "Kvaerno5" "CVODE_BDF" "KenCarp4" "KenCarp5" "Rodas4" "radau" "Rodas5" "Rodas5P" "Rodas5P Static"]
wp = WorkPrecisionSet(probs,abstols,reltols,setups;
names=names,appxsol=test_sol,maxiters=Int(1e6),error_estimate=:l2,seconds=5)
plot(wp)
```
```julia
setups = [Dict(:alg=>CVODE_BDF()),
Dict(:alg=>Rodas4()),
Dict(:alg=>radau()),
Dict(:alg=>Rodas5()),
Dict(:alg=>Rodas5P()),
Dict(:alg=>Rodas5P(), :prob_choice => 2)]
wp = WorkPrecisionSet(probs,abstols,reltols,setups;
appxsol=test_sol,maxiters=Int(1e6),error_estimate=:l2,seconds=5)
plot(wp)
```
Multithreading benchmarks with Parallel Extrapolation Methods
```julia
#Setting BLAS to one thread to measure gains
LinearAlgebra.BLAS.set_num_threads(1)
abstols = 1.0 ./ 10.0 .^ (7:11)
reltols = 1.0 ./ 10.0 .^ (4:8)
setups = [Dict(:alg=>ImplicitHairerWannerExtrapolation()),
Dict(:alg=>ImplicitHairerWannerExtrapolation(threading = true)),
Dict(:alg=>ImplicitHairerWannerExtrapolation(threading = OrdinaryDiffEq.PolyesterThreads())),
]
names = ["unthreaded","threaded","Polyester"];
wp = WorkPrecisionSet(probs,abstols,reltols,setups;
names = names,save_everystep=false,appxsol=test_sol,maxiters=Int(1e5))
plot(wp)
```
The timeseries test is a little odd here because of the high peaks in the VanDerPol oscillator. At a certain accuracy, the steps try to resolve those peaks and so the error becomes higher.
While the higher order order Julia-based Rodas methods (`Rodas4` and `Rodas4P`) Rosenbrock methods are not viable at higher tolerances, they dominate for a large portion of this benchmark. When the tolerance gets low enough, `radau` adaptive high order (up to order 13) takes the lead.
### Conclusion
`Rosenbrock23` and `Rodas3` do well when tolerances are higher. In most standard tolerances, `Rodas4` and `Rodas4P` do extremely well. Only when the tolerances get very low does `radau` do well. The Julia Rosenbrock methods vastly outperform their Fortran counterparts. `CVODE_BDF` is a top performer in the final timepoint errors with low accuracy, but take that with a grain of salt because the problem is periodic which means it's getting the spikes wrong but the low parts correct. `ARKODE` does poorly in these tests. `lsoda` does quite well in both low and high accuracy domains, but is never the top.
```julia, echo = false
using SciMLBenchmarks
SciMLBenchmarks.bench_footer(WEAVE_ARGS[:folder],WEAVE_ARGS[:file])
```
| SciMLBenchmarks | https://github.com/SciML/SciMLBenchmarks.jl.git |
|
[
"MIT"
] | 0.1.3 | f4076dd5a103010d48bb6c4e50c5526f6622fa96 | docs | 2609 | ---
title: Oval2 Long Run
author: Chris Rackauckas
---
```julia
using StochasticDiffEq, SDEProblemLibrary, Random
prob = SDEProblemLibrary.oval2ModelExample(largeFluctuations=true,useBigs=false)
```
```julia
Random.seed!(250)
prob = remake(prob,tspan = (0.0,500.0))
sol = solve(prob,SRIW1(),dt=(1/2)^(18),progress=true,qmax=1.125,
saveat=0.1,abstol=1e-5,reltol=1e-3,maxiters=1e7);
Random.seed!(250)
prob = remake(prob,tspan = (0.0,500.0))
@time sol = solve(prob,SRIW1(),dt=(1/2)^(18),progress=true,qmax=1.125,
saveat=0.1,abstol=1e-5,reltol=1e-3,maxiters=1e7);
```
```julia
println(maximum(sol[:,2]))
using Plots; gr()
lw = 2
lw2 = 3
p1 = plot(sol,vars=(0,16),
title="(A) Timeseries of Ecad Concentration",xguide="Time (s)",
yguide="Concentration",guidefont=font(16),tickfont=font(16),
linewidth=lw,leg=false)
```
```julia
p2 = plot(sol,vars=(0,17),
title="(B) Timeseries of Vim Concentration",xguide="Time (s)",
yguide="Concentration",guidefont=font(16),
tickfont=font(16),linewidth=lw,leg=false)
```
```julia
prob = remake(prob,tspan = (0.0,1.0))
## Little Run
sol = solve(prob,EM(),dt=(1/2)^(20),
progressbar=true,saveat=0.1)
println("EM")
@time sol = solve(prob,EM(),dt=(1/2)^(20),
progressbar=true,saveat=0.1)
sol = solve(prob,SRI(),dt=(1/2)^(18),adaptive=false,
progressbar=true,save_everystep=false)
println("SRI")
@time sol = solve(prob,SRI(),dt=(1/2)^(18),adaptive=false,
progressbar=true,save_everystep=false)
sol = solve(prob,SRIW1(),dt=(1/2)^(18),adaptive=false,
adaptivealg=:RSwM3,progressbar=false,qmax=4,saveat=0.1)
println("SRIW1")
@time sol = solve(prob,SRIW1(),dt=(1/2)^(18),adaptive=false,
adaptivealg=:RSwM3,progressbar=false,qmax=4,saveat=0.1)
sol = solve(prob,SRI(),dt=(1/2)^(18),
adaptivealg=:RSwM3,progressbar=false,qmax=1.125,
saveat=0.1,abstol=1e-6,reltol=1e-4)
println("SRI Adaptive")
@time sol = solve(prob,SRI(),dt=(1/2)^(18),
adaptivealg=:RSwM3,progressbar=false,qmax=1.125,
saveat=0.1,abstol=1e-6,reltol=1e-4)
@show length(sol.t)
sol = solve(prob,SRIW1(),dt=(1/2)^(18),
adaptivealg=:RSwM3,progressbar=false,qmax=1.125,
saveat=0.1,abstol=1e-6,reltol=1e-4)
println("SRIW1 Adaptive")
@time sol = solve(prob,SRIW1(),dt=(1/2)^(18),
adaptivealg=:RSwM3,progressbar=false,qmax=1.125,
saveat=0.1,abstol=1e-6,reltol=1e-4)
@show length(sol.t)
```
```julia, echo = false
using SciMLBenchmarks
SciMLBenchmarks.bench_footer(WEAVE_ARGS[:folder],WEAVE_ARGS[:file])
```
| SciMLBenchmarks | https://github.com/SciML/SciMLBenchmarks.jl.git |
|
[
"MIT"
] | 0.1.3 | f4076dd5a103010d48bb6c4e50c5526f6622fa96 | docs | 2546 | ---
title: Oval2 Long Times
author: Chris Rackauckas
---
```julia
using StochasticDiffEq, SDEProblemLibrary, Random
Random.seed!(200)
prob = SDEProblemLibrary.oval2ModelExample(largeFluctuations=true,useBigs=false)
using LinearAlgebra
BLAS.set_num_threads(1)
```
```julia
Random.seed!(200)
@time for i in 1:10
sol = solve(prob,SRIW1(),dt=(1/2)^(18),qmax=1.125,
saveat=0.1,maxiters=1e7,abstol=1e-5,reltol=1e-3)
end
```
```julia
Random.seed!(200)
@time for i in 1:10
@show i
sol = solve(prob,ImplicitEM(),dt=1/60000)
end
```
```julia
Random.seed!(200)
@time for i in 1:10
@show i
sol = solve(prob,ImplicitRKMil(),dt=1/50000)
end
```
```julia
Random.seed!(200)
@time for i in 1:10
sol = solve(prob,SOSRI(),dt=(1/2)^(18),qmax=1.125,
saveat=0.1,maxiters=1e7,abstol=1e-4,reltol=1e-2)
end
```
```julia
Random.seed!(200)
@time for i in 1:10
sol = solve(prob,SOSRI2(),dt=(1/2)^(18),qmax=1.125,
saveat=0.1,maxiters=1e7,abstol=1e-4,reltol=1e-4)
end
```
```julia
Random.seed!(200)
@time for i in 1:10
sol = solve(prob,SOSRI2(),dt=(1/2)^(18),qmax=1.125,
saveat=0.1,maxiters=1e7,abstol=1e-5,reltol=1e-3)
end
```
```julia
Random.seed!(200)
@time for i in 1:10
sol = solve(prob,SOSRI(),dt=(1/2)^(18),qmax=1.125,
saveat=0.1,maxiters=1e7,abstol=1e-3,reltol=1e-2)
end
```
```julia
Random.seed!(200)
@time for i in 1:10
sol = solve(prob,SOSRI(),dt=(1/2)^(18),qmax=1.125,
saveat=0.1,maxiters=1e7,abstol=1e-4,reltol=1e-4)
end
```
```julia
Random.seed!(200)
@time for i in 1:10
sol = solve(prob,SOSRI(),dt=(1/2)^(18),qmax=1.125,
saveat=0.1,maxiters=1e7,abstol=1e-2,reltol=1e-2)
end
```
```julia
Random.seed!(200)
@time for i in 1:10
sol = solve(prob,SOSRI(),dt=(1/2)^(18),qmax=1.125,
saveat=0.1,maxiters=1e7,abstol=1e-5,reltol=1e-3)
end
```
```julia
Random.seed!(200)
@time for i in 1:10
sol = solve(prob,SOSRI(),dt=(1/2)^(18),qmax=1.125,
saveat=0.1,maxiters=1e7,abstol=1e-2,reltol=1e-1)
end
```
```julia
Random.seed!(200)
@time for i in 1:10
sol = solve(prob,SOSRI2(),dt=(1/2)^(18),qmax=1.125,
saveat=0.1,maxiters=1e7,abstol=1e-4,reltol=1e-1)
end
```
```julia
Random.seed!(200)
@time for i in 1:10
@show i
sol = solve(prob,ImplicitEM(),dt=1/50000)
end
```
```julia
Random.seed!(200)
@time for i in 1:10
@show i
sol = solve(prob,ImplicitRKMil(),dt=1/40000)
end
```
```julia, echo = false
using SciMLBenchmarks
SciMLBenchmarks.bench_footer(WEAVE_ARGS[:folder],WEAVE_ARGS[:file])
```
| SciMLBenchmarks | https://github.com/SciML/SciMLBenchmarks.jl.git |
|
[
"MIT"
] | 0.1.3 | f4076dd5a103010d48bb6c4e50c5526f6622fa96 | docs | 11360 | ---
title: Oval2 Timings
author: Chris Rackauckas
---
```julia
using StochasticDiffEq, SDEProblemLibrary, Random, Base.Threads
prob = SDEProblemLibrary.oval2ModelExample(largeFluctuations=true,useBigs=false)
prob_func(prob,i,repeat) = remake(prob,seed=i)
prob = EnsembleProblem(remake(prob,tspan=(0.0,1.0)),prob_func=prob_func)
js = 16:21
dts = 1.0 ./ 2.0 .^ (js)
trajectories = 1000
fails = Array{Int}(undef,length(dts),3)
times = Array{Float64}(undef,length(dts),3)
```
## Timing Runs
```julia
sol = solve(prob,SRIW1(),EnsembleThreads(),abstol=2.0^(-13),reltol=2.0^(-7),maxiters=Int(1e11),qmax=1.125,save_everystep=false,trajectories=Threads.nthreads())
adaptive_time = @elapsed sol = solve(prob,SRIW1(),EnsembleThreads(),abstol=2.0^(-13),reltol=2.0^(-7),maxiters=Int(1e11),qmax=1.125,save_everystep=false,trajectories=trajectories)
numfails = sum([Int(any(isnan,sol[i]) || sol[i].t[end] != 1) for i in 1:trajectories])
best_adaptive_time = numfails != 0 ? Inf : adaptive_time
println("The number of Adaptive Fails is $numfails. Elapsed time was $adaptive_time")
```
```julia
sol = solve(prob,SRI(error_terms=2),EnsembleThreads(),abstol=2.0^(-13),reltol=2.0^(-7),maxiters=Int(1e11),qmax=1.125,save_everystep=false,trajectories=Threads.nthreads())
adaptive_time = @elapsed sol = solve(prob,SRI(error_terms=2),EnsembleThreads(),abstol=2.0^(-13),reltol=2.0^(-7),maxiters=Int(1e11),qmax=1.125,save_everystep=false,trajectories=trajectories)
numfails = sum([Int(any(isnan,sol[i]) || sol[i].t[end] != 1) for i in 1:trajectories])
best_adaptive_time = numfails != 0 ? adaptive_time : min(best_adaptive_time,adaptive_time)
println("The number of Adaptive Fails is $numfails. Elapsed time was $adaptive_time")
```
```julia
sol = solve(prob,SRI(),EnsembleThreads(),abstol=2.0^(-14),reltol=2.0^(-18),maxiters=Int(1e11),qmax=1.125,save_everystep=false,trajectories=Threads.nthreads())
adaptive_time = @elapsed sol = solve(prob,SRI(),EnsembleThreads(),abstol=2.0^(-14),reltol=2.0^(-18),maxiters=Int(1e11),qmax=1.125,save_everystep=false,trajectories=trajectories)
numfails = sum([Int(any(isnan,sol[i]) || sol[i].t[end] != 1) for i in 1:trajectories])
best_adaptive_time = numfails != 0 ? adaptive_time : min(best_adaptive_time,adaptive_time)
println("The number of Adaptive Fails is $numfails. Elapsed time was $adaptive_time")
```
```julia
sol = solve(prob,SRI(tableau=StochasticDiffEq.constructSRIOpt1()),EnsembleThreads(),abstol=2.0^(-7),reltol=2.0^(-4),maxiters=Int(1e11),qmax=1.125,save_everystep=false,trajectories=Threads.nthreads())
adaptive_time = @elapsed sol = solve(prob,SRI(tableau=StochasticDiffEq.constructSRIOpt1()),EnsembleThreads(),abstol=2.0^(-7),reltol=2.0^(-4),maxiters=Int(1e11),qmax=1.125,save_everystep=false,trajectories=trajectories)
numfails = sum([Int(any(isnan,sol[i]) || sol[i].t[end] != 1) for i in 1:trajectories])
best_adaptive_time = numfails != 0 ? adaptive_time : min(best_adaptive_time,adaptive_time)
println("The number of Adaptive Fails is $numfails. Elapsed time was $adaptive_time")
```
```julia
sol = solve(prob,SOSRI(),EnsembleThreads(),abstol=2.0^(-7),reltol=2.0^(-4),maxiters=Int(1e11),qmax=1.125,save_everystep=false,trajectories=Threads.nthreads())
adaptive_time = @elapsed sol = solve(prob,SOSRI(),EnsembleThreads(),abstol=2.0^(-7),reltol=2.0^(-4),maxiters=Int(1e11),qmax=1.125,save_everystep=false,trajectories=trajectories)
numfails = sum([Int(any(isnan,sol[i]) || sol[i].t[end] != 1) for i in 1:trajectories])
best_adaptive_time = numfails != 0 ? adaptive_time : min(best_adaptive_time,adaptive_time)
println("The number of Adaptive Fails is $numfails. Elapsed time was $adaptive_time")
```
```julia
sol = solve(prob,SOSRI(),EnsembleThreads(),abstol=2.0^(-7),reltol=2.0^(-6),maxiters=Int(1e11),qmax=1.125,save_everystep=false,trajectories=Threads.nthreads())
adaptive_time = @elapsed sol = solve(prob,SOSRI(),EnsembleThreads(),abstol=2.0^(-7),reltol=2.0^(-6),maxiters=Int(1e11),qmax=1.125,save_everystep=false,trajectories=trajectories)
numfails = sum([Int(any(isnan,sol[i]) || sol[i].t[end] != 1) for i in 1:trajectories])
best_adaptive_time = numfails != 0 ? adaptive_time : min(best_adaptive_time,adaptive_time)
println("The number of Adaptive Fails is $numfails. Elapsed time was $adaptive_time")
```
```julia
sol = solve(prob,SOSRI(),EnsembleThreads(),abstol=2.0^(-12),reltol=2.0^(-15),maxiters=Int(1e11),qmax=1.125,save_everystep=false,trajectories=Threads.nthreads())
adaptive_time = @elapsed sol = solve(prob,SOSRI(),EnsembleThreads(),abstol=2.0^(-12),reltol=2.0^(-15),maxiters=Int(1e11),qmax=1.125,save_everystep=false,trajectories=trajectories)
numfails = sum([Int(any(isnan,sol[i]) || sol[i].t[end] != 1) for i in 1:trajectories])
best_adaptive_time = numfails != 0 ? adaptive_time : min(best_adaptive_time,adaptive_time)
println("The number of Adaptive Fails is $numfails. Elapsed time was $adaptive_time")
```
```julia
sol = solve(prob,SOSRI(),EnsembleThreads(),abstol=2.0^(-13),reltol=2.0^(-7),maxiters=Int(1e11),qmax=1.125,save_everystep=false,trajectories=Threads.nthreads())
adaptive_time = @elapsed sol = solve(prob,SOSRI(),EnsembleThreads(),abstol=2.0^(-13),reltol=2.0^(-7),maxiters=Int(1e11),qmax=1.125,save_everystep=false,trajectories=trajectories)
numfails = sum([Int(any(isnan,sol[i]) || sol[i].t[end] != 1) for i in 1:trajectories])
best_adaptive_time = numfails != 0 ? adaptive_time : min(best_adaptive_time,adaptive_time)
println("The number of Adaptive Fails is $numfails. Elapsed time was $adaptive_time")
```
```julia
sol = solve(prob,SOSRI(),EnsembleThreads(),abstol=2.0^(-12),reltol=2.0^(-15),maxiters=Int(1e11),qmax=1.125,save_everystep=false,trajectories=Threads.nthreads())
adaptive_time = @elapsed sol = solve(prob,SOSRI(),EnsembleThreads(),abstol=2.0^(-12),reltol=2.0^(-15),maxiters=Int(1e11),qmax=1.125,save_everystep=false,trajectories=trajectories)
numfails = sum([Int(any(isnan,sol[i]) || sol[i].t[end] != 1) for i in 1:trajectories])
best_adaptive_time = numfails != 0 ? adaptive_time : min(best_adaptive_time,adaptive_time)
println("The number of Adaptive Fails is $numfails. Elapsed time was $adaptive_time")
```
```julia
sol = solve(prob,SOSRI2(),EnsembleThreads(),abstol=2.0^(-12),reltol=2.0^(-15),maxiters=Int(1e11),qmax=1.125,save_everystep=false,trajectories=Threads.nthreads())
adaptive_time = @elapsed sol = solve(prob,SOSRI2(),EnsembleThreads(),abstol=2.0^(-12),reltol=2.0^(-15),maxiters=Int(1e11),qmax=1.125,save_everystep=false,trajectories=trajectories)
numfails = sum([Int(any(isnan,sol[i]) || sol[i].t[end] != 1) for i in 1:trajectories])
best_adaptive_time = numfails != 0 ? adaptive_time : min(best_adaptive_time,adaptive_time)
println("The number of Adaptive Fails is $numfails. Elapsed time was $adaptive_time")
```
```julia
sol = solve(prob,SOSRI2(),EnsembleThreads(),abstol=2.0^(-13),reltol=2.0^(-11),maxiters=Int(1e11),qmax=1.125,save_everystep=false,trajectories=Threads.nthreads())
adaptive_time = @elapsed sol = solve(prob,SOSRI2(),EnsembleThreads(),abstol=2.0^(-13),reltol=2.0^(-11),maxiters=Int(1e11),qmax=1.125,save_everystep=false,trajectories=trajectories)
numfails = sum([Int(any(isnan,sol[i]) || sol[i].t[end] != 1) for i in 1:trajectories])
best_adaptive_time = numfails != 0 ? adaptive_time : min(best_adaptive_time,adaptive_time)
println("The number of Adaptive Fails is $numfails. Elapsed time was $adaptive_time")
```
```julia
sol = solve(prob,SOSRI2(),EnsembleThreads(),abstol=2.0^(-13),reltol=2.0^(-11),maxiters=Int(1e11),qmax=1.125,save_everystep=false,trajectories=Threads.nthreads())
adaptive_time = @elapsed sol = solve(prob,SOSRI2(),EnsembleThreads(),abstol=2.0^(-13),reltol=2.0^(-11),maxiters=Int(1e11),qmax=1.125,save_everystep=false,trajectories=trajectories)
numfails = sum([Int(any(isnan,sol[i]) || sol[i].t[end] != 1) for i in 1:trajectories])
best_adaptive_time = numfails != 0 ? adaptive_time : min(best_adaptive_time,adaptive_time)
println("The number of Adaptive Fails is $numfails. Elapsed time was $adaptive_time")
```
```julia
for j in eachindex(js)
println("j = $j")
sol =solve(prob,EM(),EnsembleThreads(),dt=dts[j],maxiters=Int(1e11),save_everystep=false,verbose=false,trajectories=Threads.nthreads())
t1 = @elapsed sol = solve(prob,EM(),EnsembleThreads(),dt=dts[j],maxiters=Int(1e11),save_everystep=false,verbose=false,trajectories=trajectories)
numfails = sum([Int(any(isnan,sol[i]) || sol[i].t[end] != 1) for i in 1:trajectories])
println("The number of Euler-Maruyama Fails is $numfails. Elapsed time was $t1")
fails[j,1] = numfails
times[j,1] = t1
end
```
```julia
for j in 1:4
println("j = $j")
sol =solve(prob,SRIW1(),EnsembleThreads(),dt=dts[j],maxiters=Int(1e11),save_everystep=false,verbose=false,trajectories=Threads.nthreads())
t1 = @elapsed sol = solve(prob,SRIW1(),EnsembleThreads(),dt=dts[j],maxiters=Int(1e11),save_everystep=false,verbose=false,trajectories=trajectories)
numfails = sum([Int(any(isnan,sol[i]) || sol[i].t[end] != 1) for i in 1:trajectories])
println("The number of SRIW1 Fails is $numfails. Elapsed time was $t1")
fails[j,3] = numfails
times[j,3] = t1
end
```
```julia
js = 17:21
dts = 1.0 ./2.0 .^ (js)
for j in 1:6
println("j = $j")
sol =solve(prob,ImplicitEM(),EnsembleThreads(),dt=dts[j],maxiters=Int(1e11),save_everystep=false,verbose=false,trajectories=Threads.nthreads())
t1 = @elapsed sol = solve(prob,ImplicitEM(),EnsembleThreads(),dt=dts[j],maxiters=Int(1e11),save_everystep=false,verbose=false,trajectories=trajectories)
numfails = sum([Int(any(isnan,sol[i]) || sol[i].t[end] != 1) for i in 1:trajectories])
println("The number of Implicit-EM Fails is $numfails. Elapsed time was $t1")
end
```
```julia
js = 17:21
dts = 1.0 ./ 2.0 .^(js)
for j in 1:6
println("j = $j")
sol =solve(prob,ImplicitRKMil(),EnsembleThreads(),dt=dts[j],maxiters=Int(1e11),save_everystep=false,verbose=false,trajectories=Threads.nthreads())
t1 = @elapsed sol = solve(prob,ImplicitRKMil(),EnsembleThreads(),dt=dts[j],maxiters=Int(1e11),save_everystep=false,verbose=false,trajectories=trajectories)
numfails = sum([Int(any(isnan,sol[i]) || sol[i].t[end] != 1) for i in 1:trajectories])
println("The number of Implicit-RKMil Fails is $numfails. Elapsed time was $t1")
end
```
```julia
for j in 1:6
println("j = $j")
sol =solve(prob,RKMil(),EnsembleThreads(),dt=dts[j],maxiters=Int(1e11),save_everystep=false,verbose=false,trajectories=Threads.nthreads())
t1 = @elapsed sol = solve(prob,RKMil(),EnsembleThreads(),dt=dts[j],maxiters=Int(1e11),save_everystep=false,verbose=false,trajectories=trajectories)
numfails = sum([Int(any(isnan,sol[i]) || sol[i].t[end] != 1) for i in 1:trajectories])
println("The number of RKMil Fails is $numfails. Elapsed time was $t1")
fails[j,2] = numfails
times[j,2] = t1
end
```
```julia
using Plots
lw = 3
p2 = plot(dts,times,xscale=:log2,yscale=:log2,guidefont=font(16),tickfont=font(14),yguide="Elapsed Time (s)",xguide=L"Chosen $\Delta t$",top_margin=50px,linewidth=lw,lab=["Euler-Maruyama" "RK-Mil" "RosslerSRI"],legendfont=font(14))
plot!(dts,repmat([best_adaptive_time],11),linewidth=lw,line=:dash,lab="ESRK+RSwM3",left_margin=75px)
scatter!([2.0^(-20);2.0^(-20);2.0^(-18)],[times[5,1];times[5,2];times[3,3]],markersize=20,c=:red,lab="")
plot(p2,size=(800,800))
```
```julia, echo = false
using SciMLBenchmarks
SciMLBenchmarks.bench_footer(WEAVE_ARGS[:folder],WEAVE_ARGS[:file])
```
| SciMLBenchmarks | https://github.com/SciML/SciMLBenchmarks.jl.git |
|
[
"MIT"
] | 0.1.3 | f4076dd5a103010d48bb6c4e50c5526f6622fa96 | docs | 3704 | ---
title: Quadratic Stiffness Benchmarks
author: Chris Rackauckas
---
# Quadratic Stiffness
In this notebook we will explore the quadratic stiffness problem. References:
The composite Euler method for stiff stochastic
differential equations
Kevin Burrage, Tianhai Tian
And
S-ROCK: CHEBYSHEV METHODS FOR STIFF STOCHASTIC
DIFFERENTIAL EQUATIONS
ASSYR ABDULLE AND STEPHANE CIRILLI
This is a scalar SDE with two arguments. The first controls the deterministic stiffness and the later controls the diffusion stiffness.
```julia
using SDEProblemLibrary, StochasticDiffEq, DiffEqDevTools
import SDEProblemLibrary: prob_sde_stiffquadito
using Plots; gr()
const N = 10
```
```julia
prob = remake(prob_sde_stiffquadito,p=(50.0,1.0))
sol = solve(prob,SRIW1())
plot(sol)
```
```julia
prob = remake(prob_sde_stiffquadito,p=(500.0,1.0))
sol = solve(prob,SRIW1())
plot(sol)
```
## Top dts
Let's first determine the maximum dts which are allowed. Anything higher is mostly unstable.
### Deterministic Stiffness Mild
```julia
prob = remake(prob_sde_stiffquadito,p=(50.0,1.0))
@time sol = solve(prob,SRIW1())
@time sol = solve(prob,SRIW1(),adaptive=false,dt=0.01)
@time sol = solve(prob,ImplicitRKMil(),dt=0.005)
@time sol = solve(prob,EM(),dt=0.01);
```
### Deterministic Stiffness High
```julia
prob = remake(prob_sde_stiffquadito,p=(500.0,1.0))
@time sol = solve(prob,SRIW1())
@time sol = solve(prob,SRIW1(),adaptive=false,dt=0.002)
@time sol = solve(prob,ImplicitRKMil(),dt=0.001)
@time sol = solve(prob,EM(),dt=0.002);
```
### Mixed Stiffness
```julia
prob = remake(prob_sde_stiffquadito,p=(5000.0,70.0))
@time sol = solve(prob,SRIW1(),dt=0.0001)
@time sol = solve(prob,SRIW1(),adaptive=false,dt=0.00001)
@time sol = solve(prob,ImplicitRKMil(),dt=0.00001)
@time sol = solve(prob,EM(),dt=0.00001);
```
Notice that in this problem, the stiffness in the noise term still prevents the semi-implicit integrator to do well. In that case, the advantage of implicitness does not take effect, and thus explicit methods do well. When we don't care about the error, Euler-Maruyama is fastest. When there's mixed stiffness, the adaptive algorithm is unstable.
## Work-Precision Diagrams
```julia
prob = remake(prob_sde_stiffquadito,p=(50.0,1.0))
reltols = 1.0 ./ 10.0 .^ (3:5)
abstols = reltols#[0.0 for i in eachindex(reltols)]
setups = [Dict(:alg=>SRIW1()),
Dict(:alg=>EM(),:dts=>1.0./8.0.^((1:length(reltols)) .+ 1)),
Dict(:alg=>SRIW1(),:dts=>1.0./8.0.^((1:length(reltols)) .+ 1),:adaptive=>false)
#Dict(:alg=>RKMil(),:dts=>1.0./8.0.^((1:length(reltols)) .+ 1),:adaptive=>false),
]
names = ["SRIW1","EM","SRIW1 Fixed"] #"RKMil",
wp = WorkPrecisionSet(prob,abstols,reltols,setups;numruns=N,names=names,error_estimate=:l2)
plot(wp)
```
```julia
prob = remake(prob_sde_stiffquadito,p=(500.0,1.0))
reltols = 1.0 ./ 10.0 .^ (3:5)
abstols = reltols#[0.0 for i in eachindex(reltols)]
setups = [Dict(:alg=>SRIW1()),
Dict(:alg=>EM(),:dts=>1.0./8.0.^((1:length(reltols)) .+ 2)),
Dict(:alg=>SRIW1(),:dts=>1.0./8.0.^((1:length(reltols)) .+ 2),:adaptive=>false)
#Dict(:alg=>RKMil(),:dts=>1.0./8.0.^((1:length(reltols)) .+ 2),:adaptive=>false),
]
names = ["SRIW1","EM","SRIW1 Fixed"] #"RKMil",
wp = WorkPrecisionSet(prob,abstols,reltols,setups;numruns=N,names=names,error_estimate=:l2,print_names=true)
plot(wp)
```
## Conclusion
Noise stiffness is tough. Right now the best solution is to run an explicit integrator with a low enough dt. Adaptivity does have a cost in this case, likely due to memory management.
```julia, echo = false
using SciMLBenchmarks
SciMLBenchmarks.bench_footer(WEAVE_ARGS[:folder],WEAVE_ARGS[:file])
```
| SciMLBenchmarks | https://github.com/SciML/SciMLBenchmarks.jl.git |
|
[
"MIT"
] | 0.1.3 | f4076dd5a103010d48bb6c4e50c5526f6622fa96 | docs | 4053 | ---
title: Stochastic Heat Equation Benchmarks
author: Chris Rackauckas
---
# Stochastic Heat Equation Benchmarks
In this notebook we will benchmark against the stochastic heat equation with Dirichlet BCs and scalar noise. The function for generating the problem is as follows:
Stochastic Heat Equation with scalar multiplicative noise
S-ROCK: CHEBYSHEV METHODS FOR STIFF STOCHASTIC
DIFFERENTIAL EQUATIONS
ASSYR ABDULLE AND STEPHANE CIRILLI
Raising D or k increases stiffness
```julia
using StochasticDiffEq, DiffEqNoiseProcess, LinearAlgebra, Statistics
function generate_stiff_stoch_heat(D=1,k=1;N = 100, t_end = 3.0, adaptivealg = :RSwM3)
A = Array(Tridiagonal([1.0 for i in 1:N-1],[-2.0 for i in 1:N],[1.0 for i in 1:N-1]))
dx = 1/N
A = D/(dx^2) * A
function f(du,u,p,t)
mul!(du,A,u)
end
#=
function f(::Type{Val{:analytic}},u0,p,t,W)
exp((A-k/2)*t+W*I)*u0 # no -k/2 for Strat
end
=#
function g(du,u,p,t)
@. du = k*u
end
SDEProblem(f,g,ones(N),(0.0,t_end),noise=WienerProcess(0.0,0.0,0.0,rswm=RSWM(adaptivealg=adaptivealg)))
end
N = 100
D = 1; k = 1
A = Array(Tridiagonal([1.0 for i in 1:N-1],[-2.0 for i in 1:N],[1.0 for i in 1:N-1]))
dx = 1/N
A = D/(dx^2) * A;
```
Now lets solve it with high accuracy.
```julia
prob = generate_stiff_stoch_heat(1.0,1.0)
@time sol = solve(prob,SRIW1(),progress=true,abstol=1e-6,reltol=1e-6);
```
## Highest dt
Let's try to find the highest possible dt:
```julia
@time sol = solve(generate_stiff_stoch_heat(1.0,1.0),SRIW1());
```
```julia
@time sol = solve(generate_stiff_stoch_heat(1.0,1.0),SRIW1(),progress=true,adaptive=false,dt=0.00005);
```
```julia
@time sol = solve(generate_stiff_stoch_heat(1.0,1.0),EM(),progress=true,adaptive=false,dt=0.00005);
```
```julia
@time sol = solve(generate_stiff_stoch_heat(1.0,1.0),ImplicitRKMil(),progress=true,dt=0.1);
```
```julia
@time sol = solve(generate_stiff_stoch_heat(1.0,1.0),ImplicitRKMil(),progress=true,dt=0.01);
```
```julia
@time sol = solve(generate_stiff_stoch_heat(1.0,1.0),ImplicitRKMil(),progress=true,dt=0.001);
```
```julia
@time sol = solve(generate_stiff_stoch_heat(1.0,1.0),ImplicitEM(),progress=true,dt=0.001);
```
## Simple Error Analysis
Now let's check the error at an arbitrary timepoint in there. Our analytical solution only exists in the Stratanovich sense, so we are limited in the methods we can calculate errors for.
```julia
function simple_error(alg;kwargs...)
sol = solve(generate_stiff_stoch_heat(1.0,1.0,t_end=0.25),alg;kwargs...);
sum(abs2,sol[end] - exp(A*sol.t[end]+sol.W[end]*I)*prob.u0)
end
```
```julia
mean(simple_error(EulerHeun(),dt=0.00005) for i in 1:400)
```
```julia
mean(simple_error(ImplicitRKMil(interpretation=:Stratanovich),dt=0.1) for i in 1:400)
```
```julia
mean(simple_error(ImplicitRKMil(interpretation=:Stratanovich),dt=0.01) for i in 1:400)
```
```julia
mean(simple_error(ImplicitRKMil(interpretation=:Stratanovich),dt=0.001) for i in 1:400)
```
```julia
mean(simple_error(ImplicitEulerHeun(),dt=0.001) for i in 1:400)
```
```julia
mean(simple_error(ImplicitEulerHeun(),dt=0.01) for i in 1:400)
```
```julia
mean(simple_error(ImplicitEulerHeun(),dt=0.1) for i in 1:400)
```
## Interesting Property
Note that RSwM1 and RSwM2 are not stable on this problem.
```julia
sol = solve(generate_stiff_stoch_heat(1.0,1.0,adaptivealg=:RSwM1),SRIW1());
```
## Conclusion
In this problem, the implicit methods do not have a stepsize limit. This is because the stiffness almost entirely deteriministic due to diffusion. In that case, if we do not care about the error too much, the implicit methods dominate. Of course, as the tolerance gets lower there is a tradeoff point where the higher order methods will become more efficient. The explicit methods are clearly stability-bound and thus unless we want an error of like 10^-10 we are better off using an implicit method here.
```julia, echo = false
using SciMLBenchmarks
SciMLBenchmarks.bench_footer(WEAVE_ARGS[:folder],WEAVE_ARGS[:file])
```
| SciMLBenchmarks | https://github.com/SciML/SciMLBenchmarks.jl.git |
|
[
"MIT"
] | 0.1.3 | f4076dd5a103010d48bb6c4e50c5526f6622fa96 | docs | 507 | ---
title: Test
author: Chris Rackauckas
---
This is a test of the builder system. It often gets bumped in PRs related to CI.
```julia
using InteractiveUtils
versioninfo()
```
```julia
Threads.nthreads()
```
```julia
using Plots
plot(rand(10,10))
```
```math
\begin{equation}
y'(t) = \frac{0.2y(t-14)}{1 + y(t-14)^{10}} - 0.1y(t)
\end{equation}
```
$\alpha$
``u_0``
## Appendix
```julia, echo = false
using SciMLBenchmarks
SciMLBenchmarks.bench_footer(WEAVE_ARGS[:folder],WEAVE_ARGS[:file])
```
| SciMLBenchmarks | https://github.com/SciML/SciMLBenchmarks.jl.git |
|
[
"MIT"
] | 3.6.1 | db6084790646024c59a036eb1e694c646b3b738e | code | 1040 | using Documenter, DiffEqBayes
cp("./docs/Manifest.toml", "./docs/src/assets/Manifest.toml", force = true)
cp("./docs/Project.toml", "./docs/src/assets/Project.toml", force = true)
ENV["PLOTS_TEST"] = "true"
ENV["GKSwstype"] = "100"
include("pages.jl")
makedocs(sitename = "DiffEqBayes.jl",
authors = "Chris Rackauckas, Vaibhav Kumar Dixit et al.",
clean = true,
doctest = false,
modules = [DiffEqBayes],
strict = [
:doctest,
:linkcheck,
:parse_error,
:example_block,
# Other available options are
# :autodocs_block, :cross_references, :docs_block, :eval_block, :example_block, :footnote, :meta_block, :missing_docs, :setup_block
],
format = Documenter.HTML(assets = ["assets/favicon.ico"],
canonical = "https://docs.sciml.ai/DiffEqBayes/stable/"),
pages = pages)
deploydocs(repo = "github.com/SciML/DiffEqBayes.jl.git";
push_preview = true)
| DiffEqBayes | https://github.com/SciML/DiffEqBayes.jl.git |
|
[
"MIT"
] | 3.6.1 | db6084790646024c59a036eb1e694c646b3b738e | code | 113 | pages = ["index.md",
"Methods" => "methods.md",
"Examples" => ["examples.md", "examples/pendulum.md"],
]
| DiffEqBayes | https://github.com/SciML/DiffEqBayes.jl.git |
|
[
"MIT"
] | 3.6.1 | db6084790646024c59a036eb1e694c646b3b738e | code | 808 | """
$(DocStringExtensions.README)
"""
module DiffEqBayes
using DiffEqBase, Distributions, Turing, MacroTools
using RecursiveArrayTools, ModelingToolkit, LinearAlgebra
using Parameters, Distributions, Optim, Requires
using Distances, DocStringExtensions, Random, StanSample
using DynamicHMC, TransformVariables, LogDensityProblemsAD, TransformedLogDensities
STANDARD_PROB_GENERATOR(prob, p) = remake(prob; u0 = eltype(p).(prob.u0), p = p)
function STANDARD_PROB_GENERATOR(prob::EnsembleProblem, p)
EnsembleProblem(remake(prob.prob; u0 = eltype(p).(prob.prob.u0), p = p))
end
include("turing_inference.jl")
# include("abc_inference.jl")
include("stan_string.jl")
include("stan_inference.jl")
include("dynamichmc_inference.jl")
export turing_inference, stan_inference, dynamichmc_inference
end # module
| DiffEqBayes | https://github.com/SciML/DiffEqBayes.jl.git |
|
[
"MIT"
] | 3.6.1 | db6084790646024c59a036eb1e694c646b3b738e | code | 1820 | function createabcfunction(prob, t, distancefunction, alg; save_idxs = nothing,
sample_u0 = false, kwargs...)
function simfunc(params, constants, data)
local u0
if sample_u0
u0 = save_idxs === nothing ? params[1:length(prob.u0)] :
params[1:length(save_idxs)]
if length(u0) < length(prob.u0)
for i in length(u0):length(prob.u0)
push!(u0, prob.u0[i])
end
end
else
u0 = prob.u0
end
sol = solve(prob, alg, u0 = u0, p = params, saveat = t, save_idxs = save_idxs,
kwargs...)
if size(sol, 2) < length(t)
return Inf, nothing
else
simdata = convert(Array, sol)
return distancefunction(data, simdata), nothing
end
end
end
function abc_inference(prob::DiffEqBase.DEProblem, alg, t, data, priors; ϵ = 0.001,
distancefunction = euclidean, ABCalgorithm = ABCSMC,
progress = false,
num_samples = 500, maxiterations = 10^5, save_idxs = nothing,
sample_u0 = false, parallel = false, kwargs...)
abcsetup = ABCalgorithm(createabcfunction(prob, t, distancefunction, alg;
save_idxs = save_idxs, sample_u0 = sample_u0,
kwargs...),
length(priors),
ϵ,
ApproxBayes.Prior(priors);
nparticles = num_samples,
maxiterations = maxiterations)
abcresult = runabc(abcsetup, data, progress = progress, parallel = parallel)
return abcresult
end
| DiffEqBayes | https://github.com/SciML/DiffEqBayes.jl.git |
|
[
"MIT"
] | 3.6.1 | db6084790646024c59a036eb1e694c646b3b738e | code | 6102 | """
$(TYPEDEF)
Defines a callable that returns the log density for given parameter values when called with
a `NamedTuple` `(parameters = ..., σ = ...)` where `parameters` is a vector of parameters,
and `σ` is the vector of noise scales.
For a common use case, see [`dynamichmc_inference`](@ref).
# Fields
$(FIELDS)
"""
Base.@kwdef struct DynamicHMCPosterior{TA, TP, TD, TT, TR, TS, TK, TI}
"Algorithm for the ODE solver."
algorithm::TA
"An ODE problem definition (`DiffEqBase.DEProblem`)."
problem::TP
"Time values at which the simulated path is compared to `data`."
t::TT
"Data, as a matrix with each time value in a column."
data::TD
"Priors for parameters, an iterable with the same length as the number of parameters."
parameter_priors::TR
"""
Priors for the noise scales (currently the standard deviation of a normal distribution),
one for each variable.
"""
σ_priors::TS
"Keyword arguments passed on the the ODE solver `solve`."
solve_kwargs::TK
sample_u0::Bool
save_idxs::TI
end
function (P::DynamicHMCPosterior)(θ)
@unpack parameters, σ = θ
@unpack algorithm, problem, data, t, parameter_priors = P
@unpack σ_priors, solve_kwargs, sample_u0, save_idxs = P
T = eltype(parameters)
nu = save_idxs === nothing ? length(problem.u0) : length(save_idxs)
u0 = convert.(T, sample_u0 ? parameters[1:nu] : problem.u0)
p = convert.(T, sample_u0 ? parameters[(nu + 1):end] : parameters)
if length(u0) < length(problem.u0)
# assumes u is ordered such that the observed variables are in the beginning, consistent with ordered theta
for i in length(u0):length(problem.u0)
push!(u0, convert(T, problem.u0[i]))
end
end
_saveat = t === nothing ? Float64[] : t
sol = solve(problem, algorithm; u0 = u0, p = p, saveat = _saveat, save_idxs = save_idxs,
solve_kwargs...)
failure = size(sol, 2) < length(_saveat)
failure && return T(0) * sum(σ) + T(-Inf)
log_likelihood = sum(sum(map(logpdf, Normal.(0.0, σ), sol[:, i] .- data[:, i]))
for (i, t) in enumerate(t))
log_prior_parameters = sum(map(logpdf, parameter_priors, parameters))
log_prior_σ = sum(map(logpdf, σ_priors, σ))
log_likelihood + log_prior_parameters + log_prior_σ
end
# function (P::DynamicHMCPosterior)(θ)
# @unpack parameters, σ = θ
# @unpack algorithm, problem, data, t, parameter_priors, σ_priors, solve_kwargs = P
# prob = remake(problem, u0 = convert.(eltype(parameters), problem.u0), p = parameters)
# solution = solve(prob, algorithm; solve_kwargs...)
# any((s.retcode ≠ :Success && s.retcode ≠ :Terminated) for s in solution) && return -Inf
# log_likelihood = sum(sum(logpdf.(Normal.(0.0, σ), solution(t) .- data[:, i]))
# for (i, t) in enumerate(t))
# log_prior_parameters = sum(map(logpdf, parameter_priors, parameters))
# log_prior_σ = sum(map(logpdf, σ_priors, σ))
# log_likelihood + log_prior_parameters + log_prior_σ
# end
"""
$(SIGNATURES)
Run MCMC for an ODE problem. Return a `NamedTuple`, which is similar to the one returned by
`DynamicHMC.mcmc_with_warmup`, with an added field `posterior` which contains a vector of
posterior values (transformed from `ℝⁿ`).
# Arguments
- `problem` is the ODE problem
- `algorithm` is the ODE algorithm
- `t` is the time values at which the solution is compared to `data`
- `data` is a matrix of data, with one column for each element in `t`
- `parameter_priors` is an iterable with the length of the number of paramers, and is used
as a prior on it, should have comparable structure.
- `parameter_transformations`: a `TransformVariables` transformation to mapping `ℝⁿ` to the
vector of valid parameters.
# Keyword arguments
- `rng` is the random number generator used for MCMC. Defaults to the global one.
- `num_samples` is the number of MCMC draws (default: 1000)
- `AD_gradient_kind` is passed on to `LogDensityProblems.ADgradient`, make sure to `import`
the corresponding library.
- `solve_kwargs` is passed on to `solve`
- `mcmc_kwargs` are passed on as keyword arguments to `DynamicHMC.mcmc_with_warmup`
"""
function dynamichmc_inference(problem::DiffEqBase.DEProblem, algorithm, t, data,
parameter_priors,
parameter_transformations = as(Vector, asℝ₊,
length(parameter_priors));
σ_priors = fill(Normal(0, 5), size(data, 1)),
sample_u0 = false, rng = Random.GLOBAL_RNG,
num_samples = 1000, AD_gradient_kind = Val(:ForwardDiff),
save_idxs = nothing, solve_kwargs = (),
mcmc_kwargs = (initialization = (q = zeros(length(parameter_priors) +
(save_idxs ===
nothing ?
length(data[:, 1]) :
length(save_idxs))),),))
P = DynamicHMCPosterior(; algorithm = algorithm, problem = problem, t = t, data = data,
parameter_priors = parameter_priors, σ_priors = σ_priors,
solve_kwargs = solve_kwargs, sample_u0 = sample_u0,
save_idxs = save_idxs)
trans = as((parameters = parameter_transformations,
σ = as(Vector, asℝ₊, length(σ_priors))))
ℓ = TransformedLogDensity(trans, P)
∇ℓ = LogDensityProblemsAD.ADgradient(AD_gradient_kind, ℓ)
results = mcmc_with_warmup(rng, ∇ℓ, num_samples; mcmc_kwargs...)
chain = if haskey(results, :chain) # DynamicHMC < 3.3.0
results.chain
else
eachcol(results.posterior_matrix)
end
posterior = map(Base.Fix1(TransformVariables.transform, trans), chain)
merge((; posterior), results)
end
| DiffEqBayes | https://github.com/SciML/DiffEqBayes.jl.git |
|
[
"MIT"
] | 3.6.1 | db6084790646024c59a036eb1e694c646b3b738e | code | 8116 |
struct StanResult{M, R, C}
model::M
return_code::R
chains::C
end
function Base.show(io::IO, mime::MIME"text/plain", res::StanResult)
show(io, mime, res.chains)
end
struct StanODEData end
function generate_priors(n, priors)
priors_string = ""
if priors === nothing
for i in 1:n
priors_string = string(priors_string, "theta_$i ~ normal(0, 1)", " ; ")
end
else
for i in 1:n
priors_string = string(priors_string, "theta_$i ~ ", stan_string(priors[i]),
";")
end
end
priors_string
end
function generate_theta(n, priors)
theta = ""
for i in 1:n
upper_bound = ""
lower_bound = ""
if !isnothing(priors) && maximum(priors[i]) != Inf
upper_bound = string("upper=", maximum(priors[i]))
end
if !isnothing(priors) && minimum(priors[i]) != -Inf
lower_bound = string("lower=", minimum(priors[i]))
end
if lower_bound != "" && upper_bound != ""
theta = string(theta, "real", "<$lower_bound", ",", "$upper_bound>",
" theta_$i", ";")
elseif lower_bound != ""
theta = string(theta, "real", "<$lower_bound", ">", " theta_$i", ";")
elseif upper_bound != ""
theta = string(theta, "real", "<", "$upper_bound>", " theta_$i", ";")
else
theta = string(theta, "real", " theta_$i", ";")
end
end
return theta
end
function stan_inference(prob::DiffEqBase.DEProblem,
# Positional arguments
t, data, priors = nothing, stanmodel = nothing;
# DiffEqBayes keyword arguments
likelihood = Normal, vars = (StanODEData(), InverseGamma(3, 3)),
sample_u0 = false, save_idxs = nothing, diffeq_string = nothing,
# Stan differential equation function keyword arguments
alg = :rk45, reltol = 1e-3, abstol = 1e-6, maxiter = Int(1e5),
# stan_sample keyword arguments
num_samples = 1000, num_warmups = 1000,
num_cpp_chains = 1, num_chains = 1, num_threads = 1,
delta = 0.8,
# read_samples arguments
output_format = :mcmcchains,
# read_summary arguments
print_summary = true,
# pass in existing tmpdir
tmpdir = mktempdir())
save_idxs !== nothing && length(save_idxs) == 1 ? save_idxs = save_idxs[1] :
save_idxs = save_idxs
length_of_y = length(prob.u0)
save_idxs = something(save_idxs, 1:length_of_y)
length_of_params = length(vars)
if isnothing(diffeq_string)
sys = ModelingToolkit.modelingtoolkitize(prob)
length_of_parameter = length(ModelingToolkit.parameters(sys)) +
sample_u0 * length(save_idxs)
else
length_of_parameter = length(prob.p) + sample_u0 * length(save_idxs)
end
if stanmodel === nothing
if alg == :adams
algorithm = "ode_adams_tol"
elseif alg == :rk45
algorithm = "ode_rk45_tol"
elseif alg == :bdf
algorithm = "ode_bdf_tol"
else
error("The choices for alg are :adams, :rk45, or :bdf")
end
hyper_params = ""
tuple_hyper_params = ""
setup_params = ""
thetas = ""
theta_names = ""
theta_string = generate_theta(length_of_parameter, priors)
for i in 1:length_of_parameter
thetas = string(thetas, "real theta_$i", ";")
theta_names = string(theta_names, "theta_$i", ",")
end
for i in 1:length_of_params
if isa(vars[i], StanODEData)
tuple_hyper_params = string(tuple_hyper_params, "u_hat[t,$save_idxs]", ",")
else
dist = stan_string(vars[i])
hyper_params = string(hyper_params, "sigma$(i-1) ~ $dist;")
tuple_hyper_params = string(tuple_hyper_params, "sigma$(i-1)", ",")
setup_params = string(setup_params,
"row_vector<lower=0>[$(length(save_idxs))] sigma$(i-1);")
end
end
tuple_hyper_params = tuple_hyper_params[1:(length(tuple_hyper_params) - 1)]
priors_string = string(generate_priors(length_of_parameter, priors))
stan_likelihood = stan_string(likelihood)
if sample_u0
nu = length(save_idxs)
dv_names_ind = findfirst("$nu", theta_names)[1]
if nu < length(prob.u0)
u0 = ""
for u_ in prob.u0[(nu + 1):length(prob.u0)]
u0 = u0 * string(u_)
end
integral_string = "u_hat = $algorithm(sho, [$(theta_names[1:dv_names_ind]),$u0]', t0, ts, $reltol, $abstol, $maxiter, $(rstrip(theta_names[dv_names_ind+2:end],',')));"
else
integral_string = "u_hat = $algorithm(sho, [$(theta_names[1:dv_names_ind])]', t0, ts, $reltol, $abstol, $maxiter, $(rstrip(theta_names[dv_names_ind+2:end],',')));"
end
else
integral_string = "u_hat = $algorithm(sho, u0, t0, ts, $reltol, $abstol, $maxiter, $(rstrip(theta_names,',')));"
end
binsearch_string = """
int bin_search(real x, int min_val, int max_val){
int range = (max_val - min_val + 1) / 2;
int mid_pt = min_val + range;
int out;
while (range > 0) {
if (x == mid_pt) {
out = mid_pt;
range = 0;
} else {
range = (range + 1) / 2;
mid_pt = x > mid_pt ? mid_pt + range: mid_pt - range;
}
}
return out;
}
"""
if isnothing(diffeq_string)
diffeq_string = ModelingToolkit.build_function(ModelingToolkit.equations(sys),
ModelingToolkit.states(sys),
ModelingToolkit.parameters(sys),
ModelingToolkit.get_iv(sys);
expression = Val{true},
fname = :sho,
target = ModelingToolkit.StanTarget())
end
parameter_estimation_model = "
functions {
$diffeq_string
}
data {
vector[$length_of_y] u0;
int<lower=1> T;
real internal_var___u[T,$(length(save_idxs))];
real t0;
real ts[T];
}
parameters {
$setup_params
$theta_string
}
model{
vector[$length_of_y] u_hat[T];
$hyper_params
$priors_string
$integral_string
for (t in 1:T){
internal_var___u[t,:] ~ $stan_likelihood($tuple_hyper_params);
}
}
"
stanmodel = SampleModel("parameter_estimation_model",
parameter_estimation_model,
tmpdir)
end
data = Dict("u0" => prob.u0, "T" => length(t),
"internal_var___u" => view(data, :, 1:length(t)),
"t0" => prob.tspan[1], "ts" => t)
@time rc = stan_sample(stanmodel; data, num_threads, num_cpp_chains,
num_samples, num_warmups, num_chains, delta)
if success(rc)
return StanResult(stanmodel, rc, read_samples(stanmodel, output_format))
else
rc.err
end
end
| DiffEqBayes | https://github.com/SciML/DiffEqBayes.jl.git |
|
[
"MIT"
] | 3.6.1 | db6084790646024c59a036eb1e694c646b3b738e | code | 6100 | using Distributions
function stan_string(p::Union{Type{Bernoulli}, Bernoulli})
try
parameters = (params(p)[1])
return string("bernoulli($parameters)")
catch
return string("bernoulli")
end
end
function stan_string(p::Union{Type{Binomial}, Binomial})
try
parameters = (params(p)[1], params(p)[2])
return string("binomial$parameters")
catch
return string("binomial")
end
end
function stan_string(p::Union{Type{BetaBinomial}, BetaBinomial})
try
parameters = (params(p)[1], params(p)[2], params(p)[3])
return string("beta_binomial$parameters")
catch
return string("beta_binomial")
end
end
function stan_string(p::Union{Type{Hypergeometric}, Hypergeometric})
try
parameters = (params(p)[1], params(p)[2], params(p)[3])
return string("hypergeometric$parameters")
catch
return string("hypergeometric")
end
end
function stan_string(p::Union{Type{Categorical}, Categorical})
try
parameters = (params(p)[1])
return string("categorical($parameters)")
catch
return string("categorical")
end
end
function stan_string(p::Union{Type{NegativeBinomial}, NegativeBinomial})
try
parameters = (params(p)[1], params(p)[2])
return string("neg_binomial$parameters")
catch
return string("neg_binomial")
end
end
function stan_string(p::Union{Type{Poisson}, Poisson})
try
parameters = (params(p)[1])
return string("poisson($parameters)")
catch
return string("poisson")
end
end
function stan_string(p::Union{Type{Normal}, Normal})
try
parameters = (params(p)[1], params(p)[2])
return string("normal$parameters")
catch
return string("normal")
end
end
function stan_string(p::Union{Type{TDist}, TDist})
try
parameters = (params(p)[1])
return string("student_t($parameters,0,1)")
catch
return string("student_t")
end
end
function stan_string(p::Union{Type{Cauchy}, Cauchy})
try
parameters = (params(p)[1], params(p)[2])
return string("cauchy$parameters")
catch
return string("cauchy")
end
end
function stan_string(p::Union{Type{Laplace}, Laplace})
try
parameters = (params(p)[1], params(p)[2])
return string("double_exponential$parameters")
catch
return string("double_exponential")
end
end
function stan_string(p::Union{Type{Distributions.Logistic}, Distributions.Logistic})
try
parameters = (params(p)[1], params(p)[2])
return string("logistic$parameters")
catch
return string("logistic")
end
end
function stan_string(p::Union{Type{Gumbel}, Gumbel})
try
parameters = (params(p)[1], params(p)[2])
return string("gumbel$parameters")
catch
return string("gumbel")
end
end
function stan_string(p::Union{Type{LogNormal}, LogNormal})
try
parameters = (params(p)[1], params(p)[2])
return string("lognormal$parameters")
catch
return string("lognormal")
end
end
function stan_string(p::Union{Type{Chisq}, Chisq})
try
parameters = (params(p)[1])
return string("chi_square($parameters)")
catch
return string("chi_square")
end
end
function stan_string(p::Union{Type{Exponential}, Exponential})
try
parameters = (params(p)[1])
return string("exponential($parameters)")
catch
return string("exponential")
end
end
function stan_string(p::Union{Type{Gamma}, Gamma})
try
parameters = (params(p)[1], params(p)[2])
return string("gamma$parameters")
catch
return string("gamma")
end
end
function stan_string(p::Union{Type{InverseGamma}, InverseGamma})
try
parameters = (params(p)[1], params(p)[2])
return string("inv_gamma$parameters")
catch
return string("inv_gamma")
end
end
function stan_string(p::Union{Type{Weibull}, Weibull})
try
parameters = (params(p)[1], params(p)[2])
return string("weibull$parameters")
catch
return string("weibull")
end
end
function stan_string(p::Union{Type{Frechet}, Frechet})
try
parameters = (params(p)[1], params(p)[2])
return string("frechet$parameters")
catch
return string("frechet")
end
end
function stan_string(p::Union{Type{Rayleigh}, Rayleigh})
try
parameters = (params(p)[1])
return string("rayleigh($parameters)")
catch
return string("rayleigh")
end
end
function stan_string(p::Union{Type{Pareto}, Pareto})
try
parameters = (params(p)[1], params(p)[2])
return string("pareto$parameters")
catch
return string("pareto")
end
end
function stan_string(p::Union{Type{GeneralizedPareto}, GeneralizedPareto})
try
parameters = (params(p)[1], params(p)[2], params(p)[3])
return string("pareto_type_2$parameters")
catch
return string("pareto_type_2")
end
end
function stan_string(p::Union{Type{Beta}, Beta})
try
parameters = (params(p)[1], params(p)[2])
return string("beta$parameters")
catch
return string("beta")
end
end
function stan_string(p::Union{Type{Uniform}, Uniform})
try
parameters = (params(p)[1], params(p)[2])
return string("uniform$parameters")
catch
return string("uniform")
end
end
function stan_string(p::Union{Type{VonMises}, VonMises})
try
parameters = (params(p)[1], params(p)[2])
return string("von_mises$parameters")
catch
return string("von_mises")
end
end
function stan_string(p::Truncated)
min_truncated, max_truncated = extrema(p)
min_untruncated, max_untruncated = extrema(p.untruncated)
lower = min_truncated == min_untruncated ? "" : string(min_truncated)
upper = max_truncated == max_untruncated ? "" : string(max_truncated)
raw_string = stan_string(p.untruncated)
return string(raw_string, " T[", lower, ",", upper, "]")
end
| DiffEqBayes | https://github.com/SciML/DiffEqBayes.jl.git |
|
[
"MIT"
] | 3.6.1 | db6084790646024c59a036eb1e694c646b3b738e | code | 2675 | function turing_inference(prob::DiffEqBase.DEProblem,
alg,
t,
data,
priors;
likelihood_dist_priors = [InverseGamma(2, 3)],
likelihood = (u, p, t, σ) -> MvNormal(u,
Diagonal((σ[1])^2 *
ones(length(u)))),
num_samples = 1000,
sampler = Turing.NUTS(0.65),
parallel_type = MCMCSerial(),
n_chains = 1,
syms = [Turing.@varname(theta[i]) for i in 1:length(priors)],
sample_u0 = false,
save_idxs = nothing,
progress = false,
kwargs...)
N = length(priors)
Turing.@model function infer(x, ::Type{T} = Float64) where {T <: Real}
theta = Vector{T}(undef, length(priors))
for i in 1:length(priors)
theta[i] ~ NamedDist(priors[i], syms[i])
end
σ = Vector{T}(undef, length(likelihood_dist_priors))
for i in 1:length(likelihood_dist_priors)
σ[i] ~ likelihood_dist_priors[i]
end
nu = save_idxs === nothing ? length(prob.u0) : length(save_idxs)
u0 = convert.(T, sample_u0 ? theta[1:nu] : prob.u0)
p = convert.(T, sample_u0 ? theta[(nu + 1):end] : theta)
if length(u0) < length(prob.u0)
# assumes u is ordered such that the observed variables are in the beginning, consistent with ordered theta
for i in length(u0):length(prob.u0)
push!(u0, convert(T, prob.u0[i]))
end
end
_saveat = t === nothing ? Float64[] : t
sol = solve(prob, alg; u0 = u0, p = p, saveat = _saveat, progress = progress,
save_idxs = save_idxs, kwargs...)
failure = size(sol, 2) < length(_saveat)
if failure
Turing.DynamicPPL.acclogp!!(__varinfo__, -Inf)
return
end
if ndims(sol) == 1
x ~ likelihood(Array(sol), theta, Inf, σ)
else
for i in 1:length(t)
x[:, i] ~ likelihood(sol[:, i], theta, sol.t[i], σ)
end
end
return
end false
# Instantiate a Model object.
model = infer(data)
chn = sample(
model,
sampler,
parallel_type,
num_samples,
n_chains;
progress = progress
)
return chn
end
| DiffEqBayes | https://github.com/SciML/DiffEqBayes.jl.git |
|
[
"MIT"
] | 3.6.1 | db6084790646024c59a036eb1e694c646b3b738e | code | 3395 | using DiffEqBayes, OrdinaryDiffEq, ParameterizedFunctions, Distances, StatsBase,
Distributions, RecursiveArrayTools
using Test
# One parameter case
f1 = @ode_def begin
dx = a * x - x * y
dy = -3y + x * y
end a
u0 = [1.0, 1.0]
tspan = (0.0, 10.0)
prob1 = ODEProblem(f1, u0, tspan, [1.5])
sol = solve(prob1, Tsit5())
t = collect(range(1, stop = 10, length = 10))
randomized = VectorOfArray([(sol(t[i]) + 0.01randn(2)) for i in 1:length(t)])
data = convert(Array, randomized)
priors = [Normal(1.5, 0.01)]
bayesian_result = abc_inference(prob1, Tsit5(), t, data, priors;
num_samples = 500, ϵ = 0.001)
@test mean(bayesian_result.parameters, weights(bayesian_result.weights))≈1.5 atol=0.1
priors = [Normal(1.0, 0.01), Normal(1.0, 0.01), Normal(1.5, 0.01)]
bayesian_result = abc_inference(prob1, Tsit5(), t, data, priors;
num_samples = 500, ϵ = 0.001, sample_u0 = true)
meanvals = mean(bayesian_result.parameters, weights(bayesian_result.weights), 1)
@test meanvals[1]≈1.0 atol=0.1
@test meanvals[2]≈1.0 atol=0.1
@test meanvals[3]≈1.5 atol=0.1
sol = solve(prob1, Tsit5(), save_idxs = [1])
randomized = VectorOfArray([(sol(t[i]) + 0.01randn(1)) for i in 1:length(t)])
data = convert(Array, randomized)
priors = [Normal(1.5, 0.01)]
bayesian_result = abc_inference(prob1, Tsit5(), t, data, priors;
num_samples = 500, ϵ = 0.001, save_idxs = [1])
@test mean(bayesian_result.parameters, weights(bayesian_result.weights))≈1.5 atol=0.1
priors = [Normal(1.0, 0.01), Normal(1.5, 0.01)]
bayesian_result = abc_inference(prob1, Tsit5(), t, data, priors;
num_samples = 500, ϵ = 0.001, sample_u0 = true,
save_idxs = [1])
meanvals = mean(bayesian_result.parameters, weights(bayesian_result.weights), 1)
@test meanvals[1]≈1.0 atol=0.1
@test meanvals[2]≈1.5 atol=0.1
# custom distance-function
weights_ = ones(size(data)) # weighted data
for i in 1:3:length(data)
weights_[i] = 0
data[i] = 1e20 # to test that those points are indeed not used
end
distfn = function (d1, d2)
d = 0.0
for i in 1:length(d1)
d += (d1[i] - d2[i])^2 * weights_[i]
end
return sqrt(d)
end
priors = [Normal(1.5, 0.01)]
bayesian_result = abc_inference(prob1, Tsit5(), t, data, priors;
num_samples = 500, ϵ = 0.001,
distancefunction = distfn)
@test mean(bayesian_result.parameters, weights(bayesian_result.weights))≈1.5 atol=0.1
# Four parameter case
f1 = @ode_def begin
dx = a * x - b * x * y
dy = -c * y + d * x * y
end a b c d
u0 = [1.0, 1.0]
tspan = (0.0, 10.0)
p = [1.5, 1.0, 3.0, 1.0]
prob1 = ODEProblem(f1, u0, tspan, p)
sol = solve(prob1, Tsit5())
t = collect(range(1, stop = 10, length = 10))
randomized = VectorOfArray([(sol(t[i]) + 0.01randn(2)) for i in 1:length(t)])
data = convert(Array, randomized)
priors = [truncated(Normal(1.5, 1), 0, 2), truncated(Normal(1.0, 1), 0, 1.5),
truncated(Normal(3.0, 1), 0, 4), truncated(Normal(1.0, 1), 0, 2)]
bayesian_result = abc_inference(prob1, Tsit5(), t, data, priors; num_samples = 500)
meanvals = mean(bayesian_result.parameters, weights(bayesian_result.weights), 1)
@test meanvals[1]≈1.5 atol=3e-1
@test meanvals[2]≈1.0 atol=3e-1
@test meanvals[3]≈3.0 atol=3e-1
@test meanvals[4]≈1.0 atol=3e-1
| DiffEqBayes | https://github.com/SciML/DiffEqBayes.jl.git |
|
[
"MIT"
] | 3.6.1 | db6084790646024c59a036eb1e694c646b3b738e | code | 4316 | using DiffEqBayes, OrdinaryDiffEq, ParameterizedFunctions, RecursiveArrayTools
using DynamicHMC, TransformVariables, LinearAlgebra
using Parameters, Distributions, Optim
using Test
reporter = LogProgressReport(nothing, 100, 60.0)
f1 = @ode_def LotkaVolterraTest1 begin
dx = a * x - x * y
dy = -3 * y + x * y
end a
p = [1.5]
u0 = [1.0, 1.0]
tspan = (0.0, 10.0)
prob1 = ODEProblem(f1, u0, tspan, p)
σ = 0.01 # noise, fixed for now
t = collect(range(1, stop = 10, length = 10)) # observation times
sol = solve(prob1, Tsit5())
randomized = VectorOfArray([(sol(t[i]) + σ * randn(2)) for i in 1:length(t)])
data = convert(Array, randomized)
mcmc_kwargs = (initialization = (q = zeros(1 + 2),), reporter = reporter)
bayesian_result = dynamichmc_inference(prob1, Tsit5(), t, data, (Normal(1.5, 1),),
as(Vector, asℝ₊, 1), mcmc_kwargs = mcmc_kwargs)
@test mean(p.parameters[1] for p in bayesian_result.posterior)≈p[1] atol=0.1
priors = [Normal(1.0, 0.01), Normal(1.0, 0.01), Normal(1.5, 0.01)]
mcmc_kwargs = (initialization = (q = zeros(3 + 2),), reporter = reporter)
bayesian_result = dynamichmc_inference(prob1, Tsit5(), t, data, priors,
as(Vector, asℝ₊, 3), mcmc_kwargs = mcmc_kwargs,
sample_u0 = true)
@test mean(p.parameters[1] for p in bayesian_result.posterior)≈1.0 atol=0.1
@test mean(p.parameters[2] for p in bayesian_result.posterior)≈1.0 atol=0.1
@test mean(p.parameters[3] for p in bayesian_result.posterior)≈1.5 atol=0.1
sol = solve(prob1, Tsit5(), save_idxs = [1])
randomized = VectorOfArray([(sol(t[i]) + σ * randn(1)) for i in 1:length(t)])
data = convert(Array, randomized)
mcmc_kwargs = (initialization = (q = zeros(1 + 1),), reporter = reporter)
bayesian_result = dynamichmc_inference(prob1, Tsit5(), t, data, (Normal(1.5, 1),),
as(Vector, asℝ₊, 1), mcmc_kwargs = mcmc_kwargs,
save_idxs = [1])
@test mean(p.parameters[1] for p in bayesian_result.posterior)≈p[1] atol=0.1
priors = [Normal(1.0, 0.001), Normal(1.5, 0.001)]
mcmc_kwargs = (initialization = (q = zeros(2 + 1),), reporter = reporter)
bayesian_result = dynamichmc_inference(prob1, Tsit5(), t, data, priors,
as(Vector, asℝ₊, 2), mcmc_kwargs = mcmc_kwargs,
save_idxs = [1], sample_u0 = true)
@test mean(p.parameters[1] for p in bayesian_result.posterior)≈1.0 atol=0.1
@test mean(p.parameters[2] for p in bayesian_result.posterior)≈1.5 atol=0.1
# With hand-code likelihood function
weights_ = ones(size(data)) # weighted data
for i in 1:3:length(data)
weights_[i] = 0
data[i] = 1e20 # to test that those points are indeed not used
end
likelihood = function (sol)
l = zero(eltype(first(sol)))
for (i, t) in enumerate(t)
l += sum(logpdf.(Normal(0.0, σ), sol(t) - data[:, i]) .* weights_[:, i])
end
return l
end
@test_broken bayesian_result = dynamichmc_inference(prob1, Tsit5(), likelihood,
[truncated(Normal(1.5, 1), 0, 2)],
as((a = asℝ₊,)))
@test_broken mean(bayesian_result[1][1])≈1.5 atol=1e-1
f1 = @ode_def LotkaVolterraTest4 begin
dx = a * x - b * x * y
dy = -c * y + d * x * y
end a b c d
u0 = [1.0, 1.0]
tspan = (0.0, 10.0)
p = [1.5, 1.0, 3.0, 1.0]
prob1 = ODEProblem(f1, u0, tspan, p)
sol = solve(prob1, Tsit5())
t = collect(range(1, stop = 10, length = 10))
randomized = VectorOfArray([(sol(t[i]) + 0.01randn(2)) for i in 1:length(t)])
data = convert(Array, randomized)
priors = (a = truncated(Normal(1.5, 0.01), 0, 2),
b = truncated(Normal(1.0, 0.01), 0, 1.5),
c = truncated(Normal(3.0, 0.01), 0, 4),
d = truncated(Normal(1.0, 0.01), 0, 2))
mcmc_kwargs = (initialization = (q = zeros(4 + 2), ϵ = 1.0), reporter = reporter,
warmup_stages = default_warmup_stages(; stepsize_search = nothing))
bayesian_result = dynamichmc_inference(prob1, Tsit5(), t, data, priors,
as(Vector, asℝ₊, 4), mcmc_kwargs = mcmc_kwargs)
@test norm(mean([p.parameters for p in bayesian_result.posterior]) .- p, Inf) ≤ 0.1
| DiffEqBayes | https://github.com/SciML/DiffEqBayes.jl.git |
|
[
"MIT"
] | 3.6.1 | db6084790646024c59a036eb1e694c646b3b738e | code | 495 | using SafeTestsets
const LONGER_TESTS = false
const GROUP = get(ENV, "GROUP", "All")
if GROUP == "All" || GROUP == "Core"
@time @safetestset "DynamicHMC" begin include("dynamicHMC.jl") end
@time @safetestset "Turing" begin include("turing.jl") end
# @time @safetestset "ABC" begin include("abc.jl") end
end
if GROUP == "Stan" || GROUP == "All"
@time @safetestset "Stan_String" begin include("stan_string.jl") end
@time @safetestset "Stan" begin include("stan.jl") end
end
| DiffEqBayes | https://github.com/SciML/DiffEqBayes.jl.git |
|
[
"MIT"
] | 3.6.1 | db6084790646024c59a036eb1e694c646b3b738e | code | 3459 | using DiffEqBayes, OrdinaryDiffEq, ParameterizedFunctions,
RecursiveArrayTools, Distributions, Test
println("One parameter case")
f1 = @ode_def begin
dx = a * x - x * y
dy = -3y + x * y
end a
u0 = [1.0, 1.0]
tspan = (0.0, 10.0)
p = [1.5]
prob1 = ODEProblem(f1, u0, tspan, p)
sol = solve(prob1, Tsit5())
t = collect(range(1, stop = 10, length = 50))
randomized = VectorOfArray([(sol(t[i]) + 0.01randn(2)) for i in 1:length(t)])
data = convert(Array, randomized)
priors = [truncated(Normal(1.5, 0.1), 1.0, 1.8)]
bayesian_result = stan_inference(prob1, t, data, priors; num_samples = 300,
num_warmups = 500, likelihood = Normal)
@test mean(get(bayesian_result.chains, :theta_1)[1])≈1.5 atol=3e-1
# Test norecompile
bayesian_result2 = stan_inference(prob1, t, data, priors, bayesian_result.model;
num_samples = 300, num_warmups = 500, likelihood = Normal)
@test mean(get(bayesian_result2.chains, :theta_1)[1])≈1.5 atol=3e-1
priors = [
truncated(Normal(1.0, 0.01), 0.5, 2.0),
truncated(Normal(1.0, 0.01), 0.5, 2.0),
truncated(Normal(1.5, 0.01), 1.0, 2.0),
]
bayesian_result = stan_inference(prob1, t, data, priors; num_samples = 300,
num_warmups = 500, likelihood = Normal, sample_u0 = true)
@test mean(get(bayesian_result.chains, :theta_1)[1])≈1.0 atol=3e-1
@test mean(get(bayesian_result.chains, :theta_2)[1])≈1.0 atol=3e-1
@test mean(get(bayesian_result.chains, :theta_3)[1])≈1.5 atol=3e-1
sol = solve(prob1, Tsit5(), save_idxs = [1])
randomized = VectorOfArray([(sol(t[i]) + 0.01 * randn(1)) for i in 1:length(t)])
data = convert(Array, randomized)
priors = [truncated(Normal(1.5, 0.1), 0.5, 2)]
bayesian_result = stan_inference(prob1, t, data, priors; num_samples = 300,
num_warmups = 500, likelihood = Normal, save_idxs = [1])
@test mean(get(bayesian_result.chains, :theta_1)[1])≈1.5 atol=3e-1
priors = [truncated(Normal(1.0, 0.01), 0.5, 2), truncated(Normal(1.5, 0.01), 0.5, 2)]
bayesian_result = stan_inference(prob1, t, data, priors; num_samples = 300,
num_warmups = 500, likelihood = Normal, save_idxs = [1],
sample_u0 = true)
@test mean(get(bayesian_result.chains, :theta_1)[1])≈1.0 atol=3e-1
@test mean(get(bayesian_result.chains, :theta_2)[1])≈1.5 atol=3e-1
println("Four parameter case")
f1 = @ode_def begin
dx = a * x - b * x * y
dy = -c * y + d * x * y
end a b c d
u0 = [1.0, 1.0]
tspan = (0.0, 10.0)
p = [1.5, 1.0, 3.0, 1.0]
prob1 = ODEProblem(f1, u0, tspan, p)
sol = solve(prob1, Tsit5())
t = collect(range(1, stop = 10, length = 50))
randomized = VectorOfArray([(sol(t[i]) + 0.01randn(2)) for i in 1:length(t)])
data = convert(Array, randomized)
priors = [truncated(Normal(1.5, 0.01), 0.5, 2), truncated(Normal(1.0, 0.01), 0.5, 1.5),
truncated(Normal(3.0, 0.01), 0.5, 4), truncated(Normal(1.0, 0.01), 0.5, 2)]
bayesian_result = stan_inference(prob1, t, data, priors; num_samples = 100,
num_warmups = 500,
vars = (DiffEqBayes.StanODEData(), InverseGamma(4, 1)))
@test mean(get(bayesian_result.chains, :theta_1)[1])≈1.5 atol=1e-1
@test mean(get(bayesian_result.chains, :theta_2)[1])≈1.0 atol=1e-1
@test mean(get(bayesian_result.chains, :theta_3)[1])≈3.0 atol=1e-1
@test mean(get(bayesian_result.chains, :theta_4)[1])≈1.0 atol=1e-1
| DiffEqBayes | https://github.com/SciML/DiffEqBayes.jl.git |
|
[
"MIT"
] | 3.6.1 | db6084790646024c59a036eb1e694c646b3b738e | code | 4884 | using Distributions, DiffEqBayes
println("Starting the test")
@test DiffEqBayes.stan_string(Bernoulli(1)) == "bernoulli(1.0)"
@test DiffEqBayes.stan_string(Bernoulli) == "bernoulli"
@test DiffEqBayes.stan_string(Binomial(5, 0.3)) == "binomial(5, 0.3)"
@test DiffEqBayes.stan_string(Binomial) == "binomial"
@test DiffEqBayes.stan_string(BetaBinomial(5, 1, 1)) == "beta_binomial(5, 1.0, 1.0)"
@test DiffEqBayes.stan_string(BetaBinomial) == "beta_binomial"
@test DiffEqBayes.stan_string(Hypergeometric(5, 5, 3)) == "hypergeometric(5, 5, 3)"
@test DiffEqBayes.stan_string(Hypergeometric) == "hypergeometric"
@test DiffEqBayes.stan_string(NegativeBinomial(5, 0.3)) == "neg_binomial(5.0, 0.3)"
@test DiffEqBayes.stan_string(NegativeBinomial) == "neg_binomial"
@test DiffEqBayes.stan_string(Poisson(5)) == "poisson(5.0)"
@test DiffEqBayes.stan_string(Poisson) == "poisson"
@test DiffEqBayes.stan_string(Normal(0, 1)) == "normal(0.0, 1.0)"
@test DiffEqBayes.stan_string(Normal) == "normal"
@test DiffEqBayes.stan_string(TDist(5)) == "student_t(5.0,0,1)"
@test DiffEqBayes.stan_string(TDist) == "student_t"
@test DiffEqBayes.stan_string(Cauchy(0, 1)) == "cauchy(0.0, 1.0)"
@test DiffEqBayes.stan_string(Cauchy) == "cauchy"
@test DiffEqBayes.stan_string(Laplace(0, 1)) == "double_exponential(0.0, 1.0)"
@test DiffEqBayes.stan_string(Laplace) == "double_exponential"
@test DiffEqBayes.stan_string(Distributions.Logistic(0, 1)) == "logistic(0.0, 1.0)"
@test DiffEqBayes.stan_string(Distributions.Logistic) == "logistic"
@test DiffEqBayes.stan_string(Gumbel(0, 1)) == "gumbel(0.0, 1.0)"
@test DiffEqBayes.stan_string(Gumbel) == "gumbel"
@test DiffEqBayes.stan_string(LogNormal(0, 1)) == "lognormal(0.0, 1.0)"
@test DiffEqBayes.stan_string(LogNormal) == "lognormal"
@test DiffEqBayes.stan_string(Chisq(5)) == "chi_square(5.0)"
@test DiffEqBayes.stan_string(Chisq) == "chi_square"
@test DiffEqBayes.stan_string(Exponential(5)) == "exponential(5.0)"
@test DiffEqBayes.stan_string(Exponential) == "exponential"
@test DiffEqBayes.stan_string(Gamma(2, 3)) == "gamma(2.0, 3.0)"
@test DiffEqBayes.stan_string(Gamma) == "gamma"
@test DiffEqBayes.stan_string(InverseGamma(2, 3)) == "inv_gamma(2.0, 3.0)"
@test DiffEqBayes.stan_string(InverseGamma) == "inv_gamma"
@test DiffEqBayes.stan_string(Weibull(1, 1)) == "weibull(1.0, 1.0)"
@test DiffEqBayes.stan_string(Weibull) == "weibull"
@test DiffEqBayes.stan_string(Frechet(1, 1)) == "frechet(1.0, 1.0)"
@test DiffEqBayes.stan_string(Frechet) == "frechet"
@test DiffEqBayes.stan_string(Rayleigh(5)) == "rayleigh(5.0)"
@test DiffEqBayes.stan_string(Rayleigh) == "rayleigh"
@test DiffEqBayes.stan_string(Pareto(2, 3)) == "pareto(2.0, 3.0)"
@test DiffEqBayes.stan_string(Pareto) == "pareto"
@test DiffEqBayes.stan_string(GeneralizedPareto(0, 1, 2)) == "pareto_type_2(0.0, 1.0, 2.0)"
@test DiffEqBayes.stan_string(GeneralizedPareto) == "pareto_type_2"
@test DiffEqBayes.stan_string(Beta(3, 3)) == "beta(3.0, 3.0)"
@test DiffEqBayes.stan_string(Beta) == "beta"
@test DiffEqBayes.stan_string(Uniform(1, 4)) == "uniform(1.0, 4.0)"
@test DiffEqBayes.stan_string(Uniform) == "uniform"
@test DiffEqBayes.stan_string(VonMises(0, 2)) == "von_mises(0.0, 2.0)"
@test DiffEqBayes.stan_string(VonMises) == "von_mises"
@test DiffEqBayes.stan_string(truncated(Normal(1, 2), -1, 3)) ==
"normal(1.0, 2.0) T[-1.0,3.0]"
@test DiffEqBayes.stan_string(truncated(Normal(1, 2); lower = -1, upper = 3)) ==
"normal(1.0, 2.0) T[-1.0,3.0]"
@test DiffEqBayes.stan_string(truncated(Normal(1, 2), -Inf, 3)) ==
"normal(1.0, 2.0) T[,3.0]"
@test DiffEqBayes.stan_string(truncated(Normal(1, 2), nothing, 3)) ==
"normal(1.0, 2.0) T[,3.0]"
@test DiffEqBayes.stan_string(truncated(Normal(1, 2); upper = 3)) ==
"normal(1.0, 2.0) T[,3.0]"
@test DiffEqBayes.stan_string(truncated(Normal(1, 2), -1, Inf)) ==
"normal(1.0, 2.0) T[-1.0,]"
@test DiffEqBayes.stan_string(truncated(Normal(1, 2), -1, nothing)) ==
"normal(1.0, 2.0) T[-1.0,]"
@test DiffEqBayes.stan_string(truncated(Normal(1, 2); lower = -1)) ==
"normal(1.0, 2.0) T[-1.0,]"
@test DiffEqBayes.stan_string(truncated(Beta(2, 3), 0.1, 0.4)) ==
"beta(2.0, 3.0) T[0.1,0.4]"
@test DiffEqBayes.stan_string(truncated(Beta(2, 3); lower = 0.1, upper = 0.4)) ==
"beta(2.0, 3.0) T[0.1,0.4]"
@test DiffEqBayes.stan_string(truncated(Beta(2, 3), 0, 0.4)) == "beta(2.0, 3.0) T[,0.4]"
@test DiffEqBayes.stan_string(truncated(Beta(2, 3), nothing, 0.4)) ==
"beta(2.0, 3.0) T[,0.4]"
@test DiffEqBayes.stan_string(truncated(Beta(2, 3); upper = 0.4)) ==
"beta(2.0, 3.0) T[,0.4]"
@test DiffEqBayes.stan_string(truncated(Beta(2, 3), 0.1, 1)) == "beta(2.0, 3.0) T[0.1,]"
@test DiffEqBayes.stan_string(truncated(Beta(2, 3), 0.1, nothing)) ==
"beta(2.0, 3.0) T[0.1,]"
@test DiffEqBayes.stan_string(truncated(Beta(2, 3); lower = 0.1)) ==
"beta(2.0, 3.0) T[0.1,]"
| DiffEqBayes | https://github.com/SciML/DiffEqBayes.jl.git |
|
[
"MIT"
] | 3.6.1 | db6084790646024c59a036eb1e694c646b3b738e | code | 4187 | using DiffEqBayes, OrdinaryDiffEq, ParameterizedFunctions, RecursiveArrayTools
using Test, Distributions, SteadyStateDiffEq
using Turing
println("One parameter case")
f1 = @ode_def begin
dx = a * x - x * y
dy = -3y + x * y
end a
u0 = [1.0, 1.0]
tspan = (0.0, 10.0)
prob1 = ODEProblem(f1, u0, tspan, [1.5])
sol = solve(prob1, Tsit5())
t = collect(range(1, stop = 10, length = 10))
randomized = VectorOfArray([(sol(t[i]) + 0.01randn(2)) for i in 1:length(t)])
data = convert(Array, randomized)
priors = [Normal(1.5, 0.01)]
bayesian_result = turing_inference(prob1, Tsit5(), t, data, priors; num_samples = 500, syms = [:a])
@show bayesian_result
@test mean(get(bayesian_result, :a)[1])≈1.5 atol=3e-1
bayesian_result = turing_inference(prob1, Rosenbrock23(autodiff = false), t, data, priors; num_samples = 500, syms = [:a])
bayesian_result = turing_inference(prob1, Rosenbrock23(), t, data, priors;
num_samples = 500,
syms = [:a])
# --- test Multithreaded sampling
println("Multithreaded case")
result_threaded = turing_inference(prob1, Tsit5(), t, data, priors; num_samples = 500, syms = [:a], parallel_type=MCMCThreads(), n_chains=2)
@test length(result_threaded.value.axes[3]) == 2
@test mean(get(result_threaded, :a)[1])≈1.5 atol=3e-1
# ---
priors = [Normal(1.0, 0.01), Normal(1.0, 0.01), Normal(1.5, 0.01)]
bayesian_result = turing_inference(prob1, Tsit5(), t, data, priors; num_samples = 500, sample_u0 = true, syms = [:u1, :u2, :a])
@test mean(get(bayesian_result, :a)[1])≈1.5 atol=3e-1
@test mean(get(bayesian_result, :u1)[1])≈1.0 atol=3e-1
@test mean(get(bayesian_result, :u2)[1])≈1.0 atol=3e-1
sol = solve(prob1, Tsit5(), save_idxs = [1])
randomized = VectorOfArray([(sol(t[i]) + 0.01 * randn(1)) for i in 1:length(t)])
data = convert(Array, randomized)
priors = [Normal(1.5, 0.01)]
bayesian_result = turing_inference(prob1, Tsit5(), t, data, priors; num_samples = 500,
syms = [:a], save_idxs = [1])
@test mean(get(bayesian_result, :a)[1])≈1.5 atol=3e-1
priors = [Normal(1.0, 0.01), Normal(1.5, 0.01)]
bayesian_result = turing_inference(prob1, Tsit5(), t, data, priors; num_samples = 500,
sample_u0 = true,
syms = [:u1, :a], save_idxs = [1])
@test mean(get(bayesian_result, :a)[1])≈1.5 atol=3e-1
@test mean(get(bayesian_result, :u1)[1])≈1.0 atol=3e-1
println("Four parameter case")
f2 = @ode_def begin
dx = a * x - b * x * y
dy = -c * y + d * x * y
end a b c d
u0 = [1.0, 1.0]
tspan = (0.0, 10.0)
p = [1.5, 1.0, 3.0, 1.0]
prob2 = ODEProblem(f2, u0, tspan, p)
sol = solve(prob2, Tsit5())
t = collect(range(1, stop = 10, length = 10))
randomized = VectorOfArray([(sol(t[i]) + 0.01randn(2)) for i in 1:length(t)])
data = convert(Array, randomized)
priors = [truncated(Normal(1.5, 0.01), 0, 2), truncated(Normal(1.0, 0.01), 0, 1.5),
truncated(Normal(3.0, 0.01), 0, 4), truncated(Normal(1.0, 0.01), 0, 2)]
bayesian_result = turing_inference(prob2, Tsit5(), t, data, priors; num_samples = 500,
syms = [:a, :b, :c, :d])
@show bayesian_result
@test mean(get(bayesian_result, :a)[1])≈1.5 atol=3e-1
@test mean(get(bayesian_result, :b)[1])≈1.0 atol=3e-1
@test mean(get(bayesian_result, :c)[1])≈3.0 atol=3e-1
@test mean(get(bayesian_result, :d)[1])≈1.0 atol=3e-1
println("Steady state problem")
function f(du, u, p, t)
α = p[1]
du[1] = 2 - α * u[1]
du[2] = u[1] - 4u[2]
end
p = [2.0]
u0 = zeros(2)
s_prob = SteadyStateProblem(f, u0, p)
s_sol = solve(s_prob, SSRootfind())
s_sol = solve(s_prob, DynamicSS(Tsit5()), abstol = 1e-4, reltol = 1e-3)
# true data is 1.00, 0.25
data = [1.05, 0.23]
priors = [truncated(Normal(2.0, 0.2), 0, 3)]
bayesian_result = turing_inference(s_prob, DynamicSS(Tsit5()),
nothing, data, priors;
num_samples = 500,
maxiters = 1e6,
syms = [:α],
abstol = 1e-4, reltol = 1e-3,)
@test mean(get(bayesian_result, :α)[1])≈2.0 atol=3e-1
| DiffEqBayes | https://github.com/SciML/DiffEqBayes.jl.git |
|
[
"MIT"
] | 3.6.1 | db6084790646024c59a036eb1e694c646b3b738e | docs | 3848 | # DiffEqBayes.jl
[![Join the chat at https://julialang.zulipchat.com #sciml-bridged](https://img.shields.io/static/v1?label=Zulip&message=chat&color=9558b2&labelColor=389826)](https://julialang.zulipchat.com/#narrow/stream/279055-sciml-bridged)
[![Global Docs](https://img.shields.io/badge/docs-SciML-blue.svg)](https://docs.sciml.ai/DiffEqBayes/stable/)
[![codecov](https://codecov.io/gh/SciML/DiffEqBayes.jl/branch/master/graph/badge.svg)](https://codecov.io/gh/SciML/DiffEqBayes.jl)
[![Build Status](https://github.com/SciML/DiffEqBayes.jl/workflows/CI/badge.svg)](https://github.com/SciML/DiffEqBayes.jl/actions?query=workflow%3ACI)
[![ColPrac: Contributor's Guide on Collaborative Practices for Community Packages](https://img.shields.io/badge/ColPrac-Contributor%27s%20Guide-blueviolet)](https://github.com/SciML/ColPrac)
[![SciML Code Style](https://img.shields.io/static/v1?label=code%20style&message=SciML&color=9558b2&labelColor=389826)](https://github.com/SciML/SciMLStyle)
This repository is a set of extension functionality for estimating the parameters of differential equations using Bayesian methods. It allows the choice of using [CmdStan.jl](https://stanjulia.github.io/CmdStan.jl/stable/), [Turing.jl](https://turing.ml/stable/docs/using-turing/), [DynamicHMC.jl](https://www.tamaspapp.eu/DynamicHMC.jl/stable/) and [ApproxBayes.jl](https://github.com/marcjwilliams1/ApproxBayes.jl) to perform a Bayesian estimation of a differential equation problem specified via the [DifferentialEquations.jl](https://docs.sciml.ai/DiffEqDocs/stable/) interface.
To begin you first need to add this repository using the following command.
```julia
Pkg.add("DiffEqBayes")
using DiffEqBayes
```
## Tutorials and Documentation
For information on using the package,
[see the stable documentation](https://docs.sciml.ai/DiffEqBayes/stable/). Use the
[in-development documentation](https://docs.sciml.ai/DiffEqBayes/dev/) for the version of
the documentation, which contains the unreleased features.
## Example
```julia
using ParameterizedFunctions, OrdinaryDiffEq, RecursiveArrayTools, Distributions
f1 = @ode_def LotkaVolterra begin
dx = a * x - x * y
dy = -3 * y + x * y
end a
p = [1.5]
u0 = [1.0, 1.0]
tspan = (0.0, 10.0)
prob1 = ODEProblem(f1, u0, tspan, p)
σ = 0.01 # noise, fixed for now
t = collect(1.0:10.0) # observation times
sol = solve(prob1, Tsit5())
priors = [Normal(1.5, 1)]
randomized = VectorOfArray([(sol(t[i]) + σ * randn(2)) for i in 1:length(t)])
data = convert(Array, randomized)
using CmdStan #required for using the Stan backend
bayesian_result_stan = stan_inference(prob1, t, data, priors)
bayesian_result_turing = turing_inference(prob1, Tsit5(), t, data, priors)
using DynamicHMC #required for DynamicHMC backend
bayesian_result_hmc = dynamichmc_inference(prob1, Tsit5(), t, data, priors)
bayesian_result_abc = abc_inference(prob1, Tsit5(), t, data, priors)
```
### Using save_idxs to declare observables
You don't always have data for all of the variables of the model. In case of certain latent variables
you can utilise the `save_idxs` kwarg to declare the observed variables and run the inference using any
of the backends as shown below.
```julia
sol = solve(prob1, Tsit5(), save_idxs = [1])
randomized = VectorOfArray([(sol(t[i]) + σ * randn(1)) for i in 1:length(t)])
data = convert(Array, randomized)
using CmdStan #required for using the Stan backend
bayesian_result_stan = stan_inference(prob1, t, data, priors, save_idxs = [1])
bayesian_result_turing = turing_inference(prob1, Tsit5(), t, data, priors, save_idxs = [1])
using DynamicHMC #required for DynamicHMC backend
bayesian_result_hmc = dynamichmc_inference(prob1, Tsit5(), t, data, priors, save_idxs = [1])
bayesian_result_abc = abc_inference(prob1, Tsit5(), t, data, priors, save_idxs = [1])
```
| DiffEqBayes | https://github.com/SciML/DiffEqBayes.jl.git |
|
[
"MIT"
] | 3.6.1 | db6084790646024c59a036eb1e694c646b3b738e | docs | 1696 | # Bayesian Inference of ODE
For this tutorial, we will show how to do Bayesian inference to infer the parameters of
the Lotka-Volterra equations using each of the three backends:
- Turing.jl
- Stan.jl
- DynamicHMC.jl
## Setup
First, let's set up our ODE and the data. For the data, we will simply solve the ODE and
take that solution at some known parameters as the dataset. This looks like the following:
```@example all
using DiffEqBayes, ParameterizedFunctions, OrdinaryDiffEq, RecursiveArrayTools,
Distributions
f1 = @ode_def LotkaVolterra begin
dx = a * x - x * y
dy = -3 * y + x * y
end a
p = [1.5]
u0 = [1.0, 1.0]
tspan = (0.0, 10.0)
prob1 = ODEProblem(f1, u0, tspan, p)
σ = 0.01 # noise, fixed for now
t = collect(1.0:10.0) # observation times
sol = solve(prob1, Tsit5())
priors = [Normal(1.5, 1)]
randomized = VectorOfArray([(sol(t[i]) + σ * randn(2)) for i in 1:length(t)])
data = convert(Array, randomized)
```
## Inference Methods
### Stan
```@example all
using CmdStan #required for using the Stan backend
bayesian_result_stan = stan_inference(prob1, t, data, priors)
```
### Turing
```@example all
bayesian_result_turing = turing_inference(prob1, Tsit5(), t, data, priors)
```
### DynamicHMC
We can use [DynamicHMC.jl](https://github.com/tpapp/DynamicHMC.jl) as the backend
for sampling with the `dynamic_inference` function. It is similarly used as follows:
```@example all
bayesian_result_hmc = dynamichmc_inference(prob1, Tsit5(), t, data, priors)
```
## More Information
For a better idea of the summary statistics and plotting, you can take a look at the [benchmarks](https://github.com/SciML/SciMLBenchmarks.jl).
| DiffEqBayes | https://github.com/SciML/DiffEqBayes.jl.git |
|
[
"MIT"
] | 3.6.1 | db6084790646024c59a036eb1e694c646b3b738e | docs | 2965 | # DiffEqBayes.jl: Bayesian Parameter Estimation for Differential Equations
This repository is a set of extension functionality for estimating the parameters
of differential equations using Bayesian methods. It allows the choice of using
[CmdStan.jl](https://stanjulia.github.io/CmdStan.jl/stable/), [Turing.jl](https://turing.ml/stable/docs/using-turing/), [DynamicHMC.jl](https://www.tamaspapp.eu/DynamicHMC.jl/stable/) and
[ApproxBayes.jl](https://github.com/marcjwilliams1/ApproxBayes.jl) to perform a
Bayesian estimation of a differential equation problem specified via the [DifferentialEquations.jl](https://docs.sciml.ai/DiffEqDocs/stable/) interface.
## Installation
To install DiffEqBayes.jl, use the Julia package manager:
```julia
using Pkg
Pkg.add("DiffEqBayes")
```
## Contributing
- Please refer to the
[SciML ColPrac: Contributor's Guide on Collaborative Practices for Community Packages](https://github.com/SciML/ColPrac/blob/master/README.md)
for guidance on PRs, issues, and other matters relating to contributing to SciML.
- See the [SciML Style Guide](https://github.com/SciML/SciMLStyle) for common coding practices and other style decisions.
- There are a few community forums:
+ The #diffeq-bridged and #sciml-bridged channels in the
[Julia Slack](https://julialang.org/slack/)
+ The #diffeq-bridged and #sciml-bridged channels in the
[Julia Zulip](https://julialang.zulipchat.com/#narrow/stream/279055-sciml-bridged)
+ On the [Julia Discourse forums](https://discourse.julialang.org)
+ See also [SciML Community page](https://sciml.ai/community/)
## Reproducibility
```@raw html
<details><summary>The documentation of this SciML package was built using these direct dependencies,</summary>
```
```@example
using Pkg # hide
Pkg.status() # hide
```
```@raw html
</details>
```
```@raw html
<details><summary>and using this machine and Julia version.</summary>
```
```@example
using InteractiveUtils # hide
versioninfo() # hide
```
```@raw html
</details>
```
```@raw html
<details><summary>A more complete overview of all dependencies and their versions is also provided.</summary>
```
```@example
using Pkg # hide
Pkg.status(; mode = PKGMODE_MANIFEST) # hide
```
```@raw html
</details>
```
```@raw html
You can also download the
<a href="
```
```@eval
using TOML
version = TOML.parse(read("../../Project.toml", String))["version"]
name = TOML.parse(read("../../Project.toml", String))["name"]
link = "https://github.com/SciML/" * name * ".jl/tree/gh-pages/v" * version *
"/assets/Manifest.toml"
```
```@raw html
">manifest</a> file and the
<a href="
```
```@eval
using TOML
version = TOML.parse(read("../../Project.toml", String))["version"]
name = TOML.parse(read("../../Project.toml", String))["name"]
link = "https://github.com/SciML/" * name * ".jl/tree/gh-pages/v" * version *
"/assets/Project.toml"
```
```@raw html
">project</a> file.
```
| DiffEqBayes | https://github.com/SciML/DiffEqBayes.jl.git |
|
[
"MIT"
] | 3.6.1 | db6084790646024c59a036eb1e694c646b3b738e | docs | 5185 | # Bayesian Methods
The following methods require DiffEqBayes.jl:
```julia
using Pkg
Pkg.add("DiffEqBayes")
using DiffEqBayes
```
### stan_inference
```julia
stan_inference(prob::ODEProblem, t, data, priors = nothing; alg = :rk45,
num_samples = 1000, num_warmups = 1000, reltol = 1e-3,
abstol = 1e-6, maxiter = Int(1e5), likelihood = Normal,
vars = (StanODEData(), InverseGamma(2, 3)))
```
`stan_inference` uses [Stan.jl](https://stanjulia.github.io/CmdStan.jl/latest/INTRO/)
to perform the Bayesian inference. The
[Stan installation process](https://stanjulia.github.io/CmdStan.jl/latest/INSTALLATION/)
is required to use this function. `t` is the array of time
and `data` is the array where the first dimension (columns) corresponds to the
array of system values. `priors` is an array of prior distributions for each
parameter, specified via a [Distributions.jl](https://juliastats.github.io/Distributions.jl/dev/)
type. `alg` is a choice between `:rk45` and `:bdf`, the two internal integrators
of Stan. `num_samples` is the number of samples to take per chain, and `num_warmups`
is the number of MCMC warm-up steps. `abstol` and `reltol` are the keyword
arguments for the internal integrator. `likelihood` is the likelihood distribution
to use with the arguments from `vars`, and `vars` is a tuple of priors for the
distributions of the likelihood hyperparameters. The special value `StanODEData()`
in this tuple denotes the position that the ODE solution takes in the likelihood's
parameter list.
### turing_inference
```julia
function turing_inference(prob::DiffEqBase.DEProblem, alg, t, data, priors;
likelihood_dist_priors, likelihood, num_samples = 1000,
sampler = Turing.NUTS(num_samples, 0.65), parallel_type = MCMCSerial(), n_chains = 1, syms, kwargs...)
end
```
`turing_inference` uses [Turing.jl](https://github.com/TuringLang/Turing.jl) to
perform its parameter inference. `prob` can be any `DEProblem` with a corresponding
`alg` choice. `t` is the array of time points and `data` is the set of
observations for the differential equation system at time point `t[i]` (or higher
dimensional). `priors` is an array of prior distributions for each
parameter, specified via a
[Distributions.jl](https://juliastats.github.io/Distributions.jl/dev/)
type. `num_samples` is the number of samples per MCMC chain. Sampling from multiple chains is possible, see [`Turing.jl` documentation](https://turinglang.org/v0.26/docs/using-turing/guide#sampling-multiple-chains), serially or parallelly using `parallel_type` and `n_chains`. The extra `kwargs` are given to the internal differential equation solver.
### dynamichmc_inference
```julia
dynamichmc_inference(prob::DEProblem, alg, t, data, priors, transformations;
σ = 0.01, ϵ = 0.001, initial = Float64[])
```
`dynamichmc_inference` uses [DynamicHMC.jl](https://github.com/tpapp/DynamicHMC.jl) to
perform the Bayesian parameter estimation. `prob` can be any `DEProblem`, `data` is the set
of observations for our model which is to be used in the Bayesian Inference process. `priors` represent the
choice of prior distributions for the parameters to be determined, passed as an array of [Distributions.jl]
(https://juliastats.github.io/Distributions.jl/dev/) distributions. `t` is the array of time points. `transformations`
is an array of [Transformations](https://github.com/tpapp/ContinuousTransformations.jl) imposed for constraining the
parameter values to specific domains. `initial` values for the parameters can be passed, if not passed the means of the
`priors` are used. `ϵ` can be used as a kwarg to pass the initial step size for the NUTS algorithm.
### abc_inference
```julia
abc_inference(prob::DEProblem, alg, t, data, priors; ϵ = 0.001,
distancefunction = euclidean, ABCalgorithm = ABCSMC, progress = false,
num_samples = 500, maxiterations = 10^5, kwargs...)
```
`abc_inference` uses [ApproxBayes.jl](https://github.com/marcjwilliams1/ApproxBayes.jl), which uses Approximate Bayesian Computation (ABC) to
perform its parameter inference. `prob` can be any `DEProblem` with a corresponding
`alg` choice. `t` is the array of time points and `data[:,i]` is the set of
observations for the differential equation system at time point `t[i]` (or higher
dimensional). `priors` is an array of prior distributions for each
parameter, specified via a
[Distributions.jl](https://juliastats.github.io/Distributions.jl/dev/)
type. `num_samples` is the number of posterior samples. `ϵ` is the target
distance between the data and simulated data. `distancefunction` is a distance metric specified from the
[Distances.jl](https://github.com/JuliaStats/Distances.jl)
package, the default is `euclidean`. `ABCalgorithm` is the ABC algorithm to use, options are `ABCSMC` or `ABCRejection` from
[ApproxBayes.jl](https://github.com/marcjwilliams1/ApproxBayes.jl), the default
is the former which is more efficient. `maxiterations` is the maximum number of iterations before the algorithm terminates. The extra `kwargs` are given to the internal differential
equation solver.
| DiffEqBayes | https://github.com/SciML/DiffEqBayes.jl.git |
|
[
"MIT"
] | 3.6.1 | db6084790646024c59a036eb1e694c646b3b738e | docs | 4712 | # Bayesian Inference of Pendulum Parameters
In this tutorial, we will perform Bayesian parameter inference of the parameters of a
pendulum.
## Set up simple pendulum problem
```@example pendulum
using DiffEqBayes, OrdinaryDiffEq, RecursiveArrayTools, Distributions, Plots, StatsPlots,
BenchmarkTools, TransformVariables, CmdStan, DynamicHMC
```
Let's define our simple pendulum problem. Here, our pendulum has a drag term `ω`
and a length `L`.
![pendulum](https://user-images.githubusercontent.com/1814174/59942945-059c1680-942f-11e9-991c-2025e6e4ccd3.jpg)
We get first order equations by defining the first term as the velocity and the
second term as the position, getting:
```@example pendulum
function pendulum(du, u, p, t)
ω, L = p
x, y = u
du[1] = y
du[2] = -ω * y - (9.8 / L) * sin(x)
end
u0 = [1.0, 0.1]
tspan = (0.0, 10.0)
prob1 = ODEProblem(pendulum, u0, tspan, [1.0, 2.5])
```
## Solve the model and plot
To understand the model and generate data, let's solve and visualize the solution
with the known parameters:
```@example pendulum
sol = solve(prob1, Tsit5())
plot(sol)
```
It's the pendulum, so you know what it looks like. It's periodic, but since we
have not made a small angle assumption, it's not exactly `sin` or `cos`. Because
the true dampening parameter `ω` is 1, the solution does not decay over time,
nor does it increase. The length `L` determines the period.
## Create some dummy data to use for estimation
We now generate some dummy data to use for estimation
```@example pendulum
t = collect(range(1, stop = 10, length = 10))
randomized = VectorOfArray([(sol(t[i]) + 0.01randn(2)) for i in 1:length(t)])
data = convert(Array, randomized)
```
Let's see what our data looks like on top of the real solution
```@example pendulum
scatter!(data')
```
This data captures the non-dampening effect and the true period, making it
perfect for attempting a Bayesian inference.
## Perform Bayesian Estimation
Now let's fit the pendulum to the data. Since we know our model is correct,
this should give us back the parameters that we used to generate the data!
Define priors on our parameters. In this case, let's assume we don't have much
information, but have a prior belief that ω is between 0.1 and 3.0, while the
length of the pendulum L is probably around 3.0:
```@example pendulum
priors = [
truncated(Normal(0.1, 1.0), lower = 0.0),
truncated(Normal(3.0, 1.0), lower = 0.0),
]
```
Finally, let's run the estimation routine from DiffEqBayes.jl with the Turing.jl backend to check if we indeed recover the parameters!
```@example pendulum
bayesian_result = turing_inference(prob1, Tsit5(), t, data, priors; num_samples = 10_000,
syms = [:omega, :L])
```
Notice that while our guesses had the wrong means, the learned parameters converged
to the correct means, meaning that it learned good posterior distributions for the
parameters. To look at these posterior distributions on the parameters, we can
examine the chains:
```@example pendulum
plot(bayesian_result)
```
As a diagnostic, we will also check the parameter chains. The chain is the MCMC
sampling process. The chain should explore parameter space and converge reasonably
well, and we should be taking a lot of samples after it converges (it is these
samples that form the posterior distribution!)
```@example pendulum
plot(bayesian_result, colordim = :parameter)
```
Notice that after a while these chains converge to a “fuzzy line”, meaning it
found the area with the most likelihood and then starts to sample around there,
which builds a posterior distribution around the true mean.
DiffEqBayes.jl allows the choice of using Stan.jl, Turing.jl and DynamicHMC.jl
for MCMC, you can also use ApproxBayes.jl for Approximate Bayesian computation algorithms.
Let's compare the timings across the different MCMC backends.
We'll stick with the default arguments and 10,000 samples in each.
However, there is a lot of room for micro-optimization
specific to each package and algorithm combinations,
you might want to do your own experiments for specific problems
to get better understanding of the performance.
```@example pendulum
@btime bayesian_result = turing_inference(prob1, Tsit5(), t, data, priors;
syms = [:omega, :L], num_samples = 10_000)
```
```@example pendulum
@btime bayesian_result = stan_inference(prob1, t, data, priors; num_samples = 10_000,
print_summary = false)
```
```@example pendulum
@btime bayesian_result = dynamichmc_inference(prob1, Tsit5(), t, data, priors;
num_samples = 10_000)
```
| DiffEqBayes | https://github.com/SciML/DiffEqBayes.jl.git |
|
[
"Apache-2.0"
] | 0.3.4 | ad5850d26616ed692edc843ef584b5f4c9cabdd4 | code | 818 | using LeafOptics
using Documenter
# define default docs pages
pages = Any[
"Home" => "index.md",
"API" => "API.md"
];
@show pages;
# format the docs
mathengine = MathJax(
Dict(
:TeX => Dict(
:equationNumbers => Dict(:autoNumber => "AMS"),
:Macros => Dict()
)
)
);
format = Documenter.HTML(
prettyurls = get(ENV, "CI", nothing) == "true",
mathengine = mathengine,
collapselevel = 1,
assets = ["assets/favicon.ico"]
);
# build the docs
makedocs(
sitename = "LeafOptics",
format = format,
clean = false,
modules = [LeafOptics],
pages = pages
);
# deploy the docs to Github gh-pages
deploydocs(
repo = "github.com/Yujie-W/LeafOptics.jl.git",
target = "build",
devbranch = "main",
push_preview = true
);
| LeafOptics | https://github.com/Yujie-W/LeafOptics.jl.git |
|
[
"Apache-2.0"
] | 0.3.4 | ad5850d26616ed692edc843ef584b5f4c9cabdd4 | code | 475 | module LeafOptics
using ClimaCache: HyperspectralAbsorption, HyperspectralRadiation, HyperspectralLeafBiophysics, WaveLengthSet
using ClimaCache: MonoMLGrassSPAC, MonoMLPalmSPAC, MonoMLTreeSPAC
using EmeraldConstants: AVOGADRO, H_PLANCK, LIGHT_SPEED, M_H₂O, ρ_H₂O
using SpecialFunctions: expint
using UnPack: @unpack
include("fluorescence.jl" )
include("photon.jl" )
include("radiation.jl" )
include("spectra.jl" )
include("transmittance.jl")
end # module
| LeafOptics | https://github.com/Yujie-W/LeafOptics.jl.git |
|
[
"Apache-2.0"
] | 0.3.4 | ad5850d26616ed692edc843ef584b5f4c9cabdd4 | code | 2837 | #######################################################################################################################################################################################################
#
# Changes made to this function
# General
# 2021-Jul-08: add leaf level SIF simulation
# 2021-Jul-08: use mat_b and mat_f for SIF at backward and forward directions
# 2021-Aug-05: add option to sumulate SIF in photon to photon mode
# 2021-Oct-22: refactor the function to leaf_SIF to return the SIFs directly
# 2022-Jan-13: use LeafBiophysics directly in the function rather than Leaf
# 2022-Jun-15: rename LeafBiophysics to HyperspectralLeafBiophysics to be more descriptive
#
#######################################################################################################################################################################################################
"""
leaf_SIF(bio::HyperspectralLeafBiophysics{FT}, wls::WaveLengthSet{FT}, rad::HyperspectralRadiation{FT}, ϕ::FT = FT(0.01); ϕ_photon::Bool = true) where {FT<:AbstractFloat}
Return the leaf level SIF at backward and forward directions, given
- `bio` `HyperspectralLeafBiophysics` type struct that contains leaf biophysical parameters
- `wls` `WaveLengthSet` type struct that contains wave length bins
- `rad` `HyperspectralRadiation` type struct that contains incoming radiation information
- `ϕ` Fluorescence quantum yield
- `ϕ_photon` If true (default), convert photon to photon when computing SIF; otherwise, convert energy to energy
---
# Examples
```julia
wls = ClimaCache.WaveLengthSet{Float64}();
bio = ClimaCache.HyperspectralLeafBiophysics{Float64}();
rad = ClimaCache.HyperspectralRadiation{Float64}();
sif_b,sif_f = leaf_SIF(bio, wls, rad, 0.01);
sif_b,sif_f = leaf_SIF(bio, wls, rad, 0.01; ϕ_photon=false);
```
"""
function leaf_SIF(bio::HyperspectralLeafBiophysics{FT}, wls::WaveLengthSet{FT}, rad::HyperspectralRadiation{FT}, ϕ::FT = FT(0.01); ϕ_photon::Bool = true) where {FT<:AbstractFloat}
@unpack IΛ_SIFE, ΔΛ_SIFE, Λ_SIF, Λ_SIFE = wls;
# calculate the excitation energy and photons
_e_excitation = (view(rad.e_direct, IΛ_SIFE) .+ view(rad.e_diffuse, IΛ_SIFE)) .* ΔΛ_SIFE;
# convert energy to energy using the matrices
if !ϕ_photon
_sif_b = bio.mat_b * _e_excitation * ϕ / FT(pi);
_sif_f = bio.mat_f * _e_excitation * ϕ / FT(pi);
return _sif_b, _sif_f
end;
# convert energy to photon
_phot_excitation = photon.(Λ_SIFE, _e_excitation);
# convert photon to photon using the matrices
_phot_b = bio.mat_b * _phot_excitation * ϕ / FT(pi);
_phot_f = bio.mat_f * _phot_excitation * ϕ / FT(pi);
# convert photon to back to energy
_sif_b = energy.(Λ_SIF, _phot_b);
_sif_f = energy.(Λ_SIF, _phot_f);
return _sif_b, _sif_f
end
| LeafOptics | https://github.com/Yujie-W/LeafOptics.jl.git |
|
[
"Apache-2.0"
] | 0.3.4 | ad5850d26616ed692edc843ef584b5f4c9cabdd4 | code | 4234 | # constants
const FAC = 1e-9 / (H_PLANCK() * LIGHT_SPEED() * AVOGADRO());
#######################################################################################################################################################################################################
#
# Changes made to this function
# General
# 2021-Oct-22: rename the function to photon
# 2021-Oct-22: add a method to convert direct from number to number
#
#######################################################################################################################################################################################################
"""
photon(λ::FT, E::FT) where {FT<:AbstractFloat}
Return the number of moles of photons, given
- `λ` Wave length in `[nm]`, converted to `[m]` by FAC
- `E` Joules of energy
"""
function photon(λ::FT, E::FT) where {FT<:AbstractFloat}
return E * λ * FT(FAC)
end
#######################################################################################################################################################################################################
#
# Changes made to this function
# General
# 2022-Jun-13: add function
# 2021-Jun-13: add method to save to provided 3rd variable
# 2021-Jun-13: add method to save to provided 2rd variable
#
#######################################################################################################################################################################################################
"""
photon!(λ::Vector{FT}, E::Vector{FT}, phot::Vector{FT}) where {FT<:AbstractFloat}
photon!(λ::Vector{FT}, E::Vector{FT}) where {FT<:AbstractFloat}
Compute and save the number of moles of photons, given
- `λ` Wave length in `[nm]`, converted to `[m]` by FAC
- `E` Joules of energy (will be converted to moles of photons if phot in not given)
- `phot` Mole of photons (variable to save)
"""
function photon! end
photon!(λ::Vector{FT}, E::Vector{FT}, phot::Vector{FT}) where {FT<:AbstractFloat} = (phot .= photon.(λ, E); return nothing);
photon!(λ::Vector{FT}, E::Vector{FT}) where {FT<:AbstractFloat} = (E .*= λ .* FT(FAC); return nothing);
#######################################################################################################################################################################################################
#
# Changes made to this function
# General
# 2021-Oct-22: define function to convert photon back to energy
#
#######################################################################################################################################################################################################
"""
energy(λ::FT, phot::FT) where {FT<:AbstractFloat}
Return the energy, given
- `λ` Wave length in `[nm]`, converted to `[m]` by FAC
- `phot` Number of moles of photon
"""
function energy(λ::FT, phot::FT) where {FT<:AbstractFloat}
return phot / (λ * FT(FAC))
end
#######################################################################################################################################################################################################
#
# Changes made to this function
# General
# 2022-Jun-13: add function
# 2021-Jun-13: add method to save to provided 3rd variable
# 2021-Jun-13: add method to save to provided 2rd variable
#
#######################################################################################################################################################################################################
"""
energy!(λ::Vector{FT}, phot::Vector{FT}, E::Vector{FT}) where {FT<:AbstractFloat}
energy!(λ::Vector{FT}, phot::Vector{FT}) where {FT<:AbstractFloat}
Compute and save the number of moles of photons, given
- `λ` Wave length in `[nm]`, converted to `[m]` by FAC
- `phot` Mole of photons (will be converted to moles of photons if E is not given)
- `E` Joules of energy (variable to save)
"""
function energy! end
energy!(λ::Vector{FT}, phot::Vector{FT}, E::Vector{FT}) where {FT<:AbstractFloat} = (E .= energy.(λ, phot); return nothing);
energy!(λ::Vector{FT}, phot::Vector{FT}) where {FT<:AbstractFloat} = (phot ./= λ .* FT(FAC); return nothing);
| LeafOptics | https://github.com/Yujie-W/LeafOptics.jl.git |
|
[
"Apache-2.0"
] | 0.3.4 | ad5850d26616ed692edc843ef584b5f4c9cabdd4 | code | 3082 | #######################################################################################################################################################################################################
#
# Changes made to this function
# General
# 2021-Oct-22: add function to compute leaf level PAR and APAR
# 2022-Jan-13: use LeafBiophysics directly in the function rather than Leaf
# 2022-Jun-15: rename LeafBiophysics to HyperspectralLeafBiophysics to be more descriptive
# 2022-Jun-27: refactor the function to return PAR, APAR, and PPAR
#
#######################################################################################################################################################################################################
"""
leaf_PAR(bio::HyperspectralLeafBiophysics{FT}, wls::WaveLengthSet{FT}, rad::HyperspectralRadiation{FT}; APAR_car::Bool = true) where {FT<:AbstractFloat}
Return leaf level PAR, APAR, and PPAR, given
- `bio` `HyperspectralLeafBiophysics` type struct that contains leaf biophysical parameters
- `wls` `WaveLengthSet` type struct that contains wave length bins
- `rad` `HyperspectralRadiation` type struct that contains incoming radiation information
- `APAR_car` If true (default), account carotenoid absorption as PPAR; otherwise, PPAR is only by chlorophyll
---
# Examples
```julia
wls = ClimaCache.WaveLengthSet{Float64}();
bio = ClimaCache.HyperspectralLeafBiophysics{Float64}();
rad = ClimaCache.HyperspectralRadiation{Float64}();
par,apar,ppar = leaf_PAR(bio, wls, rad);
par,apar,ppar = leaf_PAR(bio, wls, rad; APAR_car=false);
```
"""
function leaf_PAR(bio::HyperspectralLeafBiophysics{FT}, wls::WaveLengthSet{FT}, rad::HyperspectralRadiation{FT}; APAR_car::Bool = true) where {FT<:AbstractFloat}
@unpack IΛ_PAR, ΔΛ_PAR, Λ_PAR = wls;
# PPAR absorption feature (after APAR is computed)
_α_ppar = (APAR_car ? view(bio.α_cabcar, IΛ_PAR) : view(bio.α_cab, IΛ_PAR));
# PAR, APAR, and PPAR energy from direct and diffuse light
_e_par_dir = view(rad.e_direct , IΛ_PAR);
_e_par_diff = view(rad.e_diffuse, IΛ_PAR);
_e_apar_dir = view(bio.α_sw, IΛ_PAR) .* _e_par_dir;
_e_apar_diff = view(bio.α_sw, IΛ_PAR) .* _e_par_diff;
_e_ppar_dir = _α_ppar .* _e_apar_dir;
_e_ppar_diff = _α_ppar .* _e_apar_diff;
# PAR, APAR, and PPAR photons from direct and diffuse light
_par_dir = photon.(Λ_PAR, _e_par_dir );
_par_diff = photon.(Λ_PAR, _e_par_diff );
_apar_dir = photon.(Λ_PAR, _e_apar_dir );
_apar_diff = photon.(Λ_PAR, _e_apar_diff);
_ppar_dir = photon.(Λ_PAR, _e_ppar_dir );
_ppar_diff = photon.(Λ_PAR, _e_ppar_diff);
# total PAR and APAR in μmol photons m⁻² s⁻¹
_Σpar_dir = _par_dir' * ΔΛ_PAR * 1000;
_Σpar_diff = _par_diff' * ΔΛ_PAR * 1000;
_Σapar_dir = _apar_dir' * ΔΛ_PAR * 1000;
_Σapar_diff = _apar_diff' * ΔΛ_PAR * 1000;
_Σppar_dir = _ppar_dir' * ΔΛ_PAR * 1000;
_Σppar_diff = _ppar_diff' * ΔΛ_PAR * 1000;
return _Σpar_dir + _Σpar_diff, _Σapar_dir + _Σapar_diff, _Σppar_dir + _Σppar_diff
end
| LeafOptics | https://github.com/Yujie-W/LeafOptics.jl.git |
|
[
"Apache-2.0"
] | 0.3.4 | ad5850d26616ed692edc843ef584b5f4c9cabdd4 | code | 14264 | #######################################################################################################################################################################################################
#
# Changes made to this function
# General
# 2021-Oct-01: rename the function to leaf_spectra! as the function updates not only fluorescence but also reflectance, transmittance, and absorption spectra
# 2021-Oct-22: add another method to prescribe leaf spectra such as transmittance and reflectance from broadband method
#
#######################################################################################################################################################################################################
"""
This function updates leaf level reflectance, transmittance, and fluorescence spectra related parameters. Supported methods are
- Update leaf spectra based on pigment concentrations
- Update leaf spectra (reflectance and transmittance) to given broadband values
- Update leaf spectra based on pigment concentrations for the entire SPAC
"""
function leaf_spectra! end
#######################################################################################################################################################################################################
#
# Changes made to this method
# General
# 2020-Mar-30: account for carotenoid absorption as PPAR as well as chlorophyll
# 2020-Mar-31: use 40° rather than 59° for _τ_α calculation (following PROSPECT-D)
# 2021-Aug-07: replace function `expint` with that from SpecialFunctions
# 2021-Oct-21: add α to input parameters so that one can roll back to 50° for _τ_α calculation
# 2021-Nov-29: separate HyperspectralAbsorption as constant struct
# 2022-Jan-13: use LeafBiophysics directly in the function rather than Leaf
# 2022-Jun-15: rename LeafBiophysics to HyperspectralLeafBiophysics to be more descriptive
# 2022-Jul-22: add lwc to function variable list
# 2022-Jul-28: run leaf_spectra! only if lwc differs from _v_storage
# 2022-Aug-17: add option reabsorb to function to enable/disable SIF reabsorption
# Bug fix
# 2021-Aug-06: If bio.CBC and bio.PRO are not zero, they are accounted for twice in bio.LMA, thus the spectrum from LMA need to subtract the contribution from CBC and PRO
# To do
# TODO: add References for this methods
# TODO: speed up this function by preallocate memories using a cache structure
#
#######################################################################################################################################################################################################
"""
leaf_spectra!(
bio::HyperspectralLeafBiophysics{FT},
wls::WaveLengthSet{FT},
lha::HyperspectralAbsorption{FT},
lwc::FT;
APAR_car::Bool = true,
reabsorb::Bool = true,
α::FT = FT(40)
) where {FT<:AbstractFloat}
Update leaf reflectance and transmittance spectra, and fluorescence spectrum matrices, given
- `bio` `HyperspectralLeafBiophysics` type struct that contains leaf biophysical parameters
- `wls` `WaveLengthSet` type struct that contain wave length bins
- `lha` `HyperspectralAbsorption` type struct that contains absorption characteristic curves
- `lwc` Leaf water content `[mol m⁻²]`
- `APAR_car` If true, carotenoid absorption is accounted for in PPAR, default is `true`
- `reabsorb` If true, SIF reabsorption is enabled; otherwise, mat_b and mat_f should be based on the case with no reabsorption
- `α` Optimum angle of incidence (default is 40° as in PROSPECT-D, SCOPE uses 59°)
# Examples
```julia
wls = ClimaCache.WaveLengthSet{Float64}();
bio = ClimaCache.HyperspectralLeafBiophysics{Float64}();
lha = ClimaCache.HyperspectralAbsorption{Float64}();
leaf_spectra!(bio, wls, lha, 50.0);
leaf_spectra!(bio, wls, lha, 50.0; APAR_car=false);
leaf_spectra!(bio, wls, lha, 50.0; APAR_car=false, α=59.0);
```
"""
leaf_spectra!(
bio::HyperspectralLeafBiophysics{FT},
wls::WaveLengthSet{FT},
lha::HyperspectralAbsorption{FT},
lwc::FT;
APAR_car::Bool = true,
reabsorb::Bool = true,
α::FT = FT(40)
) where {FT<:AbstractFloat} = (
# if leaf water content is the same as the historical value, do nothing
if lwc == bio._v_storage
return nothing
end;
@unpack MESOPHYLL_N, NDUB = bio;
@unpack K_ANT, K_BROWN, K_CAB, K_CAR_V, K_CAR_Z, K_CBC, K_H₂O, K_LMA, K_PRO, K_PS, NR = lha;
@unpack IΛ_SIF, IΛ_SIFE, Λ_SIF, Λ_SIFE = wls;
# calculate the average absorption feature and relative Cab and Car partitions
bio.k_all .= (K_CAB .* bio.cab .+ # chlorophyll absorption
K_CAR_V .* bio.car .* (1 - bio.f_zeax) .+ # violaxanthin carotenoid absorption
K_CAR_Z .* bio.car .* bio.f_zeax .+ # zeaxanthin carotenoid absorption
K_ANT .* bio.ant .+ # anthocynanin absorption absorption
K_BROWN .* bio.brown .+ # TODO: needs to be a concentration
K_H₂O .* (lwc * M_H₂O() / ρ_H₂O() * 100) .+ # water absorption
K_CBC .* bio.cbc .+ # carbon-based constituents absorption
K_PRO .* bio.pro .+ # protein absorption
K_LMA .* (bio.lma - bio.cbc - bio.pro) # dry mass absorption (if some remained)
) ./ MESOPHYLL_N;
bio.α_cab .= (K_CAB .* bio.cab) ./ bio.k_all ./ MESOPHYLL_N;
bio.α_cabcar .= (K_CAB .* bio.cab .+ K_CAR_V .* bio.car .* (1 - bio.f_zeax) .+ K_CAR_Z .* bio.car .* bio.f_zeax) ./ bio.k_all ./ MESOPHYLL_N;
# calculate the reflectance and transmittance at the interfaces of one layer
_τ = (1 .- bio.k_all) .* exp.(-bio.k_all) .+ bio.k_all .^ 2 .* expint.(bio.k_all .+ eps(FT));
_τ_α = average_transmittance.(α, NR);
_ρ_α = 1 .- _τ_α;
_τ₁₂ = average_transmittance.(FT(90), NR);
_ρ₁₂ = 1 .- _τ₁₂;
_τ₂₁ = _τ₁₂ ./ (NR .^ 2);
_ρ₂₁ = 1 .- _τ₂₁;
# top surface side
_denom = 1 .- (_τ .* _ρ₂₁) .^ 2;
_τ_top = _τ_α .* _τ .* _τ₂₁ ./ _denom;
_ρ_top = _ρ_α .+ _ρ₂₁ .* _τ .* _τ_top;
# bottom surface side
_τ_bottom = _τ₁₂ .* _τ .* _τ₂₁ ./ _denom;
_ρ_bottom = _ρ₁₂ .+ _ρ₂₁ .* _τ .* _τ_bottom;
# calculate the reflectance and transmittance at the interfaces of N layer
_d = sqrt.((1 .+ _ρ_bottom .+ _τ_bottom) .* (1 .+ _ρ_bottom .- _τ_bottom) .* (1 .- _ρ_bottom .+ _τ_bottom) .* (1 .- _ρ_bottom .- _τ_bottom));
_ρ² = _ρ_bottom .^ 2;
_τ² = _τ_bottom .^ 2;
_a = (1 .+ _ρ² .- _τ² .+ _d) ./ (2 .* _ρ_bottom);
_b = (1 .- _ρ² .+ _τ² .+ _d) ./ (2 .* _τ_bottom);
_bⁿ⁻¹ = _b .^ (MESOPHYLL_N - 1);
_b²ⁿ⁻² = _bⁿ⁻¹ .^ 2;
_a² = _a .^ 2;
_denom = _a² .* _b²ⁿ⁻² .- 1;
_ρ_sub = _a .* (_b²ⁿ⁻² .- 1) ./ _denom;
_τ_sub = _bⁿ⁻¹ .* (_a² .- 1) ./ _denom;
# avoid case of zero absorption
_j = findall(_ρ_bottom .+ _τ_bottom .>= 1);
_τ_sub[_j] = _τ_bottom[_j] ./ (_τ_bottom[_j] + (1 .- _τ_bottom[_j]) * (MESOPHYLL_N - 1));
_ρ_sub[_j] = 1 .- _τ_sub[_j];
# reflectance & transmittance of the leaf: combine top layer with next N-1 layers
_denom = 1 .- _ρ_sub .* _ρ_bottom;
bio.τ_sw = _τ_top .* _τ_sub ./ _denom;
bio.ρ_sw = _ρ_top .+ _τ_top .* _ρ_sub .* _τ_bottom ./ _denom;
bio.α_sw = 1 .- bio.τ_sw .- bio.ρ_sw;
# Doubling method used to calculate fluoresence is now only applied to the part of the leaf where absorption takes place, that is, the part exclusive of the leaf-air interfaces.
# The reflectance (rho) and transmittance (tau) of this part of the leaf are now determined by "subtracting" the interfaces.
# CF Note: All of the below takes about 10 times more time than the RT above. Need to rething speed and accuracy. (10nm is bringing it down a lot!)
_ρ_b = (bio.ρ_sw .- _ρ_α) ./ (_τ_α .* _τ₂₁ .+ (bio.ρ_sw - _ρ_α) .* _ρ₂₁);
_tt1 = _τ_α .* _τ₂₁;
_tt2 = bio.τ_sw .* (1 .- _ρ_b .* _ρ₂₁);
_z = _tt2 ./ _tt1;
_tt1 = _ρ_b - _ρ₂₁ .* _z .^ 2;
_tt2 = 1 .- (_ρ₂₁.* _z) .^ 2;
_ρ = max.(0, _tt1 ./ _tt2);
_tt1 = 1 .- _ρ_b .* _ρ₂₁;
_τ = _tt1 ./ _tt2 .* _z;
# Derive Kubelka-Munk s and k
_i = findall((_ρ .+ _τ) .< 1);
_j = findall((_ρ .+ _τ) .> 1);
_d[_i] .= sqrt.((1 .+ _ρ[_i] .+ _τ[_i]) .* (1 .+ _ρ[_i] .- _τ[_i]) .* (1 .- _ρ[_i] .+ _τ[_i]) .* (1 .- _ρ[_i] .- _τ[_i]));
_a[_i] .= (1 .+ _ρ[_i] .^ 2 .- _τ[_i] .^ 2 .+ _d[_i]) ./ (2 .* _ρ[_i]);
_b[_i] .= (1 .- _ρ[_i] .^ 2 .+ _τ[_i] .^ 2 .+ _d[_i]) ./ (2 .* _τ[_i]);
_a[_j] .= 1;
_b[_j] .= 1;
_i = findall((_a .> 1) .& (_a .!= Inf));
_s = _ρ ./ _τ;
_k = log.(_b);
_s[_i] .= 2 .* _a[_i] ./ (_a[_i] .^ 2 .- 1) .* log.(_b[_i]);
_k[_i] .= (_a[_i] .- 1) ./ (_a[_i] .+ 1) .* log.(_b[_i]);
_k_chl = (APAR_car ? bio.α_cabcar : bio.α_cab) .* _k;
# indices of WLE and WLF within wlp
_ϵ = FT(2) ^ -NDUB;
_τ_e = 1 .- (_k[IΛ_SIFE] .+ _s[IΛ_SIFE]) * _ϵ;
_τ_f = reabsorb ? 1 .- (_k[IΛ_SIF] .+ _s[IΛ_SIF]) * _ϵ : 1 .- _s[IΛ_SIF] * _ϵ;
_ρ_e = _s[IΛ_SIFE] * _ϵ;
_ρ_f = _s[IΛ_SIF] * _ϵ;
_sigmoid = 1 ./ (1 .+ exp.(-Λ_SIF ./ 10) .* exp.(Λ_SIFE' ./ 10));
_mat_f = K_PS[IΛ_SIF] .* _ϵ ./ 2 .* _k_chl[IΛ_SIFE]' .* _sigmoid;
_mat_b = K_PS[IΛ_SIF] .* _ϵ ./ 2 .* _k_chl[IΛ_SIFE]' .* _sigmoid;
# Doubling adding routine
_1_h = ones(FT, 1, length(_τ_e));
_1_v = ones(FT, length(_τ_f), 1);
for i in 1:NDUB
_x_e = _τ_e ./ (1 .- _ρ_e .^ 2);
_x_f = _τ_f ./ (1 .- _ρ_f .^ 2);
_τ_e_n = _τ_e .* _x_e;
_τ_f_n = _τ_f .* _x_f;
_ρ_e_n = _ρ_e .* (1 .+ _τ_e_n);
_ρ_f_n = _ρ_f .* (1 .+ _τ_f_n);
_a₁₁ = _x_f * _1_h .+ _1_v * _x_e';
_a₁₂ = (_x_f * _x_e') .* (_ρ_f * _1_h .+ _1_v * _ρ_e');
_a₂₁ = 1 .+ (_x_f * _x_e') .* (1 .+ _ρ_f * _ρ_e');
_a₂₂ = (_x_f .* _ρ_f) * _1_h .+ _1_v * (_x_e.*_ρ_e)';
_mat_f_n = _mat_f .* _a₁₁ .+ _mat_b .* _a₁₂;
_mat_b_n = _mat_b .* _a₂₁ .+ _mat_f .* _a₂₂;
_τ_e = _τ_e_n;
_ρ_e = _ρ_e_n;
_τ_f = _τ_f_n;
_ρ_f = _ρ_f_n;
_mat_f = _mat_f_n;
_mat_b = _mat_b_n;
end;
# This reduced red SIF quite a bit in backscatter, not sure why.
_ρ_b = _ρ .+ _τ .^ 2 .* _ρ₂₁ ./ (1 .- _ρ .* _ρ₂₁);
_x_e = _1_v * (_τ_α[IΛ_SIFE] ./ (1 .- _ρ₂₁[IΛ_SIFE] .* _ρ_b[IΛ_SIFE]))';
_x_f = _τ₂₁[IΛ_SIF] ./ (1 .- _ρ₂₁[IΛ_SIF] .* _ρ_b[IΛ_SIF]) * _1_h;
_y_e = _1_v * (_τ[IΛ_SIFE] .* _ρ₂₁[IΛ_SIFE] ./ (1 .- _ρ[IΛ_SIFE] .* _ρ₂₁[IΛ_SIFE]))';
_y_f = _τ[IΛ_SIF] .* _ρ₂₁[IΛ_SIF] ./ (1 .- _ρ[IΛ_SIF] .* _ρ₂₁[IΛ_SIF]) * _1_h;
_a = _x_e .* (1 .+ _y_e .* _y_f) .* _x_f;
_b = _x_e .* (_y_e .+ _y_f) .* _x_f;
bio.mat_b = _a .* _mat_b + _b .* _mat_f;
bio.mat_f = _a .* _mat_f + _b .* _mat_b;
# store leaf water content
bio._v_storage = lwc;
return nothing
);
#######################################################################################################################################################################################################
#
# Changes made to this method
# General
# 2021-Oct-22: add another method to prescribe leaf spectra such as transmittance and reflectance from broadband method
# 2021-Nov-29: separate HyperspectralAbsorption as constant struct
# 2022-Jan-13: use LeafBiophysics directly in the function rather than Leaf
# 2022-Jun-15: rename LeafBiophysics to HyperspectralLeafBiophysics to be more descriptive
#
#######################################################################################################################################################################################################
"""
leaf_spectra!(bio::HyperspectralLeafBiophysics{FT}, wls::WaveLengthSet{FT}, ρ_par::FT, ρ_nir::FT, τ_par::FT, τ_nir::FT) where {FT<:AbstractFloat}
Update leaf reflectance and transmittance (e.g., prescribe broadband PAR and NIR values), given
- `bio` `HyperspectralLeafBiophysics` type struct that contains leaf biophysical parameters
- `wls` `WaveLengthSet` type struct that contain wave length bins
- `ρ_par` Reflectance at PAR region
- `ρ_nir` Reflectance at NIR region
- `τ_par` Transmittance at PAR region
- `τ_nir` Transmittance at NIR region
# Examples
```julia
wls = ClimaCache.WaveLengthSet{Float64}();
bio = ClimaCache.HyperspectralLeafBiophysics{Float64}();
leaf_spectra!(bio, wls, 0.1, 0.45, 0.05, 0.25);
```
"""
leaf_spectra!(bio::HyperspectralLeafBiophysics{FT}, wls::WaveLengthSet{FT}, ρ_par::FT, ρ_nir::FT, τ_par::FT, τ_nir::FT) where {FT<:AbstractFloat} = (
@unpack IΛ_NIR, IΛ_PAR = wls;
bio.ρ_sw[IΛ_PAR] .= ρ_par;
bio.ρ_sw[IΛ_NIR] .= ρ_nir;
bio.τ_sw[IΛ_PAR] .= τ_par;
bio.τ_sw[IΛ_NIR] .= τ_nir;
bio.α_sw = 1 .- bio.τ_sw .- bio.ρ_sw;
return nothing
);
#######################################################################################################################################################################################################
#
# Changes made to this method
# General
# 2022-Jun-29: add method for MonoMLGrassSPAC, MonoMLPalmSPAC, and MonoMLTreeSPAC
#
#######################################################################################################################################################################################################
"""
leaf_spectra!(spac::Union{MonoMLGrassSPAC{FT}, MonoMLPalmSPAC{FT}, MonoMLTreeSPAC{FT}}) where {FT<:AbstractFloat}
Update leaf reflectance and transmittance for SPAC, given
- `spac` `MonoMLGrassSPAC`, `MonoMLPalmSPAC`, or `MonoMLTreeSPAC` type SPAC
"""
leaf_spectra!(spac::Union{MonoMLGrassSPAC{FT}, MonoMLPalmSPAC{FT}, MonoMLTreeSPAC{FT}}) where {FT<:AbstractFloat} = (
@unpack CANOPY, LEAVES = spac;
for _leaf in LEAVES
leaf_spectra!(_leaf.BIO, CANOPY.WLSET, CANOPY.LHA, _leaf.HS.v_storage; APAR_car = _leaf.APAR_CAR);
end;
return nothing
);
| LeafOptics | https://github.com/Yujie-W/LeafOptics.jl.git |
|
[
"Apache-2.0"
] | 0.3.4 | ad5850d26616ed692edc843ef584b5f4c9cabdd4 | code | 2271 | #######################################################################################################################################################################################################
#
# Changes made to this function
# General
# 2020-Mar-30: migrate the function from SCOPE
# 2021-Oct-21: rename the function to average_transmittance
# To do
# TODO: figure out where does this equation comes from
#
#######################################################################################################################################################################################################
"""
average_transmittance(α::FT, nr::FT) where {FT<:AbstractFloat}
Return the average transmittance of isotropic radiation across an interface between two dielectrics, given
- `α` angle of incidence
- `nr` Index of refraction
# References
- Stern (1964) Transmission of isotropic radiation across an interface between two dielectrics. Applied Optics 3(1): 111-113.
- Allen (1973) Transmission of isotropic light across a dielectric surface in two and three dimensions. Journal of the Optical Society of America 63(6): 664-666.
"""
function average_transmittance(α::FT, nr::FT) where {FT<:AbstractFloat}
@assert 0 < α <= 90;
# some shortcuts to avoid overly comlicated equation
_a = (nr + 1) ^ 2 / 2;
_a³ = _a ^ 3;
_n² = nr ^ 2;
_n⁴ = nr ^ 4;
_n⁶ = nr ^ 6;
_n²p = _n² + 1;
_n²p² = _n²p ^ 2;
_n²p³ = _n²p ^ 3;
_n²m² = (_n² - 1) ^ 2;
_k = -1 * _n²m² / 4;
_k² = _k ^ 2;
_sin²α = sind(α) ^ 2;
_b₂ = _sin²α - _n²p/2;
_b₁ = (α==90 ? 0 : sqrt(_b₂ ^ 2 + _k));
_b = _b₁ - _b₂;
_b³ = _b ^ 3;
_npanm = 2 * _n²p * _a - _n²m²;
_npbnm = 2 * _n²p * _b - _n²m²;
# S polarization
_ts = ( _k² / (6*_b³) + _k/_b - _b/2 ) - ( _k² / (6*_a³) + _k/_a - _a/2 );
# P polarization
_tp₁ = -2 * _n² * (_b - _a) / _n²p²;
_tp₂ = -2 * _n² * _n²p * log(_b / _a) / _n²m²;
_tp₃ = _n² * (1/_b - 1/_a) / 2;
_tp₄ = 16 * _n⁴ * (_n⁴ + 1) * log(_npbnm / _npanm) / (_n²p³ * _n²m²);
_tp₅ = 16 * _n⁶ * (1/_npbnm - 1/_npanm) / _n²p³;
_tp = _tp₁ + _tp₂ + _tp₃ + _tp₄ + _tp₅;
return (_ts + _tp) / (2 * _sin²α)
end
| LeafOptics | https://github.com/Yujie-W/LeafOptics.jl.git |
|
[
"Apache-2.0"
] | 0.3.4 | ad5850d26616ed692edc843ef584b5f4c9cabdd4 | code | 2446 | using ClimaCache
using LeafOptics
using Test
@testset verbose = true "LeafOptics CI Coverage" begin
# file spectra.jl
@testset "Spectra" begin
for FT in [Float32, Float64]
wls = ClimaCache.WaveLengthSet{FT}();
bio = ClimaCache.HyperspectralLeafBiophysics{FT}();
lha = ClimaCache.HyperspectralAbsorption{FT}();
spac = ClimaCache.MonoMLTreeSPAC{FT}();
LeafOptics.leaf_spectra!(bio, wls, lha, FT(50));
@test true;
LeafOptics.leaf_spectra!(bio, wls, lha, FT(50));
@test true;
LeafOptics.leaf_spectra!(bio, wls, lha, FT(49); APAR_car = false);
@test true;
LeafOptics.leaf_spectra!(bio, wls, lha, FT(48); reabsorb = false);
@test true;
LeafOptics.leaf_spectra!(bio, wls, FT(0.1), FT(0.45), FT(0.05), FT(0.25));
@test true;
LeafOptics.leaf_spectra!(spac);
@test true;
end;
end;
# file radiation.jl
@testset "PAR & APAR" begin
for FT in [Float32, Float64]
wls = ClimaCache.WaveLengthSet{FT}();
bio = ClimaCache.HyperspectralLeafBiophysics{FT}();
rad = ClimaCache.HyperspectralRadiation{FT}();
par,apar,ppar = LeafOptics.leaf_PAR(bio, wls, rad);
@test true;
par,apar,ppar = LeafOptics.leaf_PAR(bio, wls, rad; APAR_car=false);
@test true;
end;
end;
# file fluorescence.jl
@testset "SIF" begin
for FT in [Float32, Float64]
wls = ClimaCache.WaveLengthSet{FT}();
bio = ClimaCache.HyperspectralLeafBiophysics{FT}();
rad = ClimaCache.HyperspectralRadiation{FT}();
sif_b,sif_f = LeafOptics.leaf_SIF(bio, wls, rad, FT(0.01));
@test true;
sif_b,sif_f = LeafOptics.leaf_SIF(bio, wls, rad, FT(0.01); ϕ_photon = false);
@test true;
end;
end;
# file photon.jl
@testset "Utils" begin
for FT in [Float32, Float64]
xs = rand(FT,2);
ys = rand(FT,2);
LeafOptics.photon!(FT[400,500], xs, ys);
@test true;
LeafOptics.photon!(FT[400,500], xs);
@test true;
LeafOptics.energy!(FT[400,500], ys, xs);
@test true;
LeafOptics.energy!(FT[400,500], ys);
@test true;
end;
end;
end;
| LeafOptics | https://github.com/Yujie-W/LeafOptics.jl.git |
|
[
"Apache-2.0"
] | 0.3.4 | ad5850d26616ed692edc843ef584b5f4c9cabdd4 | docs | 1732 | # LeafOptics.jl
<!-- Links and shortcuts -->
[ju-url]: https://github.com/Yujie-W/LeafOptics.jl
[ju-api]: https://yujie-w.github.io/LeafOptics.jl/stable/API/
[dev-img]: https://img.shields.io/badge/docs-dev-blue.svg
[dev-url]: https://Yujie-W.github.io/LeafOptics.jl/dev/
[rel-img]: https://img.shields.io/badge/docs-stable-blue.svg
[rel-url]: https://Yujie-W.github.io/LeafOptics.jl/stable/
[st-img]: https://github.com/Yujie-W/LeafOptics.jl/workflows/JuliaStable/badge.svg?branch=main
[st-url]: https://github.com/Yujie-W/LeafOptics.jl/actions?query=branch%3A"main"++workflow%3A"JuliaStable"
[min-img]: https://github.com/Yujie-W/LeafOptics.jl/workflows/Julia-1.6/badge.svg?branch=main
[min-url]: https://github.com/Yujie-W/LeafOptics.jl/actions?query=branch%3A"main"++workflow%3A"Julia-1.6"
[cov-img]: https://codecov.io/gh/Yujie-W/LeafOptics.jl/branch/main/graph/badge.svg
[cov-url]: https://codecov.io/gh/Yujie-W/LeafOptics.jl
## About
LeafOptics.jl is a remasted package for leaf transmittance, refleclectance, and fluorescence spectra. The main functionalities are from CanopyLayers.jl, which would be rebranded to account for canopy
structure.
| Documentation | CI Status | Compatibility | Code Coverage |
|:------------------------------------------------|:----------------------|:------------------------|:------------------------|
| [![][dev-img]][dev-url] [![][rel-img]][rel-url] | [![][st-img]][st-url] | [![][min-img]][min-url] | [![][cov-img]][cov-url] |
## Installation
```julia
julia> using Pkg;
julia> Pkg.add("LeafOptics");
```
## API
See [`API`][ju-api] for more detailed information about how to use [`LeafOptics.jl`][ju-url].
| LeafOptics | https://github.com/Yujie-W/LeafOptics.jl.git |
|
[
"Apache-2.0"
] | 0.3.4 | ad5850d26616ed692edc843ef584b5f4c9cabdd4 | docs | 742 | # LeafOptics
```@meta
CurrentModule = LeafOptics
```
## Leaf spectra
```@docs
leaf_spectra!
leaf_spectra!(bio::HyperspectralLeafBiophysics{FT}, wls::WaveLengthSet{FT}, lha::HyperspectralAbsorption{FT}, lwc::FT; APAR_car::Bool = true, reabsorb::Bool = true, α::FT = FT(40)) where {FT<:AbstractFloat}
leaf_spectra!(bio::HyperspectralLeafBiophysics{FT}, wls::WaveLengthSet{FT}, ρ_par::FT, ρ_nir::FT, τ_par::FT, τ_nir::FT) where {FT<:AbstractFloat}
leaf_spectra!(spac::Union{MonoMLGrassSPAC{FT}, MonoMLPalmSPAC{FT}, MonoMLTreeSPAC{FT}}) where {FT<:AbstractFloat}
```
## Leaf PAR, APAR, and PPAR
```@docs
leaf_PAR
```
## Leaf SIF
```@docs
leaf_SIF
```
## Utility functions
```@docs
average_transmittance
photon
photon!
energy
energy!
```
| LeafOptics | https://github.com/Yujie-W/LeafOptics.jl.git |
|
[
"Apache-2.0"
] | 0.3.4 | ad5850d26616ed692edc843ef584b5f4c9cabdd4 | docs | 133 | # LeafOptics.jl
Functions to calculate leaf spectra, PAR, and SIF.
## Installation
```julia
using Pkg;
Pkg.add("LeafOptics");
```
| LeafOptics | https://github.com/Yujie-W/LeafOptics.jl.git |
|
[
"MIT"
] | 0.1.2 | 607fd77863fd04cdd6010a33236006949b6cfd69 | code | 286 | using Documenter, QuakeML
makedocs(
sitename = "QuakeML.jl documentation",
pages = [
"Home" => "index.md",
"Manual" => "manual.md",
"Function index" => "function-index.md",
]
)
deploydocs(
repo = "github.com/anowacki/QuakeML.jl.git",
)
| QuakeML | https://github.com/anowacki/QuakeML.jl.git |
|
[
"MIT"
] | 0.1.2 | 607fd77863fd04cdd6010a33236006949b6cfd69 | code | 1078 | """
# QuakeML
Read and write files in the QuakeML format which describes seismic events.
## User functions
- [`QuakeML.read`](@ref): Read a QuakeML file
- [`QuakeML.readstring`](@ref): Read a QuakeML document from a string
- [`preferred_focal_mechanism`](@ref): Get the preferred focal mechanism for an event
- [`preferred_magnitude`](@ref): Get the preferred magnitude for an event
- [`preferred_origin`](@ref): Get the preferred origin for an event
- [`quakeml`](@ref): Create an XML document from a set of events which can
be written with `print(io, quakeml(qml))`
"""
module QuakeML
using Dates: DateTime, Time
import UUIDs
import EzXML
export
EventParameters,
has_focal_mechanism,
has_magnitude,
has_origin,
preferred_focal_mechanism,
preferred_focal_mechanisms,
preferred_magnitude,
preferred_magnitudes,
preferred_origin,
preferred_origins,
quakeml
include("compat.jl")
include("util.jl")
include("types.jl")
include("io.jl")
include("constructors.jl")
include("accessors.jl")
include("types_module.jl")
end # module
| QuakeML | https://github.com/anowacki/QuakeML.jl.git |
|
[
"MIT"
] | 0.1.2 | 607fd77863fd04cdd6010a33236006949b6cfd69 | code | 4605 | # Functions to get and check values
"""
has_focal_mechanism(event) -> ::Bool
Return `true` if `event` contains one or more focal mechanisms defined.
"""
has_focal_mechanism(event::Event) = !isempty(event.focal_mechanism)
"""
has_magnitude(event) --> ::Bool
Return `true` if `event` has one or more magnitudes defined.
"""
has_magnitude(event::Event) = !isempty(event.magnitude)
"""
has_origin(event) -> ::Bool
Return `true` if `event` has one or more origins defined.
"""
has_origin(event::Event) = !isempty(event.origin)
"""
preferred_focal_mechanism(event; verbose=false) -> focal_mechanism
Return the preferred focal mechanism for an `event`. This may be defined if
there is more than one focal mechanism given for an event, and the
`preferred_focal_mechanism_id` field is set. If there is only one focal mechanism
for this `event`, then that is returned. If there is no focal mechanism
associated with this event which matches the stated `preferred_focal_mechanism_id`,
then the first focal mechanism is returned, and a warning given is `verbose` is `true`.
"""
function preferred_focal_mechanism(e::Event; verbose=false)
has_focal_mechanism(e) ||
throw(ArgumentError("event contains no focal mechanisms"))
length(e.focal_mechanism) == 1 && return first(e.focal_mechanism)
preferred_id = e.preferred_focal_mechanism_id
ind = findfirst(x -> x.public_id === preferred_id, e.focal_mechanism)
focal_mechanism = if ind === nothing
verbose &&
@warn("no focal mechanism with preferred id; returning the first focal mechanism")
first(e.focal_mechanism)
else
e.focal_mechanism[ind]
end
focal_mechanism
end
"""
preferred_focal_mechanisms(quakeml::EventParameters; verbose=false) -> focal_mechanisms
Return the preferred focal mechanisms for the events contained within `quakeml`.
See [`preferred_magnitude`](@ref).
"""
preferred_focal_mechanisms(ep::EventParameters; verbose=false) =
preferred_focal_mechanism.(ep.event; verbose=verbose)
"""
preferred_magnitude(event; verbose=false) -> magnitude
Return the preferred magnitude for an `event`. This may be defined if
there is more than one magnitude given for an event, and the
`preferred_magnitude_id` field is set. If there is only one magnitude
for this `event`, then that is returned. If there is no magnitude
associated with this event which matches the stated `preferred_magnitude_id`,
then the first magnitude is returned, and a warning given is `verbose` is `true`.
"""
function preferred_magnitude(e::Event; verbose=false)
has_magnitude(e) || throw(ArgumentError("event contains no magnitudes"))
length(e.magnitude) == 1 && return first(e.magnitude)
preferred_id = e.preferred_magnitude_id
ind = findfirst(x -> x.public_id === preferred_id, e.magnitude)
magnitude = if ind === nothing
verbose && @warn("no magnitude with preferred id; returning the first magnitude")
first(e.magnitude)
else
e.magnitude[ind]
end
magnitude
end
"""
preferred_magnitueds(quakeml::EventParameters; verbose=false) -> magnitudes
Return the preferred magnitudes for the events contained within `quakeml`.
See [`preferred_magnitude`](@ref).
"""
preferred_magnitudes(ep::EventParameters; verbose=false) =
preferred_magnitude.(ep.event; verbose=verbose)
"""
preferred_origin(event; verbose=false) -> origin
Return the preferred origin for an `event`. This may be defined if
there is more than one origin given for an event, and the `preferred_origin_id`
field is set. If there is only one origin for this `event`, then that is
returned. If there is no origin associated with this event which matches
the stated `preferred_origin_id`, then the first origin is returned
and a warning is given when `verbose=true`
"""
function preferred_origin(e::Event; verbose=false)
has_origin(e) || throw(ArgumentError("event contains no origins"))
length(e.origin) == 1 && return first(e.origin)
preferred_id = e.preferred_origin_id
ind = findfirst(x -> x.public_id === preferred_id, e.origin)
origin = if ind === nothing
verbose && @warn("no origin with preferred id; returning the first origin")
first(e.origin)
else
e.origin[ind]
end
origin
end
"""
preferred_origins(quakeml::EventParameters; verbose=false) -> origins
Return the preferred origins for the events contained within `quakeml`.
See [`preferred_origin`](@ref).
"""
preferred_origins(ep::EventParameters; verbose=false) =
preferred_origin.(ep.event; verbose=verbose)
| QuakeML | https://github.com/anowacki/QuakeML.jl.git |
|
[
"MIT"
] | 0.1.2 | 607fd77863fd04cdd6010a33236006949b6cfd69 | code | 154 | @static if VERSION < v"1.2"
function hasfield(T::Type, name::Symbol)
Base.@_pure_meta
Base.fieldindex(T, name, false) > 0
end
end
| QuakeML | https://github.com/anowacki/QuakeML.jl.git |
|
[
"MIT"
] | 0.1.2 | 607fd77863fd04cdd6010a33236006949b6cfd69 | code | 1062 | # More convenient constructors for types and conversions to types
RealQuantity(value::Real) = RealQuantity(value=value)
IntegerQuantity(value::Number) = IntegerQuantity(value=value)
# Allow filling of fields which are types with only a single field
# e.g., EventParameters(public_id="example string")
# rather than EventParameters(public_id=ResourceReference("example string"))
for T in Base.uniontypes(ValueTypes)
@eval Base.convert(::Type{$T}, s::AbstractString) = $T(s)
end
# Allow contruction of types which use the following more easily.
# e.g.,
# QuakeML.Origin(time=DateTime("2012-01-01T00:00:00"),
# longitude=1, latitude=2, public_id="smi:a.com/b")
# rather than
# QuakeML.Origin(time=TimeQuantity(value=DateTime("2012-01-01T00:00:00")),
# longitude=RealQuantity(value=1), etc...)
Base.convert(::Type{RealQuantity}, value::Real) = RealQuantity(value=value)
Base.convert(::Type{IntegerQuantity}, value::Integer) = IntegerQuantity(value=value)
Base.convert(::Type{TimeQuantity}, value::DateTime) = TimeQuantity(value=value)
| QuakeML | https://github.com/anowacki/QuakeML.jl.git |
|
[
"MIT"
] | 0.1.2 | 607fd77863fd04cdd6010a33236006949b6cfd69 | code | 13305 | # Reading and parsing functions
#
# Reading
#
"""
read(filename) -> ::EventParameters
Read a QuakeML file with name `filename` from disk and return an
`EventParameters` object.
# Example
```
julia> file = joinpath(dirname(pathof(QuakeML)), "..", "test", "data", "nepal_mw7.2.qml");
julia> events = QuakeML.read(file)
EventParameters
comment: Array{QuakeML.Comment}((0,))
event: Array{QuakeML.Event}((1,))
description: Missing missing
creation_info: QuakeML.CreationInfo
public_id: QuakeML.ResourceIdentifier
```
---
read(io) -> ::EventParameters
Read a QuakeML document from the stream `io`.
# Example
```
julia> io = IOBuffer(\"\"\"
<quakeml xmlns="http://quakeml.org/xmlns/quakeml/1.2">
<eventParameters></eventParameters>
</quakeml>
\"\"\");
julia> QuakeML.read(io)
EventParameters
comment: Array{QuakeML.Comment}((0,))
event: Array{QuakeML.Event}((0,))
description: Missing missing
creation_info: Missing missing
public_id: QuakeML.ResourceIdentifier
```
"""
read(filename::AbstractString) = readstring(String(Base.read(filename)), filename=filename)
read(io) = readstring(String(Base.read(io)))
"""
readstring(xml_string) -> ::EventParameters
Read the QuakeML contained in `xml_string` and return a `EventParameters` object.
"""
function readstring(xml_string; filename=nothing)
# Extremely basic check that this is XML at all
occursin(r"^\s*<", xml_string) ||
throw(ArgumentError("string does not appear to be XML:\n'$(first(xml_string, 100))'"))
xml = EzXML.parsexml(xml_string)
file_string = filename === nothing ? "" : " in file $filename"
xml_is_quakeml(xml) ||
throw(ArgumentError("QuakeML$file_string does not appear to be a StationXML file"))
schema_version_is_okay(xml) ||
throw(ArgumentError("QuakeML$file_string does not have the correct schema version"))
elements = EzXML.elements(xml.root)
length(elements) == 1 || error("QuakeML$file_string does not have one single root element")
parse_node(first(elements))
end
"""
xml_is_quakeml(xml)
Return `true` if `xml` appears to be a QuakeML file.
"""
xml_is_quakeml(xml) = EzXML.hasroot(xml) && xml.root.name == "quakeml"
"""
schema_version_is_okay(xml::EzXML.Document) -> ::Bool
Return `true` if this XML document is of a version which we
know we can correctly parse.
Note: QuakeML does not include the schema version as a field
of its own, so we simply try and parse the namespace definition.
QuakeML files in the wild appear to do this a number of ways.
"""
function schema_version_is_okay(xml::EzXML.Document)
namespaces = Dict(EzXML.namespaces(xml.root))
version_string = if haskey(namespaces, "q")
last(split(namespaces["q"], '/'))
elseif haskey(namespaces, "")
last(split(namespaces[""], '/'))
else
@warn("cannot determine QuakeML schema version from file")
return true
end
version = VersionNumber(version_string)
if version <= v"1.2"
return true
elseif version > v"1.2"
@warn("document is StationXML version $version; only v1.2 data will be read")
return true
end
end
attributes_and_elements(node::EzXML.Node) = vcat(EzXML.attributes(node), EzXML.elements(node))
"""
parse_node(root::EzXML.Node) -> ::EventParameters
Parse the `root` node of a QuakeML document. This can be accessed as
`EzXML.readxml(file).root`.
"""
parse_node(root::EzXML.Node) = parse_node(EventParameters, root)
"Types which can be directly parsed from a Node"
const ParsableTypes = Union{Type{String},Type{Float64},Type{Int},Type{Bool}}
parse_node(T::ParsableTypes, node::EzXML.Node) = local_parse(T, node.content)
# Handle dates with greater than millisecond precision by truncating to nearest millisecond,
# cope with UTC time zone information (ends with 'Z'), and convert non-UTC time zones to UTC
function parse_node(T::Type{DateTime}, node::EzXML.Node)
# Remove sub-millisecond intervals
m = match(r"(.*T..:..:..[\.]?)([0-9]{0,3})[0-9]*([-+Z].*)*", node.content)
dt = DateTime(m.captures[1] * m.captures[2]) # Local date to ms
(m.captures[3] === nothing || m.captures[3] in ("", "Z", "+00:00", "-00:00")) && return dt # UTC
pm = m.captures[3][1] # Whether ahead or behind UTC
offset = Time(m.captures[3][2:end]) - Time("00:00")
dt = pm == '+' ? dt + offset : dt - offset
dt
end
"Types of types with a single field: `value::String`"
const ValueFieldType = Union{
# XML URI; aliased to ResourceReference
Type{ResourceIdentifier},
# Unconstrained phase name
Type{Phase},
# String types with value restrictions
Type{OriginUncertaintyDescription},
Type{AmplitudeCategory},
Type{OriginDepthType},
Type{OriginType},
Type{MTInversionType},
Type{EvaluationMode},
Type{EvaluationStatus},
Type{PickOnset},
Type{EventType},
Type{DataUsedWaveType},
Type{AmplitudeUnit},
Type{EventDescriptionType},
Type{MomentTensorCategory},
Type{EventTypeCertainty},
Type{SourceTimeFunctionType},
Type{PickPolarity}
}
# FIXME: Maintain one list which automatically fills this and ValueFieldType
"Types with a single field: `value::String"
const ValueTypes = Union{
ResourceIdentifier,
Phase,
OriginUncertaintyDescription,
AmplitudeCategory,
OriginDepthType,
OriginType,
MTInversionType,
EvaluationMode,
EvaluationStatus,
PickOnset,
EventType,
DataUsedWaveType,
AmplitudeUnit,
EventDescriptionType,
MomentTensorCategory,
EventTypeCertainty,
SourceTimeFunctionType,
PickPolarity
}
parse_node(T::ValueFieldType, node::EzXML.Node) = T(node.content)
"""
parse_node(T, node::EzXML.Node) -> ::T
Create a type `T` from the QuakeML module from an XML `node`.
"""
function parse_node(T, node::EzXML.Node)
@debug("\n===\nParsing node type $T\n===")
# Value field types have extra attributes
is_value_field = Type{T} <: ValueFieldType
@debug("$T is a value field: $is_value_field")
node_name = transform_name(node.name)
@debug("Node name is $(node_name)")
is_attribute = is_attribute_field(T, node_name)
@debug if is_attribute
"Node corresponds to an attribute field"
end
# Arguments to the keyword constructor of the type T
args = Dict{Symbol,Any}()
all_elements = is_attribute ? EzXML.elements(node) : attributes_and_elements(node)
all_names = [transform_name(e.name) for e in all_elements]
@debug("Element names: $all_names")
@debug("Field names: $(fieldnames(T))")
# Fill in the field
for field in fieldnames(T)
field_type = fieldtype(T, field)
@debug field, T, field_type
# Skip fields not in our types
if !(field in all_names)
# Types with a `value` field with the same name as the upper field would
# fail the test without `field == :value`
if !(is_value_field && field == :value)
@debug(" Skipping non-value field")
continue
end
end
if !(is_value_field && field == :value)
elm = all_elements[findfirst(isequal(field), all_names)]
end
# Unions are Missing-supporting fields; should only ever have two types
if field_type isa Union
@debug("Field $field is a Union type")
union_types = Base.uniontypes(field_type)
@assert length(union_types) == 2 && Missing in union_types
field_type = union_types[1] == Missing ? union_types[2] : union_types[1]
@debug("Field type is $field_type")
args[field] = parse_node(field_type, elm)
@debug("\n Saving $field as $(args[field])")
# Multiple elements allowed
elseif field_type <: AbstractVector
el_type = eltype(field_type)
@debug("Element type is $el_type")
ifields = findall(isequal(field), all_names)
values = el_type[]
for i in ifields
push!(values, parse_node(el_type, all_elements[i]))
end
args[field] = values
@debug("\n Saving $field as $values")
# The value field of a ValueFieldType
elseif field == :value && is_value_field
@assert value !== nothing
@debug("Value of field is $(repr(value))")
args[field] = local_parse(field_type, value)
@debug("\n Saving $field as $(repr(args[field]))")
# Just one (maybe optional) field
else
args[field] = parse_node(field_type, elm)
@debug("\n Saving $field as $(repr(args[field]))")
end
end
T(; args...)
end
# Versions of parse which accept String as the type.
# Don't define this for Base as this is type piracy.
local_tryparse(T::Type{<:AbstractString}, s::AbstractString) = s
local_tryparse(T::DataType, s::AbstractString) = tryparse(T, s)
local_parse(T::Type{<:AbstractString}, s::AbstractString) = s
local_parse(T::DataType, s::AbstractString) = parse(T, s)
#
# Writing
#
"""
write(io, qml::EventParameters; kwargs...)
Write a set of `EventParameters` to `io`. `kwargs` are passed to
[`quakeml`](@ref) to control the creation of the XML representing
the catalogue.
# Examples
(Note that `"example_quakeml_file.xml"` may not exist.)
Write a file with the default settings
```
julia> qml = QuakeML.read("example_quakeml_file.xml");
julia> write("new_file.xml", qml)
```
Write a file with custom version
```
julia> write("new_file2.xml", qml, version="1.1")
```
"""
function Base.write(io::IO, qml::EventParameters; kwargs...)
EzXML.prettyprint(io, quakeml(qml; kwargs...))
end
"""
quakeml(qml::EventParameters; version="1.2") -> xml::EzXML.XMLDocument
Create an XML document from `qml`, a set of events of type `EventParameters`.
`xml` is an `EzXML.XMLDocument` suitable for output.
The user may also set the nominal `version` of QuakeML created.
The QuakeML document `xml` may be written with `write(io, xml)`
or converted to a string with `string(xml)`.
"""
function quakeml(qml::EventParameters; version::AbstractString="1.2")
doc = EzXML.XMLDocument("1.0")
root = EzXML.ElementNode("quakeml")
# FIXME: Is this the only way to set a namespace in EzXML?
namespace = EzXML.AttributeNode("xmlns", "http://quakeml.org/xmlns/quakeml/" * version)
EzXML.link!(root, namespace)
EzXML.setroot!(doc, root)
event_parameters = EzXML.ElementNode("eventParameters")
EzXML.link!(root, event_parameters)
add_attributes!(event_parameters, qml)
add_elements!(event_parameters, :event_parameters, qml)
doc
end
"""
add_attributes!(node, value) -> node
Add the attribute fields from the structure `value` to a `node`.
For QuakeML documents, all attributes should be `ResourceReference`s.
"""
function add_attributes!(node, value::T) where T
for field in attribute_fields(T)
content = getfield(value, field)
content === missing && continue
@assert content isa ResourceIdentifier
name = retransform_name(field)
attr = EzXML.AttributeNode(name, content.value)
EzXML.link!(node, attr)
end
node
end
"""
add_elements!(node, parent_field, value) -> node
Add the elements to `node` contained within `value`. `parent_field`
is the name of the field which contains `value`.
"""
function add_elements!(node, parent_field, value::T) where T
for field in fieldnames(T)
@debug("adding $parent_field: $field")
is_attribute_field(T, field) && continue
content = getfield(value, field)
if content === missing
continue
end
add_element!(node, field, content)
end
node
end
function add_elements!(node, parent_field, values::AbstractArray)
for value in values
add_elements!(node, parent_field, value)
end
node
end
"Union of types which can be natively written"
const WritableTypes = Union{Float64, Int, String, DateTime, Bool}
"""
add_element!(node, field, value) -> node
Add an element called `field` to `node` with content `value`.
"""
function add_element!(node, field, value::WritableTypes)
@debug(" adding writable type name $field with value $value")
name = retransform_name(field)
elem = EzXML.ElementNode(name)
content = EzXML.TextNode(string(value))
EzXML.link!(elem, content)
EzXML.link!(node, elem)
node
end
function add_element!(node, field, value::ValueTypes)
@debug(" adding value type name $field with value $value")
name = retransform_name(field)
elem = EzXML.ElementNode(name)
content = EzXML.TextNode(value.value)
EzXML.link!(elem, content)
EzXML.link!(node, elem)
node
end
function add_element!(node, field, values::AbstractArray)
@debug(" adding array type name $field with $(length(values)) values")
for value in values
add_element!(node, field, value)
end
node
end
function add_element!(node, field, value)
@debug(" adding compound type name $field of type $(typeof(value))")
name = retransform_name(field)
elem = EzXML.ElementNode(name)
EzXML.link!(node, elem)
add_attributes!(elem, value)
add_elements!(elem, field, value)
node
end
| QuakeML | https://github.com/anowacki/QuakeML.jl.git |
|
[
"MIT"
] | 0.1.2 | 607fd77863fd04cdd6010a33236006949b6cfd69 | code | 73167 | # Definition of types as per the QuakeML schema
using Parameters: @with_kw
# Shorthand for single values which may or may not be present once,
# equivalent to `minOccurs="0" maxOccurs="1"` in the schema.
const M{T} = Union{Missing,T}
"""
RealQuantity(; kwargs...)
Physical quantities that can be expressed numerically—either as integers
or as floating point numbers—are represented by their measured or
computed values and optional values for symmetric or upper and lower
uncertainties. The interpretation of these uncertainties is not defined
in the standard. They can contain statistically well-defined error
measures, but the mechanism can also be used to simply describe a possible
value range. Ifthe confidence level of the uncertainty is known, it can be
listed in the optional field `confidence_level`. Note that `uncertainty`,
`upper_uncertainty`, and `lower_uncertainty` are given as absolute values
of the deviation from the main `value`.
# List of fields
- `value :: Float64`: Value of the quantity. The unit is implicitly defined and depends
on the context. (**Required field.**)
- `uncertainty :: Float64`: Uncertainty as the absolute value of symmetric deviation
from the main value.
- `lower_uncertainty :: Float64`: Uncertainty as the absolute value of deviation from
the main `value` towards smaller values.
- `upper_uncertainty :: Float64`: Uncertainty as the absolute value of deviation from
the main `value` towards larger values.
- `confidence_level :: Float64`: Confidence level of the uncertainty, given in percent.
"""
@with_kw mutable struct RealQuantity
value::Float64
uncertainty::M{Float64} = missing
lower_uncertainty::M{Float64} = missing
upper_uncertainty::M{Float64} = missing
confidence_level::M{Float64} = missing
end
"""
IntegerQuantity(; kwargs...)
Physical quantities that can be expressed numerically—either as integers
or as floating point numbers—are represented by their measured or
computed values and optional values for symmetric or upper and lower
uncertainties. The interpretation of these uncertainties is not defined
in the standard. They can contain statistically well-defined error
measures, but the mechanism can also be used to simply describe a possible
value range. Ifthe confidence level of the uncertainty is known, it can be
listed in the optional field `confidence_level`. Note that `uncertainty`,
`upper_uncertainty`, and `lower_uncertainty` are given as absolute values
of the deviation from the main `value`.
# List of fields
- `value :: Int`: Value of the quantity. The unit is implicitly defined and depends
on the context. (**Required field.**)
- `uncertainty :: Int`: Uncertainty as the absolute value of symmetric deviation
from the main value.
- `lower_uncertainty :: Int`: Uncertainty as the absolute value of deviation from
the main `value` towards smaller values.
- `upper_uncertainty :: Int`: Uncertainty as the absolute value of deviation from
the main `value` towards larger values.
- `confidence_level :: Float64`: Confidence level of the uncertainty, given in percent.
"""
@with_kw mutable struct IntegerQuantity
value::Int
uncertainty::M{Int} = missing
lower_uncertainty::M{Int} = missing
upper_uncertainty::M{Int} = missing
confidence_level::M{Float64} = missing
end
"""
ResourceReference(value)
ResourceReference(; value=::String)
`String` that is used as a reference to a QuakeML resource. It must adhere
to the format specificationsgiven in Sect. 3.1 of the QuakeML specificaiton.
The string has a maximum length of 255 characters.
In this package, when creating objects which require a `ResourceReference`
(usually in a field called `public_id`), a unique URI is created of the form
`"smi:local/XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"`, where `X` represents
a hexadecimal characters (matching `r"[0-9a-f]"`). This is generated
by calling [`QuakeML.random_reference`](@ref).
# Further information
Identifiers take the generic form of:
[smi|quakeml]:〈authority-id〉/〈resource-id〉[#〈local-id〉]
They consist of an authority identifier, a unique resource identifier, and an
optional local identifier. The URI schema name `smi` stands for
'seismological meta-information', thus indicating a connection to a set of
metadata associated with the resource.
The authority-id part must consist of at least three characters, of which
the first character has to be alphanu-meric. The subsequent characters can be
alphanumeric or from the following list: `-`, `.`, `~`, `*`, `'`, `(`, `)`.
After the authority-id, a forward slash (`"/"`) must follow which separates
the authority-id from the resource-id. The resource-id must contain at least
one character, which can be either alphanumeric, or from the eight special
characters which are allowed for the authority-id. For the remaining characters
of the resource-id, also the comma (`","`) and semicolon (`";"`) characters
and characters from the following list can be used: `+`, `?`, `=`, `#`, `/`, `&`.
Note that the forward slash which separates authority-id and resource-id is
always the first forwards lash in the resource identifier. The resource-id
may be followed by a stop character (`"#"`) and a local identifier which
can be made up of alphanumeric characters, the comma (`","`) and semicolon
(`";"`) characters, and the characters from the following list:
`-`, `.`, `~`, `*`, `'`, `(`, `)`, `/`, `+`, `=`, `?`. Local identifiers
are thought to denote resources that have no own metadata description associated,
but are part of a larger collection for which such metadata exists.
For even more information, see
[Section 3.1 of the QuakeML specification](https://quake.ethz.ch/quakeml/docs/latest?action=AttachFile&do=get&target=QuakeML-BED.pdf)
!!! note
`ResourceReference`s are also called `ResourceIdentifier`s.
"""
@with_kw struct ResourceIdentifier
value::String
function ResourceIdentifier(value)
occursin(r"(smi|quakeml):[\w\d][\w\d\-\.\*\(\)_~']{2,}/[\w\d\-\.\*\(\)_~'][\w\d\-\.\*\(\)\+\?_~'=,;#/&]*",
value) || throw(ArgumentError("ResourceIdentifier '$value' is not valid URI"))
check_string_length("value", value, 255)
new(value)
end
end
"""
WhitespaceOrEmptyString
Contains a single field, `value`, which may only contain an empty
`String`, or one that contains only whitespace characters.
"""
@with_kw struct WhitespaceOrEmptyString
value::String
WhitespaceOrEmptyString(value) = (occursin(r"^\s*$", value) ||
throw(ArgumentError("\"" * value *"\" is not blank")); new(value))
end
const ResourceReference = ResourceIdentifier
const ResourceReference_optional = Union{ResourceReference, WhitespaceOrEmptyString}
@enumerated_struct(
OriginUncertaintyDescription,
String,
("horizontal uncertainty", "uncertainty ellipse", "confidence ellipsoid")
)
@enumerated_struct(
AmplitudeCategory,
String,
("point", "mean", "duration", "period", "integral", "other")
)
@enumerated_struct(
OriginDepthType,
String,
("from location", "from moment tensor inversion",
"from modeling of broad-band P waveforms", "constrained by depth phases",
"constrained by direct phases", "constrained by depth and direct phases",
"operator assigned", "other")
)
@enumerated_struct(
OriginType,
String,
("hypocenter", "centroid", "amplitude", "macroseismic", "rupture start",
"rupture end")
)
@enumerated_struct(
MTInversionType,
String,
("general", "zero trace", "double couple")
)
@enumerated_struct(
EvaluationMode,
String,
("manual", "automatic")
)
@enumerated_struct(
EvaluationStatus,
String,
("preliminary", "confirmed", "reviewed", "final", "rejected")
)
@enumerated_struct(
PickOnset,
String,
("emergent", "impulsive", "questionable")
)
@enumerated_struct(
EventType,
String,
("not existing", "not reported", "earthquake", "anthropogenic event",
"collapse", "cavity collapse", "mine collapse", "building collapse",
"explosion", "accidental explosion", "chemical explosion",
"controlled explosion", "experimental explosion", "industrial explosion",
"mining explosion", "quarry blast", "road cut", "blasting levee",
"nuclear explosion", "induced or triggered event", "rock burst",
"reservoir loading", "fluid injection", "fluid extraction", "crash",
"plane crash", "train crash", "boat crash", "other event", "atmospheric event",
"sonic boom", "sonic blast", "acoustic noise", "thunder", "avalanche",
"snow avalanche", "debris avalanche", "hydroacoustic event", "ice quake",
"slide", "landslide", "rockslide", "meteorite", "volcanic eruption")
)
@enumerated_struct(
DataUsedWaveType,
String,
("P waves", "body waves", "surface waves", "mantle waves", "combined", "unknown")
)
@enumerated_struct(
AmplitudeUnit,
String,
("m", "s", "m/s", "m/(s*s)", "m*s", "dimensionless", "other")
)
@enumerated_struct(
EventDescriptionType,
String,
("felt report", "Flinn-Engdahl region", "local time", "tectonic summary",
"nearest cities", "earthquake name", "region name")
)
@enumerated_struct(
MomentTensorCategory,
String,
("teleseismic", "regional")
)
@enumerated_struct(
EventTypeCertainty,
String,
("known", "suspected")
)
@enumerated_struct(
SourceTimeFunctionType,
String,
("box car", "triangle", "trapezoid", "unknown")
)
@enumerated_struct(
PickPolarity,
String,
("positive", "negative", "undecidable")
)
"""
TimeQuantity(; kwargs...)
Describes a point in time, given in ISO 8601 format, with
optional symmetric or asymmetric uncertainties given in seconds.
The time has to be specified in UTC.
# List of fields
- `value :: Dates.DateTime`: Point in time (UTC), given in ISO 8601 format.
(**Required field.**)
- `uncertainty :: Float64`: Symmetric uncertainty of point in time. Unit: s.
- `lower_uncertainty :: Float64`: Lower uncertainty of point in time. Unit: s.
- `upper_uncertainty :: Float64`: Upper uncertainty of point in time. Unit: s.
- `confidence_level :: Float64`: Confidence level of the uncertainty, given in percent.
"""
@with_kw mutable struct TimeQuantity
value::DateTime
uncertainty::M{Float64} = missing
lower_uncertainty::M{Float64} = missing
upper_uncertainty::M{Float64} = missing
confidence_level::M{Float64} = missing
end
"""
CreationInfo(; kwargs...)
Used to describe creation metadata (author, version, and creation time)
of a resource.
# List of fields
- `agency_id :: String`: Designation of agency that published a resource. The string
has a maximum length of 64 characters.
- `agency_uri :: ResourceReference`: URI of the agency that published a resource.
- `author :: String`: Name describing the author of a resource. The string has a
maximum length of 128 characters.
- `author_uri :: ResourceReference`: URI of the author of a resource.
- `creation_time :: Dates.DateTime`: Time of creation of a resource, in ISO 8601 format.
It has to be given in UTC.
- `version :: String`: Version string of a resource. The string has a maximum length
of 64 characters.
"""
@with_kw mutable struct CreationInfo
agency_id::M{String} = missing
agency_uri::M{ResourceReference} = missing
author::M{String} = missing
author_uri::M{ResourceReference} = missing
creation_time::M{DateTime} = missing
version::M{String} = missing
function CreationInfo(agency_id, agency_uri, author, author_uri, creation_time, version)
check_string_length("agency_id", agency_id, 64)
check_string_length("author", author, 128)
check_string_length("version", version, 64)
new(agency_id, agency_uri, author, author_uri, creation_time, version)
end
end
# Enforce string lengths upon field setting
function Base.setproperty!(ci::CreationInfo, field::Symbol, value)
if field === :agency_id || field === :version
check_string_length(String(field), value, 64)
elseif field === :author
check_string_length(String(field), value, 128)
end
setfield!(ci, field, value)
end
"""
EventDescription(; text, type)
Free-form string with additional event description. This can be a
well-known name, like `"1906 San Francisco Earthquake"`.
A number of categories can be given in `type`.
# List of fields
- `text :: String`: Free-form text with earthquake description. (**Required field.**)
- `type :: EventDescriptionType`: Category of earthquake description. Values can be taken from the following:
- `"felt report"`
- `"Flinn-Engdahl region"`
- `"local time"`
- `"tectonic summary"`
- `"nearest cities"`
- `"earthquake name"`
- `"region name"`
"""
@with_kw mutable struct EventDescription
text::String
type::M{EventDescriptionType} = missing
end
"""
Phase(code)
Phase(; value=code)
Phase code as given in the IASPEI Standard Seismic Phase List
(Storchak et al. 2003). String with a maximum length of 32 characters.
# List of fields
- `value :: String`: Phase code. (**Required field.**)
"""
@with_kw mutable struct Phase
value::String
end
"""
Comment(; text, creation_info, id)
Holds information on comments to a resource as well as author
and creation time information.
# List of fields
- `text :: String`: Text of comment. (**Required field.**)
- `creation_info :: CreationInfo`: [`CreationInfo`](@ref QuakeML.CreationInfo) for the `Comment` object.
- `id :: ResourceReference`: Identifier of comment, in QuakeML URI format.
"""
@with_kw mutable struct Comment
text::String
creation_info::M{CreationInfo} = missing
id::M{ResourceReference} = missing
end
"""
Axis(; azimuth, plunge, length)
Describes an eigenvector of a moment tensor expressed in its
principal-axes system. It uses the angles `azimuth`, `plunge`, and the
eigenvalue `length`.
# List of fields
- `azimuth :: RealQuantity`: Azimuth of eigenvector of moment tensor expressed in
principal-axes system. Measured clockwisefrom south-north direction at
epicenter. Unit: °. (**Required field.**)
- `plunge :: RealQuantity`: Plunge of eigenvector of moment tensor expressed in principal-axes
system. Measured against downward vertical direction at epicenter. Unit: °. (**Required field.**)
- `length :: RealQuantity`: Eigenvalue of moment tensor expressed in principal-axes system.
Unit: N m. (**Required field.**)
"""
@with_kw mutable struct Axis
azimuth::RealQuantity
plunge::RealQuantity
length::RealQuantity
end
"""
PrincipleAxes(; t_axis, p_axis, n_axis)
# List of fields
- `tAxis :: Axis`: T (tension) axis of a moment tensor. (**Required field.**)
- `p_axis :: Axis`: P (pressure) axis of a moment tensor. (**Required field.**)
- `n_axis :: Axis`: N (neutral) axis of a moment tensor.
"""
@with_kw mutable struct PrincipleAxes
t_axis::Axis
p_axis::Axis
n_axis::M{Axis} = missing
end
"""
DataUsed(; kwargs...)
Describes the type of data that has been used for a moment-tensor inversion.
# List of fields
- `wave_type : DataUsedWaveType`: Type of waveform data. This can be one of the following
values (see [`DataUsedWaveType`](@ref)):
- `"P waves"`
- `"body waves"`
- `"surface waves"`
- `"mantle waves"`
- `"combined"`
- `"unknown"`
(**Required field.**)
- `station_count :: Int`: Number of stations that have contributed data of the type
given in `wave_type`.
- `component_count :: Int`: Number of data components of the type given in `wave_type`.
- `shortest_period :: Float64`: Shortest period present in data. Unit: s.
- `longest_period :: Float64`: Longest period present in data. Unit: s.
"""
@with_kw mutable struct DataUsed
wave_type::DataUsedWaveType
station_count::M{Int} = missing
component_count::M{Int} = missing
shortest_period::M{Float64} = missing
longest_period::M{Float64} = missing
end
"""
CompositeTime(; year, month, day, hour, minute, second)
Focal times differ significantly in their precision. While focal times of
instrumentally located earthquakes areestimated precisely down to seconds,
historic events have only incomplete time descriptions. Sometimes, even
contradictory information about the rupture time exist. The `CompositeTime`
type allows for such complex descriptions. If the specification is given with
no greater accuracy than days (i.e., no time components are given), the date
refers to local time. However, if time components are given, they have to
refer to UTC.
As an example, consider a historic earthquake in California, e.g., on 28
February 1730, with no time information given. Expressed in UTC, this day
extends from 1730-02-28T08:00:00Z until 1730-03-01T08:00:00Z. Such a
specification would be against intuition. Therefore, for date-time
specifications without time components, local time is used. In the example,
the `CompositeTime` fields are simply `year=1730`, `month=2`, and `day=28`.
In the corresponding time attribute of the origin, however, UTC has to be used.
If the unknown time components are assumed to be zero, the value is
`DateTime("1730-02-28T08:00:00")`.
# List of fields
- `year ::IntegerQuantity`: Year or range of years of the event’s focal time.
- `month ::IntegerQuantity`: Month or range of months of the event’s focal time.
- `day ::IntegerQuantity`: Day or range of days of the event’s focal time.
- `hour ::IntegerQuantity`: Hour or range of hours of the event’s focal time.
- `minute ::IntegerQuantity`: Minute or range of minutes of the event’s focal time.
- `second :: RealQuantity`: Second and fraction of seconds or range of seconds with fraction
of the event’s focal time.
"""
@with_kw mutable struct CompositeTime
year::M{IntegerQuantity} = missing
month::M{IntegerQuantity} = missing
day::M{IntegerQuantity} = missing
hour::M{IntegerQuantity} = missing
minute::M{IntegerQuantity} = missing
second::M{RealQuantity} = missing
end
"""
Tensor(mrr, mtt, mpp, mrt, mrp, mtp)
Tensor(; mrr, mtt, mpp, mrt, mrp, mtp)
The `Tensor` type represents the six moment-tensor elements
Mrr, Mtt, Mpp, Mrt, Mrp, Mtp in the spherical coordinate system defined by
local upward vertical (r), North-South (t), and West-East (p) directions.
See Aki and Richards(1980) for conversions to other coordinate systems.
# List of fields
- `mrr :: RealQuantity`: Moment-tensor component Mrr. Unit: N m. (**Required field.**)
- `mtt :: RealQuantity`: Moment-tensor component Mtt. Unit: N m. (**Required field.**)
- `mpp :: RealQuantity`: Moment-tensor component Mpp. Unit: N m. (**Required field.**)
- `mrt :: RealQuantity`: Moment-tensor component Mrt. Unit: N m. (**Required field.**)
- `mrp :: RealQuantity`: Moment-tensor component Mrp. Unit: N m. (**Required field.**)
- `mtp :: RealQuantity`: Moment-tensor component Mtp. Unit: N m. (**Required field.**)
"""
@with_kw mutable struct Tensor
mrr::RealQuantity
mtt::RealQuantity
mpp::RealQuantity
mrt::RealQuantity
mrp::RealQuantity
mtp::RealQuantity
end
"""
OriginQuality(; kwargs...)
This type contains various attributes commonly used to describe the quality
of an origin, e. g., errors, azimuthal coverage, etc. `Origin` objects have
an optional attribute of the type `OriginQuality`.
# List of fields
- `associated_phase_count :: Int`: Number of associated phases, regardless of their
use for origin computation.
- `used_phase_count :: Int`: Number of defining phases, i. e., phase observations
that were actually used for computingthe origin. Note that there may be more
than one defining phase per station.
- `associated_station_count :: Int`: Number of stations at which the event was observed.
- `used_station_count :: Int`: Number of stations from which data was used for origin
computation.
- `depth_phase_count :: Int`: Number of depth phases (typically pP, sometimes sP)
used in depth computation.
- `standard_error :: Float64`: RMS of the travel time residuals of the arrivals used for
the origin computation. Unit: s.
- `azimuthal_gap :: Float64`: Largest azimuthal gap in station distribution as seen from
epicenter. For an illustration of azimuthal gap and secondary azimuthal gap
(see below), see Fig. 5 of Bondár et al. (2004). Unit: °.
- `secondary_azimuthal_gap :: Float64`: Secondary azimuthal gap in station distribution,
i. e., the largest azimuthal gap a station closes. Unit: °.
- `ground_truth_level :: String`: `String` describing ground-truth level, e. g. GT0,
GT5, etc. It has a maximum length of 32 characters.
- `minimum_distance :: Float64`: Epicentral distance of station closest to the epicenter.
Unit: °.
- `maximum_distance :: Float64`: Epicentral distance of station farthest from the epicenter.
Unit: °.
- `median_distance :: Float64`: Median epicentral distance of used stations. Unit: °.
"""
@with_kw mutable struct OriginQuality
associated_phase_count::M{Int} = missing
used_phase_count::M{Int} = missing
associated_station_count::M{Int} = missing
used_station_count::M{Int} = missing
depth_phase_count::M{Int} = missing
standard_error::M{Float64} = missing
azimuthal_gap::M{Float64} = missing
secondary_azimuthal_gap::M{Float64} = missing
ground_truth_level::M{String} = missing
maximum_distance::M{Float64} = missing
minimum_distance::M{Float64} = missing
median_distance::M{Float64} = missing
function OriginQuality(associated_phase_count, used_phase_count,
associated_station_count, used_station_count, depth_phase_count,
standard_error, azimuthal_gap, secondary_azimuthal_gap,
ground_truth_level, maximum_distance, minimum_distance, median_distance)
check_string_length("ground_truth_level", ground_truth_level, 32)
new(associated_phase_count, used_phase_count, associated_station_count,
used_station_count, depth_phase_count, standard_error, azimuthal_gap,
secondary_azimuthal_gap, ground_truth_level, maximum_distance,
minimum_distance, median_distance)
end
end
function Base.setproperty!(oq::OriginQuality, field::Symbol, value)
if field === :ground_truth_level
check_string_length("ground_truth_level", value, 32)
end
type = fieldtype(OriginQuality, field)
setfield!(oq, field, convert(type, value))
end
"""
NodalPlane(; strike, dip, rake)
This class describes a nodal plane using the fields `strike`, `dip`, and
`rake`. For a definition of the angles see Aki and Richards (1980).
# List of fields
- `strike :: RealQuantity`: Strike angle of nodal plane. Unit: °. (**Required field.**)
- `dip :: RealQuantity`: Dip angle of nodal plane. Unit: °. (**Required field.**)
- `rake :: RealQuantity`: Rake angle of nodal plane. Unit: °. (**Required field.**)
"""
@with_kw mutable struct NodalPlane
strike::RealQuantity
dip::RealQuantity
rake::RealQuantity
end
"""
TimeWindow(; begin_, end_, reference)
Describes a time window for amplitude measurements, given by a central point
in time, and points in time before and after this central point. Both points
before and after may coincide with the central point.
# List of fields
- `begin_ :: Float64`: Absolute value of duration of time interval before `reference` point
in time window. The value may be zero, but not negative. Unit: s.
(**Required field.**)
- `end_ :: Float64`: Absolute value of duration of time interval after `reference` point
in time window. The value may be zero, but not negative. Unit: s.
(**Required field.**)
- `reference :: Dates.DateTime`: Reference point in time (“central” point).
It has to be given in UTC. (**Required field.**)
"""
@with_kw mutable struct TimeWindow
begin_::Float64
end_::Float64
reference::DateTime
function TimeWindow(begin_, end_, reference)
any(x->x<0, (begin_, end_)) &&
throw(ArgumentError("begin and end times cannot be negative"))
new(begin_, end_, reference)
end
end
"""
WaveformStreamID(; kwargs...)
Reference to a stream description in an inventory. This is mostly equivalent
to the combination of `network_code`, `station_code`, `location_code`,
and `channel_code`. However, additional information, e. g., sampling rate,
can be referenced by the resource `uri`. It is recommended to use
resource URI as a flexible, abstract, and unique stream ID that allows
to describe different processing levels, or resampled/filtered products of
the same initialstream, without violating the intrinsic meaning of the legacy
identifiers (network, station, channel, and location codes). However, for
operation in the context of legacy systems, the classical identifier
components are upported.
# List of fields
- `network_code :: String`: Network code. String with a maximum length of 8 characters. (**Required field.**)
- `station_code :: String`: Station code. String with a maximum length of 8 characters. (**Required field.**)
- `channel_code :: String`: Channel code. String with a maximum length of 8 characters.
- `location_code :: String`: Location code. String with a maximum length of 8 characters.
- `uri :: ResourceReference`: Resource identifier for the waveform stream.
"""
@with_kw mutable struct WaveformStreamID
uri::M{ResourceReference} = missing
network_code::String
station_code::String
channel_code::M{String} = missing
location_code::M{String} = missing
function WaveformStreamID(uri, net, sta, cha, loc)
check_string_length("network_code", net, 8)
check_string_length("station_code", sta, 8)
check_string_length("channel_code", cha, 8)
check_string_length("location_code", loc, 8)
new(uri, net, sta, cha, loc)
end
end
function Base.setproperty!(ws::WaveformStreamID, field::Symbol, value)
if field !== :uri
check_string_length(String(field), value, 8)
end
type = fieldtype(WaveformStreamID, field)
setfield!(ws, field, convert(type, value))
end
"""
SourceTimeFunction(; type, duration, rise_time, decay_time)
Source time function used in moment-tensor inversion.
# List of fields
- `type :: SourceTimeFunctionType`: Type of source time function. Values can be taken from the following:
- `"box car"`
- `"triangle"`
- `"trapezoid"`
- `"unknown"`
(**Required field.**)
- `duration :: Float64` Source time function duration. Unit: s. (**Required field.**)
- `rise_time :: Float64`: Source time function rise time. Unit: s.
- `decay_time :: Float64`: Source time function decay time. Unit: s.
"""
@with_kw mutable struct SourceTimeFunction
type::SourceTimeFunctionType
duration::Float64
rise_time::M{Float64} = missing
decay_time::M{Float64} = missing
end
"""
NodalPlanes(; nodal_plane1=::NodalPlane, nodal_plane2=::NodalPlane, preferred_plane=::Int)
This describes the nodal planes of a moment tensor. The field
`preferred_plane` can be used to define which plane is the preferred one,
taking a value of `1` or `2`.
# List of fields
- `nodal_plane1 :: NodalPlane`: First nodal plane of moment tensor.
- `nodal_plane2 :: NodalPlane`: Second nodal plane of moment tensor.
- `preferred_plane :: Int`: Indicator for preferred nodal plane of moment tensor.
It can take integer values `1` or `2`.
"""
@with_kw mutable struct NodalPlanes
nodal_plane1::M{NodalPlane} = missing
nodal_plane2::M{NodalPlane} = missing
preferred_plane::M{Int} = missing
function NodalPlanes(nodal_plane1, nodal_plane2, preferred_plane)
if preferred_plane !== missing
preferred_plane in (1, 2) ||
throw(ArgumentError("preferred_plane must be 1 or 2"))
end
new(nodal_plane1, nodal_plane2, preferred_plane)
end
end
function Base.setproperty!(nps::NodalPlanes, field::Symbol, value)
if field === :preferred_plane && value !== missing
value in (1, 2) || throw(ArgumentError("preferred_plane must be 1 or 2"))
value = Int(value)
end
type = fieldtype(NodalPlanes, field)
# Don't convert here, since preferred_plane should really be
# an Integer
setfield!(nps, field, value)
end
"""
ConfidenceEllipsoid(; kwargs...)
This type represents a description of the location uncertainty as a
confidence ellipsoid with arbitrary orientationin space. The orientation
of a rigid body in three-dimensional Euclidean space can be described by
three parameters. We use the convention of Euler angles, which can be
interpreted as a composition of three elemental rotations (i.e., rotations
around a single axis). In the special case of Euler angles we use here, the
angles are referred to as Tait-Bryan (or Cardan) angles. These angles may be
familiar to the reader from their application in flight dynamics, and are
referred to as heading (yaw, ψ), elevation (attitude, pitch, φ), and bank
(roll, θ).
For a definition of the angles, see Figure 4 of the QuakeML specification
document at https://quake.ethz.ch/quakeml/docs/latest?action=AttachFile&do=get&target=QuakeML-BED.pdf.
Through the three elemental rotations, a Cartesian system `(x,y,z)`
centered at the epicenter, with the south-north direction `x`, the west-east
direction `y`, and the downward vertical direction `z`, is transferred into a
different Cartesian system `(X,Y,Z)` centered on the confidence ellipsoid.
Here, `X` denotes the direction of the major axis, and `Y` denotes the
direction of the minor axis of the ellipsoid. Note that Figure 4 can be
interpreted as a hypothetical view from the _interior_ of the Earth to the
inner face of a shell representing Earth's surface.
The three Tait-Bryan rotations are performed as follows:
(i) a rotation about the `Z` axis with angle ψ (heading, or azimuth);
(ii) a rotation about the `Y` axis with angle φ (elevation, or plunge); and
(iii) a rotation about the `X` axis with angle θ (bank). Note that in the
case of Tait-Bryan angles, the rotations are performed about the ellipsoid's
axes, not about the axes of the fixed `(x,y,z)` Cartesian system.
# List of fields
- `semi_major_axis_length :: Float64`: Largest uncertainty, corresponding to the semi-major axis
of the confidence ellipsoid. Unit: m. (**Required field.**)
- `semi_minor_axis_length :: Float64`: Smallest uncertainty, corresponding to the semi-minor axis
of the confidence ellipsoid. Unit: m. (**Required field.**)
- `semi_intermediate_axis_length :: Float64`: Uncertainty in direction orthogonal to major
and minor axesof the confidence ellipsoid. Unit: m. (**Required field.**)
- `major_axis_plunge :: Float64`: Plunge angle of major axis of confidence ellipsoid.
Corresponds to Tait-Bryan angle φ. Unit: °. (**Required field.**)
- `major_axis_azimuth :: Float64`: Azimuth angle of major axis of confidence ellipsoid.
Corresponds to Tait-Bryan angle ψ. Unit: °. (**Required field.**)
- `major_axis_rotation :: Float64`: This angle describes a rotation about the confidence
ellipsoid's major axis which is required to define the direction of the
ellipsoid's minor axis. Corresponds to Tait-Bryan angle θ. Unit: °. (**Required field.**)
"""
@with_kw mutable struct ConfidenceEllipsoid
semi_major_axis_length::Float64
semi_minor_axis_length::Float64
semi_intermediate_axis_length::Float64
major_axis_plunge::Float64
major_axis_azimuth::Float64
major_axis_rotation::Float64
end
"""
MomentTensor(; kwargs...)
Represents a moment tensor solution for an event. It is an optional
part of a `FocalMechanism` description.
# List of fields
- `public_id :: ResourceReference` Resource identifier of `MomentTensor`.
(**Required field.**)
- `derived_origin_id :: ResourceReference`: Refers to the `public_id` of the `Origin` derived
in the moment tensor inversion. (**Required field.**)
- `moment_magnitude_id :: ResourceReference`: Refers to the `public_id` of the `Magnitude`
object which represents the derived moment magnitude.
- `scalar_moment :: RealQuantity`: Scalar moment as derived in moment tensor inversion.
Unit: N m.
- `tensor :: Tensor`: `Tensor` object holding the moment tensor elements.
- `variance :: Float64`: Variance of moment tensor inversion.
- `variance_reduction :: Float64`: Variance reduction of moment tensor inversion,
given in percent (Dreger 2003). This is a goodness-of-fit measure.
- `double_couple :: Float64`: Double couple parameter obtained from moment tensor
inversion (decimal fraction between 0 and 1).
- `clvd :: Float64`: CLVD (compensated linear vector dipole) parameter obtained
from moment tensor inversion (decimal fraction between 0 and 1).
- `iso :: Float64`: Isotropic part obtained from moment tensor inversion (decimal
fraction between 0 and 1).
- `greens_function_id :: ResourceReference`: Resource identifier of the Green’s function used
in moment tensor inversion.
- `filter_id :: ResourceReference`: Resource identifier of the filter setup used in moment
tensor inversion.
- `source_time_function :: SourceTimeFunction`: Source time function used in moment-tensor inversion.
- `data_used :: Vector{DataUsed}`: Describes waveform data used for moment-tensor inversion.
- `method_id :: ResourceReference`: Resource identifier of the method used for moment-tensor
inversion.
- `category :: MomentTensorCategory`: Category of moment tensor inversion. Valid entries are
given in the following list (see [`MomentTensorCategory`](@ref)):
- `"teleseismic"`
- `"regional"`
- `inversion_type :: MTInversionType`: Type of moment tensor inversion. Users should avoid
giving contradictory information in `inversion_type` and `method_id`.
Valid entries are given in the following list (see
[`MTInversionType`](@ref)):
- general
- zero trace
- double couple
- `comment :: Vector{Comment}`: Additional comments.
- `creation_info :: CreationInfo`: [`CreationInfo`](@ref QuakeML.CreationInfo) for the `MomentTensor` object.
"""
@with_kw mutable struct MomentTensor
data_used::Vector{DataUsed} = DataUsed[]
comment::Vector{Comment} = Comment[]
derived_origin_id::ResourceReference
moment_magnitude_id::M{ResourceReference} = missing
scalar_moment::M{RealQuantity} = missing
tensor::M{Tensor} = missing
variance::M{Float64} = missing
variance_reduction::M{Float64} = missing
double_couple::M{Float64} = missing
clvd::M{Float64} = missing
iso::M{Float64} = missing
greens_function_id::M{ResourceReference} = missing
filter_id::M{ResourceReference} = missing
source_time_function::M{SourceTimeFunction} = missing
method_id::M{ResourceReference} = missing
category::M{MomentTensorCategory} = missing
inversion_type::M{MTInversionType} = missing
creation_info::M{CreationInfo} = missing
public_id::ResourceReference = random_reference()
end
"""
FocalMechanism(; kwargs...)
Describes the focal mechanism of an event. It includes different
descriptions like nodal planes, principal axes, and a moment tensor.
The moment tensor description is provided by objects of the type
`MomentTensor` which can be specified as fields of `FocalMechanism`.
# List of fields
- `public_id :: ResourceReference`: Resource identifier of `FocalMechanism`.
(**Required field.**)
- `triggering_origin_id :: ResourceReference`: Refers to the `public_id` of the triggering
origin.
- `nodal_planes :: NodalPlanes`: Nodal planes of the focal mechanism.
- `principal_axes :: PrincipleAxes`: Principal axes of the focal mechanism.
- `azimuthal_gap :: Float64`: Largest azimuthal gap in distribution of stations
used for determination of focal mechanism. Unit: °.
- `station_polarity_count :: Int`: Number of station polarities used for
determination of focal mechanism.
- `misfit :: Float64`: Fraction of misfit polarities in a first-motion focal
mechanism determination. Decimal fraction between 0 and 1.
- `station_distribution_ratio :: Float64`: Station distribution ratio (STDR)
parameter. Indicates how the stations are distributed about the
focal sphere (Reasenberg and Oppenheimer 1985). Decimal fraction
between 0 and 1.
- `method_id :: ResourceReference`: Resource identifier of the method used for determination
of the focal mechanism.
- `waveform_id :: Vector{ResourceReference}`: Refers to a set of waveform streams from which the
focal mechanism was derived.
- `evaluation_mode :: EvaluationMode`: Evaluation mode of `FocalMechanism` (see
[`EvaluationMode`](@ref)).
- `evaluation_status :: EvaluationStatus`: Evaluation status of `FocalMechanism`
(see [`EvaluationStatus`](@ref)).
- `comment :: Vector{Comment}`: Additional comments.
- `creation_info :: CreationInfo`: [`CreationInfo`](@ref QuakeML.CreationInfo) for the `FocalMechanism` object.
"""
@with_kw mutable struct FocalMechanism
waveform_id::Vector{WaveformStreamID} = WaveformStreamID[]
comment::Vector{Comment} = Comment[]
moment_tensor::Vector{MomentTensor} = MomentTensor[]
triggering_origin_id::M{ResourceReference} = missing
nodal_planes::M{NodalPlanes} = missing
principle_axes::M{PrincipleAxes} = missing
azimuthal_gap::M{Float64} = missing
station_polarity_count::M{Int} = missing
misfit::M{Float64} = missing
station_distribution_ratio::M{Float64} = missing
method_id::M{ResourceReference} = missing
evaluation_mode::M{EvaluationMode} = missing
evaluation_status::M{EvaluationStatus} = missing
creation_info::M{CreationInfo} = missing
public_id::ResourceReference = random_reference()
end
"""
Amplitude(; kwargs...)
Represents a quantification of the waveform anomaly, usually a single
amplitude measurement or a measurement of the visible signal duration
for duration magnitudes.
# List of fields
- `public_id :: ResourceReference`: Resource identifier of `Amplitude`.
(**Required field.**)
- `genericAmplitude :: RealQuantity`: Measured amplitude value for the given
`waveform_id`. Note that this attribute can describe different physical
quantities, depending on the `type` and `category` of the amplitude.
These can be, e.g., displacement, velocity, or a period. If the only
amplitude information is a period, it has to specified here, not in the
`period` field. The latter can be used if the amplitude measurement
contains information on, e.g., displacement and an additional period.
Since the physical quantity described by this attributeis not fixed,
the unit of measurement cannot be defined in advance. However, the
quantity has to be specified in SI base units. The enumeration given
in the field `unit` provides the most likely units that could be needed
here. For clarity, using the optional `unit` field is highly encouraged.
(**Required field.**)
- `type :: String`: `String` that describes the type of amplitude using the
nomenclature from Storchak et al. (2003). Possible values include
unspecified amplitude reading (`"A"`), amplitude reading for local
magnitude (`"AML"`), amplitude reading for body wave magnitude (`"AMB"`),
amplitude reading for surface wave magnitude (`"AMS"`), and time of
visible end of record for duration magnitude (`"END"`). It has a maximum
length of 32 characters.
- `category :: AmplitudeCategory`: This field describes the way the waveform trace is evaluated
to derive an amplitude value. This can be just reading a single value for
a given point in time (`"point"`), taking a mean value over a time
interval (`"mean"`), integrating the trace over a time interval
(`"integral"`), specifying just a time interval (`"duration"`), or
evaluating a period (`"period"`). (See [`AmplitudeCategory`](@ref).)
- `"point"`
- `"mean"`
- `"duration"`
- `"period"`
- `"integral"`
- `"other"`
- `unit :: AmplitudeUnit`: This field provides the most likely measurement units for the
physical quantity described in the `generic_Amplitude` field. Possible
values are specified as combinations of SI base units.
(See [`AmplitudeUnit`](@ref)
- `"m"`
- `"s:`
- `"m/s"`
- `"m/(s*s)"`
- `"m*s"`
- `"dimensionless"`
- `"other"`
- `method_id :: ResourceReference`: Describes the method of amplitude determination.
- `period :: RealQuantity`: Dominant period in the `time_window` in case of amplitude
measurements. Not used for duration magnitude. Unit: s.
- `snr :: Float64`: Signal-to-noise ratio of the spectrogram at the location the
amplitude was measured.
- `time_window :: TimeWindow`: Description of the time window used for amplitude
measurement. Recommended for duration magnitudes.
- `pick_id :: ResourceReference`: Refers to the `public_id` of an associated `Pick` object.
- `waveform_id :: ResourceReference`: Identifies the waveform stream on which the amplitude
was measured.
- `filter_id :: ResourceReference`: Identifies the filter or filter setup used for filtering
the waveform stream referenced by `waveform_id`.
- `scaling_time :: TimeQuantity`: Scaling time for amplitude measurement.
- `magnitude_hint :: String`: Type of magnitude the amplitude measurement is used
for. For valid values see [`Magnitude`](@ref QuakeML.Magnitude). String value with a
maximum length of 32 characters.
- `evaluation_mode :: EvaluationMode`: Evaluation mode of `Amplitude` (see [`EvaluationMode`](@ref)).
- `evaluation_status :: EvaluationStatus`: Evaluation status of `Amplitude` (see
[`EvaluationStatus`](@ref)).
- `comment :: Vector{Comment}`: Additional comments.
- `creation_info :: CreationInfo`: [`CreationInfo`](@ref QuakeML.CreationInfo) for the `Amplitude` object.
"""
@with_kw mutable struct Amplitude
comment::Vector{Comment} = Comment[]
generic_amplitude::RealQuantity
type::M{String} = missing
category::M{AmplitudeCategory} = missing
unit::M{AmplitudeUnit} = missing
method_id::M{ResourceReference} = missing
period::M{RealQuantity} = missing
snr::M{Float64} = missing
time_window::M{TimeWindow} = missing
pick_id::M{ResourceReference} = missing
waveform_id::M{WaveformStreamID} = missing
filter_id::M{ResourceReference} = missing
scaling_time::M{TimeQuantity} = missing
magnitude_hint::M{String} = missing
evaluation_mode::M{EvaluationMode} = missing
evaluation_status::M{EvaluationStatus} = missing
creation_info::M{CreationInfo} = missing
public_id::ResourceReference = random_reference()
function Amplitude(comment, generic_amplitude, type, category, unit,
method_id, period, snr, time_window, pick_id, waveform_id, filter_id,
scaling_time, magnitude_hint, evaluation_mode, evaluation_status,
creation_info, public_id)
check_string_length("type", type, 32)
check_string_length("magnitude_hint", magnitude_hint, 32)
new(comment, generic_amplitude, type, category, unit,
method_id, period, snr, time_window, pick_id, waveform_id, filter_id,
scaling_time, magnitude_hint, evaluation_mode, evaluation_status,
creation_info, public_id)
end
end
function Base.setproperty!(amp::Amplitude, field::Symbol, value)
if field === :type || field === :magnitude_hint
check_string_length(String(field), value, 32)
end
type = fieldtype(Amplitude, field)
setfield!(amp, field, convert(type, value))
end
"""
StationMagnitudeContribution(; station_magnitude_id, residual, weight)
Describes the weighting of magnitude values froms everal
`StationMagnitude` objects for computing a network magnitude estimation.
# List of fields
- `stationMagnitudeID :: ResourceReference`: Refers to the `publicID` of a [`StationMagnitude`](@ref QuakeML.StationMagnitude)
object. (**Required field.**)
- `residual :: Float64`: Residual of magnitude computation.
- `weight :: Float64`: Weight of the magnitude value from [`StationMagnitude`](@ref QuakeML.StationMagnitude)
for computing the magnitude value in [`Magnitude`](@ref).
Note that there is no rule for the sum of the weights of all station
magnitude contributions to a specific network magnitude. In particular,
the weights are not required to sum up to unity.
"""
@with_kw mutable struct StationMagnitudeContribution
station_magnitude_id::ResourceReference
residual::M{Float64} = missing
weight::M{Float64} = missing
end
"""
Magnitude(; kwargs...)
Describes a magnitude which can, but does not need to be associated
with an origin. Association with an origin is expressed with the optional
field `origin_id`. It is either a combination of different magnitude
estimations, or it represents the reported magnitude for the given event.
# List of fields
- `public_id :: ResourceReference`: Resource identifier of `Magnitude`.
(**Required field.**)
- `mag :: RealQuantity`: Resulting magnitude value from combining values of type
`StationMagnitude`. If no estimations are available, this value can
represent the reported magnitude. (**Required field.**)
- `type :: String`: Describes the type of magnitude. This is a free-text field
because it is impossible to cover all existing magnitude type designations
with an enumeration. Possible values are unspecified magitude (`"M"`),
local magnitude (`"ML"`), body wave magnitude (`"Mb"`), surface wave
magnitude (`"MS"`), moment magnitude (`"Mw"`), duration magnitude (`"Md"`),
coda magnitude (`"Mc"`), `"MH"`, `"Mwp"`, `"M50"`, `"M100"`, etc.
- `station_magnitude_contribution :: Vector{StationMagnitudeContribution}`:
Set of [`StationMagnitudeContribution`](@ref QuakeML.StationMagnitudeContribution)s
describing the contributions of each station used to compute the magnitude.
- `origin_id :: ResourceReference`: Reference to an origin’s `public_id` if the magnitude
has an associated `Origin`.
- `method_id :: ResourceReference`: Identifies the method of magnitude estimation. Users
should avoid giving contradictory information in `method_id` and `type`.
- `station_count` :: Int: Number of used stations for this magnitude computation.
- `azimuthal_gap :: Float64`: Azimuthal gap for this magnitude computation. Unit: °.
- `evaluation_mode :: EvaluationMode`: Evaluation mode of `Magnitude` (see [`EvaluationMode`](@ref)).
- `evaluation_status :: EvaluationStatus`: Evaluation status of `Magnitude` (see
[`EvaluationStatus`](@ref)).
- `comment :: Vector{Comment}`: Additional comments.
- `creation_info :: CreationInfo`: [`CreationInfo`](@ref QuakeML.CreationInfo) for the `Magnitude` object.
"""
@with_kw mutable struct Magnitude
comment::Vector{Comment} = Comment[]
station_magnitude_contribution::Vector{StationMagnitudeContribution} = StationMagnitudeContribution[]
mag::RealQuantity
type::M{String} = missing
origin_id::M{ResourceReference} = missing
method_id::M{ResourceReference} = missing
station_count::M{Int} = missing
azimuthal_gap::M{Float64} = missing
evaluation_mode::M{EvaluationMode} = missing
evaluation_status::M{EvaluationStatus} = missing
creation_info::M{CreationInfo} = missing
public_id::ResourceReference = random_reference()
function Magnitude(comment, station_magnitude_contribution, mag, type,
origin_id, method_id, station_count, azimuthal_gap, evaluation_mode,
evaluation_status, creation_info, public_id)
check_string_length("type", type, 32)
new(comment, station_magnitude_contribution, mag, type,
origin_id, method_id, station_count, azimuthal_gap, evaluation_mode,
evaluation_status, creation_info, public_id)
end
end
function Base.setproperty!(mag::Magnitude, field::Symbol, value)
if field === :type
check_string_length("type", value, 32)
end
type = fieldtype(Magnitude, field)
setfield!(mag, field, convert(type, value))
end
"""
StationMagnitude(; kwargs...)
Describes the magnitude derived from a single waveform stream.
# List of fields
- `public_id :: ResourceReference`: Resource identifier of `StationMagnitude`.
(**Required field.**)
- `origin_id :: ResourceReference`: Reference to an origin’s `public_id` if the
`StationMagnitude` has an `associatedOrigin`.
- `mag :: RealQuantity`: Estimated magnitude. (**Required field.**)
- `type :: String`: See [`Magnitude`](@ref QuakeML.Magnitude).
- `amplitude_id :: ResourceReference`: Identifies the data source of the `StationMagnitude`.
For magnitudes derived from amplitudes in waveforms (e. g., local
magnitude ML), `amplitude_id` points to `public_id` in [`Amplitude`](@ref QuakeML.Amplitude).
- `method_id :: ResourceReference`: See [`Magnitude`](@ref QuakeML.Magnitude).
- `waveform_id :: ResourceReference`: Identifies the waveform stream. This element can be
helpful if no amplitude is referenced, or the amplitude is not
available in the context. Otherwise, it would duplicate the
`waveform_id` provided there and can be omitted.
- `comment :: Vector{Comment}`: Additional comments.
- `creationInfo :: CreationInfo`: [`CreationInfo`](@ref QuakeML.CreationInfo) for the `StationMagnitude` object.
"""
@with_kw mutable struct StationMagnitude
comment::Vector{Comment} = Comment[]
mag::RealQuantity
type::M{String} = missing
origin_id::M{ResourceReference} = missing
method_id::M{ResourceReference} = missing
creation_info::M{CreationInfo} = missing
public_id::ResourceReference = random_reference()
function StationMagnitude(comment, mag, type,
origin_id, method_id, creation_info, public_id)
check_string_length("type", type, 32)
new(comment, mag, type, origin_id, method_id, creation_info, public_id)
end
end
function Base.setproperty!(stamag::StationMagnitude, field::Symbol, value)
if field === :type
check_string_length(String(field), value, 32)
end
type = fieldtype(StationMagnitude, field)
setfield!(stamag, field, convert(type, value))
end
"""
OriginUncertainty(; kwargs...)
Describes the location uncertainties of an origin. The uncertainty can
be described either as a simple circular horizontal uncertainty, an
uncertainty ellipse according to IMS1.0, or a confidence ellipsoid.
If multiple uncertainty models are given, the preferred variant can be
specified in the field `preferred_description`.
# List of fields
- `horizontal_uncertainty :: Float64`: Circular confidence region, given by single
value of horizontal uncertainty. Unit: m.
- `min_horizontal_uncertainty :: Float64`: Semi-minor axis of confidence ellipse.
Unit: m.
- `max_horizontal_uncertainty :: Float64`: Semi-major axis of confidence ellipse.
Unit: m.
- `azimuth_max_horizontal_uncertainty :: Float64`: Azimuth of major axis of confidence
ellipse. Measured clockwise from south-north direction at epicenter.
Unit: °.
- `confidence_ellipsoid :: ConfidenceEllipsoid`: Confidence ellipsoid (see [`ConfidenceEllipsoid`](@ref QuakeML.ConfidenceEllipsoid)).
- `preferred_description :: OriginUncertaintyDescription`: Preferred uncertainty description. Allowed
values are the following (see [`OriginUncertaintyDescription`](@ref):
- `"horizontal uncertainty"`
- `"uncertainty ellipse"`
- `"confidence ellipsoid"`
- `confidence_level :: Float64`: Confidence level of the uncertainty, given in
percent.
"""
@with_kw mutable struct OriginUncertainty
horizontal_uncertainty::M{Float64} = missing
min_horizontal_uncertainty::M{Float64} = missing
max_horizontal_uncertainty::M{Float64} = missing
azimuth_max_horizontal_uncertainty::M{Float64} = missing
confidence_ellipsoid::M{ConfidenceEllipsoid} = missing
preferred_description::M{OriginUncertaintyDescription} = missing
confidence_level::M{Float64} = missing
end
"""
Arrival(; kwargs...)
Successful association of a pick with an origin qualifies this pick as
an arrival. An arrival thus connects a pick with an origin and provides
additional attributes that describe this relationship. Usually
qualification of a pick as an arrival for a given origin is a
hypothesis, which is based on assumptions about the type of arrival
(phase) as well as observed and (on the basis of an earth model)
computed arrival times, or the residual, respectively. Additional pick
attributes like the horizontal slowness and backazimuth of the observed
wave—especially if derived from array data—may further constrain the
nature of the arrival.
# List of fields
- `public_id :: ResourceReference`: Resource identifier of `Arrival`.
(**Required field.**)
- `pick_id :: ResourceReference`: Refers to a `public_id` of a [`Pick`](@ref QuakeML.Pick).
(**Required field.**)
- `phase :: Phase`: Phase identification. For possible values, please refer to the
description of the [`Phase`](@ref QuakeML.Phase) type. (**Required field.**)
- `time_correction :: Float64`: Time correction value. Usually, a value characteristic
for the station at which the pick was detected, sometimes also characteristic
for the phase type or the slowness. Unit: s.
- `azimuth :: Float64`: Azimuth of station as seen from the epicenter. Unit: °.
- `distance :: Float64`: Epicentral distance. Unit: °.
- `takeoff_angle :: RealQuantity`: Angle of emerging ray at the source, measured against
the downward normal direction. Unit: °.
- `time_residual :: Float64`: Residual between observed and expected arrival time
assuming proper phase identification and given the `earth_model_id` of
the `Origin`, taking into account the `timeCorrection`. Unit: s.
- `horizontal_slowness_residual :: Float64`: Residual of horizontal slowness and
the expected slowness given the current origin (refers to field
`horizontal_slowness` of [`Pick`](@ref QuakeML.Pick)). Unit: s/°
- `backazimuthResidual :: Float64`: Residual of backazimuth and the backazimuth
computed for the current origin (refers to field `backazimuth` of
[`Pick`](@ref QuakeML.Pick)). Unit: °.
- `time_weight :: Float64`: Weight of the arrival time for computation of the associated
`Origin`. Note that the sum of all weights is not required to be unity.
- `horizontal_slowness_weight :: Float64`: Weight of the horizontal slowness for
computation of the associated `Origin`. Note that the sum of all
weights is not required to be unity.
- `backazimuth_weight :: Float64`: Weight of the backazimuth for computation of the
associated `Origin`. Note that the sum of all weights is not required
to be unity.
- `earth_model_id :: ResourceReference`: Earth model which is used for the association of
`Arrival` to `Pick` and computation of the residuals.
- `comment :: Vector{Comment}`: Additional comments.
- `creation_info :: CreationInfo`: [`CreationInfo`](@ref QuakeML.CreationInfo) for the `Arrival` object
"""
@with_kw mutable struct Arrival
comment::Vector{Comment} = Comment[]
pick_id::ResourceReference
phase::Phase
time_correction::M{Float64} = missing
azimuth::M{Float64} = missing
distance::M{Float64} = missing
takeoff_angle::M{RealQuantity} = missing
time_residual::M{Float64} = missing
horizontal_slowness_residual::M{Float64} = missing
backazimuth_residual::M{Float64} = missing
time_weight::M{Float64} = missing
horizontal_slowness_weight::M{Float64} = missing
backazimuth_weight::M{Float64} = missing
earth_model_id::M{ResourceReference} = missing
creation_info::M{CreationInfo} = missing
public_id::ResourceReference = random_reference()
end
"""
Origin(; kwargs...)
Represents the focal time and geographical location of an earthquake
hypocenter, as well as additional meta-information. `Origin` can have
objects of type `OriginUncertainty` and `Arrival` as fields.
# List of fields
- `public_id :: ResourceReference`: Resource identifier of `Origin`.
(**Required field.**)
- `time`: Focal time. (**Required field.**)
- `longitude :: RealQuantity`: Hypocenter longitude, with respect to the World Geodetic
System 1984 (WGS84) reference system (National Imagery and Mapping
Agency 2000). Unit: °. (**Required field.**)
- `latitude :: RealQuantity`: Hypocenter latitude, with respect to the WGS84 reference
system. Unit: °. (**Required field.**)
- `depth :: RealQuantity`: Depth of hypocenter with respect to the nominal sea level
given by the WGS84 geoid (Earth Gravitational Model, EGM96, Lemoine
et al. 1998). Positive values indicate hypocenters below sea level.
For shallow hypocenters, the `depth` value can be negative. Note:
Other standards use different conventions for depth measurement.
As an example, GSE 2.0, defines depth with respect to the local
surface. If event data is converted from other formats to QuakeML,
depth values may have to be modified accordingly. Unit: m.
- `depth_type :: OriginDepthType`: Type of depth determination. Allowed values are the following
(see [`OriginDepthType`](@ref)):
- `"from location"`
- `"from moment tensor inversion",`
- `"from modeling of broad-band P waveforms"`
- `"constrained by depth phases",`
- `"constrained by direct phases"`
- `"constrained by depth and direct phases",`
- `"operator assigned"`
- `"other"`
- `time_fixed :: Bool`: Boolean flag. `true` if focal time was kept fixed for
computation of the `Origin`.
- `epicenter_fixed :: Bool`: Boolean flag. `true` if epicenter was kept fixed
for computationof `Origin`.
- `reference_system_id :: ResourceReference`: Identifies the reference system used for
hypocenter determination. This is only necessary if a modified version
of the standard (with local extensions) is used that provides a
non-standard coordinate system.
- `method_id :: ResourceReference`: Identifies the method used for locating the event.
- `earth_model_id :: ResourceReference`: Identifies the earth model used in `methodID`.
- `composite_time :: CompositeTime`: Supplementary information on time of rupture start.
Complex descriptions of focal times of historic events are possible,
see description of the [`CompositeTime`](@ref QuakeML.CompositeTime) type.
Note that even if `composite_time` is used, the mandatory `time` field
has to be set too.
It has to be set to the single point in time (with uncertainties allowed)
that is most characteristic for the event.
- `quality :: OriginQuality`: Additional parameters describing the quality of an `Origin`
determination.
- `type :: OriginType`: Describes the `Origin` type. Allowed values are the following
(see [`OriginType`](@ref QuakeML.OriginType)):
- `"hypocenter"`
- `"centroid"`
- `"amplitude"`
- `"macroseismic"`
- `"rupture start"`
- `"rupture end"`
- `region :: String`: Can be used to decribe the geographical region of the
epicenter location. Useful if an event has multiple origins from
different agencies, and these have different region designations.
Note that an event-wide region can be defined in the `description`
field of an [`Event`](@ref QuakeML.Event) object. The user has to take care
that this information corresponds to the region attribute of the preferred
`Origin`. String with maximum length of 255 chars.
- `evaluation_mode :: EvaluationMode`: Evaluation mode of `Origin` (see [`EvaluationMode`](@ref QuakeML.EvaluationMode).
- `evaluation_status :: EvaluationStatus`: Evaluation status of `Origin` (see [`EvaluationStatus`](@ref QuakeML.EvaluationStatus)).
- `comment :: Vector{Comment}`: Additional comments.
- `creation_info :: CreationInfo`: [`CreationInfo`](@ref QuakeML.CreationInfo) for the `Origin` object.
"""
@with_kw mutable struct Origin
composite_time::Vector{CompositeTime} = CompositeTime[]
comment::Vector{Comment} = Comment[]
origin_uncertainty::Vector{OriginUncertainty} = OriginUncertainty[]
arrival::Vector{Arrival} = Arrival[]
time::TimeQuantity
longitude::RealQuantity
latitude::RealQuantity
depth::M{RealQuantity} = missing
depth_type::M{OriginDepthType} = missing
time_fixed::M{Bool} = missing
epicenter_fixed::M{Bool} = missing
reference_system_id::M{ResourceReference} = missing
method_id::M{ResourceReference} = missing
earth_model_id::M{ResourceReference} = missing
quality::M{OriginQuality} = missing
type::M{OriginType} = missing
region::M{String} = missing
evaluation_mode::M{EvaluationMode} = missing
evaluation_status::M{EvaluationStatus} = missing
creation_info::M{CreationInfo} = missing
public_id::ResourceReference = random_reference()
function Origin(composite_time, comment, origin_uncertainty, arrival, time,
longitude, latitude, depth, depth_type, time_fixed, epicenter_fixed,
reference_system_id, method_id, earth_model_id, quality, type, region,
evaluation_mode, evaluation_status, creation_info, public_id)
check_string_length("region", region, 128)
new(composite_time, comment, origin_uncertainty, arrival, time,
longitude, latitude, depth, depth_type, time_fixed, epicenter_fixed,
reference_system_id, method_id, earth_model_id, quality, type, region,
evaluation_mode, evaluation_status, creation_info, public_id)
end
end
function Base.setproperty!(origin::Origin, field::Symbol, value)
if field === :region
check_string_length("region", value, 128)
end
type = fieldtype(Origin, field)
setfield!(origin, field, convert(type, value))
end
"""
Pick(; kwargs...)
A pick is the observation of an amplitude anomaly in a seismogram at a
specific point in time. It is notnecessarily related to a seismic event.
# List of fields
- `public_id :: ResourceReference`: Resource identifier of `Pick`. (**Required field.**)
- `time :: TimeQuantity`: Observed onset time of signal (“pick time”). (**Required field.**)
- `waveform_id :: ResourceReference`: Identifes the waveform stream.
(**Required field.**)
- `filter_id :: ResourceReference`: Identifies the filter or filter setup used for filtering
the waveform stream referenced by `waveform_id`.
- `method_id :: ResourceReference`: Identifies the picker that produced the pick. This can be
either a detection software program or aperson.
- `horizontal_slowness :: RealQuantity`: Observed horizontal slowness of the signal. Most
relevant in array measurements. Unit: s/°.
- `backazimuth :: RealQuantity`: Observed backazimuth of the signal. Most relevant in
array measurements. Unit: °.
- `slowness_method_id :: ResourceReference`: Identifies the method that was used to determine
the slowness.
- `onset :: PickOnset`: Flag that roughly categorizes the sharpness of the onset.
Allowed values are (see [`PickOnset`](@ref QuakeML.PickOnset)):
- `"impulsive"`
- `"emergent"`
- `"questionable"`
- `phase_hint :: Phase`: Tentative phase identification as specified by the picker.
- `polarity :: PickPolarity`: Indicates the polarity of first motion, usually from impulsive
onsets. Allowed values are (see [`PickPolarity`](@ref)):
- `"positive"`
- `"negative"`
- `"undecidable"`
- `evaluation_mode :: EvaluationMode`: Evaluation mode of `Pick` (see [`EvaluationMode`](@ref QuakeML.EvaluationMode)).
- `evaluation_status :: EvaluationStatus`: Evaluation status of `Pick` (see [`EvaluationStatus`](@ref QuakeML.EvaluationStatus)).
- `comment :: Vector{Comment}`: Additional comments.
- `creation_info :: CreationInfo`: [`CreationInfo`](@ref QuakeML.CreationInfo) for the `Pick` object.
"""
@with_kw mutable struct Pick
comment::Vector{Comment} = Comment[]
time::TimeQuantity
waveform_id::WaveformStreamID
filter_id::M{ResourceReference} = missing
method_id::M{ResourceReference} = missing
horizontal_slowness::M{RealQuantity} = missing
backazimuth::M{RealQuantity} = missing
slowness_method_id::M{ResourceReference} = missing
onset::M{PickOnset} = missing
phase_hint::M{Phase} = missing
polarity::M{PickPolarity} = missing
evaluation_mode::M{EvaluationMode} = missing
evaluation_status::M{EvaluationStatus} = missing
creation_info::M{CreationInfo} = missing
public_id::ResourceReference = random_reference()
end
"""
Event(; kwargs...)
Describes a seismic event which does not necessarily need to be a
tectonic earthquake. An event is usually associated with one or more
origins, which contain information about focal time and geographic
allocation of the event. Multiple origins can cover automatic and
manual locations, a set of location from different agencies, locations
generated with different location programs and earth models, etc.
Furthermore, an eventis usually associated with one or more magnitudes,
and with one or more focal mechanism determinations. In
standard QuakeML-BED, `Origin`, `Magnitude`, `StationMagnitude`, and
`FocalMechanism` are fields of `Event`. In BED-RT (the real-time version)
all these fields are on the same hierarchy level as child elements of
`EventParameters`. The association of origins, magnitudes, and focal
mechanisms to a particular event is expressed using references inside `Event`.
# List of fields
- `public_id :: ResourceReference`: Resource identifier of `Event`.
(**Required field.**)
- `preferred_origin_id :: ResourceReference`: Refers to the `public_id` of the
`preferred_origin` object.
- `preferred_magnitude_id :: ResourceReference`: Refers to the `public_id` of the
`preferred_magnitude` object.
- `preferred_focal_mechanism_id :: ResourceReference`: Refers to the `public_id`of the
`preferred_focal_mechanism` object.
- `type :: EventType`: Describes the type of an event (Storchak et al. 2012).
Allowed values are the following (see [`EventType`](@ref)):
- `"not existing"`
- `"not reported"`
- `"earthquake"`
- `"anthropogenic event"`
- `"collapse"`
- `"cavity collapse"`
- `"mine collapse"`
- `"building collapse"`
- `"explosion"`
- `"accidental explosion"`
- `"chemical explosion"`
- `"controlled explosion"`
- `"experimental explosion"`
- `"industrial explosion"`
- `"mining explosion"`
- `"quarry blast"`
- `"road cut"`
- `"blasting levee"`
- `"nuclear explosion"`
- `"induced or triggered event"`
- `"rock burst"`
- `"reservoir loading"`
- `"fluid injection"`
- `"fluid extraction"`
- `"crash"`
- `"plane crash"`
- `"train crash"`
- `"boat crash"`
- `"other event"`
- `"atmospheric event"`
- `"sonic boom"`
- `"sonic blast"`
- `"acoustic noise"`
- `"thunder"`
- `"avalanche"`
- `"snow avalanche"`
- `"debris avalanche"`
- `"hydroacoustic event"`
- `"ice quake"`
- `"slide"`
- `"landslide"`
- `"rockslide"`
- `"meteorite"`
- `"volcanic eruption"`
- `type_certainty :: EventTypeCertainty`: Denotes how certain the information on event type is
(Storchak et al. 2012). Allowed values are the following
(see [`EventTypeCertainty`](@ref)):
- `"known"`
- `"suspected"`
- `description :: Vector{EventDescription}` Additional event description, like earthquake name,
Flinn-Engdahl region, etc.
- `comment :: Vector{Comment}`: Comments.
- `creation_info :: CreationInfo`: `CreationInfo` for the `Event` object.
- `origin :: Vector{Event}`: Set of [`Origin`](@ref QuakeML.Event)s associated
with this `Event`. One of these may be the preferred origin, in which case
preferred_origin_id` should be set.
- `magnitude :: Vector{Magnitude}`: Set of [`Magnitude`](@ref QuakeML.Magnitude)s
for this `Event`. One of these may be the preferred magnitude, in which case
`preferred_magnitude_id` should be set.
- `station_magnitude :: Vector{StationMagnitude}`: Set of
[`StationMagnitude`](@ref QuakeML.StationMagnitude)s contributing to the
magnitude of this event.
- `focal_mechanism :: Vector{FocalMechanism}`: Set of
[`FocalMechanism`](@ref QuakeML.FocalMechanism)s for this event. One of these
may be the preferred focal mechanism, in which case `preferred_focal_mechanism_id`
should be set.
- `pick :: Vector{Pick}`: Set of [`Pick`](@ref QuakeML.Pick)s made from this
event.
- `amplitude :: Vector{Amplitude}`: Set of [`Amplitude`](@ref QuakeML.Amplitude)s
measured at stations from this event.
(Note: The additional real-time fields `origin_reference`,
`magnitude_reference` and `focal_mechanism_reference` are not
yet implemented.)
"""
@with_kw mutable struct Event
description::Vector{EventDescription} = EventDescription[]
comment::Vector{Comment} = Comment[]
focal_mechanism::Vector{FocalMechanism} = FocalMechanism[]
amplitude::Vector{Amplitude} = Amplitude[]
magnitude::Vector{Magnitude} = Magnitude[]
station_magnitude::Vector{StationMagnitude} = StationMagnitude[]
origin::Vector{Origin} = Origin[]
pick::Vector{Pick} = Pick[]
preferred_origin_id::M{ResourceReference} = missing
preferred_magnitude_id::M{ResourceReference} = missing
preferred_focal_mechanism_id::M{ResourceReference} = missing
type::M{EventType} = missing
type_certainty::M{EventTypeCertainty} = missing
creation_info::M{CreationInfo} = missing
public_id::ResourceReference = random_reference()
end
"""
EventParameters(; comment, event, description, creation_info, public_id)
Root type of QuakeML. `EventParameters` objects contain a set of events
and a QuakeML XML file can contain only one `EventParameters` object.
In the bulletin-type (non real-time) model, this type serves as a
container for `Event` objects. In the real-time version, it can hold
objects of type `Event`, `Origin`, `Magnitude`, `StationMagnitude`,
`FocalMechanism`, `Reading`, `Amplitude`, and `Pick`.
# List of fields
- `event :: Vector{Event}`: Set of [`Event`](@ref QuakeML.Event)s making up
a catalog or collection of events.
- `description :: String`: Description string that can be assigned to the earthquake
catalog, or collection of events.
- `comment :: Vector{Comment}`: Additional comments.
- `creation_info :: CreationInfo`: [`CreationInfo`](@ref QuakeML.CreationInfo) for the earthquake catalog.
- `public_id :: ResourceReference`: Resource identifier of `EventParameters`.
(**Required field.**)
!!! note
At present, QuakeML.jl only supports the non-real-time version of QuakeML.
"""
@with_kw mutable struct EventParameters
comment::Vector{Comment} = Comment[]
event::Vector{Event} = Event[]
description::M{String} = missing
creation_info::M{CreationInfo} = missing
public_id::ResourceReference = random_reference()
end
"""
is_attribute_field(T, field) -> ::Bool
Return `true` if `field` is an attribute of the type `T`, and
`false` otherwise. Other fields are assumed to be elements.
"""
is_attribute_field(::Type, field) = field === :public_id
is_attribute_field(::Type{Comment}, field) = field === :id
is_attribute_field(::Type{NodalPlanes}, field) = field === :preferred_plane
is_attribute_field(::Type{WaveformStreamID}, field) =
any(x -> x === field, attribute_fields(WaveformStreamID))
"""
has_attributes(T) -> ::Bool
Return `true` if the type `T` has fields which are contained
in QuakeML documents as attributes rather than elements.
"""
has_attributes(::Union{Type{Comment}, Type{NodalPlanes}, Type{WaveformStreamID}}) = true
has_attributes(T::Type) = hasfield(T, :public_id)
"""
attribute_fields(T::Type) -> (:a, :b, ...)
Return a tuple of `Symbol`s giving the names of the fields of
type `T` which are contained in QuakeML documents as attributes
rather than elements.
"""
attribute_fields(T::Type) = hasfield(T, :public_id) ? (:public_id,) : ()
attribute_fields(::Type{Comment}) = (:id,)
attribute_fields(::Type{NodalPlanes}) = (:preferred_plane,)
attribute_fields(::Type{WaveformStreamID}) = (:network_code, :station_code,
:location_code, :channel_code)
# FIXME: Do this by reflection or some other non-manual means
"List of types which are mutable structs"
const MUTABLE_STRUCTS = (
RealQuantity, IntegerQuantity, TimeQuantity, CreationInfo,
EventDescription, Phase, Comment, Axis, PrincipleAxes, DataUsed,
CompositeTime, Tensor, OriginQuality, NodalPlane, TimeWindow,
WaveformStreamID, SourceTimeFunction, NodalPlanes,
ConfidenceEllipsoid, MomentTensor, FocalMechanism, Amplitude,
StationMagnitudeContribution, Magnitude,
StationMagnitude, OriginUncertainty, Arrival, Origin, Pick, Event,
EventParameters
)
# Define equality and hashing for sorting/comparison purposes
for T in MUTABLE_STRUCTS
fields = fieldnames(T)
Tsym = nameof(T)
@eval Base.:(==)(a::$Tsym, b::$Tsym) = a === b ? true : local_equals(a, b)
@eval function Base.hash(x::$Tsym, h::UInt)
$([:(h = hash(x.$f, h)) for f in fields]...)
h
end
end
"Types which should be compared using Base.=="
const COMPARABLE_TYPES = Union{Int, Float64, String, DateTime, Bool}
"""Local function to compare all types by each of their fields, apart from the types from
Base we use."""
local_equals(a::COMPARABLE_TYPES, b::COMPARABLE_TYPES) = a == b
local_equals(::Missing, ::Missing) = true
local_equals(::Missing, ::COMPARABLE_TYPES) = false
local_equals(a::COMPARABLE_TYPES, b::Missing) = local_equals(b, a)
function local_equals(a::T1, b::T2) where {T1,T2}
T1 == T2 ? all(local_equals(getfield(a, f), getfield(b, f)) for f in fieldnames(T1)) : false
end
local_equals(a::AbstractArray, b::AbstractArray) =
eltype(a) == eltype(b) && size(a) == size(b) &&
all(local_equals(aa, bb) for (aa, bb) in zip(a,b))
| QuakeML | https://github.com/anowacki/QuakeML.jl.git |
|
[
"MIT"
] | 0.1.2 | 607fd77863fd04cdd6010a33236006949b6cfd69 | code | 1553 | module Types
import ..QuakeML
"All types exported by this module"
const EXPORTED_TYPES = (
:RealQuantity,
:IntegerQuantity,
:ResourceReference,
:TimeQuantity,
:CreationInfo,
:EventDescription,
:Phase,
:Comment,
:Axis,
:PrincipleAxes,
:DataUsed,
:CompositeTime,
:Tensor,
:OriginQuality,
:NodalPlane,
:TimeWindow,
:WaveformStreamID,
:SourceTimeFunction,
:NodalPlanes,
:ConfidenceEllipsoid,
:MomentTensor,
:FocalMechanism,
:Amplitude,
:StationMagnitudeContribution,
:Magnitude,
:StationMagnitude,
:OriginUncertainty,
:Arrival,
:Origin,
:Pick,
:Event,
:EventParameters)
for type in EXPORTED_TYPES
@eval begin
const $type = QuakeML.$type
export $type
end
end
# Document the module
let exported_types_list = join(string.("- `", sort([s for s in String.(EXPORTED_TYPES)]), "`"), "\n")
@doc """
The `Types` module exports all the public-facing types used by
QuakeML.
By doing
```julia
julia> using QuakeML.Types
```
you may more succinctly write code.
!!! note
QuakeML's types share names with other packages, such as
[Seis.jl](https://github.com/anowacki/Seis.jl)'s `Event` and `Pick`,
and [SeisTau.jl](https://github.com/anowacki/SeisTau.jl)'s
`Phase`, amongst others. This is because QuakeML's names follow
those in the QuakeML specification.
# List of exported types
$(exported_types_list)
""" Types
end
end
| QuakeML | https://github.com/anowacki/QuakeML.jl.git |
|
[
"MIT"
] | 0.1.2 | 607fd77863fd04cdd6010a33236006949b6cfd69 | code | 5337 | # Utility functions
"""
@enumerated_struct(name, T, values)
Create a `struct` called `name` with a single field, `:value` which
must match one of the items in `values`.
Also create a keyword constructor with one required keyword argument,
`value`.
# Example
The following code
```
@enumerated_struct(Example, Float64, (1.0, 2.0))
```
is equivalent to
```
struct Example
value::Float64
function Example(value)
if value ∉ (1.0, 2.0)
throw(ArgumentError("value must be one of `(1.0, 2.0)`"))
end
new(value)
end
Example(; value) = Example(value)
end
```
"""
macro enumerated_struct(name, T, values)
values.head === :tuple || throw(ArgumentError("final argument must be a tuple of values"))
values_string = string(values)
# A nice set of Markdown-formatted values.
values_docstring = join((string("`\"", val, "\"`") for val in values.args), ", ", " or ")
# For the example in the docstring
first_value = string(first(values.args))
@assert length(values.args) > 1
second_value = string(values.args[2])
T = esc(T)
name = esc(name)
quote
"""
$($name)(value)
$($name)(; value)
Enumerated struct containing a single string which must be one
of the following: $($values_docstring).
Note that when a field of another type is a `$($name)`, it
is not necessary to assign a field of type `$($name)` to the
field. Instead, one can simply use a `String`, from which a
`$($name)` will be automatically constructed.
For this reason, $($name) is not exported even when bringing
QuakeML's types into scope by doing `using QuakeML.Types`.
# Example
```
julia> using QuakeML
julia> mutable struct ExampleStruct
field::$($name)
end
julia> es = ExampleStruct("$($first_value)")
ExampleStruct($($name)("$($first_value)"))
julia> es.field = "$($second_value)"
"$($second_value)"
```
"""
struct $name
value::$T
function $name(value)
if value ∉ $values
$(esc(throw))($(esc(ArgumentError))("value must be one of $($values_string)"))
end
new(value)
end
$name(; value) = $name(value)
end
end
end
"""
check_string_length(name, value, maxlen) -> nothing
Throw an `ArgumentError` if `value` is longer than `maxlen` characters.
`name` is the name of the field to report in the error message.
"""
function check_string_length(name, value, maxlen)
value === missing && return nothing
length(value) > maxlen &&
throw(ArgumentError("field `$name` can be at most $maxlen characters long"))
nothing
end
"""
transform_name(s::AbstractString) -> s′::Symbol
Transform the name of an attribute or element of a QuakeML XML
document into a `Symbol` suitable for assignment into a `struct`.
# Example
```julia
julia> QuakeML.transform_name("triggeringOriginID")
:triggering_origin_id
```
"""
function transform_name(s)
s = string(s)
# CamelCase to Camel_Case
s = replace(s, r"([a-z])([A-Z])" => s"\1_\2")
# lowercase
s = lowercase(s)
# Special cases
s = replace(s, r"^begin$" => "begin_")
s = replace(s, r"^end$" => "end_")
Symbol(s)
end
"""
retransform_name(s::Symbol) -> s′::String
Transform the field name of a struct into an element or attribute name
as a string, suitable for inclusion into a QuakeML XML document.
"""
function retransform_name(s)
s = string(s)
# Special cases
s = replace(s, r"^begin_$" => "begin")
s = replace(s, r"^end_$" => "end")
s = replace(s, "_id" => "ID")
# 'x_y' to 'x_Y'
s = replace(s, r"(_.)" => uppercase)
# 'x_Y' to 'xY'
s = replace(s, "_" => "")
s
end
"""
xml_unescape(s) -> s′
Replace escaped occurrences of the five XML character entity
references `&`, `<`, `>`, `"` and `'` with their unescaped equivalents.
Reference:
https://en.wikipedia.org/wiki/Character_encodings_in_HTML#XML_character_references
"""
xml_unescape(s) =
# Workaround for JuliaLang/julia#28967
reduce(replace,
("&" => "&",
"<" => "<",
">" => ">",
""" => "\"",
"'" => "'"),
init=s)
"""
xml_escape(s) -> s′
Replace unescaped occurrences of the five XML characters
`&`, `<`, `>`, `"` and `'` with their escaped equivalents.
Reference:
https://en.wikipedia.org/wiki/Character_encodings_in_HTML#XML_character_references
"""
xml_escape(s) =
# Workaround for JuliaLang/julia#28967
reduce(replace,
("&" => "&",
"<" => "<",
">" => ">",
"\"" => """,
"'" => "'"),
init=s)
"""
random_reference() -> ::ResourceReference
Create a new, random [`ResourceReference`](@ref QuakeML.ResourceReference).
"""
random_reference(prefix="smi") =
ResourceReference(prefix * string(":local/", UUIDs.uuid4()))
| QuakeML | https://github.com/anowacki/QuakeML.jl.git |
|
[
"MIT"
] | 0.1.2 | 607fd77863fd04cdd6010a33236006949b6cfd69 | code | 6783 | using Test, QuakeML
using Dates: DateTime
@testset "Accessors" begin
@testset "has_" begin
let event = QuakeML.Event(public_id="smi:QuakeML.jl/event/a")
@test !has_focal_mechanism(event)
@test !has_magnitude(event)
@test !has_origin(event)
push!(event.focal_mechanism,
QuakeML.FocalMechanism(public_id="smi:QuakeML.jl/focal_mechanism/a"))
push!(event.magnitude,
QuakeML.Magnitude(public_id="smi:QuakeML.jl/magnitude/a", mag=1))
push!(event.origin, QuakeML.Origin(public_id="smi:QuakeML.jl/origin/a",
latitude=1, longitude=1, time=Dates.now()))
@test has_focal_mechanism(event)
@test has_magnitude(event)
@test has_origin(event)
end
end
@testset "preferred_origin" begin
let qml = QuakeML.read(joinpath(@__DIR__, "data", "nepal_mw7.2.qml"))
@test preferred_origin(qml.event[1]).public_id ==
qml.event[1].preferred_origin_id
@test preferred_origin(qml.event[1]) == qml.event[1].origin[2]
empty!(qml.event[1].origin)
@test_throws ArgumentError preferred_origin(qml.event[1])
end
origin1 = QuakeML.Origin(time=Dates.now(), longitude=0, latitude=0,
public_id="smi:QuakeML.jl/origin/a")
origin2 = QuakeML.Origin(time=Dates.now(), longitude=1, latitude=1,
public_id="smi:QuakeML.jl/origin/b")
origin3 = QuakeML.Origin(time=Dates.now(), longitude=2, latitude=2,
public_id="smi:QuakeML.jl/origin/c")
event = QuakeML.Event(public_id="smi:QuakeML.jl/event/a",
preferred_origin_id="smi:QuakeML.jl/origin/b")
# No origins
@test_throws ArgumentError preferred_origin(event)
# Returns first regardless
push!(event.origin, origin1) # Add one origin with wrong ID
@test preferred_origin(event) == origin1
@test_nowarn preferred_origin(event, verbose=true)
# Finds the preferred one
push!(event.origin, origin2) # Add the right origin
@test preferred_origin(event) == origin2
@test preferred_origin(event).longitude.value == 1
# Returns the first if no match
empty!(event.origin)
append!(event.origin, [origin1, origin3]) # Two wrong origins
@test preferred_origin(event) == origin1
@test_nowarn preferred_origin(event)
@test_logs((:warn, "no origin with preferred id; returning the first origin"),
preferred_origin(event, verbose=true))
# Returns the first if no preferred origin at all
event = QuakeML.Event(public_id="smi:QuakeML.jl/event/a",
origin=[origin1, origin2, origin3])
@test preferred_origin(event) == origin1
end
@testset "preferred_origins" begin
let qml = QuakeML.read(joinpath(@__DIR__, "data", "nepal_mw7.2.qml"))
@test preferred_origins(qml) == [preferred_origin(qml.event[1])]
empty!(qml.event[1].origin)
@test_throws ArgumentError preferred_origins(qml)
end
end
@testset "preferred_magnitude" begin
mag1 = QuakeML.Magnitude(mag=1, public_id="smi:QuakeML.jl/magnitude/a")
mag2 = QuakeML.Magnitude(mag=2, public_id="smi:QuakeML.jl/magnitude/b")
mag3 = QuakeML.Magnitude(mag=3, public_id="smi:QuakeML.jl/magnitude/c")
event = QuakeML.Event(public_id="smi:QuakeML.jl/event/a",
preferred_magnitude_id="smi:QuakeML.jl/magnitude/b")
# No magnitudes
@test_throws ArgumentError preferred_magnitude(event)
# Returns first regardless
push!(event.magnitude, mag1)
@test preferred_magnitude(event) == mag1
@test_nowarn preferred_magnitude(event, verbose=true)
# Finds the preferred one
push!(event.magnitude, mag2)
@test preferred_magnitude(event) == mag2
@test preferred_magnitude(event).mag.value == 2
# Return the first if no match
empty!(event.magnitude)
append!(event.magnitude, [mag1, mag3])
@test preferred_magnitude(event) == mag1
@test_nowarn preferred_magnitude(event)
@test_logs((:warn, "no magnitude with preferred id; returning the first magnitude"),
preferred_magnitude(event, verbose=true))
# Returns the first if no preferred magnitude at all
event = QuakeML.Event(public_id="smi:QuakeML.jl/event/a",
magnitude=[mag1, mag2, mag3])
@test preferred_magnitude(event) == mag1
end
@testset "preferred_magnitudes" begin
let qml = QuakeML.read(joinpath(@__DIR__, "data", "nepal_mw7.2.qml"))
@test preferred_magnitudes(qml) == [preferred_magnitude(qml.event[1])]
empty!(qml.event[1].magnitude)
@test_throws ArgumentError preferred_magnitudes(qml)
end
end
@testset "preferred_focal_mechanism" begin
fm1 = QuakeML.FocalMechanism(public_id="smi:QuakeML.jl/focmech/a")
fm2 = QuakeML.FocalMechanism(public_id="smi:QuakeML.jl/focmech/b")
fm3 = QuakeML.FocalMechanism(public_id="smi:QuakeML.jl/focmech/c")
event = QuakeML.Event(public_id="smi:QuakeML.jl/event/a",
preferred_focal_mechanism_id="smi:QuakeML.jl/focmech/b")
# No focal mechanisms
@test_throws ArgumentError preferred_focal_mechanism(event)
# Returns first regardless
push!(event.focal_mechanism, fm1)
@test preferred_focal_mechanism(event) == fm1
@test_nowarn preferred_focal_mechanism(event, verbose=true)
# Finds the preferred one
push!(event.focal_mechanism, fm2)
@test preferred_focal_mechanism(event) == fm2
# Return the first if no match
empty!(event.focal_mechanism)
append!(event.focal_mechanism, [fm1, fm3])
@test preferred_focal_mechanism(event) == fm1
@test_nowarn preferred_focal_mechanism(event)
@test_logs((:warn, "no focal mechanism with preferred id; returning the first focal mechanism"),
preferred_focal_mechanism(event, verbose=true))
# Returns the first if no preferred focal mechanism at all
event = QuakeML.Event(public_id="smi:QuakeML.jl/event/a",
focal_mechanism=[fm1, fm2, fm3])
@test preferred_focal_mechanism(event) == fm1
end
@testset "preferred_focal_mechanisms" begin
let qml = QuakeML.read(joinpath(@__DIR__, "data", "nepal_mw7.2.qml"))
@test preferred_focal_mechanisms(qml) == [preferred_focal_mechanism(qml.event[1])]
empty!(qml.event[1].focal_mechanism)
@test_throws ArgumentError preferred_focal_mechanisms(qml)
end
end
end
| QuakeML | https://github.com/anowacki/QuakeML.jl.git |
|
[
"MIT"
] | 0.1.2 | 607fd77863fd04cdd6010a33236006949b6cfd69 | code | 815 | using Test
using QuakeML
@testset "Comparison" begin
# Two identical EventParameters
datafile = joinpath(@__DIR__, "data", "2004-12-26_mag5+.qml")
qml = QuakeML.read(datafile)
qml′ = QuakeML.read(datafile)
# A different EventParameters: one field is missing in one and set in another
qml″ = deepcopy(qml)
qml″.event[end].magnitude[1].mag.uncertainty = 0.1
@testset "==" begin
@test qml == qml′
@test qml != qml″
end
@testset "hash" begin
@test hash(qml) == hash(qml′)
@test hash(qml) != hash(qml″)
end
# These should follow from the above
@testset "Others" begin
@test unique([qml, qml′]) == [qml]
@test unique([qml, qml″]) == [qml, qml″]
@test Dict(qml=>1) == Dict(qml′=>1) != Dict(qml″=>1)
end
end | QuakeML | https://github.com/anowacki/QuakeML.jl.git |
|
[
"MIT"
] | 0.1.2 | 607fd77863fd04cdd6010a33236006949b6cfd69 | code | 1363 | using Test, QuakeML
using Dates: DateTime
@testset "Construction" begin
@testset "Convenience" begin
@test QuakeML.RealQuantity(1) == QuakeML.RealQuantity(value=1)
@test QuakeML.IntegerQuantity(2) == QuakeML.IntegerQuantity(value=2)
@test convert(QuakeML.IntegerQuantity, 3) == QuakeML.IntegerQuantity(value=3)
@test QuakeML.Origin(time=DateTime(2000), longitude=1, latitude=2,
public_id="smi:QuakeML.jl/origin/a").time.value == DateTime(2000)
end
@testset "Schema version" begin
end
@testset "ResourceReference" begin
# Not a proper URI
@test_throws ArgumentError QuakeML.ResourceReference(value="bad URI")
# String too long
@test_throws ArgumentError QuakeML.ResourceReference(value="smi:local/" * "a"^246)
@test QuakeML.ResourceReference("quakeml:QuakeML.jl/refA") isa QuakeML.ResourceReference
@test QuakeML.ResourceReference("smi:QuakeML.jl/refB") isa QuakeML.ResourceReference
@test QuakeML.ResourceReference("smi:local/a") isa QuakeML.ResourceReference
end
@testset "WhitespaceOrEmptyString" begin
@test_throws ArgumentError QuakeML.WhitespaceOrEmptyString("x")
@test QuakeML.WhitespaceOrEmptyString(" \t \n ").value == " \t \n "
@test isempty(QuakeML.WhitespaceOrEmptyString("").value)
end
end | QuakeML | https://github.com/anowacki/QuakeML.jl.git |
|
[
"MIT"
] | 0.1.2 | 607fd77863fd04cdd6010a33236006949b6cfd69 | code | 2577 | using QuakeML, Test
using Dates: DateTime
@testset "Field access" begin
@testset "CreationInfo" begin
let ci = QuakeML.CreationInfo()
@test ci.agency_id === missing
ci.agency_id = "a"^64
@test ci.agency_id == "a"^64
@test_throws ArgumentError ci.agency_id = "a"^65
@test_throws ArgumentError ci.version = "a"^65
@test_throws ArgumentError ci.author = "a"^129
end
end
@testset "WaveformStreamID" begin
let ws = QuakeML.WaveformStreamID(network_code="AN", station_code="QML")
@test ws.network_code == "AN"
@test ws.station_code == "QML"
@test ws.uri === missing
@test_throws ArgumentError ws.uri = "not a URI"
ws.uri = "smi:local/uri"
@test ws.uri == QuakeML.ResourceReference("smi:local/uri")
@test_throws ArgumentError ws.network_code = "123456789"
@test_throws ArgumentError ws.station_code = "123456789"
@test_throws ArgumentError ws.location_code = "123456789"
@test_throws ArgumentError ws.channel_code = "123456789"
end
end
@testset "Amplitude" begin
let a = QuakeML.Amplitude(generic_amplitude=1)
a.snr = 1
@test a.snr === 1.0
a.snr = 1.f0
@test a.snr === 1.0
@test_throws ArgumentError a.type = "a"^33
@test_throws ArgumentError a.magnitude_hint = "a"^33
end
end
@testset "Magnitude" begin
let a = QuakeML.Magnitude(mag=1)
a.mag == QuakeML.RealQuantity(value=1.0)
@test_throws ArgumentError a.type = "a"^33
end
end
@testset "StationMagnitude" begin
let a = QuakeML.StationMagnitude(mag=1)
@test a.mag == QuakeML.RealQuantity(value=1)
@test_throws ArgumentError a.type = "a"^33
end
end
@testset "Origin" begin
let a = QuakeML.Origin(time=DateTime(2000), longitude=0, latitude=1)
@test a.time == QuakeML.TimeQuantity(value=DateTime(2000))
@test a.longitude == QuakeML.RealQuantity(value=0.0)
@test a.latitude == QuakeML.RealQuantity(value=1.0)
@test_throws ArgumentError a.region = "a"^129
end
end
@testset "OriginQuality" begin
let oq = QuakeML.OriginQuality()
@test_throws ArgumentError oq.ground_truth_level = "a"^33
oq.ground_truth_level = "a"^32
@test oq.ground_truth_level == "a"^32
end
end
end
| QuakeML | https://github.com/anowacki/QuakeML.jl.git |
|
[
"MIT"
] | 0.1.2 | 607fd77863fd04cdd6010a33236006949b6cfd69 | code | 14090 | using Test, QuakeML
using Dates: DateTime
import EzXML
datafile1 = joinpath(@__DIR__, "data", "nepal_mw7.2.qml")
datafile2 = joinpath(@__DIR__, "data", "2004-12-26_mag6+.qml")
datafile3 = joinpath(@__DIR__, "data", "2004-12-26_mag5+.qml")
datafiles = (datafile1, datafile2, datafile3)
@testset "IO" begin
@testset "Read string" begin
for file in datafiles
@test QuakeML.read(file) == QuakeML.readstring(String(read(file)))
end
end
@testset "Read" begin
let badstring = """
<?xml version="1.0" encoding="UTF8"?>
<SomeWeirdThing xmlns="http://quakeml.org/xmlns/bed/1.2">
</SomeWeirdThing>
"""
@test_throws ArgumentError QuakeML.readstring(badstring)
end
@test_throws ArgumentError QuakeML.readstring(" \nThis is not XML.")
let qml = QuakeML.read(datafile1)
@test qml isa QuakeML.EventParameters
@test isempty(qml.comment)
let ci = qml.creation_info
test_all_missing(ci, :agency_id, :agency_uri, :author, :author_uri)
@test ci.creation_time == DateTime("2020-03-11T11:41:23.271")
@test ci.version == "V10"
end
@test qml.description === missing
@test qml.public_id.value == "smi:service.iris.edu/fdsnws/event/1/query"
@test length(qml.event) == 1
let e = qml.event[1]
@test isempty(e.amplitude)
@test isempty(e.comment)
@test e.creation_info === missing
@test length(e.focal_mechanism) == 1
let fm = e.focal_mechanism[1]
test_all_missing(fm, :azimuthal_gap, :evaluation_status,
:evaluation_mode, :method_id,
:misfit, :principle_axes, :station_distribution_ratio,
:station_polarity_count)
@test isempty(fm.comment)
ci = fm.creation_info
test_all_missing(ci, :agency_uri, :author, :author_uri,
:creation_time)
@test ci.agency_id == "GCMT"
@test ci.version == "V10"
@test length(fm.moment_tensor) == 1
let mt = fm.moment_tensor[1]
test_all_missing(mt, :category, :clvd, :creation_info,
:double_couple, :filter_id, :greens_function_id,
:inversion_type, :iso, :method_id, :variance,
:variance_reduction)
@test length(mt.data_used) == 3
@test mt.data_used[1] == QuakeML.DataUsed(
QuakeML.DataUsedWaveType("body waves"), 169, 459, 50.0,
missing)
@test mt.data_used[2] == QuakeML.DataUsed(
QuakeML.DataUsedWaveType("surface waves"), 173, 459, 50.0,
missing)
@test mt.data_used[3] == QuakeML.DataUsed(
QuakeML.DataUsedWaveType("mantle waves"), 168, 404, 150.0,
missing)
@test mt.derived_origin_id.value ==
"smi:www.iris.edu/spudservice/momenttensor/gcmtid/C201505120705A#cmtorigin"
@test mt.moment_magnitude_id.value ==
"smi:www.iris.washington.edu/spudservice/momenttensor/gcmtid/C201505120705A/quakeml#magnitude"
@test mt.public_id.value ==
"smi:www.iris.washington.edu/spudservice/momenttensor/gcmtid/C201505120705A/quakeml#momenttensor"
@test mt.scalar_moment == QuakeML.RealQuantity(; value=88440000000000000000.0)
@test mt.source_time_function.type.value == "triangle"
@test mt.source_time_function.duration == 20.2
test_all_missing(mt.source_time_function, :rise_time, :decay_time)
let t = mt.tensor
@test t.mrr == QuakeML.RealQuantity(;
value=27000000000000000000.0,
uncertainty=90000000000000000.0)
@test t.mtt == QuakeML.RealQuantity(;
value=-26200000000000000000.0,
uncertainty=80000000000000000.0)
@test t.mpp == QuakeML.RealQuantity(;
value=-830000000000000000.0,
uncertainty=80000000000000000.0)
@test t.mrt == QuakeML.RealQuantity(;
value=82500000000000000000.0,
uncertainty=740000000000000000.0)
@test t.mrp == QuakeML.RealQuantity(;
value=-12800000000000000000.0,
uncertainty=800000000000000000.0)
@test t.mtp == QuakeML.RealQuantity(;
value=12200000000000000000.0,
uncertainty=70000000000000000.0)
end # t
@test mt.public_id.value == "smi:www.iris.washington.edu/spudservice/momenttensor/gcmtid/C201505120705A/quakeml#momenttensor"
end # mt
@test fm.triggering_origin_id.value == "smi:www.iris.edu/spudservice/momenttensor/gcmtid/C201505120705A#reforigin"
@test isempty(fm.waveform_id)
end # fm
@test length(e.magnitude) == 1
let mag = e.magnitude[1]
test_all_missing(mag, :azimuthal_gap, :creation_info,
:evaluation_mode, :evaluation_status, :method_id,
:origin_id, :station_count)
test_all_empty(mag, :comment, :station_magnitude_contribution)
@test mag.mag == QuakeML.RealQuantity(value=7.2)
@test mag.public_id.value == "smi:www.iris.washington.edu/spudservice/momenttensor/gcmtid/C201505120705A/quakeml#magnitude"
@test mag.type == "Mwc"
end # mag
@test length(e.origin) == 2
let o = e.origin[1]
test_all_missing(o, :creation_info, :depth_type,
:earth_model_id, :epicenter_fixed, :evaluation_mode,
:evaluation_status, :method_id, :quality,
:reference_system_id, :region, :time_fixed, :type)
test_all_empty(o, :comment)
@test o.depth == QuakeML.RealQuantity(value=15000.0)
@test o.latitude == QuakeML.RealQuantity(value=27.81)
@test o.longitude == QuakeML.RealQuantity(value=86.07)
@test o.public_id.value == "smi:www.iris.edu/spudservice/momenttensor/gcmtid/C201505120705A#reforigin"
@test o.time == QuakeML.TimeQuantity(value=DateTime(2015, 05, 12, 07, 05, 19, 700))
end # o
let o = e.origin[2]
test_all_missing(o, :creation_info, :depth_type,
:earth_model_id, :evaluation_mode,
:evaluation_status, :method_id, :quality,
:reference_system_id, :region, :type)
test_all_empty(o, :comment)
@test o.depth == QuakeML.RealQuantity(value=12000.0)
@test o.epicenter_fixed == false
@test o.latitude == QuakeML.RealQuantity(value=27.67)
@test o.longitude == QuakeML.RealQuantity(value=86.08)
@test o.public_id.value == "smi:www.iris.edu/spudservice/momenttensor/gcmtid/C201505120705A#cmtorigin"
@test o.time == QuakeML.TimeQuantity(value=DateTime(2015, 05, 12, 07, 05, 27, 500))
@test o.time_fixed == false
end # o
@test isempty(e.pick)
@test e.preferred_focal_mechanism_id.value ==
"smi:www.iris.washington.edu/spudservice/momenttensor/gcmtid/C201505120705A/quakeml#focalmechanism"
@test e.preferred_origin_id.value ==
"smi:www.iris.edu/spudservice/momenttensor/gcmtid/C201505120705A#cmtorigin"
@test e.public_id.value ==
"smi:service.iris.edu/fdsnws/event/1/query?eventid=5113514"
@test isempty(e.station_magnitude)
@test e.type.value == "earthquake"
@test e.type_certainty === missing
end # e
end
# File with quite a few events
let qml = QuakeML.read(datafile2)
@test qml.creation_info.agency_id == "ISC"
@test qml.creation_info.creation_time == DateTime(2020, 03, 11, 11, 45, 58)
@test qml.description == "ISC Bulletin"
@test qml.public_id.value == "smi:ISC/bulletin"
@test length(qml.event) == 23
@test qml.event[1].description[1].text == "Off west coast of northern Sumatera"
@test qml.event[1].description[1].type.value == "Flinn-Engdahl region"
@test qml.event[1].origin[1].time.value == DateTime(2004, 12, 26, 00, 58, 53, 080)
@test qml.event[1].origin[1].time.uncertainty == 0.26
@test qml.event[1].origin[1].latitude.value == 3.3148
@test qml.event[1].origin[1].longitude.value == 95.9829
@test qml.event[1].origin[1].depth.value == 26451.8
q = qml.event[1].origin[1].quality
@test q.used_phase_count == 1671
@test q.associated_station_count == 1653
@test q.standard_error == 2.3141
@test q.azimuthal_gap == 15.980
@test q.minimum_distance == 2.273
@test q.maximum_distance == 173.412
@test length(qml.event[1].origin[1].origin_uncertainty) == 1
ou = qml.event[1].origin[1].origin_uncertainty[1]
@test ou.preferred_description.value == "uncertainty ellipse"
@test ou.min_horizontal_uncertainty == 3652.95
@test ou.max_horizontal_uncertainty == 4573.66
@test ou.azimuth_max_horizontal_uncertainty == 49.5
@test length(qml.event[1].magnitude) == 2
mag = qml.event[1].magnitude[1]
@test mag.mag.value == 6.96
@test mag.type == "mb"
@test mag.station_count == 275
@test mag.origin_id.value == "smi:ISC/origid=7900012"
end
end
@testset "Writing string" begin
let events = EventParameters(public_id=
QuakeML.ResourceReference("smi:QuakeML.jl/events"))
evt = QuakeML.Event(
public_id=QuakeML.ResourceReference("smi:QuakeML.jl/event/1"))
evt = QuakeML.Event(evt, type=QuakeML.EventType("earthquake"))
push!(events.event, evt)
xml = QuakeML.quakeml(events)
@test string(xml) == """
<?xml version="1.0" encoding="UTF-8"?>
<quakeml xmlns="http://quakeml.org/xmlns/quakeml/1.2"><eventParameters publicID="smi:QuakeML.jl/events"><event publicID="smi:QuakeML.jl/event/1"><type>earthquake</type></event></eventParameters></quakeml>
"""
io1 = IOBuffer()
io2 = IOBuffer()
# Write converted XML
print(io1, xml)
# Write EventParameters
write(io2, events)
seekstart(io1)
seekstart(io2)
str1 = String(read(io1))
@test str1 == """
<?xml version="1.0" encoding="UTF-8"?>
<quakeml xmlns="http://quakeml.org/xmlns/quakeml/1.2"><eventParameters publicID="smi:QuakeML.jl/events"><event publicID="smi:QuakeML.jl/event/1"><type>earthquake</type></event></eventParameters></quakeml>
"""
str2 = String(read(io2))
@test str2 == """
<?xml version="1.0" encoding="UTF-8"?>
<quakeml xmlns="http://quakeml.org/xmlns/quakeml/1.2">
<eventParameters publicID="smi:QuakeML.jl/events">
<event publicID="smi:QuakeML.jl/event/1">
<type>earthquake</type>
</event>
</eventParameters>
</quakeml>
"""
seekstart(io1)
seekstart(io2)
qml1 = QuakeML.read(io1)
qml2 = QuakeML.read(io2)
@test qml1 == events
@test qml2 == events
end
# Round trip
for file in datafiles
events = QuakeML.read(file)
xml = QuakeML.quakeml(events)
io = IOBuffer()
print(io, xml)
seekstart(io)
events′ = QuakeML.read(io)
@test events == events′
io2 = IOBuffer()
write(io2, events)
seekstart(io2)
events″ = QuakeML.read(io2)
@test events == events″
end
end
@testset "Writing" begin
for file in datafiles
let events = QuakeML.read(file), xml = QuakeML.quakeml(events)
mktemp() do tempfile, f
print(f, xml)
seekstart(f)
events′ = QuakeML.read(f)
@test events == events′
end
end
end
# Writing version
let events = EventParameters(public_id="quakeml:QuakeML.jl/events/0")
qml = quakeml(events, version="1.1")
@test split(qml.root["xmlns"], '/')[end] == "1.1"
io = IOBuffer()
write(io, events, version="1.1")
seekstart(io)
xml = EzXML.readxml(io)
@test split(EzXML.namespace(xml.root), '/')[end] == "1.1"
end
end
end
| QuakeML | https://github.com/anowacki/QuakeML.jl.git |
|
[
"MIT"
] | 0.1.2 | 607fd77863fd04cdd6010a33236006949b6cfd69 | code | 2954 | using QuakeML, Test
import Dates
@testset "Parsing" begin
@testset "Local parsing" begin
@test QuakeML.local_parse(String, "xyzx̂") == "xyzx̂"
@test QuakeML.local_parse(String, SubString("φabc")) == "φabc"
@test QuakeML.local_parse(SubString, "ABC ♪") == "ABC ♪"
@test QuakeML.local_parse(Float64, "-1.0") == -1.0 == parse(Float64, "-1.0")
@test QuakeML.local_tryparse(Int, "12") == 12
@test QuakeML.local_tryparse(Int, "1.23") === nothing
@test QuakeML.local_tryparse(String, "⊫") == "⊫"
end
@testset "Dates" begin
let
# Too much precision
@test QuakeML.readstring("""
<?xml version="1.0" encoding="UTF-8"?>
<quakeml xmlns="http://quakeml.org/xmlns/quakeml/1.0">
<eventParameters publicID="smi:TEST/test">
<creationInfo>
<agencyID>ISC</agencyID>
<creationTime>2020-03-11T11:45:58.1234567890</creationTime>
</creationInfo>
</eventParameters>
</quakeml>
""").creation_info.creation_time == Dates.DateTime(2020, 03, 11, 11, 45, 58, 123)
# Time zone ahead of UTC and too much precision
@test QuakeML.readstring("""
<?xml version="1.0" encoding="UTF-8"?>
<quakeml xmlns="http://quakeml.org/xmlns/quakeml/1.0">
<eventParameters publicID="smi:TEST/test">
<creationInfo>
<agencyID>ISC</agencyID>
<creationTime>2000-01-01T12:34:00.123456789-12:34</creationTime>
</creationInfo>
</eventParameters>
</quakeml>
""").creation_info.creation_time == Dates.DateTime(2000, 1, 1, 0, 0, 0, 123)
# UTC specified
@test QuakeML.readstring("""
<?xml version="1.0" encoding="UTF-8"?>
<quakeml xmlns="http://quakeml.org/xmlns/quakeml/1.0">
<eventParameters publicID="smi:TEST/test">
<creationInfo>
<agencyID>ISC</agencyID>
<creationTime>2020-03-11T11:45:58.1234567890Z</creationTime>
</creationInfo>
</eventParameters>
</quakeml>
""").creation_info.creation_time == Dates.DateTime(2020, 03, 11, 11, 45, 58, 123)
end
end
@testset "Version" begin
@test_logs (:warn,
"document is StationXML version 1.3.0; only v1.2 data will be read") QuakeML.readstring("""
<?xml version="1.0" encoding="UTF-8"?>
<quakeml xmlns="http://quakeml.org/xmlns/quakeml/1.3">
<eventParameters publicID="smi:TEST/test">
</eventParameters>
</quakeml>
""")
end
end | QuakeML | https://github.com/anowacki/QuakeML.jl.git |
|
[
"MIT"
] | 0.1.2 | 607fd77863fd04cdd6010a33236006949b6cfd69 | code | 666 | using Test
using QuakeML
"For each field in `fields`, test that x.field is `missing`"
function test_all_missing(x, fields...)
for f in fields
getfield(x, f) === missing || (@show f)
@test getfield(x, f) === missing
end
end
"For each field in `fields`, test that x.field is empty"
function test_all_empty(x, fields...)
for f in fields
@test isempty(getfield(x, f))
end
end
@testset "All tests" begin
include("util.jl")
include("construction.jl")
include("comparison.jl")
include("parsing.jl")
include("io.jl")
include("accessors.jl")
include("field_access.jl")
include("types_module.jl")
end
| QuakeML | https://github.com/anowacki/QuakeML.jl.git |
|
[
"MIT"
] | 0.1.2 | 607fd77863fd04cdd6010a33236006949b6cfd69 | code | 892 | using QuakeML.Types
using Test
@testset "Types" begin
for type in Types.EXPORTED_TYPES
@test isdefined(@__MODULE__, type)
end
for type in (
:OriginUncertaintyDescription,
:AmplitudeCategory,
:OriginDepthType,
:OriginType,
:MTInversionType,
:EvaluationMode,
:EvaluationStatus,
:PickOnset,
:EventType,
:DataUsedWaveType,
:AmplitudeUnit,
:EventDescriptionType,
:MomentTensorCategory,
:EventTypeCertainty,
:SourceTimeFunctionType,
:PickPolarity,
# Not an enumerated type, but unused in the module
:WhitespaceOrEmptyString
)
@test !isdefined(@__MODULE__, type)
end
events = EventParameters()
@test events isa EventParameters
end | QuakeML | https://github.com/anowacki/QuakeML.jl.git |
|
[
"MIT"
] | 0.1.2 | 607fd77863fd04cdd6010a33236006949b6cfd69 | code | 2868 | using QuakeML, Test
import UUIDs
@testset "Utils" begin
@testset "Macros" begin
@eval QuakeML.@enumerated_struct(ExampleStruct, Float32, (1.f0, 2.f0))
@test isdefined(Main, :ExampleStruct)
@test fieldnames(ExampleStruct) == (:value,)
@test fieldtype(ExampleStruct, :value) == Float32
@test ExampleStruct(1.f0) isa ExampleStruct
@test_throws ArgumentError ExampleStruct(3.f0)
end
@testset "String length" begin
@test QuakeML.check_string_length("A", "ABC", 3) === nothing
@test QuakeML.check_string_length("A", "ABC", 10) === nothing
@test_throws ArgumentError QuakeML.check_string_length("A", "ABC", 2)
end
@testset "XML escaping" begin
let s = "a&b<c>d"e'f", s′ = "a&b<c>d\"e'f"
@test QuakeML.xml_unescape(s) == s′
@test QuakeML.xml_escape(s′) == s
end
end
@testset "Name transform" begin
let f = QuakeML.transform_name
@test f("ModuleURI") == :module_uri
@test f("Email") == :email
@test f("SelectedNumberChannels") == :selected_number_channels
@test f("SomethingLikeID") == :something_like_id
end
let f = QuakeML.retransform_name
@test f(:public_id) == "publicID"
@test f(:moment_tensor) == "momentTensor"
@test f(:selected_number_channels) == "selectedNumberChannels"
@test f(:something_with_id_in_it) == "somethingWithIDInIt"
end
# Round trip for all names in all types
function test_round_trip(T::Union{QuakeML.ParsableTypes,Type{Missing}}, name)
@test name == QuakeML.transform_name(QuakeML.retransform_name(name))
end
test_round_trip(type::Type{Union{Missing,T}}, name) where T = test_round_trip(T, name)
test_round_trip(type::Type{<:AbstractArray{T}}, name) where T = test_round_trip(T, name)
function test_round_trip(T, name)
for nm in fieldnames(T)
type = fieldtype(T, nm)
test_round_trip(type, nm)
end
end
test_round_trip(QuakeML.EventParameters, :dummy_name)
end
@testset "Random reference URI" begin
@test QuakeML.random_reference() isa QuakeML.ResourceReference
@test startswith(QuakeML.random_reference().value, "smi:local/")
@test startswith(QuakeML.random_reference("quakeml").value, "quakeml:local/")
@test occursin(
r"^(quakeml|smi):local/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$",
QuakeML.random_reference().value)
ref = QuakeML.random_reference()
uuid_string = replace(replace(ref.value, r".*/"=>""), "-"=>"")
uuid = parse(UInt128, uuid_string, base=16)
@test UUIDs.UUID(uuid) isa UUIDs.UUID
end
end
| QuakeML | https://github.com/anowacki/QuakeML.jl.git |
|
[
"MIT"
] | 0.1.2 | 607fd77863fd04cdd6010a33236006949b6cfd69 | docs | 4923 | # QuakeML
## Build status
[![Build Status](https://github.com/anowacki/QuakeML.jl/workflows/CI/badge.svg)](https://travis-ci.org/anowacki/QuakeML.jl)
[![Coverage Status](https://coveralls.io/repos/github/anowacki/QuakeML.jl/badge.svg?branch=master)](https://coveralls.io/github/anowacki/QuakeML.jl?branch=master)
## Documentation
[![](https://img.shields.io/badge/docs-stable-blue.svg)](https://anowacki.github.io/QuakeML.jl/stable)
[![](https://img.shields.io/badge/docs-dev-blue.svg)](https://anowacki.github.io/QuakeML.jl/dev)
## What is QuakeML.jl?
QuakeML.jl is a Julia package to read and write information about
earthquakes and seismic events in the
[QuakeML format](https://quake.ethz.ch/quakeml).
## User-facing functions
- `QuakeML.read`: Read a QuakeML file. (This function is not exported.
and requires the module prefix `QuakeML`.)
- `QuakeML.readstring`: Read a QuakeML document from a string. (This
function is not exported.)
- `write`: Write a set of `EventParameters` as a QuakeML XML document.
- `preferred_focal_mechanism`: Get the preferred focal mechanism for an event
- `preferred_magnitude`: Get the preferred magnitude for an event
- `preferred_origin`: Get the preferred origin for an event
- `has_focal_mechanism`: Check to see if an event contains any
focal mechanisms
- `has_magnitude`: Check to see if an event contains any magnitude
- `has_origin`: Check to see if an event contains any origins
- `quakeml`: Create an XML document from a set of events which can
be written with `print(io, quakeml(qml))`
## Examples
### Reading
To read a QuakeML document on your computer (e.g., one of the ones
supplied with QuakeML.jl), do:
```julia
julia> using QuakeML
julia> qml_file = joinpath(dirname(dirname(pathof(QuakeML))), "test", "data", "nepal_mw7.2.qml");
julia> qml = QuakeML.read(qml_file)
```
To read a set of events from a string:
```julia
julia> QuakeML.readstring(String(read(qml_file)))
```
### Writing
To write a set of events to disk:
```julia
julia> write("file/on/disk.xml", qml)
```
For more control of output, convert your set of `EventParameters`
into an XML document, and write that:
```julia
julia> xml = quakeml(qml);
julia> println("/tmp/quakeml_file.qml", quakeml(qml))
```
Note that here `xml` is an
[`EzXML.XMLDocument`](https://bicycle1885.github.io/EzXML.jl/stable/manual/).
Or convert your XML document into a `String`:
```julia
julia> str = string(xml)
```
## Export of types
By default, QuakeML does not export the types it uses. The user should
usually create sets of `EventParameters`, for example, by calling the
type's qualified constructor:
```julia
julia> QuakeML.EventParameters()
QuakeML.EventParameters
comment: Array{QuakeML.Comment}((0,))
event: Array{QuakeML.Event}((0,))
description: Missing missing
creation_info: Missing missing
public_id: QuakeML.ResourceIdentifier
```
To allow less typing, one could create a module alias, such as:
```julia
julia> const QML = QuakeML
```
### `QuakeML.Types` module
As an **experimental** feature, the user may use the `QuakeML.Types`
module, which exports all the types which are needed to construct a
full set of `EventParameters`. For example, to specify a catalogue
with one event with an unspecified magnitude type with magnitude 1.0:
```julia
julia> using QuakeML.Types
julia> event = Event(magnitude=[Magnitude(mag=1.0)])
QuakeML.Event
description: Array{QuakeML.EventDescription}((0,))
comment: Array{QuakeML.Comment}((0,))
focal_mechanism: Array{QuakeML.FocalMechanism}((0,))
amplitude: Array{QuakeML.Amplitude}((0,))
magnitude: Array{QuakeML.Magnitude}((1,))
station_magnitude: Array{QuakeML.StationMagnitude}((0,))
origin: Array{QuakeML.Origin}((0,))
pick: Array{QuakeML.Pick}((0,))
preferred_origin_id: Missing missing
preferred_magnitude_id: Missing missing
preferred_focal_mechanism_id: Missing missing
type: Missing missing
type_certainty: Missing missing
creation_info: Missing missing
public_id: QuakeML.ResourceIdentifier
```
## Repo status
QuakeML.jl is beta software. All functionality included is tested
and works as advertised, but the public API of the package is
still to be decided and may break in v0.2, as per
[SemVer](https://semver.org/). So long as any packages you have
created declare their compatibility with QuakeML.jl correctly,
this will cause no problems.
### Activating debugging messages
To turn debugging messages on when running QuakeML, set the
environment variable `JULIA_DEBUG` to `QuakeML` or `"all"`, which can
even be done at run time in the repl like so:
```julia
julia> ENV["JULIA_DEBUG"] = QuakeML
```
Unsetting this value will turn these debugging messages off.
See the [manual section on environment variables and logging messages](https://docs.julialang.org/en/v1/stdlib/Logging/#Environment-variables-1) for more information on setting the debug level for QuakeML or other modules.
| QuakeML | https://github.com/anowacki/QuakeML.jl.git |
|
[
"MIT"
] | 0.1.2 | 607fd77863fd04cdd6010a33236006949b6cfd69 | docs | 2192 | # Function index
## Public types and functions
### IO
```@docs
QuakeML.read(filename::AbstractString)
QuakeML.readstring
write(io::IO, qml::EventParameters; kwargs...)
quakeml
```
### Accessors
```@docs
preferred_focal_mechanism
preferred_magnitude
preferred_origin
has_focal_mechanism
has_magnitude
has_origin
```
### Types
Where a constructor's arguments are given as `Constructor(; kwargs...)`,
this means that each listed field name can be given as a keyword
argument and a value passed to the constructor that way.
!!! note
By default, calling a constructor for a type which is required to
have a public ID (URI) by the QuakeML specification creates a
unique, random URI for that object. To specify your own ID for
an object, provide a `String` to the constructor's `public_id`
keyword argument; or you can later set the `public_id` field directly.
See [`ResourceReference`](@ref QuakeML.ResourceReference) for details
of the form that URIs must take.
```@docs
QuakeML.Amplitude
QuakeML.Arrival
QuakeML.Axis
QuakeML.Comment
QuakeML.CompositeTime
QuakeML.ConfidenceEllipsoid
QuakeML.CreationInfo
QuakeML.DataUsed
QuakeML.Event
QuakeML.EventDescription
QuakeML.EventParameters
QuakeML.FocalMechanism
QuakeML.IntegerQuantity
QuakeML.Magnitude
QuakeML.MomentTensor
QuakeML.NodalPlane
QuakeML.NodalPlanes
QuakeML.Origin
QuakeML.OriginQuality
QuakeML.OriginUncertainty
QuakeML.Phase
QuakeML.Pick
QuakeML.PrincipleAxes
QuakeML.RealQuantity
QuakeML.ResourceReference
QuakeML.SourceTimeFunction
QuakeML.StationMagnitude
QuakeML.StationMagnitudeContribution
QuakeML.Tensor
QuakeML.TimeQuantity
QuakeML.TimeWindow
QuakeML.WaveformStreamID
```
## Private types and functions
### ID generation
```@docs
QuakeML.random_reference
```
### Enumerated types
```@docs
QuakeML.AmplitudeCategory
QuakeML.AmplitudeUnit
QuakeML.DataUsedWaveType
QuakeML.EvaluationMode
QuakeML.EvaluationStatus
QuakeML.EventDescriptionType
QuakeML.EventType
QuakeML.EventTypeCertainty
QuakeML.MomentTensorCategory
QuakeML.MTInversionType
QuakeML.OriginDepthType
QuakeML.OriginType
QuakeML.OriginUncertaintyDescription
QuakeML.PickOnset
QuakeML.PickPolarity
QuakeML.SourceTimeFunctionType
```
| QuakeML | https://github.com/anowacki/QuakeML.jl.git |
|
[
"MIT"
] | 0.1.2 | 607fd77863fd04cdd6010a33236006949b6cfd69 | docs | 1384 | # QuakeML.jl
## What is [QuakeML.jl](https://github.com/anowacki/QuakeML.jl)?
A [Julia](http://julialang.org) package for reading and writing files
in the [QuakeML](https://quake.ethz.ch/quakeml) format, which describes
the properties of sets of seismic events, such as earthquakes and explosions.
This package is primarily meant to be used by other software to correctly
and reliably interact with QuakeML files. For example,
[Seis.jl](https://github.com/anowacki/Seis.jl) and its related libraries
use QuakeML.jl to parse QuakeML files, but do not expose QuakeML.jl
types or functions to the user. Though QuakeML.jl is intended to be used
as software by other software, it is still a goal that it should be easy
to use directly and well-documented and -tested.
### Note on naming
In this documentation, ‘QuakeML’ refers to the QuakeML standard, and
‘QuakeML.jl’ refers to this Julia package, which implements the QuakeML
standard.
### Current version
The current version of QuakeML is
[1.2](https://quake.ethz.ch/quakeml/Documents). This is the version
of QuakeML supported by QuakeML.jl.
## How to install
QuakeML.jl can be added to your Julia environment like so:
```julia
julia> import Pkg; Pkg.add("QuakeML")
```
## Testing
To check that your install is working correctly, you can run the package's
tests by doing:
```julia
julia> import Pkg; Pkg.test("QuakeML")
```
| QuakeML | https://github.com/anowacki/QuakeML.jl.git |
|
[
"MIT"
] | 0.1.2 | 607fd77863fd04cdd6010a33236006949b6cfd69 | docs | 6368 | # User manual
This section describes how to use QuakeML.jl to read and write
QuakeML files, and how to create objects which describe sets
of seismic events.
## Preamble
The following examples all assume that you have first used
the module like so:
```@repl example
using QuakeML
```
### Namespace issues
QuakeML.jl deliberately does not export the types it uses by default,
since their names follow those in the QuakeML specification, and they
are quite generic to seismic processing—for example, `Event` and `Phase`.
The recommended way to interact with QuakeML.jl in the REPL or in your
own packages is to always use the module name (or an alias of it).
For instance, to define an empty set of events, which are held in the
type [`EventParameters`](@ref QuakeML.EventParameters), you would write
```@repl example
events = QuakeML.EventParameters()
```
!!! note
If you _really_ want to bring the QuakeML.jl types into scope without
manually importing them, then there is an option. You can do
`using QuakeML.Types`. Note that this API is not yet stable and use of
the `Types` module is recommended only for interactive use or
throwaway scripts.
### Important types
For a full list of QuakeML types, see [Types](@ref). The following
are a few of the most important when defining one's own catalogues.
- [`EventParameters`](@ref QuakeML.EventParameters) is the root type,
and contains one or more `Event`s.
- An [`Event`](@ref QuakeML.Event) defines a known single source of seismic
energy, which may contain one or several
- [`Origin`](@ref QuakeML.Origin)s. Each `Origin` is one interpretation of the
data, potentially containing information about the source location,
origin time, focal mechanism, magnitude, and so on.
The types in this package are directly named after those in the
QuakeML specification. Similarly, the fields of each type are named
to match the names of the attributes and elements of each QuakeML type.
Note however that rather than use [camel case](https://en.wikipedia.org/wiki/Camel_case) `likeThis` for these field names, in this package we use
[snake case](https://en.wikipedia.org/wiki/Snake_case) `like_this`.
Therefore translating between the XML and QuakeML.jl representations
of things in the specification should be simple.
### Sample data
QuakeML.jl comes with a few sample data sets. To access these,
you can define the path to them using the `pathof`
function from `Base`. We will call this path `data_dir`:
```@repl example
data_dir = joinpath(dirname(dirname(pathof(QuakeML))), "test", "data")
```
## Reading
### On-disk data
To read a set of events from disk, one simply calls [`QuakeML.read`](@ref):
```@repl example
nepal_event = QuakeML.read(joinpath(data_dir, "nepal_mw7.2.qml"))
```
### Strings
To read from a `String` which contains QuakeML, you use
[`QuakeML.readstring`](@ref):
```@repl example
qml_string = """
<?xml version="1.0"?>
<quakeml xmlns="http://quakeml.org/xmlns/quakeml/1.2">
<eventParameters publicID="smi:local/events/XXX">
<event publicID="smi:local/event/A">
</event>
</eventParameters>
</quakeml>
""";
events = QuakeML.readstring(qml_string)
```
## Writing
### Writing to disk or subtype of `IO`
To write a set of events to a file on disk, call
[`write(io, events)`](@ref Base.write(::AbstractString, ::QuakeML.EventParameters)).
```@repl example
write("nepal.xml", nepal_event)
```
You can easily verify that the file written is identical to the one we read:
```@repl example
QuakeML.read("nepal.xml") == nepal_event
```
### Converting to a string
To convert a set of events into a `String` for subsequent processing,
first convert the `EventParameters` object into an XML document, then
call `string`:
```@repl example
string2 = string(quakeml(events))
```
!!! note
One could also create a `Base.IOBuffer` and `write` to that directly.
### Converting to an in-memory XML document
Internally, QuakeML.jl uses [EzXML.jl](https://github.com/bicycle1885/EzXML.jl)
to parse XML strings and create XML objects from `EventParameters`.
If you are happy to use EzXML, you can create an XML document
(an `EzXML.Document`) by calling [`quakeml`](@ref) on an `EventParameters`
object.
```@repl example
xml = quakeml(nepal_event)
typeof(xml)
```
## Accessing fields
In QuakeML.jl, all fields of types are publicly-accessible and part
of the API. It is intended that users will directly access and
manipulate these fields. Where restrictions on fields exist
(for instance, where strings can be only a certain number of characters
long, or can only consist of certain characters), these are enforced
both upon construction of types and when changing fields (via
`setproperty!`).
For example, to get the coordinate of the Nepal event we read in
earlier, you access the fields directly:
```@repl example
nepal_event.event[1]
```
This returns the first `Event` in the `event` field. `event` is
a `Vector{Event}`, and may be empty.
In QuakeML, any `Event` may have several `Origin`s. Each `Origin`
describes a unique onset time and location of the event. Usually, one
of these origins is the 'preferred' origin. Typically, one uses
[`preferred_origin`](@ref) to return this and then uses the origin
parameters within the particular `Origin`.
```@repl example
o = preferred_origin(nepal_event.event[1])
lon, lat = o.longitude.value, o.latitude.value
```
!!! note
Note that the longitude and latitude of an `Origin` are
[`QuakeML.RealQuantity`](@ref)s. As well as the `value` field which
contains the nominal value of the quantity, they can also contain
uncertainties. Hence in this case, we needed to access the actual
value of longitude like `o.longitude.value`, and similarly for latitude.
Almost all types (apart from [Enumerated types](@ref)) are `mutable struct`s,
which means that their fields can be changed after construction.
Almost all types have at least one field which is optional. In QuakeML.jl,
these can either take a concrete value, or `missing`.
Hence setting any optional field to `missing` (like `origin.depth = missing`)
will remove that value.
Where multiple values of a field are allowed (such as the `origin` field
of an `Event`), these are represented by `Vector`s, and can be empty.
| QuakeML | https://github.com/anowacki/QuakeML.jl.git |
|
[
"MIT"
] | 1.0.3 | 4313f4d37ec6b34bb53214759f8a0df02458b6e9 | code | 971 | using Documenter
using BoundTypes
DocMeta.setdocmeta!(BoundTypes, :DocTestSetup, :(using BoundTypes); recursive = true)
makedocs(
modules = [BoundTypes],
sitename = "BoundTypes.jl",
format = Documenter.HTML(;
repolink = "https://github.com/bhftbootcamp/BoundTypes.jl",
canonical = "https://bhftbootcamp.github.io/BoundTypes.jl",
edit_link = "master",
assets = ["assets/favicon.ico"],
sidebar_sitename = true, # Set to 'false' if the package logo already contain its name
),
pages = [
"Home" => "index.md",
"API Reference" => [
"pages/bound_number.md",
"pages/bound_string.md",
"pages/bound_time.md",
"pages/utils.md",
],
"For Developers" => "pages/devs.md",
],
warnonly = [:doctest, :missing_docs],
)
deploydocs(;
repo = "github.com/bhftbootcamp/BoundTypes.jl",
devbranch = "master",
push_preview = true,
)
| BoundTypes | https://github.com/bhftbootcamp/BoundTypes.jl.git |
|
[
"MIT"
] | 1.0.3 | 4313f4d37ec6b34bb53214759f8a0df02458b6e9 | code | 1288 | using BoundTypes
# YES
NumberPositive{Float64}(10)
# NO
NumberPositive{Float64}(-10)
# YES
NumberNonPositive{Float64}(-10)
NumberNonPositive{Float64}(0)
# NO
NumberNonPositive{Float64}(10)
# YES
NumberNegative{Float64}(-10)
# NO
NumberNegative{Float64}(10)
# YES
NumberNonNegative{Float64}(10)
NumberNonNegative{Float64}(0)
# NO
NumberNonNegative{Float64}(-10)
# YES
NumberGreater{Float64,10}(20)
# NO
NumberGreater{Float64,10}(5)
# YES
NumberGreaterOrEqual{Float64,10}(20)
NumberGreaterOrEqual{Float64,10}(10)
# NO
NumberGreaterOrEqual{Float64,10}(5)
# YES
NumberLess{Float64,10}(5)
# NO
NumberLess{Float64,10}(20)
# YES
NumberLessOrEqual{Float64,10}(5)
NumberLessOrEqual{Float64,10}(10)
# NO
NumberLessOrEqual{Float64,10}(20)
# YES
NumberInterval{Float64,10,<=,<,20}(10)
NumberInterval{Float64,10,<=,<,20}(15)
# NO
NumberInterval{Float64,10,<=,<,20}(20)
NumberInterval{Float64,10,<=,<,20}(25)
# YES
NumberOdd{Float64}(3)
# NO
NumberOdd{Float64}(4)
# YES
NumberEven{Float64}(4)
# NO
NumberEven{Float64}(5)
# Nested bounds
# YES
NumberPositive{NumberLessOrEqual{NumberOdd{Float64},10}}(7)
# NO
NumberPositive{NumberLessOrEqual{NumberOdd{Float64},10}}(-7)
NumberPositive{NumberLessOrEqual{NumberOdd{Float64},10}}(70)
NumberPositive{NumberLessOrEqual{NumberOdd{Float64},10}}(6)
| BoundTypes | https://github.com/bhftbootcamp/BoundTypes.jl.git |
|
[
"MIT"
] | 1.0.3 | 4313f4d37ec6b34bb53214759f8a0df02458b6e9 | code | 900 | using BoundTypes
# YES
StringLowerCase{String}("abcdef")
# NO
StringLowerCase{String}("abCDef")
# YES
StringUpperCase{String}("ABCDEF")
# NO
StringUpperCase{String}("ABcdEF")
# YES
StringMinLength{String,5}("abcdef")
# NO
StringMinLength{String,5}("abc")
# YES
StringMaxLength{String,5}("abc")
# NO
StringMaxLength{String,5}("abcdef")
# YES
StringFixedLength{String,5}("abcde")
# NO
StringFixedLength{String,5}("abcdef")
StringFixedLength{String,5}("abc")
# YES
StringPattern{String,pattern"^[a-zA-Z0-9_]+$"}("abcdef")
# NO
StringPattern{String,pattern"^[a-zA-Z0-9_]+$"}("abc.def")
# Nested bounds
# YES
StringLowerCase{StringMinLength{StringMaxLength{String,6},3}}("abcde")
# NO
StringLowerCase{StringMinLength{StringMaxLength{String,6},3}}("abCDef")
StringLowerCase{StringMinLength{StringMaxLength{String,6},3}}("ab")
StringLowerCase{StringMinLength{StringMaxLength{String,6},3}}("abcdefg")
| BoundTypes | https://github.com/bhftbootcamp/BoundTypes.jl.git |
|
[
"MIT"
] | 1.0.3 | 4313f4d37ec6b34bb53214759f8a0df02458b6e9 | code | 1175 | using Dates
using BoundTypes
# YES
TimeAfterNow{Date}(Date("2030-01-01"))
TimeAfter{Date,Date(2023)}(Date("2024-01-01"))
# NO
TimeAfterNow{Date}(Date("2020-01-01"))
TimeAfter{Date,Date(2023)}(Date("2020-01-01"))
# YES
TimeBeforeOrEqualNow{Time}(Time(1))
TimeBeforeOrEqual{Time,Time(12)}(Time("2:00:00"))
TimeBeforeOrEqual{Time,Time(12)}(Time("12:00:00"))
# NO
TimeBeforeOrEqualNow{Time}(Time("23:59:00"))
TimeBeforeOrEqual{Time,Time(12)}(Time("13:00:00"))
# YES
TimePeriodAfterNow{DateTime,Day(1)}(now() + Hour(12))
TimePeriodBeforeNow{DateTime,Day(1)}(now() - Hour(12))
# NO
TimePeriodAfterNow{DateTime,Day(1)}(now() + Hour(1) + Day(1))
TimePeriodBeforeNow{DateTime,Day(1)}(now() - Hour(1) + Day(1))
# YES
TimeInterval{DateTime,DateTime(2020),<=,<,DateTime(2025)}(DateTime(2024))
# NO
TimeInterval{DateTime,DateTime(2020),<=,<,DateTime(2025)}(DateTime(2017))
TimeInterval{DateTime,DateTime(2020),<=,<,DateTime(2025)}(DateTime(2030))
# Nested bounds
# YES
TimeAfterOrEqual{TimeBefore{Time,Time(15)},Time(5)}(Time("10:00:00"))
# NO
TimeAfterOrEqual{TimeBefore{Time,Time(15)},Time(5)}(Time("20:00:00"))
TimeAfterOrEqual{TimeBefore{Time,Time(15)},Time(5)}(Time("2:00:00"))
| BoundTypes | https://github.com/bhftbootcamp/BoundTypes.jl.git |
|
[
"MIT"
] | 1.0.3 | 4313f4d37ec6b34bb53214759f8a0df02458b6e9 | code | 2048 | using Dates
using Serde
using BoundTypes
mutable struct UserProfile
# Usernames must consist of alphanumeric characters and underscores.
username::StringPattern{String,pattern"^[a-zA-Z0-9_]+$"}
# Passwords are exactly 12 characters long.
password::StringFixedLength{String,12}
# Simple pattern for validating email addresses.
email::StringPattern{String,pattern"^\S+@\S+\.\S+$"}
# Age must be a positive integer.
age::NumberPositive{Int64}
# Biography field.
bio::String
# Height in centimeters, bounded between 50 and 250.
height_in_cm::NumberInterval{Float64,50,<,<,250}
# Weight in kilograms, must be positive or zero.
weight_in_kg::NumberNonNegative{Float64}
# Account creation must be in the past.
account_creation_date::TimeBeforeNow{DateTime}
# Subscription must end in the future.
subscription_end_date::TimeAfter{DateTime,DateTime(2024,1,1)}
end
# Deserialization
function Serde.deser(::Type{<:UserProfile}, ::Type{<:TimeType}, x::String)
return DateTime(x)
end
valid_user_info = """
{
"username": "user123_",
"password": "Abc123!@#Def",
"email": "[email protected]",
"age": 25,
"bio": "Just a simple bio.",
"height_in_cm": 175.5,
"weight_in_kg": 70.0,
"account_creation_date": "2023-01-15T14:22:00",
"subscription_end_date": "2030-01-15T00:00:00"
}
"""
valid_user = deser_json(UserProfile, valid_user_info)
invalid_user_info = """
{
"username": "user123_@@",
"password": "Abc123!@#Def123",
"email": "user123_example!com",
"age": -30,
"bio": "Just a simple bio.",
"height_in_cm": 2000.0,
"weight_in_kg": -100.0,
"account_creation_date": "2030-01-15T14:22:00",
"subscription_end_date": "2010-01-15T00:00:00"
}
"""
invalid_user = deser_json(UserProfile, invalid_user_info)
# Serialization
user = UserProfile(
"user123_",
"Abc123!@#Def",
"[email protected]",
25,
"Just a simple bio.",
175.5,
70.0,
DateTime("2023-01-15T14:22:00"),
DateTime("2030-01-15T00:00:00"),
)
to_json(user)
| BoundTypes | https://github.com/bhftbootcamp/BoundTypes.jl.git |