Skip to content

Instantly share code, notes, and snippets.

@slwu89
Created December 4, 2021 01:00
Show Gist options
  • Save slwu89/d6dfc8b9599284560918143332338478 to your computer and use it in GitHub Desktop.
Save slwu89/d6dfc8b9599284560918143332338478 to your computer and use it in GitHub Desktop.
the same example as s3inheritance.R in julia
using Random, Distributions, Plots
# the parent type
abstract type ricker end
# derived, concrete types
mutable struct ricker_deterministic <: ricker
x::Float64
r::Float64
k::Float64
end
mutable struct ricker_stochastic <: ricker
x::Float64
r::Float64
k::Float64
sd::Float64
end
function setup_ricker(x0, r, k, sd = nothing)
if isnothing(sd)
return ricker_deterministic(x0, r, k)
else
return ricker_stochastic(x0, r, k, sd)
end
end
function output(model::ricker)
return model.x
end
# step will dispatch correctly on the concrete type
function step(model::ricker_stochastic)
theta = rand(Normal(0, model.sd))
model.x = model.x * (model.r - model.r * (model.x / model.k)) * exp(theta)
end
function step(model::ricker_deterministic)
model.x = model.x * (model.r - model.r * (model.x / model.k))
end
t = 100
x0 = 1
k = 20
sd = 0.1
r = 2.2
function draw_ricker_traj(t, x0, k, r, sd = nothing)
mod = setup_ricker(x0, r, k ,sd)
out = Vector{Float64}(undef, t)
out[1] = output(mod)
for i = 2:t
step(mod)
out[i] = output(mod)
end
return out
end
out_d = draw_ricker_traj(t, x0, k, r)
out_s = map(x -> draw_ricker_traj(t, x0, k, r, sd), 1:100)
plot(1:100, out_s, linealpha = 0.1, linecolor = "blue", legend = false)
plot!(1:100, out_d, color = "black", linewidth = 2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment