Skip to content

Commit

Permalink
Merge pull request #249 from SciML/format
Browse files Browse the repository at this point in the history
format SciML style
  • Loading branch information
Vaibhavdixit02 authored Jun 24, 2022
2 parents 3f1da73 + a9d5219 commit c983590
Show file tree
Hide file tree
Showing 16 changed files with 680 additions and 612 deletions.
1 change: 1 addition & 0 deletions .JuliaFormatter.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
style = "sciml"
42 changes: 42 additions & 0 deletions .github/workflows/FormatCheck.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
name: format-check

on:
push:
branches:
- 'master'
- 'release-'
tags: '*'
pull_request:

jobs:
build:
runs-on: ${{ matrix.os }}
strategy:
matrix:
julia-version: [1]
julia-arch: [x86]
os: [ubuntu-latest]
steps:
- uses: julia-actions/setup-julia@latest
with:
version: ${{ matrix.julia-version }}

- uses: actions/checkout@v1
- name: Install JuliaFormatter and format
# This will use the latest version by default but you can set the version like so:
#
# julia -e 'using Pkg; Pkg.add(PackageSpec(name="JuliaFormatter", version="0.13.0"))'
run: |
julia -e 'using Pkg; Pkg.add(PackageSpec(name="JuliaFormatter"))'
julia -e 'using JuliaFormatter; format(".", verbose=true)'
- name: Format check
run: |
julia -e '
out = Cmd(`git diff --name-only`) |> read |> String
if out == ""
exit(0)
else
@error "Some files have not been formatted !!!"
write(stdout, out)
exit(1)
end'
28 changes: 11 additions & 17 deletions docs/make.jl
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,14 @@ using Documenter, DiffEqBayes

include("pages.jl")

makedocs(
sitename="DiffEqBayes.jl",
authors="Chris Rackauckas, Vaibhav Kumar Dixit et al.",
clean=true,
doctest=false,
modules=[DiffEqBayes],

format=Documenter.HTML(assets=["assets/favicon.ico"],
canonical="https://diffeqbayes.sciml.ai/stable/"),

pages=pages
)

deploydocs(
repo="github.com/SciML/DiffEqBayes.jl.git";
push_preview=true
)
makedocs(sitename = "DiffEqBayes.jl",
authors = "Chris Rackauckas, Vaibhav Kumar Dixit et al.",
clean = true,
doctest = false,
modules = [DiffEqBayes],
format = Documenter.HTML(assets = ["assets/favicon.ico"],
canonical = "https://diffeqbayes.sciml.ai/stable/"),
pages = pages)

deploydocs(repo = "github.com/SciML/DiffEqBayes.jl.git";
push_preview = true)
8 changes: 4 additions & 4 deletions docs/pages.jl
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
pages = [
"DiffEqBayes.jl: Bayesian Parameter Estimation for Differential Equations" => "index.md",
"Methods" => "methods.md",
"Examples" => "examples.md"
]
"DiffEqBayes.jl: Bayesian Parameter Estimation for Differential Equations" => "index.md",
"Methods" => "methods.md",
"Examples" => "examples.md",
]
8 changes: 5 additions & 3 deletions src/DiffEqBayes.jl
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,10 @@ using RecursiveArrayTools, ModelingToolkit, LinearAlgebra
using Parameters, Distributions, Optim, Requires
using Distances, DocStringExtensions, Random, StanSample

STANDARD_PROB_GENERATOR(prob,p) = remake(prob;u0=eltype(p).(prob.u0),p=p)
STANDARD_PROB_GENERATOR(prob::EnsembleProblem,p) = EnsembleProblem(remake(prob.prob;u0=eltype(p).(prob.prob.u0),p=p))
STANDARD_PROB_GENERATOR(prob, p) = remake(prob; u0 = eltype(p).(prob.u0), p = p)
function STANDARD_PROB_GENERATOR(prob::EnsembleProblem, p)
EnsembleProblem(remake(prob.prob; u0 = eltype(p).(prob.prob.u0), p = p))
end

include("turing_inference.jl")
# include("abc_inference.jl")
Expand All @@ -25,5 +27,5 @@ function __init__()
end
end

export turing_inference, stan_inference ,abc_inference
export turing_inference, stan_inference, abc_inference
end # module
29 changes: 17 additions & 12 deletions src/abc_inference.jl
Original file line number Diff line number Diff line change
@@ -1,37 +1,42 @@
function createabcfunction(prob, t, distancefunction, alg; save_idxs = nothing, sample_u0 = false, kwargs...)
function createabcfunction(prob, t, distancefunction, alg; save_idxs = nothing,
sample_u0 = false, kwargs...)
function simfunc(params, constants, data)
local u0
if sample_u0
u0 = save_idxs === nothing ? params[1:length(prob.u0)] : params[1:length(save_idxs)]
u0 = save_idxs === nothing ? params[1:length(prob.u0)] :
params[1:length(save_idxs)]
if length(u0) < length(prob.u0)
for i in length(u0):length(prob.u0)
push!(u0,prob.u0[i])
push!(u0, prob.u0[i])
end
end
else
u0 = prob.u0
end
sol = solve(prob, alg, u0=u0, p=params, saveat = t, save_idxs = save_idxs, kwargs...)
sol = solve(prob, alg, u0 = u0, p = params, saveat = t, save_idxs = save_idxs,
kwargs...)
if size(sol, 2) < length(t)
return Inf,nothing
return Inf, nothing
else
simdata = convert(Array, sol)
return distancefunction(data, simdata), nothing
end
end
end

function abc_inference(prob::DiffEqBase.DEProblem, alg, t, data, priors; ϵ=0.001,
distancefunction = euclidean, ABCalgorithm = ABCSMC, progress = false,
num_samples = 500, maxiterations = 10^5, save_idxs = nothing, sample_u0 = false, parallel = false, kwargs...)

abcsetup = ABCalgorithm(createabcfunction(prob, t, distancefunction, alg; save_idxs = save_idxs, sample_u0 = sample_u0, kwargs...),
function abc_inference(prob::DiffEqBase.DEProblem, alg, t, data, priors; ϵ = 0.001,
distancefunction = euclidean, ABCalgorithm = ABCSMC,
progress = false,
num_samples = 500, maxiterations = 10^5, save_idxs = nothing,
sample_u0 = false, parallel = false, kwargs...)
abcsetup = ABCalgorithm(createabcfunction(prob, t, distancefunction, alg;
save_idxs = save_idxs, sample_u0 = sample_u0,
kwargs...),
length(priors),
ϵ,
ApproxBayes.Prior(priors);
nparticles = num_samples,
maxiterations = maxiterations
)
maxiterations = maxiterations)

abcresult = runabc(abcsetup, data, progress = progress, parallel = parallel)
return abcresult
Expand Down
37 changes: 24 additions & 13 deletions src/dynamichmc_inference.jl
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ For a common use case, see [`dynamichmc_inference`](@ref).
# Fields
$(FIELDS)
"""
Base.@kwdef struct DynamicHMCPosterior{TA,TP,TD,TT,TR,TS,TK,TI}
Base.@kwdef struct DynamicHMCPosterior{TA, TP, TD, TT, TR, TS, TK, TI}
"Algorithm for the ODE solver."
algorithm::TA
"An ODE problem definition (`DiffEqBase.DEProblem`)."
Expand Down Expand Up @@ -40,16 +40,18 @@ function (P::DynamicHMCPosterior)(θ)
u0 = convert.(T, sample_u0 ? parameters[1:nu] : problem.u0)
p = convert.(T, sample_u0 ? parameters[(nu + 1):end] : parameters)
if length(u0) < length(problem.u0)
# assumes u is ordered such that the observed variables are in the begining, consistent with ordered theta
for i in length(u0):length(problem.u0)
push!(u0, convert(T,problem.u0[i]))
end
# assumes u is ordered such that the observed variables are in the begining, consistent with ordered theta
for i in length(u0):length(problem.u0)
push!(u0, convert(T, problem.u0[i]))
end
end
_saveat = t === nothing ? Float64[] : t
sol = solve(problem, algorithm; u0=u0, p=p, saveat = _saveat, save_idxs = save_idxs, solve_kwargs...)
sol = solve(problem, algorithm; u0 = u0, p = p, saveat = _saveat, save_idxs = save_idxs,
solve_kwargs...)
failure = size(sol, 2) < length(_saveat)
failure && return T(0) * sum(σ) + T(-Inf)
log_likelihood = sum(sum(map(logpdf, Normal.(0.0, σ), sol[:, i] .- data[:, i])) for (i, t) in enumerate(t))
log_likelihood = sum(sum(map(logpdf, Normal.(0.0, σ), sol[:, i] .- data[:, i]))
for (i, t) in enumerate(t))
log_prior_parameters = sum(map(logpdf, parameter_priors, parameters))
log_prior_σ = sum(map(logpdf, σ_priors, σ))
log_likelihood + log_prior_parameters + log_prior_σ
Expand Down Expand Up @@ -91,17 +93,26 @@ posterior values (transformed from `ℝⁿ`).
- `mcmc_kwargs` are passed on as keyword arguments to `DynamicHMC.mcmc_with_warmup`
"""
function dynamichmc_inference(problem::DiffEqBase.DEProblem, algorithm, t, data,
parameter_priors, parameter_transformations=as(Vector, asℝ₊, length(parameter_priors));
σ_priors = fill(Normal(0, 5), size(data, 1)),sample_u0 = false, rng = Random.GLOBAL_RNG,
num_samples = 1000, AD_gradient_kind = Val(:ForwardDiff), save_idxs = nothing,solve_kwargs = (),
mcmc_kwargs = (initialization = (q = zeros(length(parameter_priors) + (save_idxs === nothing ? length(data[:,1]) : length(save_idxs))),),))
parameter_priors,
parameter_transformations = as(Vector, asℝ₊,
length(parameter_priors));
σ_priors = fill(Normal(0, 5), size(data, 1)),
sample_u0 = false, rng = Random.GLOBAL_RNG,
num_samples = 1000, AD_gradient_kind = Val(:ForwardDiff),
save_idxs = nothing, solve_kwargs = (),
mcmc_kwargs = (initialization = (q = zeros(length(parameter_priors) +
(save_idxs ===
nothing ?
length(data[:, 1]) :
length(save_idxs))),),))
P = DynamicHMCPosterior(; algorithm = algorithm, problem = problem, t = t, data = data,
parameter_priors = parameter_priors, σ_priors = σ_priors,
solve_kwargs = solve_kwargs, sample_u0 = sample_u0, save_idxs = save_idxs)
solve_kwargs = solve_kwargs, sample_u0 = sample_u0,
save_idxs = save_idxs)
trans = as((parameters = parameter_transformations,
σ = as(Vector, asℝ₊, length(σ_priors))))
= TransformedLogDensity(trans, P)
∇ℓ = LogDensityProblems.ADgradient(AD_gradient_kind, ℓ)
results = mcmc_with_warmup(rng, ∇ℓ, num_samples; mcmc_kwargs...)
merge((posterior = TransformVariables.transform.(Ref(trans), results.chain), ), results)
merge((posterior = TransformVariables.transform.(Ref(trans), results.chain),), results)
end
Loading

0 comments on commit c983590

Please sign in to comment.