Skip to content

Instantly share code, notes, and snippets.

@ChrisRackauckas
Created December 15, 2016 04:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ChrisRackauckas/44bd64d39255fd2a31ed0731c66401a1 to your computer and use it in GitHub Desktop.
Save ChrisRackauckas/44bd64d39255fd2a31ed0731c66401a1 to your computer and use it in GitHub Desktop.
importall Base
import RecursiveArrayTools.recursivecopy!
using DifferentialEquations
type SimType{T} <: AbstractArray{T,1}
x::Array{T,1}
f1::T
end
function SimType{T}(::Type{T}, length::Int64)
return SimType{T}(zeros(length), T(0))
end
function SimType{T}(S::SimType{T})
return SimType(T, length(S.x))
end
function SimType{T}(S::SimType{T}, dims::Dims)
return SimType(T, prod(dims))
end
similar{T}(A::SimType{T}) = begin
R = SimType(A)
R.f1 = A.f1
R
end
similar{T}(A::SimType{T}, ::Type{T}, dims::Dims) = begin
R = SimType(A, dims)
R.f1 = A.f1
R
end
done(A::SimType, i::Int64) = done(A.x,i)
eachindex(A::SimType) = eachindex(A.x)
next(A::SimType, i::Int64) = next(A.x,i)
start(A::SimType) = start(A.x)
length(A::SimType) = length(A.x)
ndims(A::SimType) = ndims(A.x)
size(A::SimType) = size(A.x)
recursivecopy!(B::SimType, A::SimType) = begin
recursivecopy!(B.x, A.x)
B.f1 = A.f1
end
getindex( A::SimType, i::Int...) = (A.x[i...])
setindex!(A::SimType, x, i::Int...) = (A.x[i...] = x)
function f(t,u,du)
du[1] = -0.5*u[1] + u.f1
du[2] = -0.5*u[2]
end
const tstop = [5]
function event_f(t,u) # Event when event_f(t,u) == 0
t ∉ tstop
end
function apply_event!(u,cache)
for c in cache
c.f1 = 1.5
end
end
const rootfind_event_loc = false
const interp_points = 0
callback = @ode_callback begin
@ode_event event_f apply_event! rootfind_event_loc interp_points
end
u0 = SimType{Float64}([10;10], 0.0)
prob = ODEProblem(f,u0,(0.0,10.0))
sol = solve(prob,callback = callback, tstops=tstop)
using Plots; plotly()
plot(sol)
sol = solve(prob,callback = callback, tstops=tstop, saveat = collect(0.:0.5:10))
plot(sol)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment