Skip to content

Commit 09b52ce

Browse files
format
1 parent e7d87eb commit 09b52ce

27 files changed

+1207
-627
lines changed

.JuliaFormatter.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
style = "sciml"

docs/make.jl

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
using Documenter, DocumenterMarkdown
22
using ReactiveDynamics
33

4-
makedocs(format = Documenter.HTML(prettyurls = false, edit_link=nothing), sitename="ReactiveDynamics.jl API Documentation",
5-
build="build_html", pages = ["index.md"])
4+
makedocs(format = Documenter.HTML(prettyurls = false, edit_link = nothing),
5+
sitename = "ReactiveDynamics.jl API Documentation",
6+
build = "build_html", pages = ["index.md"])
67

7-
makedocs(format = Markdown(), sitename="ReactiveDynamics.jl API Documentation",
8-
build="build_md", pages = ["index.md"])
8+
makedocs(format = Markdown(), sitename = "ReactiveDynamics.jl API Documentation",
9+
build = "build_md", pages = ["index.md"])

src/ReactiveDynamics.jl

Lines changed: 71 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,9 @@ using ComponentArrays
1111
const SampleableValues = Union{Expr, Symbol, AbstractString, Float64, Int, Function}
1212
const ActionableValues = Union{Function, Symbol, Float64, Int}
1313

14-
const SampleableRange = Union{Float64, Int64, AbstractString, Expr, Symbol, Tuple{Float64, Union{Float64, Int64, AbstractString, Expr, Symbol}}}
14+
const SampleableRange = Union{Float64, Int64, AbstractString, Expr, Symbol,
15+
Tuple{Float64,
16+
Union{Float64, Int64, AbstractString, Expr, Symbol}}}
1517

1618
Base.convert(::Type{SampleableRange}, x::Tuple) = (Float64(x[1]), x[2])
1719

@@ -24,8 +26,8 @@ end
2426
@present TheoryReactionNetwork(FreeSchema) begin
2527
(S, T)::Ob # species, transitions
2628

27-
(SymbolicAttributeT, DescriptiveAttributeT, SampleableAttributeT,
28-
ModalityAttributeT, PcsOptT, PrmAttributeT)::AttrType
29+
(SymbolicAttributeT, DescriptiveAttributeT, SampleableAttributeT,
30+
ModalityAttributeT, PcsOptT, PrmAttributeT)::AttrType
2931

3032
specName::Attr(S, SymbolicAttributeT)
3133
specModality::Attr(S, ModalityAttributeT)
@@ -62,35 +64,43 @@ end
6264

6365
@acset_type FoldedReactionNetworkType(TheoryReactionNetwork)
6466

65-
const ReactionNetwork = FoldedReactionNetworkType{Symbol, Union{String, Symbol, Missing}, SampleableValues, Set{Symbol}, FoldedObservable, Any}
67+
const ReactionNetwork = FoldedReactionNetworkType{Symbol, Union{String, Symbol, Missing},
68+
SampleableValues, Set{Symbol},
69+
FoldedObservable, Any}
6670

6771
Base.convert(::Type{Symbol}, ex::String) = Symbol(ex)
68-
Base.convert(::Type{Union{String, Symbol, Missing}}, ex::String) = try Symbol(ex) catch; string(ex) end
72+
Base.convert(::Type{Union{String, Symbol, Missing}}, ex::String) =
73+
try
74+
Symbol(ex)
75+
catch
76+
string(ex)
77+
end
6978
Base.convert(::Type{SampleableValues}, ex::String) = MacroTools.striplines(Meta.parse(ex))
7079
Base.convert(::Type{Set{Symbol}}, ex::String) = eval(Meta.parse(ex))
7180
Base.convert(::Type{FoldedObservable}, ex::String) = eval(Meta.parse(ex))
7281

73-
prettynames = Dict(
74-
:transRate => [:rate],
75-
:specInitUncertainty => [:uncertainty, :stoch, :stochasticity],
76-
:transPostAction => [:postAction, :post],
77-
:transName => [:name, :interpretation],
78-
:transPriority => [:priority],
79-
:transProbOfSuccess => [:probability, :prob, :pos],
80-
:transCapacity => [:cap, :capacity],
81-
:transCycleTime => [:ct, :cycletime],
82-
:transMaxLifeTime => [:lifetime, :maxlifetime, :maxtime, :timetolive]
83-
)
84-
85-
defargs = Dict(
86-
:T => Dict{Symbol, Any}(:transPriority => 1, :transProbOfSuccess => 1, :transCapacity => Inf, :transCycleTime => 0.,
87-
:transMaxLifeTime => Inf, :transMultiplier=>1, :transPostAction => :(), :transName => missing),
88-
:S => Dict{Symbol, Any}(:specInitUncertainty => .0, :specInitVal => .0, :specCost => .0, :specReward => .0, :specValuation => .0),
89-
:P => Dict{Symbol, Any}(:prmVal => missing),
90-
:M => Dict{Symbol, Any}(:metaVal => missing)
91-
)
92-
93-
compilable_attrs = filter(attr -> eltype(attr) == SampleableValues, propertynames(ReactionNetwork()))
82+
prettynames = Dict(:transRate => [:rate],
83+
:specInitUncertainty => [:uncertainty, :stoch, :stochasticity],
84+
:transPostAction => [:postAction, :post],
85+
:transName => [:name, :interpretation],
86+
:transPriority => [:priority],
87+
:transProbOfSuccess => [:probability, :prob, :pos],
88+
:transCapacity => [:cap, :capacity],
89+
:transCycleTime => [:ct, :cycletime],
90+
:transMaxLifeTime => [:lifetime, :maxlifetime, :maxtime, :timetolive])
91+
92+
defargs = Dict(:T => Dict{Symbol, Any}(:transPriority => 1, :transProbOfSuccess => 1,
93+
:transCapacity => Inf, :transCycleTime => 0.0,
94+
:transMaxLifeTime => Inf, :transMultiplier => 1,
95+
:transPostAction => :(), :transName => missing),
96+
:S => Dict{Symbol, Any}(:specInitUncertainty => 0.0, :specInitVal => 0.0,
97+
:specCost => 0.0, :specReward => 0.0,
98+
:specValuation => 0.0),
99+
:P => Dict{Symbol, Any}(:prmVal => missing),
100+
:M => Dict{Symbol, Any}(:metaVal => missing))
101+
102+
compilable_attrs = filter(attr -> eltype(attr) == SampleableValues,
103+
propertynames(ReactionNetwork()))
94104

95105
species_modalities = [:nonblock, :conserved, :rate]
96106

@@ -101,26 +111,36 @@ function assign_defaults!(acs::ReactionNetwork)
101111
end
102112
end
103113

104-
foreach(i -> isassigned(subpart(acs, :specModality), i) || (subpart(acs, :specModality)[i] = Set{Symbol}()), 1:nparts(acs, :S))
114+
foreach(i -> isassigned(subpart(acs, :specModality), i) ||
115+
(subpart(acs, :specModality)[i] = Set{Symbol}()), 1:nparts(acs, :S))
105116
k = [:specCost, :specReward, :specValuation]
106-
foreach(k -> foreach(i -> isassigned(subpart(acs, k), i) || (subpart(acs, k)[i] = .0), 1:nparts(acs, :S)), k)
117+
foreach(k -> foreach(i -> isassigned(subpart(acs, k), i) || (subpart(acs, k)[i] = 0.0),
118+
1:nparts(acs, :S)), k)
107119

108120
acs
109121
end
110122

111-
ReactionNetwork(transitions, reactants, obs, events) = merge_acs!(ReactionNetwork(), transitions, reactants, obs, events)
112-
ReactionNetwork(transitions, reactants, obs) = merge_acs!(ReactionNetwork(), transitions, reactants, obs, [])
123+
function ReactionNetwork(transitions, reactants, obs, events)
124+
merge_acs!(ReactionNetwork(), transitions, reactants, obs, events)
125+
end
126+
function ReactionNetwork(transitions, reactants, obs)
127+
merge_acs!(ReactionNetwork(), transitions, reactants, obs, [])
128+
end
113129

114130
function add_obs!(acs, obs)
115-
for p in obs
116-
sym = p.args[3].value; i = incident(acs, sym, :obsName)
117-
i = isempty(incident(acs, sym, :obsName)) ? add_part!(acs, :obs; obsName=sym, obsOpts=FoldedObservable()) : i[1]
131+
for p in obs
132+
sym = p.args[3].value
133+
i = incident(acs, sym, :obsName)
134+
i = isempty(incident(acs, sym, :obsName)) ?
135+
add_part!(acs, :obs; obsName = sym, obsOpts = FoldedObservable()) : i[1]
118136
for opt in p.args[4:end]
119137
if isexpr(opt, :(=)) && (opt.args[1] fieldnames(FoldedObservable))
120-
opt.args[1] == :every && (acs[i, :obsOpts].every = min(acs[i, :obsOpts].every, opt.args[2]))
138+
opt.args[1] == :every &&
139+
(acs[i, :obsOpts].every = min(acs[i, :obsOpts].every, opt.args[2]))
121140
opt.args[1] == :on && union!(acs[i, :obsOpts].on, [opt.args[2]])
122141
elseif isexpr(opt, :tuple) || opt isa SampleableValues
123-
push!(acs[i, :obsOpts].range, isexpr(opt, :tuple) ? tuple(opt.args...) : opt)
142+
push!(acs[i, :obsOpts].range,
143+
isexpr(opt, :tuple) ? tuple(opt.args...) : opt)
124144
end
125145
end
126146
end
@@ -129,24 +149,30 @@ function add_obs!(acs, obs)
129149
end
130150

131151
function merge_acs!(acs::ReactionNetwork, transitions, reactants, obs, events)
132-
foreach(t -> add_part!(acs, :T; trans=t[1][2], transRate=t[1][1], t[2]...), transitions)
133-
add_obs!(acs, obs); unique!(reactants)
134-
foreach(ev -> add_part!(acs, :E; eventTrigger=ev.trigger, eventAction=ev.action), events)
135-
foreach(r -> isempty(incident(acs, r, :specName)) && add_part!(acs, :S; specName=r), reactants)
152+
foreach(t -> add_part!(acs, :T; trans = t[1][2], transRate = t[1][1], t[2]...),
153+
transitions)
154+
add_obs!(acs, obs)
155+
unique!(reactants)
156+
foreach(ev -> add_part!(acs, :E; eventTrigger = ev.trigger, eventAction = ev.action),
157+
events)
158+
foreach(r -> isempty(incident(acs, r, :specName)) && add_part!(acs, :S; specName = r),
159+
reactants)
136160

137161
assign_defaults!(acs)
138162
end
139163

140-
include("state.jl"); include("compilers.jl")
141-
include.(readdir(joinpath(@__DIR__, "interface"), join=true))
142-
include.(readdir(joinpath(@__DIR__, "utils"), join=true))
143-
include.(readdir(joinpath(@__DIR__, "operators"), join=true))
144-
include("solvers.jl"); include("optim.jl")
164+
include("state.jl")
165+
include("compilers.jl")
166+
include.(readdir(joinpath(@__DIR__, "interface"), join = true))
167+
include.(readdir(joinpath(@__DIR__, "utils"), join = true))
168+
include.(readdir(joinpath(@__DIR__, "operators"), join = true))
169+
include("solvers.jl")
170+
include("optim.jl")
145171
include("loadsave.jl")
146172

147173
# Catlab.jl hack: bypass @isdefined check
148174
function Base.getindex(m::Catlab.ColumnImplementations.PartialVecMap, x::Int)
149175
m.v[x]
150176
end
151177

152-
end
178+
end

src/compilers.jl

Lines changed: 67 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -2,20 +2,26 @@ using MacroTools: prewalk
22

33
"Recursively find model variables in expressions."
44
function recursively_find_vars!(r, exs...)
5-
for ex in exs; ex isa Symbol ? push!(r, ex) : (ex isa Expr && recursively_find_vars!(r, ex.args[(!isexpr(ex, :call) ? 1 : 2): end]...)) end
5+
for ex in exs
6+
ex isa Symbol ? push!(r, ex) :
7+
(ex isa Expr &&
8+
recursively_find_vars!(r, ex.args[(!isexpr(ex, :call) ? 1 : 2):end]...))
9+
end
610
r
711
end
812

913
function get_contained_params(ex, prms)
10-
r = []; recursively_find_vars!(r, ex) prms
14+
r = []
15+
recursively_find_vars!(r, ex) prms
1116
end
1217

1318
"Recursively substitute model variables. Subsitution pairs are specified in `varmap`."
1419
function recursively_substitute_vars!(varmap, ex)
1520
ex isa Symbol && return (haskey(varmap, ex) ? varmap[ex] : ex)
1621
ex isa Expr && for i in 1:length(ex.args)
1722
ex.args[i] isa Expr ? recursively_substitute_vars!(varmap, ex.args[i]) :
18-
(ex.args[i] isa Symbol && haskey(varmap, ex.args[i]) && (ex.args[i] = varmap[ex.args[i]]))
23+
(ex.args[i] isa Symbol && haskey(varmap, ex.args[i]) &&
24+
(ex.args[i] = varmap[ex.args[i]]))
1925
end
2026

2127
ex
@@ -27,44 +33,65 @@ function recursively_expand_dots_in_ex!(ex, vars)
2733
expanded = recursively_expand_dots(ex)
2834
return if expanded isa Symbol && expanded in vars
2935
expanded
30-
else recursively_expand_dots_in_ex!.(ex.args, Ref(vars)); ex end
36+
else
37+
recursively_expand_dots_in_ex!.(ex.args, Ref(vars))
38+
ex
39+
end
3140
end
3241
ex isa Expr && for i in 1:length(ex.args)
33-
ex.args[i] isa Union{Expr, Symbol} && (ex.args[i] = recursively_expand_dots_in_ex!(ex.args[i], vars))
42+
ex.args[i] isa Union{Expr, Symbol} &&
43+
(ex.args[i] = recursively_expand_dots_in_ex!(ex.args[i], vars))
3444
end
3545

3646
ex
3747
end
3848

39-
reserved_names = [:t, :state, :obs, :resample, :solverarg, :take, :log, :periodic, :set_params]
49+
reserved_names = [
50+
:t,
51+
:state,
52+
:obs,
53+
:resample,
54+
:solverarg,
55+
:take,
56+
:log,
57+
:periodic,
58+
:set_params,
59+
]
4060
push!(reserved_names, :state)
4161

4262
function escape_ref(ex, species)
43-
ex isa Symbol ? ex : prewalk(ex -> isexpr(ex, :ref) && Symbol(string(ex)) species ? Symbol(string(ex)) : ex, ex)
63+
ex isa Symbol ? ex :
64+
prewalk(ex -> isexpr(ex, :ref) && Symbol(string(ex)) species ? Symbol(string(ex)) : ex,
65+
ex)
4466
end
4567

4668
function wrap_expr(fex, species_names, prm_names, varmap)
4769
!isa(fex, Union{Expr, Symbol}) && return fex
4870
# escape refs in species names: A[1] -> Symbol("A[1]")
4971
fex = escape_ref(fex, species_names)
5072
# escape dots in species' names: A.B -> Symbol("A.B")
51-
fex = deepcopy(fex); fex = recursively_expand_dots_in_ex!(fex, species_names)
73+
fex = deepcopy(fex)
74+
fex = recursively_expand_dots_in_ex!(fex, species_names)
5275

5376
# prepare the function's body
54-
letex = :(let; end)
77+
letex = :(let
78+
end)
5579
# expression walking (MacroTools): visit each expression, subsitute with the body's return value
5680
fex = prewalk(fex) do x
5781
# here we convert the query metalanguage: @t() -> time(state) etc.
5882
if isexpr(x, :macrocall) && (macroname(x) reserved_names)
5983
Expr(:call, macroname(x), :state, x.args[3:end]...)
60-
else x end
84+
else
85+
x
86+
end
6187
end
6288

6389
# substitute the species names with "pointers" into the state space: S -> state.u[1]
6490
fex = recursively_substitute_vars!(varmap, fex)
6591
# substitute the params names with "pointers" into the parameter space: β -> state.p[:β]
6692
# params can't be mutated!
67-
foreach(v -> push!(letex.args[1].args, :($v = state.p[$(QuoteNode(v))])), get_contained_params(fex, prm_names))
93+
foreach(v -> push!(letex.args[1].args, :($v = state.p[$(QuoteNode(v))])),
94+
get_contained_params(fex, prm_names))
6895
push!(letex.args[2].args, fex)
6996

7097
# the function shall be a function of the dynamic ReactiveDynamicsState structure: letex -> :(state -> $letex)
@@ -73,40 +100,55 @@ function wrap_expr(fex, species_names, prm_names, varmap)
73100
end
74101

75102
function get_wrap_fun(acs::ReactionNetwork)
76-
species_names = collect(acs[:, :specName]); prm_names = collect(acs[:, :prmName])
103+
species_names = collect(acs[:, :specName])
104+
prm_names = collect(acs[:, :prmName])
77105
varmap = Dict([name => :(state.u[$i]) for (i, name) in enumerate(species_names)])
78-
for name in prm_names push!(varmap, name => :(state.p[$(QuoteNode(name))])) end
79-
106+
for name in prm_names
107+
push!(varmap, name => :(state.p[$(QuoteNode(name))]))
108+
end
109+
80110
ex -> wrap_expr(ex, species_names, prm_names, varmap)
81111
end
82112

83-
skip_compile(attr) = any(contains.(Ref(string(attr)), ("Name", "obs", "meta"))) || (string(attr) == "trans")
113+
function skip_compile(attr)
114+
any(contains.(Ref(string(attr)), ("Name", "obs", "meta"))) || (string(attr) == "trans")
115+
end
84116

85117
function compile_attrs(acs::ReactionNetwork)
86-
species_names = collect(acs[:, :specName]); prm_names = collect(acs[:, :prmName])
118+
species_names = collect(acs[:, :specName])
119+
prm_names = collect(acs[:, :prmName])
87120
varmap = Dict([name => :(state.u[$i]) for (i, name) in enumerate(species_names)])
88-
for name in prm_names push!(varmap, name => :(state.p[$(QuoteNode(name))])) end
121+
for name in prm_names
122+
push!(varmap, name => :(state.p[$(QuoteNode(name))]))
123+
end
89124
wrap_fun = ex -> wrap_expr(ex, species_names, prm_names, varmap)
90-
attrs = Dict{Symbol, Vector}(); transitions = Dict{Symbol, Vector}()
125+
attrs = Dict{Symbol, Vector}()
126+
transitions = Dict{Symbol, Vector}()
91127
for attr in propertynames(acs.subparts)
92128
attrs_ = subpart(acs, attr)
93129
!contains(string(attr), "trans") ?
94-
(attrs[attr] = map(i -> skip_compile(attr) ? attrs_[i] : wrap_fun(attrs_[i]), 1:length(attrs_))) :
95-
(transitions[attr] = map(i -> skip_compile(attr) ? attrs_[i] : wrap_fun(attrs_[i]), 1:length(attrs_)))
130+
(attrs[attr] = map(i -> skip_compile(attr) ? attrs_[i] : wrap_fun(attrs_[i]),
131+
1:length(attrs_))) :
132+
(transitions[attr] = map(i -> skip_compile(attr) ? attrs_[i] : wrap_fun(attrs_[i]),
133+
1:length(attrs_)))
96134
end
97135
transitions[:transActivated] = fill(true, nparts(acs, :T))
98136
transitions[:transToSpawn] = zeros(nparts(acs, :T))
99-
transitions[:transHash] = [coalesce(acs[i, :transName], gensym()) for i in 1:nparts(acs, :T)]
137+
transitions[:transHash] = [coalesce(acs[i, :transName], gensym())
138+
for i in 1:nparts(acs, :T)]
100139

101140
attrs, transitions, wrap_fun
102141
end
103142

104143
function remove_choose(acs::ReactionNetwork)
105-
acs = deepcopy(acs); pcs = []
144+
acs = deepcopy(acs)
145+
pcs = []
106146
for attr in propertynames(acs.subparts)
107147
attrs_ = subpart(acs, attr)
108-
foreach(i -> isassigned(attrs_, i) && attrs_[i] isa Expr && (attrs_[i] = normalize_pcs!(pcs, attrs_[i])), 1:length(attrs_))
148+
foreach(i -> isassigned(attrs_, i) && attrs_[i] isa Expr &&
149+
(attrs_[i] = normalize_pcs!(pcs, attrs_[i])), 1:length(attrs_))
109150
end
110151

111-
add_obs!(acs, pcs); acs
112-
end
152+
add_obs!(acs, pcs)
153+
acs
154+
end

0 commit comments

Comments
 (0)