zekeriyasari / Causal.jl

Causal.jl - A modeling and simulation framework adopting causal modeling approach.
https://zekeriyasari.github.io/Causal.jl/dev/
Other
115 stars 7 forks source link

Reusing the model for several simulations #73

Closed patryk-kubiczek closed 3 years ago

patryk-kubiczek commented 3 years ago

Is it possible to restart the simulation without having to construct the model again? Say I want to explore the parameter space of the model but the construction step is costly - in such a case I would like to reuse the model rather than construct it again for each parameter combination.

This simple example with one parameter a illustrates how I would imagine doing that. Unfortunately, it doesn't work: the first simulation runs fine but the second one freezes.


using Causal

# Define the state function with a reference to params dict
params = Dict(:a => 1.)
statefunc(dx, x, u, t) = begin
    a = params[:a]
    dx[1] = -x[1] + a * u[1](t)
end

# Describe model
@defmodel model begin
    @nodes begin
        gen = SinewaveGenerator(amplitude = 1., frequency = 1/2π)
        ds = ODESystem(righthandside = statefunc, readout = (x, u, t) -> x, state=[1.],
                       input=Inport(1), output=Outport(1))
        writer = Writer(input=Inport(1))
    end
    @branches begin
        gen[1] => ds[1]
        ds[1] => writer[1]
    end
end

# Simulate the model
tinit, tsample, tfinal = 0., 0.01, 10.
simulate!(model, tinit, tsample, tfinal)
t1, x1 = read(getnode(model, :writer).component)

# Change the parameter and simulate the model again
params[:a] = 2.
# Restore the initial value
ds = getnode(model, :ds)
ds.component.state = [1.]
initialize!(model)
# Simulate
simulate!(model, tinit, tsample, tfinal)
t2, x2 = read(getnode(model, :writer).component)

# Read and plot data
using Plots
plot(t1, x1[:, 1], label="a=1", xlabel="t")
plot!(t2, x2[:, 1], label="a=2", xlabel="t")
zekeriyasari commented 3 years ago

Hi @patryk-kubiczek

Thank you for opening this issue. With the last patch release (v0.3.3) of Causal.jl, it is now possible to simulate a model multiple times.