Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Using new CoupledSDEs #116

Merged
merged 26 commits into from
Oct 11, 2024
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
ca5112c
load CoupledSDEs from DynamicalSystemsBase v3.11
reykboerner Oct 2, 2024
b529363
worked on compatibility with new CoupledSDEs
reykboerner Oct 3, 2024
268e9b5
updated LDT functions, made om_action require noise_strength input
reykboerner Oct 3, 2024
3358570
export functions from StochasticSystemsBase
reykboerner Oct 3, 2024
a27b135
worked on updating tests
reykboerner Oct 3, 2024
454162c
CoupledSDEs test's
oameye Oct 6, 2024
5c12110
try out new format action
oameye Oct 6, 2024
0f5318e
turn on all tests
oameye Oct 6, 2024
6881140
format
oameye Oct 6, 2024
06115ab
fix downgrade compat
oameye Oct 6, 2024
c220516
better format CI
oameye Oct 6, 2024
65ec611
update code example in README
reykboerner Oct 8, 2024
fa68b32
fixed Large Deviations tests by normalizing covariance matrix
reykboerner Oct 8, 2024
ec60076
updated simulation functions
reykboerner Oct 9, 2024
b5ecd7d
added simulation tests
reykboerner Oct 9, 2024
5a8f5a4
removed 'simulate', renamed 'relax' to 'deterministic_orbit'
reykboerner Oct 9, 2024
98b5db0
tried to fix docs, still not finding docstrings from DynamicalSystems…
reykboerner Oct 9, 2024
397ba55
add stochasticSystemsBase do docs modules
oameye Oct 10, 2024
78c787a
fixed typo in makedocs
reykboerner Oct 10, 2024
f520ef4
Merge branch 'main' into base_coupledsdes
oameye Oct 11, 2024
d7b2477
exported missing functions, removed unneeded dep
reykboerner Oct 11, 2024
2fbbf33
worked on fixing docs errors
reykboerner Oct 11, 2024
7b57b1e
added dependency to docs
reykboerner Oct 11, 2024
d9e2845
added another dep to docs
reykboerner Oct 11, 2024
59af416
updated changelog to v0.4.0
reykboerner Oct 11, 2024
ffd0dad
fixed errors in docstrings
reykboerner Oct 11, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Project.toml
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ Dierckx = "0.5.3"
DiffEqNoiseProcess = "5.22"
DocStringExtensions = "0.9.3"
Documenter = "^1.4.1"
DynamicalSystemsBase = "3.7.1"
DynamicalSystemsBase = "3.11"
ExplicitImports = "1.9"
Format = "1"
ForwardDiff = "0.10.36"
Expand Down
39 changes: 26 additions & 13 deletions src/CriticalTransitions.jl
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,10 @@ module CriticalTransitions

# Base
using Statistics: Statistics, mean
using LinearAlgebra: LinearAlgebra, Diagonal, I, norm, tr, dot
using LinearAlgebra: LinearAlgebra, I, norm, dot, tr #, Diagonal, tr
using StaticArrays: StaticArrays, SVector

# core
using DynamicalSystemsBase:
DynamicalSystemsBase,
ContinuousTimeDynamicalSystem,
StateSpaceSets,
dimension,
dynamic_rule
# Core
using DiffEqNoiseProcess: DiffEqNoiseProcess
using OrdinaryDiffEq: OrdinaryDiffEq, Tsit5
using StochasticDiffEq:
Expand All @@ -25,6 +19,19 @@ using StochasticDiffEq:
step!,
terminate!,
u_modified!
using DynamicalSystemsBase:
DynamicalSystemsBase,
#ContinuousTimeDynamicalSystem,
CoupledODEs,
CoupledSDEs,
#StateSpaceSets,
#dimension,
dynamic_rule,
current_state,
set_state!

#StochasticSystemsBase = Base.get_extension(DynamicalSystemsBase, :StochasticSystemsBase)
#using DynamicalSystemsBase.StochasticSystemsBase: CoupledSDEs

using ForwardDiff: ForwardDiff
using IntervalArithmetic: IntervalArithmetic, interval
Expand All @@ -49,10 +56,15 @@ using Reexport: @reexport
@reexport using StochasticDiffEq
@reexport using DiffEqNoiseProcess

StochasticSystemsBase = Base.get_extension(DynamicalSystemsBase, :StochasticSystemsBase)
covariance_matrix = StochasticSystemsBase.covariance_matrix
diffusion_matrix = StochasticSystemsBase.diffusion_matrix

include("extention_functions.jl")
include("utils.jl")
include("CoupledSDEs.jl")
include("CoupledSDEs_utils.jl")
include("system_utils.jl")
#include("CoupledSDEs.jl")
#include("CoupledSDEs_utils.jl")
include("io.jl")
include("trajectories/simulation.jl")
include("trajectories/transition.jl")
Expand All @@ -70,9 +82,9 @@ export CoupledSDEs,
idfunc!,
idfunc,
add_noise_strength,
noise_process,
covariance_matrix,
noise_strength,
#noise_process,
#covariance_matrix,
#noise_strength,
CoupledODEs

# Methods
Expand All @@ -82,6 +94,7 @@ export transition, transitions
export fw_action, om_action, action, geometric_action
export min_action_method, geometric_min_action_method
export make_jld2, make_h5, intervals_to_box
export covariance_matrix, diffusion_matrix
# export basins, basinboundary
# export edgetracking, bisect_to_edge, AttractorsViaProximity
# export fixedpoints
Expand Down
12 changes: 6 additions & 6 deletions src/largedeviations/action.jl
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ generalized norm ``||a||_Q^2 := \\langle a, Q^{-1} b \\rangle`` (see `anorm``).
function fw_action(sys::CoupledSDEs, path, time)
@assert all(diff(time) .≈ diff(time[1:2])) "Freidlin-Wentzell action is only defined for equispaced time"
# Inverse of covariance matrix
A = inv(covariance_matrix(sys)) # Do we have to take the inverse here?
A = inv(covariance_matrix(sys))
oameye marked this conversation as resolved.
Show resolved Hide resolved

# Compute action integral
integrand = fw_integrand(sys, path, time, A)
Expand All @@ -35,7 +35,7 @@ end;
"""
$(TYPEDSIGNATURES)

Calculates the Onsager-Machlup action of a given `path` with time points `time` for the drift field `sys.f` at given `sys.noise_strength`.
Calculates the Onsager-Machlup action of a given `path` with time points `time` for the drift field `sys.f` at given `noise_strength`.

The path must be a `(D x N)` matrix, where `D` is the dimensionality of the system `sys` and
`N` is the number of path points. The `time` array must have length `N`.
Expand All @@ -50,10 +50,10 @@ time of the path, and ``\\sigma`` the noise strength. The subscript ``Q`` refers
generalized norm ``||a||_Q^2 := \\langle a, Q^{-1} b \\rangle`` (see `anorm``). Here
``Q`` is the noise covariance matrix.
"""
function om_action(sys::CoupledSDEs, path, time)
function om_action(sys::CoupledSDEs, path, time, noise_strength)
@assert all(diff(time) .≈ diff(time[1:2])) "Fw_action is only defined for equispaced time"

σ = noise_strength(sys)
σ = noise_strength
# Compute action integral
S = 0
for i in 1:(size(path, 2) - 1)
Expand All @@ -75,11 +75,11 @@ Computes the action functional specified by `functional` for a given CoupledSDEs
* `functional = "FW"`: Returns the Freidlin-Wentzell action ([`fw_action`](@ref))
* `functional = "OM"`: Returns the Onsager-Machlup action ([`om_action`](@ref))
"""
function action(sys::CoupledSDEs, path::Matrix, time, functional)
function action(sys::CoupledSDEs, path::Matrix, time, functional; noise_strength=nothing)
if functional == "FW"
action = fw_action(sys, path, time)
elseif functional == "OM"
action = om_action(sys, path, time)
action = om_action(sys, path, time, noise_strength)
end
return action
end;
Expand Down
27 changes: 27 additions & 0 deletions src/system_utils.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
"""
$(TYPEDSIGNATURES)

Returns the deterministic drift ``f(x)`` of the CoupledSDEs `sys` at state `x`. For time-
dependent systems, the time can be specified as a keyword argument `t` (by default `t=0`).
"""
function drift(sys::CoupledSDEs{IIP}, x; t=0) where {IIP}
f = dynamic_rule(sys)
if IIP
dx = similar(x)
f(dx, x, sys.p0, t)
return dx
else
return f(x, sys.p0, t)
end
end

"""
$(TYPEDSIGNATURES)

Computes the divergence of the drift field ``f(x)`` at state `x`. For time-
dependent systems, the time can be specified as a keyword argument `t` (by default `t=0`).
"""
function div_drift(sys::CoupledSDEs, x; t=0)
b(x) = drift(sys, x; t)
return tr(ForwardDiff.jacobian(b, x))
end;
9 changes: 4 additions & 5 deletions src/trajectories/equib.jl
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
"""
equilib(sys::CoupledSDEs, state; kwargs...)
equilib(sys::CoupledSDEs [, state]; kwargs...)
Returns the equilibrium solution of the system `sys` for given initial condition `state`.

> Warning: This algorithm simply evolves the deterministic system forward in time until a steady-state condition is satisfied.
Expand All @@ -12,13 +12,12 @@ Returns the equilibrium solution of the system `sys` for given initial condition
* `dt = 0.01`: time step of the ODE solver.
* `solver = Euler()`: ODE solver used for evolving the state.
"""
function equilib(sys::CoupledSDEs, state; dt=0.01, tmax=1e5, abstol=1e-5, solver=Tsit5())
function equilib(sys::CoupledSDEs, state=nothing; dt=0.01, tmax=1e5, abstol=1e-5, solver=Tsit5())
oameye marked this conversation as resolved.
Show resolved Hide resolved
condition(u, t, integrator) = norm(integrator.uprev - u) < abstol
affect!(integrator) = terminate!(integrator)
equilib_cond = DiscreteCallback(condition, affect!)

prob = ODEProblem(sys.integ.f, state, (0, tmax), sys.p0)
isnothing(state) ? nothing : set_state!(sys, state)
prob = sys.integ.sol.prob
sol = solve(prob, solver; dt=dt, callback=equilib_cond, save_on=false, save_start=false)

