cscherrer / Soss.jl

Probabilistic programming via source rewriting
https://cscherrer.github.io/Soss.jl/stable/
MIT License
413 stars 30 forks source link

Ducktype sampleable objects #58

Open kskyten opened 5 years ago

kskyten commented 5 years ago

The is a draft for adding arbitrary simulators here. Would it be possible to just treat everything on the right hand side of a tilde as implementing a rand method and just add custom types? Probably related to #42 .

cscherrer commented 5 years ago

I think I'm missing something here - how is what you propose different than the draft?

kskyten commented 5 years ago

I would like to do this:

struct MySimulator
  mu
  sigma
end

Base.rand(s::MySimulator) = rand(Normal(s.mu, s.sigma))

m = @model (alpha, beta) begin
  z ~ Normal(alpha, beta)
  y ~ MySimulator(z, 1)
end
cscherrer commented 5 years ago

I like it. I think you should currently be able to do something like

m = @model (alpha, beta, sim) begin
  z ~ Normal(alpha, beta)
  y ~ sim(z, 1)
end

rand(m(alpha=a, beta=b, sim=MySimulator))

We'll be able to get rid of the last argument and use the current module scope once we're done with #42

cscherrer commented 5 years ago

Hi @kskyten ,

Thanks to @thautwarm 's recent update (https://github.com/thautwarm/GeneralizedGenerated.jl/pull/28), we can get this working:

julia> struct MySimulator
         mu
         sigma
       end;

julia> Base.rand(s::MySimulator) = rand(Normal(s.mu, s.sigma))

julia> m = @model (alpha, beta) begin
         z ~ Normal(alpha, beta)
         y ~ MySimulator(z, 1)
       end;

julia> rand(m(alpha=2,beta=4))
(alpha = 2, beta = 4, z = -2.5523934421776824, y = -2.1025024446789806)

Hope to get a PR set up with this soon :)

cscherrer commented 4 years ago

@kskyten this now works in 0.8!

thautwarm commented 4 years ago

I used to think I can make MySimulator a module... but it seems unnecessary now😄

thautwarm commented 4 years ago

Currently, due to the address of performance regression, This feature got lost again: https://github.com/cscherrer/Soss.jl/blob/80a9c2805e5d4e0b4290298b23801b3a198f0a56/src/primitives/rand.jl#L14

we should re-implement of it in recent iterations.

thautwarm commented 4 years ago

We can allow m.model to store non-models, and do static dispatch on this, certainly we can have this feature again, with no performance loss.