Hi, I’m quite new to Julia and I have stumbled upon Turing. It looks great and the documentation is nice but either I have missed something or simply it’s not possible.
I want to define models in a modular way and combine them. For example imagine I want to estimate the speed of a car moving at constant speed and I have two sensors: gps
for measuring positions and radar
for directly measuring speed. The following simple script shows that only copy-pasting in a single function works
using Distributions
using Turing
"""
x: position measure
t: time measure
speed: parameter
"""
@model function gps(t, x, speed)
for i=1:length(x)
x[i] ~ Normal(speed * t[i], 1.0)
end
end
"""
v: speed measure
speed: parameter
"""
@model function radar(v, speed)
for i=1:length(v)
v[i] ~ Normal(speed, 5.0)
end
end
"Compose gps + radar"
@model function fullmodel1(t, x, v)
speed ~ Normal(0.0, 100.0)
gps(t, x, speed)
radar(v, speed)
end
"Copy-paste GPS + radar"
@model function fullmodel2(t, x, v)
speed ~ Normal(0.0, 100.0)
for i=1:length(x)
x[i] ~ Normal(speed * t[i], 1.0)
end
for i=1:length(v)
v[i] ~ Normal(speed, 5.0)
end
end
"Compare fullmodel1 vs fullmodel2"
function testmodel(N=100)
speed = 5.0 # true value of speed
# generate measurements
t = LinRange(0, 120, N)
x = speed .* t .+ randn(N)
v = speed .+ randn(N)
# estimate speed
c1 = sample(fullmodel1(t, x, v), NUTS(0.6), 1000)
c2 = sample(fullmodel2(t, x, v), NUTS(0.6), 1000)
c1, c2
end
c1, c2 = testmodel()
println("Results for fullmodel1")
display(c1)
println("Results for fullmodel2")
display(c2)
The script will run but only fullmodel2
gives correct results. Eliminating speed
as a parameter from gps
or radar
gives identical results.
Since I don’t know what magic is @model
really doing behind the scenes I don’t know how to proceed and any help is welcomed.
I know that for such a simple example splitting into several functions is overkill but for more complex models I think is extremely important. For example, thinking again in terms of localization problems, I may have different models for accelerometers, gyroscopes, GPS just depending on the model or type of sensor (laser or MEMS gyros, differential GPS, relative GPS…) although all of them give back the same types of measures and so the structure of the problem doesn’t change, just the internal details of each part.
Thanks!