return sol.u[1]
end;
4 changes: 2 additions & 2 deletions src/trajectories/simulation.jl
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ For more info, see [`SDEProblem`](https://diffeq.sciml.ai/stable/types/sde_types
function simulate(
sys::CoupledSDEs, T, init=current_state(sys); alg=sys.integ.alg, kwargs...
)
prob = remake(referrenced_sciml_prob(sys); u0=init, tspan=(0, T))
prob = remake(sys.integ.sol.prob; u0=init, tspan=(0, T))
return solve(prob, alg; kwargs...)
end;

Expand All @@ -35,7 +35,7 @@ For stochastic integration, see [`simulate`](@ref).

"""
function relax(sys::CoupledSDEs, T, init=current_state(sys); alg=Tsit5(), kwargs...)
sde_prob = referrenced_sciml_prob(sys)
sde_prob = sys.integ.sol.prob
prob = ODEProblem{isinplace(sde_prob)}(dynamic_rule(sys), init, (0, T), sys.p0)
return solve(prob, alg; kwargs...)
end;
12 changes: 6 additions & 6 deletions test/CoupledSDEs.jl
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
# diagonal additive noise: σ*N(0,dt)
# a vector of random numbers dW whose size matches the output of g where the noise is applied element-wise
prob = SDEProblem(meier_stein, diagonal_noise(σ), zeros(2), (0.0, Inf), ())
sde = CoupledSDEs(meier_stein, idfunc, zeros(2), (), σ)
sde = CoupledSDEs(meier_stein, zeros(2); noise_strength=σ)

@test sde.integ.sol.prob.f isa SDEFunction
@test sde.integ.sol.prob.f.f.f == prob.f.f
Expand All @@ -46,7 +46,7 @@
σ = 0.25 # noise strength
W = WienerProcess(0.0, 0.0, 0.0)
prob = SDEProblem(f!, diagonal_noise!(σ), zeros(2), (0.0, Inf), (); noise=W)
sde = CoupledSDEs(f!, idfunc!, zeros(2), (), σ; noise=W)
sde = CoupledSDEs(f!, zeros(2); noise_process=W, noise_strength=σ)

@test sde.integ.sol.prob.f isa SDEFunction
@test sde.integ.sol.prob.f.f.f == prob.f.f
Expand Down Expand Up @@ -74,7 +74,7 @@
g_sde(u, p, t) = σ .* u
g_Csde(u, p, t) = σ .* u
prob = SDEProblem(meier_stein, g_sde, zeros(2), (0.0, Inf), ())
sde = CoupledSDEs(meier_stein, g_Csde, zeros(2), (), σ)
sde = CoupledSDEs(meier_stein, zeros(2); g=g_Csde)

@test sde.integ.sol.prob.f isa SDEFunction
@test sde.integ.sol.prob.f.f.f == prob.f.f
Expand Down Expand Up @@ -108,7 +108,7 @@
# prob = SDEProblem(f, g, ones(2), (0.0, 1.0), noise_rate_prototype = zeros(2, 4))
# diffeq =(alg=SRIW1(), noise_rate_prototype = zeros(2, 4))
sde = CoupledSDEs(
f, g, zeros(2); noise_rate_prototype=zeros(2, 4), diffeq=(alg=RKMilCommute(),)
f, zeros(2); g, noise_prototype=zeros(2, 4), diffeq=(alg=RKMilCommute(),)
)
prob = SDEProblem(f, g, zeros(2), (0.0, Inf); noise_rate_prototype=zeros(2, 4))

Expand All @@ -133,7 +133,7 @@
Z0 = zeros(2)
W = CorrelatedWienerProcess(Γ, t0, W0, Z0)
prob = SDEProblem(f!, diagonal_noise!(σ), zeros(2), (0.0, Inf), (); noise=W)
sde = CoupledSDEs(f!, idfunc!, zeros(2), (), σ; noise=W)
sde = CoupledSDEs(f!, zeros(2); noise_process=W, noise_strength=σ)

@test sde.integ.sol.prob.f isa SDEFunction
@test sde.integ.sol.prob.f.f.f == prob.f.f
Expand All @@ -158,4 +158,4 @@
@test W.covariance ≈ cov(sol; dims=2) / dt rtol = 1e-2
end
end
end
end
18 changes: 18 additions & 0 deletions test/basin/basin_boundary-N54XDK9GMK.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
@testset "fitzhugh_nagumo" begin
# Define systems
g = diag_noise_funtion(0.215)
system = CoupledSDEs(fitzhugh_nagumo, g, [2.0, 0.1], [0.1, 3.0, 1.0, 1.0, 1.0, 0.0])

# Set up domain
A, B, C = [0.0, 0.0], [1.0, 0.0], [0.0, 1.0]
box = intervals_to_box([-2.0, -2.0], [2.00, 2.0])
step = 0.1

boas = basins(system, A, B, C, box; bstep = [step, step])
oameye marked this conversation as resolved.
Show resolved Hide resolved
X, Y, attractors, h = boas
boundary = basinboundary(boas)
@test length(attractors) == 2
@test length(unique(h)) == 3
@test h[end÷2+1, end÷2+1] == -1
@test boundary[:,end÷2+1] == zeros(2)
oameye marked this conversation as resolved.
Show resolved Hide resolved
end
22 changes: 22 additions & 0 deletions test/issue14.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
using CriticalTransitions, StaticArrays, Test

function meier_stein(u, p, t) # in-place
x, y = u
dx = x-x^3 -10*x*y^2
dy = -(1+x^2)*y
SA[dx, dy]
oameye marked this conversation as resolved.
Show resolved Hide resolved
end
σ = 0.25
sys = StochSystem(meier_stein, [], zeros(2), σ, idfunc, nothing, I(2), "WhiteGauss")

# initial path: parabola
xx = range(-1.0,1.0, length=30)
yy = 0.3 .* (- xx .^ 2 .+ 1)
oameye marked this conversation as resolved.
Show resolved Hide resolved
init = Matrix([xx yy]')

gm = geometric_min_action_method(sys, init, maxiter=1000)
@test all(isapprox.(path[2,:][end-5:end], 0, atol=1e-3))
oameye marked this conversation as resolved.
Show resolved Hide resolved

gm[2][end]

isapprox(gm[2][end], 0.338, atol=1e-3)
oameye marked this conversation as resolved.
Show resolved Hide resolved
4 changes: 2 additions & 2 deletions test/largedeviations/MAM.jl
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
@testset "MAM FitzHugh-Nagumo" begin
p = [0.1, 3, 1, 1, 1, 0]
σ = 0.1
fhn = CoupledSDEs(fitzhugh_nagumo, idfunc, zeros(2), p, σ)
fhn = CoupledSDEs(fitzhugh_nagumo, zeros(2), p; noise_strength=σ)
x_i = SA[sqrt(2 / 3), sqrt(2 / 27)]
x_f = SA[0.001, 0.0]
N, T = 200, 2.0
Expand All @@ -14,7 +14,7 @@ end

@testset "MAM Ornstein-Uhlenbeck" begin
σ = 0.18
ou = CoupledSDEs((u, p, t) -> -u, idfunc, SA[1.0], (), σ)
ou = CoupledSDEs((u, p, t) -> -u, SA[1.0]; noise_strength=σ)
x0 = -1
xT = 2.0
T = 10.0
Expand Down
6 changes: 3 additions & 3 deletions test/largedeviations/action_fhn.jl
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@ Random.seed!(SEED)
# System setup - FitzHugh-Nagumo model
p = [1.0, 3.0, 1.0, 1.0, 1.0, 0.0] # Parameters (ϵ, β, α, γ, κ, I)
σ = 0.2 # noise strength
sys = CoupledSDEs(fitzhugh_nagumo, idfunc, zeros(2), p, σ; seed=SEED)
sys = CoupledSDEs(fitzhugh_nagumo, zeros(2), p; noise_strength=σ)#, seed=SEED)

A = inv(CT.covariance_matrix(sys))
A = inv(covariance_matrix(sys))
T, N = 2.0, 100

x_i = SA[sqrt(2 / 3), sqrt(2 / 27)]
Expand All @@ -22,7 +22,7 @@ end

# Test om_action function
@testset "om_action" begin
S = om_action(sys, path, time)
S = om_action(sys, path, time, σ)
@test isapprox(S, 0.26, atol=0.01)
end

Expand Down
4 changes: 2 additions & 2 deletions test/largedeviations/gMAM.jl
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
@testset "gMAM FitzHugh-Nagumo" begin
p = [0.1, 3, 1, 1, 1, 0]
σ = 0.1
fhn = CoupledSDEs(fitzhugh_nagumo, idfunc, zeros(2), p, σ)
fhn = CoupledSDEs(fitzhugh_nagumo, zeros(2), p; noise_strength=σ)
x_i = SA[sqrt(2 / 3), sqrt(2 / 27)]
x_f = SA[0.001, 0.0]
N = 100
Expand All @@ -19,7 +19,7 @@ end
end
σ = 0.25
# sys = CoupledSDEs(fitzhugh_nagumo, idfunc, zeros(2), p, σ)
sys = CoupledSDEs(meier_stein, idfunc, zeros(2), (), σ)
sys = CoupledSDEs(meier_stein, zeros(2); noise_strength=σ)

# initial path: parabola
xx = range(-1.0, 1.0; length=30)
Expand Down
12 changes: 6 additions & 6 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,9 @@ end
JET.test_package(CriticalTransitions; target_defined_modules=true)
end

@testset "CoupledSDEs" begin
include("CoupledSDEs.jl")
end
#@testset "CoupledSDEs" begin
# include("CoupledSDEs.jl")
#end

@testset "ModelingToolkit" begin
include("ModelingToolkit.jl")
Expand All @@ -58,9 +58,9 @@ end
include("largedeviations/gMAM.jl")
end

@testset "utilities" begin
include("utils.jl")
end
#@testset "utilities" begin
# include("utils.jl")
#end

@testset "Trajactories" begin
include("trajactories/simulate.jl")
Expand Down
4 changes: 2 additions & 2 deletions test/trajactories/simulate.jl
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@
p = [0.1, 3.0, 1.0, 1.0, 1.0, 0.0] # Parameters (ϵ, β, α, γ, κ, I)
σ = 0.1
# Simulate
sys = CoupledSDEs(fitzhugh_nagumo, idfunc, SA[1.0, 0.0], p, σ)
sys = CoupledSDEs(fitzhugh_nagumo, SA[1.0, 0.0], p; noise_strength=σ)
traj = relax(sys, 10)
sys = CoupledSDEs(fitzhugh_nagumo, idfunc, SA[1.0, 0.0], p, σ)
sys = CoupledSDEs(fitzhugh_nagumo, SA[1.0, 0.0], p; noise_strength=σ)
sim = simulate(sys, 10)
@test traj[1][1, 1] == 1.0
@test sim.u[1][1] == 1.0
Expand Down
Loading
Loading