licenses
sequencelengths
1
3
version
stringclasses
677 values
tree_hash
stringlengths
40
40
path
stringclasses
1 value
type
stringclasses
2 values
size
stringlengths
2
8
text
stringlengths
25
67.1M
package_name
stringlengths
2
41
repo
stringlengths
33
86
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
701
# example copied from th0br0 with modifications using CmdStan y = collect(1:100); x = [3:3:300 5:5:500]; model = """ data { int<lower = 0> N; int<lower = 0> k; matrix[N, k] x; real<lower=0> y[N]; } parameters { vector[k] beta; real<lower=0> sigma; } model { y ~ normal(x * beta, sigma); } """; # beta parameters are accessed using beta.[1-9+] syntax data = Dict("N"=>100, "k" => 2, "x" => x, "y" => y); stanmodel = Stanmodel(monitors = ["beta.1", "beta.2", "sigma"], model=model, output_format=:mcmcchains); rc, sim, cnames = stan(stanmodel, data; diagnostics = false); cnames |> display # 3-element Array{String,1}: "beta.1", "beta.2" ,"sigma" println() describe(sim)
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
982
using CmdStan ProjDir = @__DIR__ cd(ProjDir) shared_file = "shared_funcs.stan" bernoulli_model = " functions{ #include $(shared_file) //#include shared_funcs.stan // a comment //#include shared_funcs.stan // a comment //#include /Users/rob/shared_funcs.stan // a comment void model_specific_function(){ real x = 1.0; return; } } data { int<lower=1> N; int<lower=0,upper=1> y[N]; } parameters { real<lower=0,upper=1> theta; } model { model_specific_function(); theta ~ beta(my_function(),1); y ~ bernoulli(theta); } "; observeddata = Dict("N" => 10, "y" => [0, 1, 0, 1, 0, 0, 0, 0, 0, 1]) tmpdir = ProjDir*"/tmp" stanmodel = Stanmodel(name="bernoulli", model=bernoulli_model, printsummary=true, tmpdir=tmpdir); rc, chn, cnames = stan(stanmodel, observeddata, ProjDir); if rc == 0 # Ceate a summary df summary_df = read_summary(stanmodel) summary_df[:, [:mean, :ess]] end
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
1258
# Experimental threads example. WIP! using CmdStan #using Distributed using Statistics using StatsBase: sample ProjDir = mktempdir() cd(ProjDir) #do bernoullimodel = " data { int<lower=1> N; int<lower=0,upper=1> y[N]; } parameters { real<lower=0,upper=1> theta; } model { theta ~ beta(1,1); y ~ bernoulli(theta); } "; n = 10; observeddata = Dict("N" => n, "y" => sample([0,1],n)) sm = Stanmodel(name="bernoulli", model=bernoullimodel; output_format=:namedtuple); println("\nThreads loop\n") p1 = 16 # p1 is the number of models to fit estimates = Vector(undef, p1) Threads.@threads for i in 1:p1 pdir = pwd() while ispath(pdir) pdir = tempname() end println(pdir) new_model= deepcopy(sm) new_model.pdir = pdir new_model.tmpdir = joinpath(splitpath(pdir)...,"tmp") mkpath(new_model.tmpdir) CmdStan.update_model_file(joinpath(new_model.tmpdir, "$(new_model.name).stan"), strip(new_model.model)) rc, samples, cnames = stan(new_model, observeddata, new_model.pdir; # summary=false ); if rc == 0 estimates[i] = [mean(reshape(samples.theta, 4000)), std(reshape(samples.theta, 4000))] end #rm(pdir; force=true, recursive=true) end estimates |> display #end
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
1002
# Experimental threads example. WIP! using CmdStan using Statistics using Distributions ProjDir = @__DIR__ cd(ProjDir) #do bernoullimodel = " data { int<lower=1> N; int<lower=0,upper=1> y[N]; } parameters { real<lower=0,upper=1> theta; } model { theta ~ beta(1,1); y ~ bernoulli(theta); } "; #isdir(ProjDir * "/tmp") && rm(ProjDir * "/tmp", recursive=true) tmpdir = ProjDir * "/tmp" p1 = 24 # p1 is the number of models to fit n = 100; p = range(0, stop=1, length=p1) observeddata = [Dict("N" => n, "y" => Int.(rand(Bernoulli(p[i]), n))) for i in 1:p1] sm = [Stanmodel(name="bernoulli_m$i", model=bernoullimodel; output_format=:namedtuple, tmpdir=tmpdir) for i in 1:p1] println("\nThreads loop\n") estimates = Vector(undef, p1) Threads.@threads for i in 1:p1 rc, samples, cnames = stan(sm[i], observeddata[i]; summary=false); if rc == 0 estimates[i] = [mean(reshape(samples.theta, 4000)), std(reshape(samples.theta, 4000))] end end estimates |> display #end
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
1019
######################################################################## #Load Stan Model ######################################################################## using CmdStan, Test, Statistics ProjDir = dirname(@__FILE__) println(ProjDir) cd(ProjDir) do bernoullimodel = " data { int<lower=1> N; int<lower=0,upper=1> y[N]; real empty[0]; } parameters { real<lower=0,upper=1> theta; } model { theta ~ beta(1,1); y ~ bernoulli(theta); } " observeddata = Dict("N" => 10, "y" => [0, 1, 0, 1, 0, 0, 0, 0, 0, 1],"empty"=>Float64[]) global stanmodel, rc, sim stanmodel = Stanmodel(num_samples=1200, thin=2, name="bernoulli", output_format=:array, model=bernoullimodel); rc, sim = stan(stanmodel, [observeddata], ProjDir, diagnostics=false, CmdStanDir=CMDSTAN_HOME); if rc == 0 println() println("Test round(mean(theta), digits=1) β‰ˆ 0.3") @test round(mean(sim[:,8,:]), digits=1) β‰ˆ 0.3 end end # cd
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
4597
import DiffEqBayes: stan_inference import DiffEqBayes: StanModel, StanODEData, generate_priors, generate_theta function stan_inference(prob::DiffEqBase.DEProblem, t, data, priors=nothing, stanmodel=nothing; alg=:rk45, num_samples=1000, num_warmup=1000, reltol=1e-3, abstol=1e-6, maxiter=Int(1e5),likelihood=Normal, vars=(StanODEData(),InverseGamma(3,3)),nchains=1, sample_u0 = false, save_idxs = nothing, diffeq_string = nothing, printsummary = true) save_idxs !== nothing && length(save_idxs) == 1 ? save_idxs = save_idxs[1] : save_idxs = save_idxs length_of_y = length(prob.u0) save_idxs = something(save_idxs, 1:length_of_y) length_of_params = length(vars) if isnothing(diffeq_string) sys = first(ModelingToolkit.modelingtoolkitize(prob)) length_of_parameter = length(sys.ps) + sample_u0 * length(save_idxs) else length_of_parameter = length(prob.p) + sample_u0 * length(save_idxs) end if alg ==:rk45 algorithm = "integrate_ode_rk45" elseif alg == :bdf algorithm = "integrate_ode_bdf" else error("The choices for alg are :rk45 or :bdf") end hyper_params = "" tuple_hyper_params = "" setup_params = "" thetas = "" theta_string = generate_theta(length_of_parameter,priors) for i in 1:length_of_parameter thetas = string(thetas,"theta[$i] = theta$i",";") end for i in 1:length_of_params if isa(vars[i], StanODEData) tuple_hyper_params = string(tuple_hyper_params,"u_hat[t,$save_idxs]",",") else dist = stan_string(vars[i]) hyper_params = string(hyper_params,"sigma$(i-1) ~ $dist;") tuple_hyper_params = string(tuple_hyper_params,"sigma$(i-1)",",") setup_params = string(setup_params,"row_vector<lower=0>[$(length(save_idxs))] sigma$(i-1);") end end tuple_hyper_params = tuple_hyper_params[1:length(tuple_hyper_params)-1] priors_string = string(generate_priors(length_of_parameter,priors)) stan_likelihood = stan_string(likelihood) if sample_u0 nu = length(save_idxs) if nu < length(prob.u0) u0 = "{" for u_ in prob.u0[nu+1:length(prob.u0)] u0 = u0*string(u_) end u0 = u0*"}" integral_string = "u_hat = $algorithm(sho, append_array(theta[1:$nu],$u0), t0, ts, theta[$(nu+1):$length_of_parameter], x_r, x_i, $reltol, $abstol, $maxiter);" else integral_string = "u_hat = $algorithm(sho, theta[1:$nu], t0, ts, theta[$(nu+1):$length_of_parameter], x_r, x_i, $reltol, $abstol, $maxiter);" end else integral_string = "u_hat = $algorithm(sho, u0, t0, ts, theta, x_r, x_i, $reltol, $abstol, $maxiter);" end binsearch_string = """ int bin_search(real x, int min_val, int max_val){ int range = (max_val - min_val + 1) / 2; int mid_pt = min_val + range; int out; while (range > 0) { if (x == mid_pt) { out = mid_pt; range = 0; } else { range = (range + 1) / 2; mid_pt = x > mid_pt ? mid_pt + range: mid_pt - range; } } return out; } """ if isnothing(diffeq_string) diffeq_string = ModelingToolkit.build_function( sys.eqs,sys.states, sys.ps,sys.iv, fname = :sho, target = ModelingToolkit.StanTarget() ) end parameter_estimation_model = " functions { $binsearch_string $diffeq_string } data { real u0[$length_of_y]; int<lower=1> T; real internal_var___u[T,$(length(save_idxs))]; real t0; real ts[T]; } transformed data { real x_r[0]; int x_i[0]; } parameters { $setup_params $theta_string } transformed parameters{ real theta[$length_of_parameter]; $thetas } model{ real u_hat[T,$length_of_y]; $hyper_params $priors_string $integral_string for (t in 1:T){ internal_var___u[t,:] ~ $stan_likelihood($tuple_hyper_params); } } generated quantities{ real u_hat[T,2]; u_hat = integrate_ode_rk45(sho, u0, t0, ts, theta, x_r, x_i, 0.001, 1.0e-6, 100000); } " if isnothing(stanmodel) stanmodel = CmdStan.Stanmodel(num_samples=num_samples, num_warmup=num_warmup, name="pem", model=parameter_estimation_model, nchains=nchains, printsummary = printsummary) end parameter_estimation_data = Dict("u0"=>prob.u0, "T" => length(t), "internal_var___u" => view(data, :, 1:length(t))', "t0" => prob.tspan[1], "ts" => t) return_code, chains, cnames = CmdStan.stan(stanmodel, [parameter_estimation_data]; CmdStanDir=CMDSTAN_HOME) return StanModel(stanmodel, return_code, chains, cnames) end
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
2364
using CmdStan, DiffEqBayes, OrdinaryDiffEq, ParameterizedFunctions, ModelingToolkit, RecursiveArrayTools, Distributions, Random, Test # Uncomment for local testing only, make sure MCMCChains and StatsPlots are available using MCMCChains, StatsPlots #Random.seed!(123) cd(@__DIR__) isdir("tmp") && rm("tmp", recursive=true) include("../../stan_inference.jl") println("\nFour parameter case\n") f1 = @ode_def begin dx = a*x - b*x*y dy = -c*y + d*x*y end a b c d u0 = [1.0,1.0] tspan = (0.0,10.0) p = [1.5,1.0,3.0,1.0] prob1 = ODEProblem(f1,u0,tspan,p) sol = solve(prob1,Tsit5()) t = collect(range(1,stop=10,length=10)) randomized = VectorOfArray([(sol(t[i]) + 0.5randn(2)) for i in 1:length(t)]) data = convert(Array,randomized) priors = [truncated(Normal(1.0,1),0.1,2),truncated(Normal(1.5,0.5),0.1,1.5), truncated(Normal(2.0,1),0.1,4),truncated(Normal(1.3,0.5),0.1,2)] bayesian_result = stan_inference(prob1,t,data,priors;num_samples=2000, nchains=4, num_warmup=1000,vars =(DiffEqBayes.StanODEData(),InverseGamma(4,1))) sdf = CmdStan.read_summary(bayesian_result.model) @test sdf[sdf.parameters .== :theta1, :mean][1] β‰ˆ 1.5 atol=5e-1 @test sdf[sdf.parameters .== :theta2, :mean][1] β‰ˆ 1.0 atol=5e-1 @test sdf[sdf.parameters .== :theta3, :mean][1] β‰ˆ 3.0 atol=5e-1 @test sdf[sdf.parameters .== :theta4, :mean][1] β‰ˆ 1.0 atol=5e-1 # Uncomment for local chain inspection chn = CmdStan.convert_a3d(bayesian_result.chains, bayesian_result.cnames, Val(:mcmcchains)) plot(chn) savefig("$(@__DIR__)/four_par_case.png") v1 = [sdf[sdf.parameters .== Symbol("u_hat[$i,1]"), :mean][1] for i in 1:10] v2 = [sdf[sdf.parameters .== Symbol("u_hat[$i,2]"), :mean][1] for i in 1:10] qa_prey = zeros(10, 3); qa_pred = zeros(10, 3); achn = Array(chn); for i in 1:10 qa_prey[i, :] = quantile(achn[:, 10+i], [0.055, 0.5, 0.945]) qa_pred[i, :] = quantile(achn[:, 20+i], [0.055, 0.5, 0.945]) end p1 = plot(1:10, v1; ribbon=(qa_prey[:, 1], qa_prey[:, 3]), color=:lightgrey, leg=false) title!("Prey u_hat 89% quantiles") plot!(v1, lab="prey", xlab="time", ylab="prey", color=:darkred) p2 = plot(1:10, v2; ribbon=(qa_pred[:, 1], qa_pred[:, 3]), color=:lightgrey, leg=false) title!("Preditors u_hat 89% quantiles") plot!(v2, lab="pred", xlab="time", ylab="preditors", color=:darkblue) plot(p1, p2, layout=(2,1)) savefig("$(@__DIR__)/four_par_pred_prey.png")
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
6576
using CmdStan, DiffEqBayes, OrdinaryDiffEq, ParameterizedFunctions, ModelingToolkit, RecursiveArrayTools, Distributions, Random, Test # Uncomment for local testing only, make sure MCMCChains and StatsPlots are available using MCMCChains, StatsPlots #Random.seed!(123) cd(@__DIR__) isdir("tmp") && rm("tmp", recursive=true) include("../../stan_inference.jl") println("\nOne parameter case 1\n") f1 = @ode_def begin dx = a*x - x*y dy = -3y + x*y end a u0 = [1.0,1.0] tspan = (0.0,10.0) p = [1.5] prob1 = ODEProblem(f1,u0,tspan,p) sol = solve(prob1,Tsit5()) t = collect(range(1,stop=10,length=10)) randomized = VectorOfArray([(sol(t[i]) + .5randn(2)) for i in 1:length(t)]) data = convert(Array,randomized) priors = [truncated(Normal(0.7,1),0.1,2)] bayesian_result = stan_inference(prob1,t,data,priors;num_samples=2000, nchains=4, num_warmup=1000,likelihood=Normal) sdf = CmdStan.read_summary(bayesian_result.model) @test sdf[sdf.parameters .== :theta1, :mean][1] β‰ˆ 1.5 atol=3e-1 # Uncomment for local chain inspection chn = CmdStan.convert_a3d(bayesian_result.chains, bayesian_result.cnames, Val(:mcmcchains)) plot(chn) !isdir("tmp") && mkdir("tmp") savefig("$(@__DIR__)/one_par_case_01.png") v1 = [sdf[sdf.parameters .== Symbol("u_hat[$i,1]"), :mean][1] for i in 1:10] v2 = [sdf[sdf.parameters .== Symbol("u_hat[$i,2]"), :mean][1] for i in 1:10] qa_prey = zeros(10, 3); qa_pred = zeros(10, 3); achn = Array(chn); for i in 1:10 qa_prey[i, :] = quantile(achn[:, 4+i], [0.055, 0.5, 0.945]) qa_pred[i, :] = quantile(achn[:, 14+i], [0.055, 0.5, 0.945]) end p1 = plot(1:10, v1; ribbon=(qa_prey[:, 1], qa_prey[:, 3]), color=:lightgrey, leg=false) title!("Prey u_hat 89% quantiles") plot!(v1, lab="prey", xlab="time", ylab="prey", color=:darkred) p2 = plot(1:10, v2; ribbon=(qa_pred[:, 1], qa_pred[:, 3]), color=:lightgrey, leg=false) title!("Preditors u_hat 89% quantiles") plot!(v2, lab="pred", xlab="time", ylab="preditors", color=:darkblue) plot(p1, p2, layout=(2,1)) savefig("$(@__DIR__)/one_par_pred_prey_01.png") println("\nOne parameter case 2\n") priors = [ truncated(Normal(1.,0.5), 0.1, 3), truncated(Normal(1.,0.5), 0.1, 3), truncated(Normal(1.5,0.5), 0.1, 4) ] bayesian_result = stan_inference(prob1,t,data,priors;num_samples=2000, nchains=4, num_warmup=1000,likelihood=Normal,sample_u0=true) sdf = CmdStan.read_summary(bayesian_result.model) @test sdf[sdf.parameters .== :theta1, :mean][1] β‰ˆ 1. atol=3e-1 @test sdf[sdf.parameters .== :theta2, :mean][1] β‰ˆ 1. atol=3e-1 @test sdf[sdf.parameters .== :theta3, :mean][1] β‰ˆ 1.5 atol=3e-1 # Uncomment for local chain inspection chn = CmdStan.convert_a3d(bayesian_result.chains, bayesian_result.cnames, Val(:mcmcchains)) plot(chn) !isdir("tmp") && mkdir("tmp") savefig("$(@__DIR__)/one_par_case_02.png") v1 = [sdf[sdf.parameters .== Symbol("u_hat[$i,1]"), :mean][1] for i in 1:10] v2 = [sdf[sdf.parameters .== Symbol("u_hat[$i,2]"), :mean][1] for i in 1:10] qa_prey = zeros(10, 3); qa_pred = zeros(10, 3); achn = Array(chn); for i in 1:10 qa_prey[i, :] = quantile(achn[:, 8+i], [0.055, 0.5, 0.945]) qa_pred[i, :] = quantile(achn[:, 18+i], [0.055, 0.5, 0.945]) end p1 = plot(1:10, v1; ribbon=(qa_prey[:, 1], qa_prey[:, 3]), color=:lightgrey, leg=false) title!("Prey u_hat 89% quantiles") plot!(v1, lab="prey", xlab="time", ylab="prey", color=:darkred) p2 = plot(1:10, v2; ribbon=(qa_pred[:, 1], qa_pred[:, 3]), color=:lightgrey, leg=false) title!("Preditors u_hat 89% quantiles") plot!(v2, lab="pred", xlab="time", ylab="preditors", color=:darkblue) plot(p1, p2, layout=(2,1)) savefig("$(@__DIR__)/one_par_pred_prey_02.png") println("\nOne parameter case 3\n") sol = solve(prob1,Tsit5(),save_idxs=[1]) randomized = VectorOfArray([(sol(t[i]) + .01 * randn(1)) for i in 1:length(t)]) data = convert(Array,randomized) priors = [truncated(Normal(1.5,0.5), 0.1,2)] bayesian_result = stan_inference(prob1,t,data,priors;num_samples=2000, nchains=4, num_warmup=1000,likelihood=Normal,save_idxs=[1]) sdf = CmdStan.read_summary(bayesian_result.model) @test sdf[sdf.parameters .== :theta1, :mean][1] β‰ˆ 1.5 atol=3e-1 # Uncomment for local chain inspection chn = CmdStan.convert_a3d(bayesian_result.chains, bayesian_result.cnames, Val(:mcmcchains)) plot(chn) savefig("$(@__DIR__)/one_par_case_03.png") v1 = [sdf[sdf.parameters .== Symbol("u_hat[$i,1]"), :mean][1] for i in 1:10] v2 = [sdf[sdf.parameters .== Symbol("u_hat[$i,2]"), :mean][1] for i in 1:10] qa_prey = zeros(10, 3); qa_pred = zeros(10, 3); achn = Array(chn); for i in 1:10 qa_prey[i, :] = quantile(achn[:, 3+i], [0.055, 0.5, 0.945]) qa_pred[i, :] = quantile(achn[:, 13+i], [0.055, 0.5, 0.945]) end p1 = plot(1:10, v1; ribbon=(qa_prey[:, 1], qa_prey[:, 3]), color=:lightgrey, leg=false) title!("Prey u_hat 89% quantiles") plot!(v1, lab="prey", xlab="time", ylab="prey", color=:darkred) p2 = plot(1:10, v2; ribbon=(qa_pred[:, 1], qa_pred[:, 3]), color=:lightgrey, leg=false) title!("Preditors u_hat 89% quantiles") plot!(v2, lab="pred", xlab="time", ylab="preditors", color=:darkblue) plot(p1, p2, layout=(2,1)) savefig("$(@__DIR__)/one_par_pred_prey_03.png") println("\nOne parameter case 4\n") priors = [truncated(Normal(1.,0.5), 0.1, 3), truncated(Normal(1.5,0.5), 0.1, 4)] bayesian_result = stan_inference(prob1,t,data,priors;num_samples=2000, nchains=4, num_warmup=1000,likelihood=Normal,save_idxs=[1],sample_u0=true) sdf = CmdStan.read_summary(bayesian_result.model) @test sdf[sdf.parameters .== :theta1, :mean][1] β‰ˆ 1. atol=3e-1 @test sdf[sdf.parameters .== :theta2, :mean][1] β‰ˆ 1.5 atol=3e-1 # Uncomment for local chain inspection chn = CmdStan.convert_a3d(bayesian_result.chains, bayesian_result.cnames, Val(:mcmcchains)) plot(chn) savefig("$(@__DIR__)/one_par_case_04.png") v1 = [sdf[sdf.parameters .== Symbol("u_hat[$i,1]"), :mean][1] for i in 1:10] v2 = [sdf[sdf.parameters .== Symbol("u_hat[$i,2]"), :mean][1] for i in 1:10] qa_prey = zeros(10, 3); qa_pred = zeros(10, 3); achn = Array(chn); for i in 1:10 qa_prey[i, :] = quantile(achn[:, 4+i], [0.055, 0.5, 0.945]) qa_pred[i, :] = quantile(achn[:, 14+i], [0.055, 0.5, 0.945]) end p1 = plot(1:10, v1; ribbon=(qa_prey[:, 1], qa_prey[:, 3]), color=:lightgrey, leg=false) title!("Prey u_hat 89% quantiles") plot!(v1, lab="prey", xlab="time", ylab="prey", color=:darkred) p2 = plot(1:10, v2; ribbon=(qa_pred[:, 1], qa_pred[:, 3]), color=:lightgrey, leg=false) title!("Preditors u_hat 89% quantiles") plot!(v2, lab="pred", xlab="time", ylab="preditors", color=:darkblue) plot(p1, p2, layout=(2,1)) savefig("$(@__DIR__)/one_par_pred_prey_04.png")
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
4300
using DiffEqBayes, CmdStan, DynamicHMC, DataFrames using Distributions, BenchmarkTools, Random using OrdinaryDiffEq, RecursiveArrayTools, ParameterizedFunctions using StatsPlots gr(size=(600,900)) ProjDir = @__DIR__ cd(ProjDir) isdir("tmp") && rm("tmp", recursive=true) include("../stan_inference.jl") f = @ode_def LotkaVolterraTest begin dx = a*x - b*x*y dy = -c*y + d*x*y end a b c d u0 = [1.0,1.0] tspan = (0.0,10.0) p = [1.5,1.0,3.0,1,0] prob = ODEProblem(f,u0,tspan,p) sol = solve(prob,Tsit5()) t = collect(range(1,stop=10,length=30)) sig = 0.49 data = convert(Array, VectorOfArray([(sol(t[i]) + sig*randn(2)) for i in 1:length(t)])) scatter(t, data[1,:], lab="#prey (data)") scatter!(t, data[2,:], lab="#predator (data)") plot!(sol) savefig("$(ProjDir)/fig_01.png") priors = [truncated(Normal(1.5,0.5),0.1,3.0),truncated(Normal(1.2,0.5),0.1,2), truncated(Normal(3.0,0.5),1,4),truncated(Normal(1.0,0.5),0.1,2)] # Stan.jl backend #The solution converges for tolerance values lower than 1e-3, lower tolerance #leads to better accuracy in result but is accompanied by longer warmup and #sampling time, truncated normal priors are used for preventing Stan from stepping into negative values. nchains = 4 num_samples = 800 @time bayesian_result_stan = stan_inference(prob,t,data,priors, num_samples=num_samples, printsummary=false, nchains=4); sdf1 = CmdStan.read_summary(bayesian_result_stan.model) println() @time bayesian_result_stan = stan_inference(prob,t,data, priors,bayesian_result_stan.model, num_samples=num_samples, printsummary=false, nchains=4) sdf2 = CmdStan.read_summary(bayesian_result_stan.model) println() cnames = ["theta1", "theta2", "theta3", "theta4", "sigma1", "sigma2", ] df = CmdStan.convert_a3d(bayesian_result_stan.chains, bayesian_result_stan.cnames, Val(:dataframes)); df_stan = append!(append!(df[1], df[2]), append!(df[3], df[4])); df_stan = df_stan[:, [10, 11, 12, 13, 8, 9]] rename!(df_stan, Symbol.(cnames)) # DynamicHMC.jl backend @time bayesian_result_dynamichmc = dynamichmc_inference(prob,Tsit5(),t,data,priors, num_samples=Int(4*num_samples)); N = length(bayesian_result_dynamichmc.posterior) res_array = zeros(N, 6); for i in 1:length(bayesian_result_dynamichmc.posterior) res_array[i,:] = vcat( bayesian_result_dynamichmc.posterior[i].parameters, bayesian_result_dynamichmc.posterior[i].Οƒ ) end df_dhmc = DataFrame( :theta1 => res_array[:, 1], :theta2 => res_array[:, 2], :theta3 => res_array[:, 3], :theta4 => res_array[:, 4], :sigma1 => res_array[:, 5], :sigma2 => res_array[:, 6] ) sdf1 |> display sdf2 |> display println("\nDhmc results\n") mean(res_array, dims=1) |> display std(res_array, dims=1) |> display println() function plot_theta_results( dfs::DataFrame, dfd::DataFrame, varn::AbstractString, idx::Int, priors=priors ) prior_theta = Symbol("prior_"*varn*string(idx)) theta = Symbol(varn*string(idx)) prior_theta_array = rand(priors[idx], size(dfs, 1)) p1 = plot(prior_theta_array, xlab="prior_theta_$idx", leg=false) p2 = density(prior_theta_array, xlab="prior_theta_$idx", leg=false) p3 = plot(dfs[:, theta], xlab="theta_$idx", lab="stan") plot!(dfs[:, theta], lab="dhmc") p4 = density(dfs[:, theta], xlab="theta_$idx", lab="stan") density!(dfd[:, theta], lab="dhmc") p5 = density(dfs[:, :sigma1], xlab="sigma1", lab="stan") density!(dfd[:, :sigma1], lab="dhmc") p6 = density(dfs[:, :sigma2], xlab="sigma2", lab="stan") density!(dfd[:, :sigma2], lab="dhmc") plot(p1, p2, p3, p4, p5, p6, layout=(3,2)) savefig("$(ProjDir)/$(varn)_$idx") end for i in 1:4 plot_theta_results(df_stan, df_dhmc, "theta", i, priors) end original_stan_results =" mean se_mean sd 10% 50% 90% n_eff Rhat theta[1] 0.549 0.002 0.065 0.469 0.545 0.636 1163 1 theta[2] 0.028 0.000 0.004 0.023 0.028 0.034 1281 1 theta[3] 0.797 0.003 0.091 0.684 0.791 0.918 1125 1 theta[4] 0.024 0.000 0.004 0.020 0.024 0.029 1170 1 sigma[1] 0.248 0.001 0.045 0.198 0.241 0.306 2625 1 sigma[2] 0.252 0.001 0.044 0.201 0.246 0.310 2808 1 z_init[1] 33.960 0.056 2.909 30.363 33.871 37.649 2684 1 z_init[2] 5.949 0.011 0.533 5.294 5.926 6.644 2235 1 ";
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
3864
using DiffEqBayes, CmdStan, DynamicHMC, DataFrames using Distributions, BenchmarkTools using OrdinaryDiffEq, RecursiveArrayTools, ParameterizedFunctions using StatsPlots, CSV gr(size=(600,900)) ProjDir = @__DIR__ cd(ProjDir) isdir("tmp") && rm("tmp", recursive=true) include("../stan_inference.jl") df = CSV.read("$(ProjDir)/../lynx_hare.csv", DataFrame; delim=",") f = @ode_def LotkaVolterraTest begin dx = a*x - b*x*y dy = -c*y + d*x*y end a b c d u0 = [30.0, 4.0] tspan = (0.0, 21.0) p = [0.55, 0.028, 0.84, 0.026] prob = ODEProblem(f,u0,tspan,p) sol = solve(prob,Tsit5()) t = collect(range(1,stop=20,length=20)) sig = 0.49 data = convert(Array, VectorOfArray([(sol(t[i]) + sig*randn(2)) for i in 1:length(t)])) scatter(t, data[1,:], lab="#prey (data)") scatter!(t, data[2,:], lab="#predator (data)") plot!(sol) savefig("$(ProjDir)/fig_01.png") priors = [truncated(Normal(1,0.5),0.1,3),truncated(Normal(0.05,0.05),0,2), truncated(Normal(1,0.5),0.1,4),truncated(Normal(0.05,0.05),0,2)] # Stan.jl backend #The solution converges for tolerance values lower than 1e-3, lower tolerance #leads to better accuracy in result but is accompanied by longer warmup and #sampling time, truncated normal priors are used for preventing Stan from stepping into negative values. nchains = 4 num_samples = 800 @time bayesian_result_stan = stan_inference(prob,t,data,priors, num_samples=num_samples, printsummary=false, nchains=nchains); sdf1 = CmdStan.read_summary(bayesian_result_stan.model) println() @time bayesian_result_stan = stan_inference(prob,t,data, priors, bayesian_result_stan.model, num_samples=num_samples, printsummary=false, nchains=nchains); sdf2 = CmdStan.read_summary(bayesian_result_stan.model) println() cnames = ["theta1", "theta2", "theta3", "theta4", "sigma1", "sigma2", ] df = CmdStan.convert_a3d(bayesian_result_stan.chains, bayesian_result_stan.cnames, Val(:dataframes)); df_stan = append!(append!(df[1], df[2]), append!(df[3], df[4])); df_stan = df_stan[:, [10, 11, 12, 13, 8, 9]] rename!(df_stan, Symbol.(cnames)) sdf1 |> display sdf2 |> display #= # DynamicHMC.jl backend @time bayesian_result_dynamichmc = dynamichmc_inference(prob,Tsit5(),t,data,priors, num_samples=Int(4*num_samples)); N = length(bayesian_result_dynamichmc.posterior) res_array = zeros(N, 6); for i in 1:length(bayesian_result_dynamichmc.posterior) res_array[i,:] = vcat( bayesian_result_dynamichmc.posterior[i].parameters, bayesian_result_dynamichmc.posterior[i].Οƒ ) end df_dhmc = DataFrame( :theta1 => res_array[:, 1], :theta2 => res_array[:, 2], :theta3 => res_array[:, 3], :theta4 => res_array[:, 4], :sigma1 => res_array[:, 5], :sigma2 => res_array[:, 6] ) println("\nDhmc results\n") mean(res_array, dims=1) |> display std(res_array, dims=1) |> display println() =# function plot_theta_results( dfs::DataFrame, dfd::DataFrame, varn::AbstractString, idx::Int, priors=priors ) prior_theta = Symbol("prior_"*varn*string(idx)) theta = Symbol(varn*string(idx)) prior_theta_array = rand(priors[idx], size(dfs, 1)) p1 = plot(prior_theta_array, xlab="prior_theta_$idx", leg=false) p2 = density(prior_theta_array, xlab="prior_theta_$idx", leg=false) p3 = plot(dfs[:, theta], xlab="theta_$idx", lab="stan") #plot!(dfs[:, theta], lab="dhmc") p4 = density(dfs[:, theta], xlab="theta_$idx", lab="stan") #density!(dfd[:, theta], lab="dhmc") p5 = density(dfs[:, :sigma1], xlab="sigma1", lab="stan") #density!(dfd[:, :sigma1], lab="dhmc") p6 = density(dfs[:, :sigma2], xlab="sigma2", lab="stan") #density!(dfd[:, :sigma2], lab="dhmc") #plot(p1, p2, p3, p4, p5, p6, layout=(3,2)) plot(p1, p2, p3, p4, layout=(2, 2)) savefig("$(ProjDir)/$(varn)_$idx") end df_dhmc = DataFrame() for i in 1:4 plot_theta_results(df_stan, df_dhmc, "theta", i, priors) end
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
2423
using DiffEqBayes, CmdStan, DynamicHMC, DataFrames using Distributions, BenchmarkTools using OrdinaryDiffEq, RecursiveArrayTools, ParameterizedFunctions using StatsPlots, CSV gr(size=(600,900)) ProjDir = @__DIR__ cd(ProjDir) isdir("tmp") && rm("tmp", recursive=true) include("../stan_inference.jl") df = CSV.read("$(ProjDir)/../lynx_hare.csv", DataFrame; delim=",") f = @ode_def LotkaVolterraTest begin dx = a*x - b*x*y dy = -c*y + d*x*y end a b c d u0 = [30.0, 4.0] tspan = (0.0, 21.0) p = [0.55, 0.028, 0.84, 0.026] prob = ODEProblem(f,u0,tspan,p) sol = solve(prob,Tsit5()) t = collect(range(1,stop=20,length=20)) data = transpose(hcat(df[2:end, :Hare], df[2:end, :Lynx])) scatter(t, data[1,:], lab="#prey (data)") scatter!(t, data[2,:], lab="#predator (data)") plot!(sol) savefig("$(ProjDir)/fig_01.png") priors = [truncated(Normal(1,0.5),0.1,3),truncated(Normal(0.05,0.1),0,2), truncated(Normal(1,0.5),0.1,4),truncated(Normal(0.05,0.1),0,2)] nchains = 4 num_samples = 800 @time bayesian_result_stan = stan_inference(prob,t,data,priors, num_samples=num_samples, printsummary=false, nchains=nchains); sdf1 = CmdStan.read_summary(bayesian_result_stan.model) println() @time bayesian_result_stan = stan_inference(prob,t,data, priors,bayesian_result_stan.model, num_samples=num_samples, printsummary=false, nchains=nchains); sdf2 = CmdStan.read_summary(bayesian_result_stan.model) println() cnames = ["theta1", "theta2", "theta3", "theta4", "sigma1", "sigma2", ] df = CmdStan.convert_a3d(bayesian_result_stan.chains, bayesian_result_stan.cnames, Val(:dataframes)); df_stan = append!(append!(df[1], df[2]), append!(df[3], df[4])); df_stan = df_stan[:, [10, 11, 12, 13, 8, 9]] rename!(df_stan, Symbol.(cnames)) function plot_theta_results( dfs::DataFrame, varn::AbstractString, idx::Int, priors=priors ) prior_theta = Symbol("prior_"*varn*string(idx)) theta = Symbol(varn*string(idx)) prior_theta_array = rand(priors[idx], size(dfs, 1)) p1 = plot(prior_theta_array, xlab="prior_theta_$idx", leg=false) p2 = density(prior_theta_array, xlab="prior_theta_$idx", leg=false) p3 = plot(dfs[:, theta], xlab="theta_$idx", lab="stan") p4 = density(dfs[:, theta], xlab="theta_$idx", lab="stan") plot(p1, p2, p3, p4, layout=(2,2)) savefig("$(ProjDir)/$(varn)_$idx") end for i in 1:4 plot_theta_results(df_stan, "theta", i, priors) end sdf2 |> display
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
4515
using DiffEqBayes, CmdStan, DynamicHMC, DataFrames using Distributions, BenchmarkTools using OrdinaryDiffEq, RecursiveArrayTools, ParameterizedFunctions using ModelingToolkit using StatsPlots, CSV gr(size=(600,900)) ProjDir = @__DIR__ cd(ProjDir) isdir("tmp") && rm("tmp", recursive=true) include("../stan_inference.jl") Random.seed!(123) df = CSV.read("$(ProjDir)/../lynx_hare.csv", DataFrame; delim=",") f = @ode_def LotkaVolterraTest begin dx = a*x - b*x*y dy = -c*y + d*x*y end a b c d u0 = [30.0, 4.0] tspan = (0.0, 21.0) p = [0.55, 0.028, 0.84, 0.026] prob = ODEProblem(f,u0,tspan,p) sol = solve(prob,Tsit5()) t = collect(range(1,stop=20,length=20)) sig = 0.3 data = convert(Array, VectorOfArray([(sol(t[i]) + sig*randn(2)) for i in 1:length(t)])) #data = transpose(hcat(df[2:end, :Hare], df[2:end, :Lynx])) scatter(t, data[1,:], lab="#prey (data)") scatter!(t, data[2,:], lab="#predator (data)") plot!(sol) savefig("$(ProjDir)/fig_01.png") priors = [Truncated(Normal(1,0.5),0,3),Truncated(Normal(0.05,0.05),0,2), Truncated(Normal(1,0.5),0,3),Truncated(Normal(0.05,0.05),0,2)] # Stan.jl backend #The solution converges for tolerance values lower than 1e-3, lower tolerance #leads to better accuracy in result but is accompanied by longer warmup and #sampling time, truncated normal priors are used for preventing Stan from stepping into negative values. nchains = 4 num_samples = 800 @time bayesian_result_stan = stan_inference(prob,t,data,priors, num_samples=num_samples, printsummary=false, nchains=nchains); sdf1 = CmdStan.read_summary(bayesian_result_stan.model) println() @time bayesian_result_stan = stan_inference(prob,t,data, priors, bayesian_result_stan.model, num_samples=num_samples, printsummary=false, nchains=nchains); sdf2 = CmdStan.read_summary(bayesian_result_stan.model) println() cnames = ["theta1", "theta2", "theta3", "theta4", "sigma1", "sigma2", ] df = CmdStan.convert_a3d(bayesian_result_stan.chains, bayesian_result_stan.cnames, Val(:dataframes)); df_stan = append!(append!(df[1], df[2]), append!(df[3], df[4])); df_stan = df_stan[:, [10, 11, 12, 13, 8, 9]] rename!(df_stan, Symbol.(cnames)) sdf1 |> display sdf2 |> display # DynamicHMC.jl backend @time bayesian_result_dynamichmc = dynamichmc_inference(prob,Tsit5(),t,data,priors, num_samples=Int(4*num_samples)); N = length(bayesian_result_dynamichmc.posterior) res_array = zeros(N, 6); for i in 1:length(bayesian_result_dynamichmc.posterior) res_array[i,:] = vcat( bayesian_result_dynamichmc.posterior[i].parameters, bayesian_result_dynamichmc.posterior[i].Οƒ ) end df_dhmc = DataFrame( :theta1 => res_array[:, 1], :theta2 => res_array[:, 2], :theta3 => res_array[:, 3], :theta4 => res_array[:, 4], :sigma1 => res_array[:, 5], :sigma2 => res_array[:, 6] ) println("\nDhmc results\n") mean(res_array, dims=1) |> display std(res_array, dims=1) |> display println() function plot_theta_results( dfs::DataFrame, dfd::DataFrame, varn::AbstractString, idx::Int, priors=priors ) prior_theta = Symbol("prior_"*varn*string(idx)) theta = Symbol(varn*string(idx)) prior_theta_array = rand(priors[idx], size(dfs, 1)) p1 = plot(prior_theta_array, xlab="prior_theta_$idx", leg=false) p2 = density(prior_theta_array, xlab="prior_theta_$idx", leg=false) p3 = plot(dfs[:, theta], xlab="theta_$idx", lab="stan") plot!(dfs[:, theta], lab="dhmc") p4 = density(dfs[:, theta], xlab="theta_$idx", lab="stan") density!(dfd[:, theta], lab="dhmc") p5 = density(dfs[:, :sigma1], xlab="sigma1", lab="stan") density!(dfd[:, :sigma1], lab="dhmc") p6 = density(dfs[:, :sigma2], xlab="sigma2", lab="stan") density!(dfd[:, :sigma2], lab="dhmc") plot(p1, p2, p3, p4, p5, p6, layout=(3,2)) savefig("$(ProjDir)/$(varn)_$idx") end for i in 1:4 plot_theta_results(df_stan, df_dhmc, "theta", i, priors) end stan_results = " mean se_mean sd 10% 50% 90% n_eff Rhat theta[1] 0.549 0.002 0.065 0.469 0.545 0.636 1163 1 theta[2] 0.028 0.000 0.004 0.023 0.028 0.034 1281 1 theta[3] 0.797 0.003 0.091 0.684 0.791 0.918 1125 1 theta[4] 0.024 0.000 0.004 0.020 0.024 0.029 1170 1 sigma[1] 0.248 0.001 0.045 0.198 0.241 0.306 2625 1 sigma[2] 0.252 0.001 0.044 0.201 0.246 0.310 2808 1 z_init[1] 33.960 0.056 2.909 30.363 33.871 37.649 2684 1 z_init[2] 5.949 0.011 0.533 5.294 5.926 6.644 2235 1 ";
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
1265
######### CmdStan program example ########### using CmdStan using MCMCChains ProjDir = dirname(@__FILE__) cd(ProjDir) do bernoullimodel = " data { int<lower=1> N; int<lower=0,upper=1> y[N]; } parameters { real<lower=0,upper=1> theta; } model { theta ~ beta(1,1); y ~ bernoulli(theta); } "; observeddata = Dict("N" => 10, "y" => [0, 1, 0, 1, 0, 0, 0, 0, 0, 1]) global stanmodel, rc, chn, chns, cnames, summary_df tmpdir = ProjDir*"/tmp" stanmodel = Stanmodel(Sample(save_warmup=false, num_warmup=1000, num_samples=2000, thin=1), name="bernoulli", model=bernoullimodel, printsummary=false, tmpdir=tmpdir, output_format=:mcmcchains); rc, chns, cnames = stan(stanmodel, observeddata, ProjDir, diagnostics=false, CmdStanDir=CMDSTAN_HOME); if rc == 0 # Check if StatsPlots is available if isdefined(Main, :StatsPlots) p1 = plot(chns) savefig(p1, joinpath(tmpdir, "traceplot.pdf")) p2 = pooleddensity(chns) savefig(p2, joinpath(tmpdir, "pooleddensity.pdf")) end # Describe the results show(chns) println() # Ceate a ChainDataFrame sdf = read_summary(stanmodel) sdf[sdf.parameters .== :theta, [:mean, :ess]] end end # cd
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
1969
######### CmdStan batch program example ########### using CmdStan, MCMCChains ProjDir = dirname(@__FILE__) cd(ProjDir) do dyes =" data { int BATCHES; int SAMPLES; real y[BATCHES, SAMPLES]; // vector[SAMPLES] y[BATCHES]; } parameters { real<lower=0> tau_between; real<lower=0> tau_within; real theta; real mu[BATCHES]; } transformed parameters { real sigma_between; real sigma_within; sigma_between <- 1/sqrt(tau_between); sigma_within <- 1/sqrt(tau_within); } model { theta ~ normal(0.0, 1E5); tau_between ~ gamma(.001, .001); tau_within ~ gamma(.001, .001); mu ~ normal(theta, sigma_between); for (n in 1:BATCHES) y[n] ~ normal(mu[n], sigma_within); } generated quantities { real sigmasq_between; real sigmasq_within; sigmasq_between <- 1 / tau_between; sigmasq_within <- 1 / tau_within; } " dyesdata = Dict("BATCHES" => 6, "SAMPLES" => 5, "y" => reshape([ [1545, 1540, 1595, 1445, 1595]; [1520, 1440, 1555, 1550, 1440]; [1630, 1455, 1440, 1490, 1605]; [1595, 1515, 1450, 1520, 1560]; [1510, 1465, 1635, 1480, 1580]; [1495, 1560, 1545, 1625, 1445] ], 6, 5) ) global stanmodel, rc, sim, cnames, chns stanmodel = Stanmodel(name="dyes", model=dyes, output_format=:mcmcchains); @time rc, sim, cnames = stan(stanmodel, dyesdata, ProjDir, CmdStanDir=CMDSTAN_HOME) if rc == 0 pi = filter(p -> length(p) > 2 && p[end-1:end] == "__", cnames) p = filter(p -> !(p in pi), cnames) chns = set_section(sim, Dict( :parameters => ["theta", "tau_between", "tau_within", "sigma_between", "sigma_within", "sigmasq_between", "sigmasq_within"], :mu => ["mu.$i" for i in 1:6], :internals => pi ) ) show(chns) describe(chns, sections=[:mu]) end end # cd
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
2130
######### CmdStan batch program example ########### using CmdStan, MCMCChains, StatsPlots ProjDir = dirname(@__FILE__) cd(ProjDir) do eightschools =" data { int<lower=0> J; // number of schools real y[J]; // estimated treatment effects real<lower=0> sigma[J]; // s.e. of effect estimates } parameters { real mu; real<lower=0> tau; real eta[J]; } transformed parameters { real theta[J]; for (j in 1:J) theta[j] <- mu + tau * eta[j]; } model { eta ~ normal(0, 1); y ~ normal(theta, sigma); } " schools8data = Dict("J" => 8, "y" => [28, 8, -3, 7, -1, 1, 18, 12], "sigma" => [15, 10, 16, 11, 9, 11, 10, 18], "tau" => 25 ) global stanmodel, rc, chn, chns, cnames, tmpdir tmpdir = mktempdir() stanmodel = Stanmodel(name="schools8", model=eightschools, output_format=:mcmcchains, tmpdir=tmpdir); rc, chn, cnames = stan(stanmodel, schools8data, ProjDir, CmdStanDir=CMDSTAN_HOME) if rc == 0 chn1 = Chains(chn.value, [ "accept_stat__", "divergent__", "energy__", "eta[1]", "eta[2]", "eta[3]", "eta[4]", "eta[5]", "eta[6]", "eta[7]", "eta[8]", "lp__", "mu", "n_leapfrog__", "stepsize__", "tau", "theta[1]", "theta[2]", "theta[3]", "theta[4]", "theta[5]", "theta[6]", "theta[7]", "theta[8]", "treedepth__" ] ) chns = set_section(chn1, Dict( :parameters => ["mu", "tau"], :thetas => ["theta[$i]" for i in 1:8], :etas => ["eta[$i]" for i in 1:8], :internals => ["lp__", "accept_stat__", "stepsize__", "treedepth__", "n_leapfrog__", "divergent__", "energy__"] ) ) show(chns) println("\n") summarize(chns, sections=[:thetas]) if isdefined(Main, :StatsPlots) p1 = plot(chns) savefig(p1, joinpath(tmpdir, "traceplot.pdf")) df = DataFrame(chns, [:thetas]) p2 = plot(df[!, Symbol("theta[1]")]) savefig(p2, joinpath(tmpdir, "theta_1.pdf")) end end end # cd
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
947
######### CmdStan program example ########### using CmdStan ProjDir = dirname(@__FILE__) cd(ProjDir) do bernoullimodel = " data { int<lower=1> N; int<lower=0,upper=1> y[N]; } parameters { real<lower=0,upper=1> theta; } model { theta ~ beta(1,1); y ~ bernoulli(theta); } "; observeddata = Dict("N" => 10, "y" => [0, 1, 0, 1, 0, 0, 0, 0, 0, 1]) global stanmodel, rc, chn, nt, cnames, sdf tmpdir = ProjDir*"/tmp" stanmodel = Stanmodel(Sample(save_warmup=false, num_warmup=1000, num_samples=2000, thin=1), name="bernoulli", model=bernoullimodel, printsummary=false, tmpdir=tmpdir, output_format=:namedtuple); rc, nt, cnames = stan(stanmodel, observeddata, ProjDir, diagnostics=false, CmdStanDir=CMDSTAN_HOME); if rc == 0 display(nt) # Ceate a ChainDataFrame sdf = read_summary(stanmodel) sdf[sdf.parameters .== :theta, [:mean, :ess]] end end # cd
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
1624
######### CmdStan batch program example ########### using CmdStan ProjDir = dirname(@__FILE__) cd(ProjDir) do dyes =" data { int BATCHES; int SAMPLES; real y[BATCHES, SAMPLES]; // vector[SAMPLES] y[BATCHES]; } parameters { real<lower=0> tau_between; real<lower=0> tau_within; real theta; real mu[BATCHES]; } transformed parameters { real sigma_between; real sigma_within; sigma_between <- 1/sqrt(tau_between); sigma_within <- 1/sqrt(tau_within); } model { theta ~ normal(0.0, 1E5); tau_between ~ gamma(.001, .001); tau_within ~ gamma(.001, .001); mu ~ normal(theta, sigma_between); for (n in 1:BATCHES) y[n] ~ normal(mu[n], sigma_within); } generated quantities { real sigmasq_between; real sigmasq_within; sigmasq_between <- 1 / tau_between; sigmasq_within <- 1 / tau_within; } " dyesdata = Dict("BATCHES" => 6, "SAMPLES" => 5, "y" => reshape([ [1545, 1540, 1595, 1445, 1595]; [1520, 1440, 1555, 1550, 1440]; [1630, 1455, 1440, 1490, 1605]; [1595, 1515, 1450, 1520, 1560]; [1510, 1465, 1635, 1480, 1580]; [1495, 1560, 1545, 1625, 1445] ], 6, 5) ) global stanmodel, rc, nt stanmodel = Stanmodel(name="dyes", model=dyes, output_format=:namedtuple); @time rc, nt, cnames = stan(stanmodel, dyesdata, ProjDir, CmdStanDir=CMDSTAN_HOME) if rc == 0 #pi = filter(p -> length(p) > 2 && p[end-1:end] == "__", cnames) #p = filter(p -> !(p in pi), cnames) display(nt) end end # cd
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
1002
######### CmdStan batch program example ########### using CmdStan ProjDir = dirname(@__FILE__) cd(ProjDir) do eightschools =" data { int<lower=0> J; // number of schools real y[J]; // estimated treatment effects real<lower=0> sigma[J]; // s.e. of effect estimates } parameters { real mu; real<lower=0> tau; real eta[J]; } transformed parameters { real theta[J]; for (j in 1:J) theta[j] <- mu + tau * eta[j]; } model { eta ~ normal(0, 1); y ~ normal(theta, sigma); } " schools8data = Dict("J" => 8, "y" => [28, 8, -3, 7, -1, 1, 18, 12], "sigma" => [15, 10, 16, 11, 9, 11, 10, 18], "tau" => 25 ) global stanmodel, rc, nt tmpdir = mktempdir() stanmodel = Stanmodel(name="schools8", model=eightschools, output_format=:namedtuple, tmpdir=tmpdir); rc, nt, cnames = stan(stanmodel, schools8data, ProjDir, CmdStanDir=CMDSTAN_HOME) if rc == 0 display(nt.theta) end end # cd
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
2658
module CmdStan using Requires using DocStringExtensions: FIELDS, SIGNATURES, TYPEDEF """ The directory which contains the cmdstan executables such as `bin/stanc` and `bin/stansummary`. Inferred from the environment variable `JULIA_CMDSTAN_HOME` or `ENV["JULIA_CMDSTAN_HOME"]` when available. If these are not available, use `set_cmdstan_home!` to set the value of CMDSTAN_HOME. Example: `set_cmdstan_home!(homedir() * "/Projects/Stan/cmdstan/")` Executing `versioninfo()` will display the value of `JULIA_CMDSTAN_HOME` if defined. """ CMDSTAN_HOME="" function __init__() global CMDSTAN_HOME = if isdefined(Main, :JULIA_CMDSTAN_HOME) Main.JULIA_CMDSTAN_HOME elseif haskey(ENV, "JULIA_CMDSTAN_HOME") ENV["JULIA_CMDSTAN_HOME"] elseif haskey(ENV, "CMDSTAN_HOME") ENV["CMDSTAN_HOME"] else @warn("Environment variable CMDSTAN_HOME not set. Use set_cmdstan_home!.") "" end @require MCMCChains="c7f686f2-ff18-58e9-bc7b-31028e88f75d" include("utilities/require_mcmcchains.jl") end """Set the path for the `CMDSTAN_HOME` environment variable. Example: `set_cmdstan_home!(homedir() * "/Projects/Stan/cmdstan/")` """ set_cmdstan_home!(path) = global CMDSTAN_HOME=path const src_path = @__DIR__ """ # `rel_path_cmdstan` Relative path using the CmdStan.jl src directory. This approach has been copied from [DynamicHMCExamples.jl](https://github.com/tpapp/DynamicHMCExamples.jl) ### Example to get access to the data subdirectory ```julia rel_path_cmdstan("..", "data") ``` """ rel_path_cmdstan(parts...) = normpath(joinpath(src_path, parts...)) include("main/stanmodel.jl") include("main/stancode.jl") # preprocessing include("utilities/update_model_file.jl") include("utilities/create_r_files.jl") include("utilities/create_cmd_line.jl") # run cmdstan include("utilities/parallel.jl") # used in postprocessing include("utilities/read_samples.jl") include("utilities/read_variational.jl") include("utilities/read_diagnose.jl") include("utilities/read_optimize.jl") include("utilities/convert_a3d.jl") include("utilities/stan_summary.jl") include("utilities/read_summary.jl") include("utilities/findall.jl") include("utilities/extract.jl") # type definitions include("types/sampletype.jl") include("types/optimizetype.jl") include("types/diagnosetype.jl") include("types/variationaltype.jl") export # from this file set_cmdstan_home!, CMDSTAN_HOME, rel_path_cmdstan, # From stanmodel.jl Stanmodel, # From stancode.jl stan, # From sampletype.jl Sample, # From optimizetype.jl Optimize, # From diagnosetype.jl Diagnose, # From variationaltype.jl Variational, # From read_summary.jl read_summary end # module
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
8593
""" # stan Execute a Stan model. ### Method ```julia rc, sim, cnames = stan( model::Stanmodel, data=Nothing, ProjDir=pwd(); init=Nothing, summary=true, diagnostics=false, CmdStanDir=CMDSTAN_HOME, file_run_log=true ) ``` ### Required arguments ```julia * `model::Stanmodel` : See ?Method ``` ### Optional positional arguments ```julia * `data=Nothing` : Observed input data dictionary * `ProjDir=pwd()` : Project working directory ``` ### Keyword arguments ```julia * `init=Nothing` : Initial parameter value dictionary * `summary=true` : Use CmdStan's stansummary to display results * `diagnostics=false` : Generate diagnostics file * `CmdStanDir=CMDSTAN_HOME` : Location of cmdstan directory * `file_run_log=true` : Create run log file (if false, write log to stdout) * `file_make_log=true` : Create make log file (if false, write log to stdout) ``` If the type the `data` or `init` arguments are an AbstartcString this is interpreted as a path name to an existing .R file. This file is copied to the coresponding .R data and/or init files for for each chain. ### Return values ```julia * `rc::Int` : Return code from stan(), rc == 0 if all is well * `samples` : Samples * `cnames` : Vector of variable names ``` ### Examples ```julia # no data, use default ProjDir (pwd) stan(mymodel) # default ProjDir (pwd) stan(mymodel, mydata) # specify ProjDir stan(mymodel, mydata, "~/myproject/") # keyword arguments stan(mymodel, mydata, "~/myproject/", diagnostics=true, summary=false) # use default ProjDir (pwd), with keyword arguments stan(mymodel, mydata, diagnostics=true, summary=false) ``` ### Related help ```julia ?Stanmodel : Create a StanModel ``` """ function stan( model::Stanmodel, data=Nothing, ProjDir=pwd(); init=Nothing, summary=true, diagnostics=false, CmdStanDir=CMDSTAN_HOME, file_run_log=true, file_make_log=true) # old = pwd() local rc = 0 local res = Dict[] cnames = String[] if length(model.model) == 0 println("\nNo proper model specified in \"$(model.name).stan\".") println("This file is typically created from a String passed to Stanmodel().\n") return((-1, res)) end @assert isdir(ProjDir) "Incorrect ProjDir specified: $(ProjDir)" @assert isdir(model.tmpdir) "$(model.tmpdir) not created" local tmpmodelname::String tmpmodelname = joinpath(model.tmpdir, model.name) file_paths = [ joinpath(tmpmodelname * "_build.log"), joinpath(tmpmodelname * "_make.log"), joinpath(tmpmodelname * "_run.log")] for path in file_paths isfile(path) && rm(path) end if @static Sys.iswindows() ? true : false tmpmodelname = replace(tmpmodelname*".exe", "\\" => "/") end try cmd = setenv(`make $(tmpmodelname)`, ENV; dir=CmdStanDir) if file_make_log run(pipeline(cmd, stdout="$(tmpmodelname)_make.log", stderr="$(tmpmodelname)_build.log")) else run(pipeline(cmd, stderr="$(tmpmodelname)_build.log")) end catch println("\nAn error occurred while compiling the Stan program.\n") print("Please check your Stan program in variable '$(model.name)' ") print("and the contents of $(tmpmodelname)_build.log.\n") println("Note that Stan does not handle blanks in path names.") error("Return code = -3"); end if data != Nothing && (typeof(data) <: AbstractString || check_dct_type(data)) if typeof(data) <: AbstractString data_path = isabspath(data) ? data : joinpath(model.tmpdir, data) for i in 1:model.nchains cp(data_path, joinpath(model.tmpdir, "$(model.name)_$(i).data.R"), force=true) end else if typeof(data) <: Array && length(data) == model.nchains for i in 1:model.nchains if length(keys(data[i])) > 0 update_R_file(joinpath(model.tmpdir, "$(model.name)_$(i).data.R"), data[i]) end end else if typeof(data) <: Array for i in 1:model.nchains if length(keys(data[1])) > 0 update_R_file(joinpath(model.tmpdir, "$(model.name)_$(i).data.R"), data[1]) end end else for i in 1:model.nchains if length(keys(data)) > 0 update_R_file(joinpath(model.tmpdir, "$(model.name)_$(i).data.R"), data) end end end end end end if init != Nothing && (typeof(init) <: AbstractString || check_dct_type(init)) if typeof(init) <: AbstractString init_str = isabspath(init) ? init : joinpath(model.tmpdir, init) for i in 1:model.nchains cp(init_str, joinpath(model.tmpdir, "$(model.name)_$(i).init.R"), force=true) end else if typeof(init) <: Array && length(init) == model.nchains for i in 1:model.nchains if length(keys(init[i])) > 0 update_R_file(joinpath(model.tmpdir, "$(model.name)_$(i).init.R"), init[i]) end end else if typeof(init) <: Array for i in 1:model.nchains if length(keys(init[1])) > 0 update_R_file(joinpath(model.tmpdir, "$(model.name)_$(i).init.R"), init[1]) end end else for i in 1:model.nchains if length(keys(init)) > 0 update_R_file(joinpath(model.tmpdir, "$(model.name)_$(i).init.R"), init) end end end end end end for i in 1:model.nchains model.id = i model.data_file = joinpath(model.tmpdir, "$(model.name)_$(i).data.R") if init != Nothing model.init_file = joinpath(model.tmpdir, "$(model.name)_$(i).init.R") end if isa(model.method, Sample) sample_file = joinpath(model.tmpdir, model.name*"_samples_$(i).csv") model.output.file = sample_file isfile(sample_file) && rm(sample_file) if diagnostics diagnostic_file = joinpath(model.tmpdir, model.name*"_diagnostics_$(i).csv") model.output.diagnostic_file = diagnostic_file isfile(diagnostic_file) && rm(diagnostic_file) end elseif isa(model.method, Optimize) optimize_file = joinpath(model.tmpdir, "$(model.name)_optimize_$(i).csv") isfile(optimize_file) && rm(optimize_file) model.output.file = optimize_file elseif isa(model.method, Variational) variational_file = joinpath(model.tmpdir, "$(model.name)_variational_$(i).csv") isfile(variational_file) && rm(variational_file) model.output.file = variational_file elseif isa(model.method, Diagnose) diagnose_file = joinpath(model.tmpdir, "$(model.name)_diagnose_$(i).csv") isfile(diagnose_file) && rm(diagnose_file) model.output.file = diagnose_file end model.command[i] = cmdline(model) end try if file_run_log run(pipeline(par(setenv.(model.command, Ref(ENV); dir=model.tmpdir)), stdout="$(model.name)_run.log")) else run(par(setenv.(model.command, Ref(ENV); dir=model.tmpdir))) end catch e println("\nAn error occurred while running the previously compiled Stan program.\n") print("Please check the contents of file $(model.name)_run.log and the") println("'command' field in the Stanmodel, e.g. stanmodel.command.\n") error("Return code = -5") end local samplefiles = String[] local ftype if typeof(model.method) in [Sample, Variational] if isa(model.method, Sample) ftype = diagnostics ? "diagnostics" : "samples" else ftype = lowercase(string(typeof(model.method))) end for i in 1:model.nchains push!(samplefiles, "$(model.name)_$(ftype)_$(i).csv") end if summary stan_summary(model, par(samplefiles), CmdStanDir=CmdStanDir) end (res, cnames) = read_samples(model, diagnostics) elseif isa(model.method, Optimize) res, cnames = read_optimize(model) elseif isa(model.method, Diagnose) res, cnames = read_diagnose(model) else println("\nAn unknown method is specified in the call to stan().") error("Return code = -10") end if model.output_format != :array start_sample = 1 if isa(model.method, Sample) && !model.method.save_warmup start_sample = model.method.num_warmup+1 end res = convert_a3d(res, cnames, Val(model.output_format); start=start_sample) end # cd(model.tmpdir) (rc, res, cnames) end
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
5546
import Base: show """ # Available top level Method ### Method ```julia * Sample::Method : Sampling * Optimize::Method : Optimization * Diagnose::Method : Diagnostics * Variational::Method : Variational Bayes ``` """ abstract type Method end const DataDict = Dict{String, Any} mutable struct Random seed::Int64 end Random(;seed::Number=-1) = Random(seed) mutable struct Output file::String diagnostic_file::String refresh::Int64 end Output(;file::String="", diagnostic_file::String="", refresh::Number=100) = Output(file, diagnostic_file, refresh) mutable struct Stanmodel name::String nchains::Int num_warmup::Int num_samples::Int thin::Int id::Int model::String model_file::String monitors::Vector{String} data_file::String command::Vector{Base.AbstractCmd} method::Method random::Random init_file::String output::Output printsummary::Bool pdir::String tmpdir::String output_format::Symbol end """ # Method Stanmodel Create a Stanmodel. ### Constructors ```julia Stanmodel( method=Sample(); name="noname", nchains=4, num_warmup=1000, num_samples=1000, thin=1, model="", monitors=String[], random=Random(), output=Output(), printsummary=false, pdir::String=pwd(), tmpdir::String=joinpath(pwd(), "tmp"), output_format=:array ) ``` ### Required arguments ```julia * `method::Method` : See ?Method ``` ### Optional arguments ```julia * `name::String` : Name for the model * `nchains::Int` : Number of chains * `num_warmup::Int` : Number of samples used for num_warmup * `num_samples::Int` : Sample iterations * `thin::Int` : Stan thinning factor * `model::String` : Stan program source * `monitors::String[] ` : Variables saved for post-processing * `random::Random` : Random seed settings * `output::Output` : File output options * `printsummary=true` : Show computed stan summary * `pdir::String` : Working directory * `tmpdir::String` : Directory where output files are stored * `output_format::Symbol ` : Output format ``` ### CmdStan.jl supports 3 output_format values: ```julia 1. :array # Returns an array of draws (default) 2. :mcmcchains # Return an MCMCChains.Chains object 3. :dataframes # Return an DataFrames.DataFrame object 4. :namedtuple # Returns a NamedTuple object The first option (the default) returns an Array{Float64, 3} with ndraws, nvars, nchains as indices. The 2nd option returns an MCMCChains.Chains object, the 3rd a DataFrame object and the final option returns a NamedTuple. ``` ### Example ```julia stanmodel = Stanmodel(num_samples=1200, thin=2, name="bernoulli", model=bernoullimodel); ``` ### Related help ```julia ?stan : Run a Stanmodel ?CmdStan.Sample : Sampling settings ?CmdStan.Method : List of available methods ?CmdStan.Output : Output file settings ?CmdStan.DataDict : Input data ?CmdStan.convert_a3d : Options for output formats ``` """ function Stanmodel( method=Sample(); name="noname", nchains=4, num_warmup=1000, num_samples=1000, thin=1, model="", monitors=String[], random=Random(), output=Output(), printsummary=true, pdir::String=pwd(), tmpdir::String=joinpath(pwd(), "tmp"), output_format::Symbol=:array) if !isdir(tmpdir) mkdir(tmpdir) end model_file = "$(name).stan" if length(model) > 0 update_model_file(joinpath(tmpdir, "$(name).stan"), strip(model)) end id::Int=0 data_file::String="" init_file::String="" cmdarray = fill(``, nchains) if num_samples != 1000 method.num_samples=num_samples end if num_warmup != 1000 method.num_warmup=num_warmup end if thin != 1 method.thin=thin end Stanmodel(name, nchains, num_warmup, num_samples, thin, id, model, model_file, monitors, data_file, cmdarray, method, random, init_file, output, printsummary, pdir, tmpdir, output_format); end function model_show(io::IO, m::Stanmodel, compact) println(io, " name = \"$(m.name)\"") println(io, " nchains = $(m.nchains)") println(io, " num_samples = $(m.num_samples)") println(io, " num_warmup = $(m.num_warmup)") println(io, " thin = $(m.thin)") println(io, " monitors = $(m.monitors)") println(io, " model_file = \"$(m.model_file)\"") println(io, " data_file = \"$(m.data_file)\"") println(io, " output = Output()") println(io, " file = \"$(m.output.file)\"") println(io, " diagnostics_file = \"$(m.output.diagnostic_file)\"") println(io, " refresh = $(m.output.refresh)") println(io, " pdir = \"$(m.pdir)\"") println(io, " tmpdir = \"$(m.tmpdir)\"") println(io, " output_format = :$(m.output_format)") if isa(m.method, Sample) sample_show(io, m.method, compact) elseif isa(m.method, Optimize) optimize_show(io, m.method, compact) elseif isa(m.method, Variational) variational_show(io, m.method, compact) else diagnose_show(io, m.method, compact) end end show(io::IO, m::Stanmodel) = model_show(io, m, false)
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
1610
""" # Available method diagnostics Currently limited to Gradient(). """ abstract type Diagnostics end """ # Gradient type and constructor Settings for diagnostic=Gradient() in Diagnose(). ### Method ```julia Gradient(;epsilon=1e-6, error=1e-6) ``` ### Optional arguments ```julia * `epsilon::Float64` : Finite difference step size * `error::Float64` : Error threshold ``` ### Related help ```julia ?Diagnose : Diagnostic method ``` """ mutable struct Gradient <: Diagnostics epsilon::Float64 error::Float64 end Gradient(;epsilon=1e-6, error=1e-6) = Gradient(epsilon, error) """ # Diagnose type and constructor ### Method ```julia Diagnose(;d=Gradient()) ``` ### Optional arguments ```julia * `d::Diagnostics` : Finite difference step size ``` ### Related help ```julia ?Diagnostics : Diagnostic methods ?Gradient : Currently sole diagnostic method ``` """ mutable struct Diagnose <: Method diagnostic::Diagnostics end Diagnose(;d=Gradient()) = Diagnose(d) #Diagnose(d=Gradient()) = Diagnose(d) function diagnose_show(io::IO, d::Diagnose, compact::Bool) if compact println(io, "Diagnose($(d.diagnostic))") else println(io, " method = Diagnose()") if isa(d.diagnostic, Gradient) println(io, " diagnostic = Gradient()") println(io, " epsilon = ", d.diagnostic.epsilon) println(io, " error = ", d.diagnostic.error) end end end show(io::IO, d::Diagnose) = diagnose_show(io, d, false)
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
5377
""" # OptimizeAlgorithm types ### Types defined ```julia * Lbfgs::OptimizeAlgorithm : Euclidean manifold with unit metric * Bfgs::OptimizeAlgorithm : Euclidean manifold with unit metric * Newton::OptimizeAlgorithm : Euclidean manifold with unit metric ``` """ abstract type OptimizeAlgorithm end """ # Lbfgs type and constructor Settings for method=Lbfgs() in Optimize(). ### Method ```julia Lbfgs(;init_alpha=0.001, tol_obj=1e-8, tol_grad=1e-8, tol_param=1e-8, history_size=5) ``` ### Optional arguments ```julia * `init_alpha::Float64` : Linear search step size for first iteration * `tol_obj::Float64` : Convergence tolerance for objective function * `tol_rel_obj::Float64` : Relative change tolerance in objective function * `tol_grad::Float64` : Convergence tolerance on norm of gradient * `tol_rel_grad::Float64` : Relative change tolerance on norm of gradient * `tol_param::Float64` : Convergence tolerance on parameter values * `history_size::Int` : No of update vectors to use in Hessian approx ``` ### Related help ```julia ?OptimizeMethod : List of available optimize methods ?Optimize : Optimize arguments ``` """ mutable struct Lbfgs <: OptimizeAlgorithm init_alpha::Float64 tol_obj::Float64 tol_rel_obj::Float64 tol_grad::Float64 tol_rel_grad::Float64 tol_param::Float64 history_size::Int64 end Lbfgs(;init_alpha=0.001, tol_obj=1e-8, tol_rel_obj=1e4, tol_grad=1e-8, tol_rel_grad=1e7, tol_param=1e-8, history_size=5) = Lbfgs(init_alpha, tol_obj, tol_rel_obj, tol_grad, tol_rel_grad, tol_param, history_size) """ # Bfgs type and constructor Settings for method=Bfgs() in Optimize(). ### Method ```julia Bfgs(;init_alpha=0.001, tol_obj=1e-8, tol_rel_obj=1e4, tol_grad=1e-8, tol_rel_grad=1e7, tol_param=1e-8) ``` ### Optional arguments ```julia * `init_alpha::Float64` : Linear search step size for first iteration * `tol_obj::Float64` : Convergence tolerance for objective function * `tol_rel_obj::Float64` : Relative change tolerance in objective function * `tol_grad::Float64` : Convergence tolerance on norm of gradient * `tol_rel_grad::Float64` : Relative change tolerance on norm of gradient * `tol_param::Float64` : Convergence tolerance on parameter values ``` ### Related help ```julia ?OptimizeMethod : List of available optimize methods ?Optimize : Optimize arguments ``` """ mutable struct Bfgs <: OptimizeAlgorithm init_alpha::Float64 tol_obj::Float64 tol_rel_obj::Float64 tol_grad::Float64 tol_rel_grad::Float64 tol_param::Float64 end Bfgs(;init_alpha=0.001, tol_obj=1e-8, tol_rel_obj=1e4, tol_grad=1e-8, tol_rel_grad=1e7, tol_param=1e-8) = Bfgs(init_alpha, tol_obj, tol_rel_obj, tol_grad, tol_rel_grad, tol_param) """ # Newton type and constructor Settings for method=Newton() in Optimize(). ### Method ```julia Newton() ``` ### Related help ```julia ?OptimizeMethod : List of available optimize methods ?Optimize : Optimize arguments ``` """ mutable struct Newton <: OptimizeAlgorithm end """ # Optimize type and constructor Settings for Optimize top level method. ### Method ```julia Optimize(; method=Lbfgs(), iter=2000, save_iterations=false ) ``` ### Optional arguments ```julia * `method::OptimizeMethod` : Optimization algorithm * `iter::Int` : Total number of iterations * `save_iterations::Bool` : Stream optimization progress to output ``` ### Related help ```julia ?Stanmodel : Create a StanModel ?OptimizeAlgorithm : Available algorithms ``` """ mutable struct Optimize <: Method method::OptimizeAlgorithm iter::Int64 save_iterations::Bool end Optimize(;method::OptimizeAlgorithm=Lbfgs(), iter::Number=2000, save_iterations::Bool=false) = Optimize(method, iter, save_iterations) Optimize(method::OptimizeAlgorithm) = Optimize(method, 2000, false) function optimize_show(io::IO, o::Optimize, compact::Bool) if compact println(io, "Optimize($(o.method), $(o.iter), $(o.save_iterations))") else println(io, " method = Optimize()") if isa(o.method, Lbfgs) println(io, " algorithm = Lbfgs()") println(io, " init_alpha = ", o.method.init_alpha) println(io, " tol_obj = ", o.method.tol_obj) println(io, " tol_grad = ", o.method.tol_grad) println(io, " tol_param = ", o.method.tol_param) println(io, " history_size = ", o.method.history_size) elseif isa(o.method, Bfgs) println(io, " algorithm = Bfgs()") println(io, " init_alpha = ", o.method.init_alpha) println(io, " tol_obj = ", o.method.tol_obj) println(io, " tol_grad = ", o.method.tol_grad) println(io, " tol_param = ", o.method.tol_param) else println(io, " algorithm = Newton()") end println(io, " iterations = ", o.iter) println(io, " save_iterations = ", o.save_iterations) end end show(io::IO, o::Optimize) = optimize_show(io, o, false)
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
7637
""" # Engine types Engine for Hamiltonian Monte Carlo ### Types defined ```julia * Nuts : No-U-Turn sampler * Static : Static integration time ``` """ abstract type Engine end """ # Available sampling algorithms Currently limited to Hmc(). """ abstract type SamplingAlgorithm end """ # Nuts type and constructor Settings for engine=Nuts() in Hmc(). ### Method ```julia Nuts(;max_depth=10) ``` ### Optional arguments ```julia * `max_depth::Number` : Maximum tree depth ``` ### Related help ```julia ?Sample : Sampling settings ?Engine : Engine for Hamiltonian Monte Carlo ``` """ mutable struct Nuts <: Engine max_depth::Int64 end Nuts(;max_depth::Number=10) = Nuts(max_depth) """ # Static type and constructor Settings for engine=Static() in Hmc(). ### Method ```julia Static(;int_time=2 * pi) ``` ### Optional arguments ```julia * `;int_time::Number` : Static integration time ``` ### Related help ```julia ?Sample : Sampling settings ?Engine : Engine for Hamiltonian Monte Carlo ``` """ mutable struct Static <: Engine int_time::Float64 end Static(;int_time::Number=2 * pi) = Static(int_time) """ # Metric types Geometry of base manifold ### Types defined ```julia * unit_e::Metric : Euclidean manifold with unit metric * dense_e::Metric : Euclidean manifold with dense netric * diag_e::Metric : Euclidean manifold with diag netric ``` """ abstract type Metric end mutable struct unit_e <: Metric end mutable struct dense_e <: Metric end mutable struct diag_e <: Metric end """ # Hmc type and constructor Settings for algorithm=CmdStan.Hmc() in Sample(). ### Method ```julia Hmc(; engine=CmdStan.Nuts(), metric=CmdStan.diag_e, stepsize=1.0, stepsize_jitter=1.0 ) ``` ### Optional arguments ```julia * `engine::Engine` : Engine for Hamiltonian Monte Carlo * `metric::Metric` : Geometry for base manifold * `stepsize::Float64` : Stepsize for discrete evolutions * `stepsize_jitter::Float64` : Uniform random jitter of the stepsize [%] ``` ### Related help ```julia ?Sample : Sampling settings ?Engine : Engine for Hamiltonian Monte Carlo ?Nuts : Settings for Nuts ?Static : Settings for Static ?Metric : Base manifold geometries ``` """ mutable struct Hmc <: SamplingAlgorithm engine::Engine metric::Metric stepsize::Float64 stepsize_jitter::Float64 end Hmc(;engine::Engine=Nuts(), metric::DataType=diag_e, stepsize::Number=1.0, stepsize_jitter::Number=1.0) = Hmc(engine, metric(), stepsize, stepsize_jitter) Hmc(engine::Engine) = Hmc(engine, diag_e(), 1.0, 1.0) """ # Fixed_param type and constructor Settings for algorithm=CmdStan.Fixed_param() in Sample(). ### Method ```julia Fixed_param() ``` ### Related help ```julia ?Sample : Sampling settings ?Engine : Engine for Hamiltonian Monte Carlo ?Nuts : Settings for Nuts ?Static : Settings for Static ?Metric : Base manifold geometries ``` """ mutable struct Fixed_param <: SamplingAlgorithm end """ # Adapt type and constructor Settings for adapt=CmdStan.Adapt() in Sample(). ### Method ```julia Adapt(; engaged=true, gamma=0.05, delta=0.8, kappa=0.75, t0=10.0, init_buffer=75, term_buffer=50, window::25 ) ``` ### Optional arguments ```julia * `engaged::Bool` : Adaptation engaged? * `gamma::Float64` : Adaptation regularization scale * `delta::Float64` : Adaptation target acceptance statistic * `kappa::Float64` : Adaptation relaxation exponent * `t0::Float64` : Adaptation iteration offset * `init_buffer::Int64` : Width of initial adaptation interval * `term_buffer::Int64` : Width of final fast adaptation interval * `window::Int64` : Initial width of slow adaptation interval ``` ### Related help ```julia ?Sample : Sampling settings ``` """ mutable struct Adapt engaged::Bool gamma::Float64 delta::Float64 kappa::Float64 t0::Float64 init_buffer::Int64 term_buffer::Int64 window::Int64 end Adapt(;engaged::Bool=true, gamma::Number=0.05, delta::Number=0.8, kappa::Number=0.75, t0::Number=10.0, init_buffer::Number=75, term_buffer::Number=50, window::Number=25) = Adapt(engaged, gamma, delta, kappa, t0, init_buffer, term_buffer, window) """ # Sample type and constructor Settings for method=Sample() in Stanmodel. ### Method ```julia Sample(; num_samples=1000, num_warmup=1000, save_warmup=false, thin=1, adapt=CmdStan.Adapt(), algorithm=SamplingAlgorithm() ) ``` ### Optional arguments ```julia * `num_samples::Int64` : Number of sampling iterations ( >= 0 ) * `num_warmup::Int64` : Number of warmup iterations ( >= 0 ) * `save_warmup::Bool` : Include warmup samples in output * `thin::Int64` : Period between saved samples * `adapt::Adapt` : Warmup adaptation settings * `algorithm::SamplingAlgorithm`: Sampling algorithm ``` ### Related help ```julia ?Stanmodel : Create a StanModel ?Adapt ?SamplingAlgorithm ``` """ mutable struct Sample <: Method num_samples::Int64 num_warmup::Int64 save_warmup::Bool thin::Int64 adapt::Adapt algorithm::SamplingAlgorithm end Sample(;num_samples::Number=1000, num_warmup::Number=1000, save_warmup::Bool=false, thin::Number=1, adapt::Adapt=Adapt(), algorithm::SamplingAlgorithm=Hmc()) = Sample(num_samples, num_warmup, save_warmup, thin, adapt, algorithm) function sample_show(io::IO, s::Sample, compact) println(io, " method = Sample()") println(io, " num_samples = ", s.num_samples) println(io, " num_warmup = ", s.num_warmup) println(io, " save_warmup = ", s.save_warmup) println(io, " thin = ", s.thin) if isa(s.algorithm, Hmc) println(io, " algorithm = HMC()") if isa(s.algorithm.engine, Nuts) println(io, " engine = NUTS()") println(io, " max_depth = ", s.algorithm.engine.max_depth) elseif isa(s.algorithm.engine, Static) println(io, " engine = Static()") println(io, " int_time = ", s.algorithm.engine.int_time) end println(io, " metric = ", typeof(s.algorithm.metric)) println(io, " stepsize = ", s.algorithm.stepsize) println(io, " stepsize_jitter = ", s.algorithm.stepsize_jitter) else if isa(s.algorithm, Fixed_param) println(io, " algorithm = Fixed_param()") else println(io, " algorithm = Unknown") end end println(io, " adapt = Adapt()") println(io, " gamma = ", s.adapt.gamma) println(io, " delta = ", s.adapt.delta) println(io, " kappa = ", s.adapt.kappa) println(io, " t0 = ", s.adapt.t0) println(io, " init_buffer = ", s.adapt.init_buffer) println(io, " term_buffer = ", s.adapt.term_buffer) println(io, " window = ", s.adapt.window) end show(io::IO, s::Sample) = sample_show(io, s, false)
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
2703
mutable struct Variational <: Method algorithm::Symbol grad_samples::Int64 elbo_samples::Int64 #eta_adagrad::Float64 iter::Int64 tol_rel_obj::Float64 eval_elbo::Int64 output_samples::Int64 end """ # Variational type and constructor Settings for method=Variational() in Stanmodel. ### Method ```julia Variational(; grad_samples=1, elbo_samples=100, eta_adagrad=0.1, iter=10000, tol_rel_obj=0.01, eval_elbo=100, algorithm=:meanfield, output_samples=10000 ) ``` ### Optional arguments ```julia * `algorithm::Symbol` : Variational inference algorithm : meanfield : fullrank * `iter::Int64` : Maximum number of iterations * `grad_samples::Int` : No of samples for MC estimate of gradients * `elbo_samples::Int` : No of samples for MC estimate of ELBO * `eta::Float64` : Step size weighting parameter for adaptive sequence * `adapt::Adapt` : Warmup adaptations * `tol_rel_obj::Float64` : Tolerance on the relative norm of objective * `eval_elbo::Int` : Tolerance on the relative norm of objective * `output_samples::Int` : Number of posterior samples to draw and save ``` ### Related help ```julia ?Stanmodel : Create a StanModel ?Stan.Method : Available top level methods ?Stan.Adapt : Adaptation settings ``` """ Variational(;grad_samples=1, elbo_samples=100, eta_adagrad=0.1, iter=10000, tol_rel_obj=0.01, eval_elbo=100, algorithm=:meanfield, output_samples=10000) = Variational(algorithm, grad_samples, elbo_samples, #eta_adagrad, iter, tol_rel_obj, eval_elbo, output_samples) function variational_show(io::IO, v::Variational, compact::Bool) if compact println(io, "Variational($(v.algorithm). $(v.grad_samples), $(v.elbo_samples), $(v.eta_adagrad), $(v.iter), $(v.tol_rel_obj), $(v.eval_elbo), $(v.output_samples))") else println(io, " method = Variational()") println(io, " algorithm = ", v.algorithm) println(io, " grad_samples = ", v.grad_samples) println(io, " elbo_samples = ", v.elbo_samples) #println(io, " eta_adagrad = ", v.eta_adagrad) println(io, " iter = ", v.iter) println(io, " tol_rel_obj = ", v.tol_rel_obj) println(io, " eval_elbo = ", v.eval_elbo) println(io, " output_samples = ", v.output_samples) end end show(io::IO, v::Variational) = variational_show(io, v, false)
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
1870
using DataFrames # convert_a3d # Method that allows federation by setting the `output_format` in the Stanmodel(). """ # convert_a3d Convert the output file created by cmdstan to the shape of choice. ### Method ```julia convert_a3d(a3d_array, cnames, ::Val{Symbol}; start=1) ``` ### Required arguments ```julia * `a3d_array::Array{Float64, 3},` : Read in from output files created by cmdstan * `cnames::Vector{AbstractString}` : Monitored variable names ``` ### Optional arguments ```julia * `::Val{Symbol}` : Output format, default is :mcmcchains * `::start=1` : First draw for MCMCChains.Chains ``` Method called is based on the output_format defined in the stanmodel, e.g.: stanmodel = Stanmodel(`num_samples`=1200, thin=2, name="bernoulli", model=bernoullimodel, `output_format`=:mcmcchains); Current formats supported are: 1. :array (a3d_array format, the default for CmdStan) 2. :mcmcchains (MCMCChains.Chains object) 3. :dataframes (Array of DataFrames.DataFrame objects) 4. :namedtuple (NamedTuple object) Option 2 is available if MCMCChains is loaded. ``` ### Return values ```julia * `res` : Draws converted to the specified format. ``` """ convert_a3d(a3d_array, cnames, ::Val{:array}; start=1) = a3d_array """ # convert_a3d # Convert the output file created by cmdstan to an Array of DataFrames. $(SIGNATURES) """ function convert_a3d(a3d_array, cnames, ::Val{:dataframes}; start=1) snames = [Symbol(cnames[i]) for i in 1: length(cnames)] [DataFrame(a3d_array[:,:,i], snames) for i in 1:size(a3d_array, 3)] end """ # convert_a3d # Convert the output file created by cmdstan to NamedTuples. $(SIGNATURES) """ function convert_a3d(a3d_array, cnames, ::Val{:namedtuple}; start=1) extract(a3d_array, cnames) end
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
2843
""" # cmdline Recursively parse the model to construct command line. ### Method ```julia cmdline(m) ``` ### Required arguments ```julia * `m::Stanmodel` : Stanmodel ``` ### Related help ```julia ?Stanmodel : Create a StanModel ``` """ function cmdline(m) cmd = `` if isa(m, Stanmodel) # Handle the model name field for unix and windows cmd = @static Sys.isunix() ? `./$(getfield(m, :name))` : `cmd /c $(getfield(m, :name)).exe` # Method (sample, optimize, variational and diagnose) specific portion of the model cmd = `$cmd $(cmdline(getfield(m, :method)))` # Common to all models cmd = `$cmd $(cmdline(getfield(m, :random)))` # Init file required? if length(m.init_file) > 0 && isfile(m.init_file) cmd = `$cmd init=$(m.init_file)` end # Data file required? if length(m.data_file) > 0 && isfile(m.data_file) cmd = `$cmd id=$(m.id) data file=$(m.data_file)` end # Output options cmd = `$cmd output` if length(getfield(m, :output).file) > 0 cmd = `$cmd file=$(string(getfield(m, :output).file))` end if length(getfield(m, :output).diagnostic_file) > 0 cmd = `$cmd diagnostic_file=$(string(getfield(m, :output).diagnostic_file))` end cmd = `$cmd refresh=$(string(getfield(m, :output).refresh))` else # The 'recursive' part #println(lowercase(string(typeof(m)))) if isa(m, SamplingAlgorithm) || isa(m, OptimizeAlgorithm) cmd = `$cmd algorithm=$(split(lowercase(string(typeof(m))), '.')[end])` elseif isa(m, Engine) cmd = `$cmd engine=$(split(lowercase(string(typeof(m))), '.')[end])` elseif isa(m, Diagnostics) cmd = `$cmd test=$(split(lowercase(string(typeof(m))), '.')[end])` else cmd = `$cmd $(split(lowercase(string(typeof(m))), '.')[end])` end #println(cmd) for name in fieldnames(typeof(m)) #println("$(name) = $(getfield(m, name)) ($(typeof(getfield(m, name))))") if isa(getfield(m, name), String) || isa(getfield(m, name), Tuple) cmd = `$cmd $(name)=$(getfield(m, name))` elseif length(fieldnames(typeof(getfield(m, name)))) == 0 if isa(getfield(m, name), Bool) cmd = `$cmd $(name)=$(getfield(m, name) ? 1 : 0)` else if name == :metric || isa(getfield(m, name), DataType) cmd = `$cmd $(name)=$(split(lowercase(string(typeof(getfield(m, name)))), '.')[end])` else if name == :algorithm && typeof(getfield(m, name)) == CmdStan.Fixed_param cmd = `$cmd $(name)=fixed_param` else cmd = `$cmd $(name)=$(getfield(m, name))` end end end else cmd = `$cmd $(cmdline(getfield(m, name)))` end end end #println(cmd) cmd end
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
2022
""" # `check_dct_type(` Check if dct == Dict[] and has length > 0. ### Method ```julia check_dct_type((dct) ``` ### Required arguments ```julia * `dct::Dict{String, Any}` : Observed data or parameter init data ``` """ function check_dct_type(dct) if typeof(dct) <: Array && length(dct) > 0 if typeof(dct) <: Array{Dict{S, T}} where {S <: AbstractString, T <: Any} return true end else if typeof(dct) <: Dict{S, T} where {S <: AbstractString, T <: Any} return true end end @error "Input $(dct) not of type Dict{String, Any}, but $(typeof(dct))" return false end """ # update_R_file Rewrite a dictionary of observed data or initial parameter values in R dump file format to a file. ### Method ```julia update_R_file{T<:Any}(file, dct) ``` ### Required arguments ```julia * `file::String` : R file name * `dct::Dict{String, T}` : Dictionary to format in R ``` """ function update_R_file(file::String, dct::Dict{String, T}) where T <: Any isfile(file) && rm(file) open(file, "w") do strmout str = "" for entry in dct str = "\""*entry[1]*"\" <- " val = entry[2] if length(val)==0 && length(size(val))==1 # Empty array str = str*"c()\n" elseif length(val)==1 && length(size(val))==0 # Scalar str = str*"$(val)\n" #elseif length(val)==1 && length(size(val))==1 # Single element vector #str = str*"$(val[1])\n" elseif length(val)>=1 && length(size(val))==1 # Vector str = str*"structure(c(" write(strmout, str) str = "" writedlm(strmout, val', ',') str = str*"), .Dim=c($(length(val))))\n" elseif length(val)>1 && length(size(val))>1 # Array str = str*"structure(c(" write(strmout, str) str = "" writedlm(strmout, val[:]', ',') dimstr = "c"*string(size(val)) str = str*"), .Dim=$(dimstr))\n" end write(strmout, str) end end end
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
1160
""" # extract(chns::Array{Float64,3}, cnames::Vector{String}) RStan/PyStan style extract chns: Array: [draws, vars, chains], cnames: ["lp__", "accept_stat__", "f.1", ...] Output: name -> [size..., draws, chains] """ function extract(chns::Array{Float64,3}, cnames::Vector{String}) draws, vars, chains = size(chns) ex_dict = Dict{Symbol, Array}() group_map = Dict{Symbol, Array}() for (i, cname) in enumerate(cnames) sp_arr = split(cname, ".") name = Symbol(sp_arr[1]) if length(sp_arr) == 1 ex_dict[name] = chns[:,i,:] else if !(name in keys(group_map)) group_map[name] = Any[] end push!(group_map[name], (i, [Meta.parse(i) for i in sp_arr[2:end]])) end end for (name, group) in group_map max_idx = maximum(hcat([idx for (i, idx) in group]...), dims=2)[:,1] ex_dict[name] = similar(chns, max_idx..., draws, chains) end for (name, group) in group_map for (i, idx) in group ex_dict[name][idx..., :, :] = chns[:,i,:] end end return (;ex_dict...) end export extract
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
398
function _findall(t::Union{AbstractString,Regex}, s::AbstractString; overlap::Bool=false) found = UnitRange{Int}[] i, e = firstindex(s), lastindex(s) while true r = findnext(t, s, i) r === nothing && return found push!(found, r) j = overlap || isempty(r) ? first(r) : last(r) j > e && return found @inbounds i = nextind(s, j) end end
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
968
""" # par Rewrite dct to R format in file. ### Method ```julia par(cmds) ``` ### Required arguments ```julia * `cmds::Array{Base.AbstractCmd,1}` : Multiple commands to concatenate or * `cmd::Base.AbstractCmd` : Single command to be * `n::Number` inserted n times into cmd or * `cmd::Array{String, 1}` : Array of cmds as Strings ``` """ function par(cmds::Array{<:Base.AbstractCmd,1}) if length(cmds) > 2 return(par([cmds[1:(length(cmds)-2)]; Base.AndCmds(cmds[length(cmds)-1], cmds[length(cmds)])])) elseif length(cmds) == 2 return(Base.AndCmds(cmds[1], cmds[2])) else return(cmds[1]) end end function par(cmd::Base.AbstractCmd, n::Number) res = deepcopy(cmd) if n > 1 for i in 2:n res = Base.AndCmds(res, cmd) end end res end function par(cmd::Array{String, 1}) res = `$(cmd[1])` for i in 2:length(cmd) res = `$res $(cmd[i])` end res end
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
1916
using DelimitedFiles, Unicode """ # read_diagnose Read diagnose output file created by cmdstan. ### Method ```julia read_diagnose(m::Stanmodel) ``` ### Required arguments ```julia * `m::Stanmodel` : Stanmodel object ``` """ function read_diagnose(model::Stanmodel) ## Collect the results of a chain in an array ## cnames = String[] res_type = "diagnose" tdict = Dict() local sstr for i in 1:model.nchains file_path = joinpath(model.tmpdir, "$(model.name)_$(res_type)_$(i).csv") if isfile(file_path) ## A result type file for chain i is present ## if i == 1 # Extract cmdstan version str = read(file_path, String) sstr = split(str) tdict[:stan_version] = "$(parse(Int, sstr[4])).$(parse(Int, sstr[8])).$(parse(Int, sstr[12]))" end # Position sstr at element with with `probability=...` indx = findall(x -> length(x)>11 && x[1:11] == "probability", sstr)[1] sstr_lp = sstr[indx] sstr_lp = parse(Float64, split(sstr_lp, '=')[2]) if :lp in keys(tdict) append!(tdict[:lp], sstr_lp) append!(tdict[:var_id], parse(Int, sstr[indx+11])) append!(tdict[:value], parse(Float64, sstr[indx+12])) append!(tdict[:model], parse(Float64, sstr[indx+13])) append!(tdict[:finite_dif], parse(Float64, sstr[indx+14])) append!(tdict[:error], parse(Float64, sstr[indx+15])) else # First time around, create value array tdict[:lp] = [sstr_lp] tdict[:var_id] = [parse(Int, sstr[indx+11])] tdict[:value] = [parse(Float64, sstr[indx+12])] tdict[:model] = [parse(Float64, sstr[indx+13])] tdict[:finite_dif] = [parse(Float64, sstr[indx+14])] tdict[:error] = [parse(Float64, sstr[indx+15])] end end end (tdict, cnames) end
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
2128
using DelimitedFiles, Unicode """ # read_optimize Read optimize output file created by cmdstan. ### Method ```julia read_optimize(m::Stanmodel) ``` ### Required arguments ```julia * `m::Stanmodel` : Stanmodel object ``` """ function read_optimize(model::Stanmodel) ## Collect the results in a Dict cnames = String[] res_type = "optimize" tdict = Dict() ## tdict contains the arrays of values ## tdict = Dict() for i in 1:model.nchains file_path = joinpath(model.tmpdir, "$(model.name)_$(res_type)_$(i).csv") if isfile(file_path) # A result type file for chain i is present ## instream = open(file_path) if i == 1 open(file_path) do instream str = read(instream, String) sstr = split(str) tdict[:stan_major_version] = [parse(Int, sstr[4])] tdict[:stan_minor_version] = [parse(Int, sstr[8])] tdict[:stan_patch_version] = [parse(Int, sstr[12])] end end # After reopening the file, skip all comment lines open(file_path) do instream skipchars(isspace, instream, linecomment='#') line = Unicode.normalize(readline(instream), newline2lf=true) # Extract samples variable names idx = split(strip(line), ",") index = [idx[k] for k in 1:length(idx)] cnames = convert.(String, idx) # Read optimized values for i in 1:model.method.iter line = Unicode.normalize(readline(instream), newline2lf=true) flds = Float64[] if eof(instream) && length(line) < 2 return else flds = parse.(Float64, split(strip(line), ",")) for k in 1:length(index) if index[k] in keys(tdict) # For all subsequent chains the entry should already be in tdict append!(tdict[index[k]], flds[k]) else # First chain tdict[index[k]] = [flds[k]] end end end end end end end (tdict, cnames) end
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
2860
using DelimitedFiles, Unicode """ # read_samples Read sample output files created by cmdstan. ### Method ```julia read_samples(m::Stanmodel) ``` ### Required arguments ```julia * `m::Stanmodel` : Stanmodel object ``` """ function read_samples(m::Stanmodel, diagnostics=false, warmup_samples=false) local monitors, index, idx, indvec, ftype, noofsamples # a3d will contain the samples such that a3d[s, i, c] where # s: the sample index (corrected warmup samples and thinning by cmdstan) # i: variable name (either from monitors or read from .csv file produiced by cmdstan) # c: chain number (from m.chains) if isa(m.method, Sample) ftype = diagnostics ? "diagnostics" : "samples" # The sample index s runs from 1:noofsamples if m.method.save_warmup noofsamples = floor(Int, (m.method.num_samples+m.method.num_warmup)/m.method.thin) else noofsamples = floor(Int, m.method.num_samples/m.method.thin) end else ftype = lowercase(string(typeof(m.method))) if (ftype[1:7] == "cmdstan") ftype = ftype[9:end] end # The noofsamples is obtained from method.output_samples noofsamples = m.method.output_samples end # Read .csv files created by each chain for i in 1:m.nchains file_path = joinpath(m.tmpdir, "$(m.name)_$(ftype)_$(i).csv") if isfile(file_path) instream = open(file_path) # Skip initial set of commented lines, e.g. containing # cmdstan version info, etc. skipchars(isspace, instream, linecomment='#') # First non-comment line contains names of variables line = Unicode.normalize(readline(instream), newline2lf=true) idx = split(strip(line), ",") index = [idx[k] for k in 1:length(idx)] # Only continue with monitored variables if length(m.monitors) == 0 indvec = 1:length(index) else indvec = findall((in)(m.monitors), index) end # Preserve cnames and create a3d if i == 1 global cnames = convert.(String, idx[indvec]) global a3d = fill(0.0, noofsamples, length(indvec), m.nchains) end # Read in the samples for all chains skipchars(isspace, instream, linecomment='#') for j in 1:noofsamples skipchars(isspace, instream, linecomment='#') line = Unicode.normalize(readline(instream), newline2lf=true) if eof(instream) && length(line) < 2 return else flds = parse.(Float64, split(strip(line), ",")) flds = reshape(flds[indvec], 1, length(indvec)) a3d[j,:,i] = flds end end # read in samples end # select next file if it exists end # loop over all chains (a3d, cnames) end # end of read_samples
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
706
using DataFrames, CSV """ # read_summary Read summary output file created by stansummary. ### Method ```julia read_summary(m::Stanmodel) ``` ### Required arguments ```julia * `m::Stanmodel` : Stanmodel object ``` """ function read_summary(m::Stanmodel) fname = joinpath(m.tmpdir, "$(m.name)_summary.csv") !isfile(fname) && stan_summary(m) df = CSV.read(fname, DataFrame; delim=",", comment="#") cnames = lowercase.(convert.(String, String.(names(df)))) cnames[1] = "parameters" cnames[4] = "std" cnames[8] = "ess" #names!(df, Symbol.(cnames)) rename!(df, Symbol.(cnames), makeunique = true) df.parameters = Symbol.(df.parameters) df end # end of read_samples
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
1585
using DelimitedFiles, Unicode """ # read_variational Read variational sample output files created by cmdstan. ### Method ```julia read_variational(m::Stanmodel) ``` ### Required arguments ```julia * `m::Stanmodel` : Stanmodel object ``` """ function read_variational(m::Stanmodel) local a3d, monitors, index, idx, indvec, ftype ftype = lowercase(string(typeof(m.method))) for i in 1:m.nchains file_path = joinpath(m.tmpdir, "$(m.name)_$(ftype)_$(i).csv") if isfile(file_path) open(file_path) do instream skipchars(isspace, instream, linecomment='#') line = Unicode.normalize(readline(instream), newline2lf=true) idx = split(strip(line), ",") index = [idx[k] for k in 1:length(idx)] if length(m.monitors) == 0 indvec = 1:length(index) else indvec = findall((in)(m.monitors), index) end if i == 1 a3d = fill(0.0, m.method.output_samples, length(indvec), m.nchains) end skipchars(isspace, instream, linecomment='#') for j in 1:m.method.output_samples skipchars(isspace, instream, linecomment='#') line = Unicode.normalize(readline(instream), newline2lf=true) if eof(instream) && length(line) < 2 return else flds = parse.(Float64, (split(strip(line), ","))) flds = reshape(flds[indvec], 1, length(indvec)) a3d[j,:,i] = flds end end end end end cnames = convert.(String, idx[indvec]) (a3d, cnames) end
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
325
using .MCMCChains function convert_a3d(a3d_array, cnames, ::Val{:mcmcchains}; start=1) pi = filter(p -> length(p) > 2 && p[end-1:end] == "__", cnames) p = filter(p -> !(p in pi), cnames) MCMCChains.Chains(a3d_array, cnames, Dict( :parameters => p, :internals => pi ); start=start ) end
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
2242
""" # Method stan_summary Display cmdstan summary ### Method ```julia stan_summary( model::StanModel, file::String; CmdStanDir=CMDSTAN_HOME ) ``` ### Required arguments ```julia * `model::Stanmodel : Stanmodel * `file::String` : Name of file with samples ``` ### Optional arguments ```julia * CmdStanDir=CMDSTAN_HOME : cmdstan directory for stansummary program ``` ### Related help ```julia ?Stan.stan : Execute a StanModel ``` """ function stan_summary(model::Stanmodel, file::String; CmdStanDir=CMDSTAN_HOME) try pstring = joinpath("$(CmdStanDir)", "bin", "stansummary") csvfile = "$(model.name)_summary.csv" isfile(csvfile) && rm(csvfile) cmd = setenv(`$(pstring) -c $(csvfile) $(file)`, ENV; dir=model.tmpdir) resfile = open(cmd; read=true) println("Setting $(model.printsummary)") model.printsummary && print(read(resfile, String)) catch e println(e) end end """ # Method stan_summary Display cmdstan summary ### Method ```julia stan_summary( model::Stanmodel filecmd::Cmd; CmdStanDir=CMDSTAN_HOME ) ``` ### Required arguments ```julia * `model::Stanmodel` : Stanmodel * `filecmd::Cmd` : Run command containing names of sample files ``` ### Optional arguments ```julia * CmdStanDir=CMDSTAN_HOME : cmdstan directory for stansummary program ``` ### Related help ```julia ?Stan.stan : Create a StanModel ``` """ function stan_summary(model::Stanmodel, filecmd::Cmd; CmdStanDir=CMDSTAN_HOME) try pstring = joinpath("$(CmdStanDir)", "bin", "stansummary") csvfile = "$(model.name)_summary.csv" isfile(csvfile) && rm(csvfile) cmd = setenv(`$(pstring) -c $(csvfile) $(filecmd)`, ENV; dir=model.tmpdir) if model.printsummary resfile = open(cmd; read=true) print(read(resfile, String)) else run(pipeline(cmd, stdout="out.txt")) end catch e println(e) println("Stan.jl caught above exception in Stan's 'stansummary' program.") println("This is a usually caused by the setting:") println(" Sample(save_warmup=true, thin=n)") println("in the call to stanmodel() with n > 1.") println() end end
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
1567
""" # Method `update_model_file` Update Stan language model file if necessary ### Method ```julia CmdStan.update_model_file( file::String, str::String ) ``` ### Required arguments ```julia * `file::AbstractString` : File holding existing Stan model * `str::AbstractString` : Stan model string ``` ### Related help ```julia ?CmdStan.Stanmodel : Create a StanModel ``` """ function update_model_file(file::AbstractString, model::AbstractString) model1 = parse_and_interpolate(model) model2 = "" if isfile(file) model2 = parse_and_interpolate(strip(read(file, String))) model1 != model2 && rm(file) end if model1 != model2 println("\nFile $(file) will be updated.\n") write(file, model1) end end function parse_and_interpolate(model) newmodel = "" lines = split(model, "\n") for l in lines ls = String(strip(l)) if VERSION.minor >= 3 replace_strings = findall("#include", ls) else replace_strings = CmdStan._findall("#include", ls) end if length(replace_strings) == 1 && # handle the case the include line is commented out length(ls) > 2 && !(ls[1:2] == "//") for r in replace_strings ls = split(strip(ls[r[end]+1:end]), " ")[1] func = open(f -> read(f, String), strip(ls)) newmodel *= " "*func*"\n" end else if length(replace_strings) > 1 error("Improper number of includes in line `$l`") else newmodel *= l*"\n" end end end newmodel end
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
941
# This is a test for cmdstan issue #510 (thanks to jonalm) using Mamba, Stan ProjDir = dirname(@__FILE__) cd(ProjDir) do simplecode = " data {real sigma;} parameters {real y;} model {y ~ normal(0,sigma);} " global stanmodel1, rc1, sim1 stanmodel1 = Stanmodel(Sample(save_warmup=false, thin=5), name="simple", model=simplecode); rc1, sim1 = stan(stanmodel1, [Dict("sigma" => 1.)], CmdStanDir=CMDSTAN_HOME); describe(sim1) global stanmodel2, rc2, sim2 stanmodel2 = Stanmodel(Sample(save_warmup=true, thin=1), name="simple", thin=5, model=simplecode); rc2, sim2 = stan(stanmodel2, [Dict("sigma" => 1.)], CmdStanDir=CMDSTAN_HOME); describe(sim2) global stanmodel3, rc3, sim3 stanmodel3 = Stanmodel(Sample(save_warmup=true, thin=5), name="simple", model=simplecode); rc3, sim3 = stan(stanmodel3, [Dict("sigma" => 1.)], CmdStanDir=CMDSTAN_HOME); describe(sim3) end # stanmodel3 should not fail.
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
542
# This is a test for cmdstan issue #547 (thanks to chris fisher & bob) using Mamba, Stan ProjDir = dirname(@__FILE__) cd(ProjDir) do simplecode = " parameters { real y; } model { y ~ normal(0, 1); } " global stanmodel, rc, sim stanmodel = Stanmodel(Sample(save_warmup=true, thin=1), name="simple", model=simplecode); rc, sim, cnames = stan(stanmodel, [Dict("y" => 0.)], CmdStanDir=CMDSTAN_HOME); rc == 0 && describe(sim) end # The first sample for y (in e.g. tmp/simple_samples_1.csv, ~line 39) should be 0.
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
1038
# This script shows stansummary ESS vakues vs. MCMCChains ESS values using CmdStan, StatsPlots ProjDir = @__DIR__ cd(ProjDir) berstanmodel = " data { int<lower=0> N; int<lower=0,upper=1> y[N]; } parameters { real<lower=0,upper=1> theta; } model { theta ~ beta(1,1); for (n in 1:N) y[n] ~ bernoulli(theta); } " data = Dict("y" => [0,1,0,0,0,0,0,0,0,1], "N" => 10) stanmodel = Stanmodel( name = "berstanmodel", model = berstanmodel, nchains = 4, printsummary=false, tmpdir=mktempdir()); ess_array_mcmcchains = [] ess_array_cmdstan = [] for i in 1:100 rc, chns, cnames = stan(stanmodel, data, summary=true, ProjDir); dfc = describe(chns)[1] append!(ess_array_mcmcchains, dfc[:theta, :ess]) rs = read_summary(stanmodel) append!(ess_array_cmdstan, rs[:theta, :ess]) end p = Array{Plots.Plot{Plots.GRBackend}}(undef, 1); p[1] = plot(ess_array_cmdstan, lab="CmdStan", xlim=(0, 170)) p[1] = plot!(ess_array_mcmcchains, lab="MCMCChains") plot(p..., layout=(1,1)) savefig("ess_comparison_plot.pdf")
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
580
datatype = Union{ Dict{String, T} where {T <: Any}, Vector{Dict{String, T}} where {T <: Any} } mutable struct Mymodel data::datatype init::datatype end function Mymodel(;data=Dict{String, Any}(), init=Dict{String,Any}()) Mymodel(mydata, myinit) end dd = Dict("theta" => 1, "alpha" => 3.0) id = Dict("sigma" => 1.0) m1 = Mymodel(data=dd, init=id) @show m1 println() dd2 = [Dict("theta" => 1, "alpha" => 3.0), Dict("theta" => 1, "alpha" => 3.0)] id2 = [Dict("sigma" => 1.0)] m2 = Mymodel(data=dd2, init=id2) @show m2 println() m3 = Mymodel(data=dd2) @show m3
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
853
function rewrite_file(model, chain, chainno::Int, fname) isfile("simple_samples_1.csv") && rm("simple_samples_1.csv") open("simple_samples_1.csv", "w") do fd count = 1 for name in sim3.names write(fd, name) count += 1 count <= length(sim3.names) && write(fd, ",") end write(fd, "\n") count = 1 for i in 1:size(sim3.value, 1) for j in 1:size(sim3.value, 2) write(fd, string(sim3.value[i, j, chainno])) count += 1 if count <= size(sim3.value, 2) write(fd, ",") end end write(fd, "\n") end end pstring = joinpath("/Users/rob/Projects/Stan/cmdstan", "bin", "stansummary") cmd = `$(pstring) $(fname)` println(cmd) resfile = open(cmd, "r") print(read(resfile, String)) end rewrite_file(stanmodel1, sim1, 1, "simple_samples_1.csv")
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
1598
# Top level test script for Stan.jl using CmdStan, Test, Statistics if haskey(ENV, "JULIA_CMDSTAN_HOME") println("\nRunning tests for CmdStan-j1-v5:\n") code_tests = [ "test_env.jl", "test_utilities.jl", "test_cmdtype.jl", "test_extract.jl" ] # Run execution_tests only if cmdstan is installed and CMDSTAN_HOME is set correctly. execution_tests = [ "test_bernoulli.jl", "test_bernoulli_diagnostics.jl", "test_bernoulli_optimize.jl", "test_bernoulli_diagnose.jl", # Variational often fails on Travis. #"test_bernoulli_variational.jl", "test_bernoulliinittheta.jl", "test_bernoulliinittheta2.jl", "test_bernoulliinittheta3.jl", "test_bernoulliscalar.jl", "test_binomial.jl", "test_binormal.jl", "test_schools8.jl", "test_dyes.jl", "test_kidscore.jl", "test_fixed_param.jl", "test_zerolengtharray.jl", "test_parse_interpolate.jl", "test_init_in_stanmodel.jl", "test_mcmcchains.jl" ] if CMDSTAN_HOME != "" println("CMDSTAN_HOME set. Try to run tests.") @testset "CmdStan.jl" begin for my_test in code_tests println("\n\n\n * $(my_test) *") include(my_test) end for my_test in execution_tests println("\n\n * $(my_test) *\n") include(my_test) end println("\n") end else println("\n\nCMDSTAN_HOME not set or found.") println("Skipping all tests that depend on CmdStan!\n") end println("\n") else println("\nJULIA_CMDSTAN_HOME not set. Skipping tests") end
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
562
######### CmdStan program example ########### using CmdStan ProjDir = dirname(@__FILE__) cd(ProjDir) bernoullimodel = " data { int<lower=1> N; int<lower=0,upper=1> y[N]; } parameters { real<lower=0,upper=1> theta; } model { theta ~ beta(1,1); y ~ bernoulli(theta); } "; tmpdir = ProjDir*"/tmp" stanmodel = Stanmodel(Sample(save_warmup=true, num_warmup=1000, num_samples=2000, thin=1), name="bernoulli", model=bernoullimodel, printsummary=false, tmpdir=tmpdir); println("\nTest for Atom completed, stanmodel should not have been displayed\n")
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
991
using CmdStan, Test ProjDir = dirname(@__FILE__) cd(ProjDir) @testset "Bernoulli" begin isdir("tmp") && rm("tmp", recursive=true); bernoullimodel = " data { int<lower=1> N; int<lower=0,upper=1> y[N]; } parameters { real<lower=0,upper=1> theta; } model { theta ~ beta(1,1); y ~ bernoulli(theta); } "; observeddata = Dict("N" => 10, "y" => [0, 1, 0, 1, 0, 0, 0, 0, 0, 1]) global stanmodel, rc, chn, chns, cnames, summary_df #tmpdir = ProjDir*"/tmp" stanmodel = Stanmodel(Sample(save_warmup=false, num_warmup=1000, num_samples=2000, thin=1), name="bernoulli", model=bernoullimodel, printsummary=false, #tmpdir=tmpdir ); rc, a3d, cnames = stan(stanmodel, observeddata, ProjDir, diagnostics=false, CmdStanDir=CMDSTAN_HOME); if rc == 0 sdf = read_summary(stanmodel) @test sdf[sdf.parameters .== :theta, :mean][1] β‰ˆ 0.34 rtol=0.1 end isdir("tmp") && rm("tmp", recursive=true); end # testset
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
260
ProjDir = joinpath(dirname(@__FILE__), "..", "examples", "BernoulliDiagnose") cd(ProjDir) do isdir("tmp") && rm("tmp", recursive=true); include(joinpath(ProjDir, "bernoulli_diagnose.jl")) isdir("tmp") && rm("tmp", recursive=true); end # cd
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
264
ProjDir = joinpath(dirname(@__FILE__), "..", "examples", "BernoulliDiagnostics") cd(ProjDir) do isdir("tmp") && rm("tmp", recursive=true); include(joinpath(ProjDir, "bernoulli_diagnostics.jl")) isdir("tmp") && rm("tmp", recursive=true); end # cd
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
1272
using Test ProjDir = joinpath(dirname(@__FILE__), "..", "examples", "BernoulliInitTheta") cd(ProjDir) do isdir("tmp") && rm("tmp", recursive=true); bernoullimodel = " data { int<lower=1> N; int<lower=0,upper=1> y[N]; } parameters { real<lower=0,upper=1> theta; } model { theta ~ beta(1,1); y ~ bernoulli(theta); } " bernoullidata = [ Dict("N" => 10, "y" => [0, 1, 0, 1, 0, 0, 0, 0, 0, 1]), Dict("N" => 10, "y" => [0, 1, 0, 0, 0, 0, 1, 0, 0, 1]), Dict("N" => 10, "y" => [0, 0, 0, 0, 0, 0, 1, 0, 1, 1]), Dict("N" => 10, "y" => [0, 0, 0, 1, 0, 0, 0, 1, 0, 1]) ] theta_init = [0.1, 0.4, 0.5, 0.9] bernoulliinit = Dict[ Dict("theta" => theta_init[1]), Dict("theta" => theta_init[2]), Dict("theta" => theta_init[3]), Dict("theta" => theta_init[4]), ] monitor = ["theta", "lp__", "accept_stat__"] stanmodel = Stanmodel(name="bernoulli", model=bernoullimodel, init=Stan.Init(init=bernoulliinit), adapt=1); rc, a3d, cnames = stan(stanmodel, bernoullidata, CmdStanDir=CMDSTAN_HOME) if rc == 0 sdf = read_summary(stanmodel) @test sdf[sdf.parameters .== :theta, :mean][1] β‰ˆ 0.34 rtol=0.1 end isdir("tmp") && rm("tmp", recursive=true); end # cd
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
262
ProjDir = joinpath(dirname(@__FILE__), "..", "examples", "BernoulliNamedArray") cd(ProjDir) do isdir("tmp") && rm("tmp", recursive=true); include(joinpath(ProjDir, "bernoulli_namedarray.jl")) isdir("tmp") && rm("tmp", recursive=true); end # cd
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
285
ProjDir = joinpath(dirname(@__FILE__), "..", "examples", "BernoulliOptimize") cd(ProjDir) do isdir("tmp") && rm("tmp", recursive=true); include(joinpath(ProjDir, "bernoulli_optimize.jl")) isdir("tmp") && rm("tmp", recursive=true); println() println() end # cd
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
291
ProjDir = joinpath(dirname(@__FILE__), "..", "examples", "BernoulliVariational") cd(ProjDir) do isdir("tmp") && rm("tmp", recursive=true); include(joinpath(ProjDir, "bernoulli_variational.jl")) isdir("tmp") && rm("tmp", recursive=true); println() println() end # cd
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
259
ProjDir = joinpath(dirname(@__FILE__), "..", "examples", "BernoulliInitTheta") cd(ProjDir) do isdir("tmp") && rm("tmp", recursive=true); include(joinpath(ProjDir, "bernoulliinittheta.jl")) isdir("tmp") && rm("tmp", recursive=true); end # cd
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
260
ProjDir = joinpath(dirname(@__FILE__), "..", "examples", "BernoulliInitTheta") cd(ProjDir) do isdir("tmp") && rm("tmp", recursive=true); include(joinpath(ProjDir, "bernoulliinittheta2.jl")) isdir("tmp") && rm("tmp", recursive=true); end # cd
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
260
ProjDir = joinpath(dirname(@__FILE__), "..", "examples", "BernoulliInitTheta") cd(ProjDir) do isdir("tmp") && rm("tmp", recursive=true); include(joinpath(ProjDir, "bernoulliinittheta3.jl")) isdir("tmp") && rm("tmp", recursive=true); end # cd
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
253
ProjDir = joinpath(dirname(@__FILE__), "..", "examples", "BernoulliScalar") cd(ProjDir) do isdir("tmp") && rm("tmp", recursive=true); include(joinpath(ProjDir, "bernoulliscalar.jl")) isdir("tmp") && rm("tmp", recursive=true); end # cd
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
239
ProjDir = joinpath(dirname(@__FILE__), "..", "examples", "Binomial") cd(ProjDir) do isdir("tmp") && rm("tmp", recursive=true); include(joinpath(ProjDir, "binomial.jl")) isdir("tmp") && rm("tmp", recursive=true); end # cd
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
239
ProjDir = joinpath(dirname(@__FILE__), "..", "examples", "Binormal") cd(ProjDir) do isdir("tmp") && rm("tmp", recursive=true); include(joinpath(ProjDir, "binormal.jl")) isdir("tmp") && rm("tmp", recursive=true); end # cd
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
764
#= println("hither : ",Threads.threadid()," : ",pwd()) # hither : 1 : /tmp Threads.@spawn cd( () -> ( println("tither : ",Threads.threadid(), " : ", pwd()); sleep(3)), "..") # tither : 2 : / sleep(1);println("hither : ",Threads.threadid(), " : ", pwd());sleep(3) # hither : 1 : / println("hither : ",Threads.threadid()," : ",pwd()) # hither : 1 : /tmp =# cd(@__DIR__) println("hither : ",Threads.threadid()," : ",pwd()) # hither : 1 : ./CmdStan/test Threads.@spawn cd( () -> ( println("tither : ",Threads.threadid(), " : ", pwd()); sleep(3)), "..") # tither : 2 : ./CmdStan sleep(1) println("hither : ",Threads.threadid()," : ", pwd()) # hither : 1 : ./CmdStan sleep(3) println("hither : ",Threads.threadid()," : ", pwd()) # hither : 1 : ./CmdStan/test
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
1616
using CmdStan using Test ProjDir = dirname(@__FILE__) cd(ProjDir) do bernoulli = " data { int<lower=0> N; int<lower=0,upper=1> y[N]; } parameters { real<lower=0,upper=1> theta; } model { theta ~ beta(1,1); y ~ bernoulli(theta); } " data = [ Dict("N" => 10, "y" => [0, 1, 0, 1, 0, 0, 0, 0, 0, 1]), Dict("N" => 10, "y" => [0, 1, 0, 0, 0, 0, 1, 0, 0, 1]), Dict("N" => 10, "y" => [0, 0, 0, 0, 0, 0, 1, 0, 1, 1]), Dict("N" => 10, "y" => [0, 0, 0, 1, 0, 0, 0, 1, 0, 1]) ] m = Stanmodel(Optimize(), name="bernoulli", model=bernoulli); m.command[1] = CmdStan.cmdline(m) println() show(IOContext(stdout, :compact => true), m) println() show(m) @assert m.output.refresh == 100 s1 = Sample() println() show(IOContext(stdout, :compact => true), s1) println() show(s1) n1 = CmdStan.Lbfgs() n2 = CmdStan.Lbfgs(history_size=15) @assert 3*n1.history_size == n2.history_size b1 = CmdStan.Bfgs() b2 = CmdStan.Bfgs(tol_obj=1//100000000) @assert b1.tol_obj == b2.tol_obj o1 = Optimize() o2 = Optimize(CmdStan.Newton()) o3 = Optimize(CmdStan.Lbfgs(history_size=10)) o4 = Optimize(CmdStan.Bfgs(tol_obj=1e-9)) o5 = Optimize(method=CmdStan.Bfgs(tol_obj=1e-9), save_iterations=true) @assert o5.method.tol_obj == o1.method.tol_obj/10 println() show(IOContext(stdout, :compact => true), o5) println() show(o5) d1 = Diagnose() @assert d1.diagnostic.error == 1e-6 d2 = Diagnose(CmdStan.Gradient(error=1e-7)) @assert d2.diagnostic.error == 1e-7 println() show(IOContext(stdout, :compact => true), d2) println() show(d2) println() m.command cd(ProjDir) isdir("tmp") && rm("tmp", recursive=true); end # cd
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
609
using CmdStan N1 = 10 data1 = Dict( "Scalar" => rand(), "Single_element_vector" => [rand()], "Vector" => rand(N1), "Array" => rand(N1,3) ) N = 100000 data = Dict( "Scalar" => rand(), "Single_element_vector" => [rand()], "Vector" => rand(N), "Array" => rand(N,3) ) ProjDir = dirname(@__FILE__) cd(ProjDir) do Stan.update_R_file("testdata0", data1) Stan.update_R_file_jon("testdata1", data1) @time Stan.update_R_file("testdata0", data) @time Stan.update_R_file_jon("testdata1", data) isfile("testdata0") && rm("testdata0"); isfile("testdata1") && rm("testdata1"); end # cd
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
231
ProjDir = joinpath(dirname(@__FILE__), "..", "examples", "Dyes") cd(ProjDir) do isdir("tmp") && rm("tmp", recursive=true); include(joinpath(ProjDir, "dyes.jl")) isdir("tmp") && rm("tmp", recursive=true); end # cd
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
291
using CmdStan, Test ## testing accessors to CMDSTAN_HOME let oldpath = CmdStan.CMDSTAN_HOME newpath = CmdStan.CMDSTAN_HOME * "##test##" set_cmdstan_home!(newpath) @test CmdStan.CMDSTAN_HOME == newpath set_cmdstan_home!(oldpath) @test CmdStan.CMDSTAN_HOME == oldpath end
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
923
using CmdStan, Test cnames = ["x", "y.1", "y.2", "z.1.1", "z.2.1", "z.3.1", "z.1.2", "z.2.2", "z.3.2", "k.1.1.1.1.1"] draws = 100 vars = length(cnames) chains = 2 chns = randn(draws, vars, chains) nt = extract(chns, cnames) @testset "extract" begin # Write your tests here. @test size(nt.x) == (draws, chains) @test size(nt.y) == (2, draws, chains) @test size(nt.z) == (3, 2, draws, chains) @test size(nt.k) == (1, 1, 1, 1, 1, draws, chains) key_to_idx = Dict(name => idx for (idx, name) in enumerate(cnames)) @test nt.x[2,1] == chns[2, key_to_idx["x"], 1] @test nt.y[2,3,2] == chns[3, key_to_idx["y.2"], 2] @test nt.z[3, 1, 10, 1] == chns[10, key_to_idx["z.3.1"], 1] @test nt.k[1,1,1,1,1,draws,2] == chns[draws, key_to_idx["k.1.1.1.1.1"], 2] @test keys(nt) == (:y, :k, :z, :x) @test size(values(nt.z)) == (3, 2, 100, 2) @test size(nt.z) == (3, 2, 100, 2) end
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
701
using CmdStan ProjDir = dirname(@__FILE__); cd(ProjDir) do isdir("tmp") && rm("tmp", recursive=true); ar1 = " data { int T; real y0; real phi; real sigma; } parameters{} model{} generated quantities { vector[T] yhat; yhat[1] = y0; for (t in 2:T) yhat[t] = normal_rng(phi*yhat[t-1],sigma); } " # T = 100; y0 = 1; phi = 0.95; sigma = 1; # make the data dictionary dat = Dict("T"=>T,"y0"=>y0,"phi"=>phi,"sigma"=>sigma); stanmodel= Stanmodel(name = "ar1", model = ar1, Sample(algorithm=CmdStan.Fixed_param())); rc, sim1 = stan(stanmodel, dat, ProjDir, CmdStanDir=CMDSTAN_HOME); isdir("tmp") && rm("tmp", recursive=true); end
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
1587
using CmdStan, DataFrames, Test, Statistics tempdir = pwd() nwarmup, nsamples, nchains = 1000, 1000, 4 stan_code = " data { int<lower = 1> J; // number of cases real<lower = 0> onset_day_reported[J]; //day of illness onset } parameters { real<lower = 0> incubation[J]; real mu; real<lower = 0> sigma; } model { mu ~ normal(0, 5); sigma ~ cauchy(0, 5); incubation ~ lognormal(mu,sigma); for (j in 1:J) { target += normal_lpdf(incubation[j] | onset_day_reported[j]+0.5, 0.5); } } generated quantities { real incubation_mean = exp(mu+sigma^2/2.0); real incubation_sd = sqrt((exp(sigma^2)-1.0)*exp(2.0*mu+sigma^2)); } " df_inc = DataFrame(Dict("n" => [1, 5, 7, 9, 17, 18, 16, 6, 8, 10, 7, 1, 2, 4, 4, 1], "day" => [6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 25])) days_inc = vcat(fill.(df_inc[!,:day],df_inc[!,:n])...) stan_data = Dict("J" => length(days_inc), "onset_day_reported" => days_inc) # stan_init = Dict("mu" => 2.5, "sigma" => 0.2, "incubation" => days_inc .+ 0.5) stan_init = Dict("incubation[$i]"=>v+.5 for (i,v) in enumerate(days_inc)) temp_init = Dict("mu" => 2.5, "sigma" => 1.0) merge!(stan_init, temp_init) stanmodel = Stanmodel( name = "init_array", model = stan_code, nchains = nchains, #init = [stan_init], num_warmup = nwarmup, num_samples = nsamples); rc, a3d, cnames = stan(stanmodel, stan_data, init = stan_init, summary = true); if rc == 0 sdf = read_summary(stanmodel) @test sdf[sdf.parameters .== :mu, :mean][1] β‰ˆ 2.5 rtol=0.1 end
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
956
function f(x) println("Calling f($x)") end function f(x, y::Number) println("Calling y::Number f($x, $y)") end function f(x, y::Array) println("Calling y::Array f($x, $y)") end function f(x, y::Matrix) println("Calling y::Matrix f($x, $y)") end function f(x, y::Dict) println("Calling y::Dict f($x, $y)") end function f(x, y::Vector{Dict{Symbol, Any}}) println("Calling y::Vector{Dict{Symbol, Any}} f($x, $y)") end function f(x, y::Vector{Dict{String, Any}}) println("Calling y::Vector{Dict{String, Any}} f($x, $y)") end f(5) f(5, 3) f(5, [2]) f(5, [2.0]) f(5, [1 2;3 4]) dct1 = Dict{Symbol, Any}(:y => 1) f(5, dct1) dct2 = Dict{Symbol, Any}[ Dict(:theta => 0.1), Dict(:theta => [0.4]), Dict(:theta => [0.1, 0.2, 0.4]), Dict(:theta => [0.4 0.5; 0.6 0.7]), ] f(5, dct2) dct3 = Dict[ Dict("theta" => 0.1), Dict("theta" => [0.4]), Dict("theta" => [0.1, 0.2, 0.4]), Dict("theta" => [0.4 0.5; 0.6 0.7]), ] f(5, dct3)
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
249
ProjDir = joinpath(dirname(@__FILE__), "..", "examples", "ARM", "Ch03", "Kid") cd(ProjDir) do isdir("tmp") && rm("tmp", recursive=true); include(joinpath(ProjDir, "kidscore.jl")) isdir("tmp") && rm("tmp", recursive=true); end # cd
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
1265
######### CmdStan program example ########### using CmdStan using MCMCChains ProjDir = dirname(@__FILE__) cd(ProjDir) do bernoullimodel = " data { int<lower=1> N; int<lower=0,upper=1> y[N]; } parameters { real<lower=0,upper=1> theta; } model { theta ~ beta(1,1); y ~ bernoulli(theta); } "; observeddata = Dict("N" => 10, "y" => [0, 1, 0, 1, 0, 0, 0, 0, 0, 1]) global stanmodel, rc, chn, chns, cnames, summary_df tmpdir = ProjDir*"/tmp" stanmodel = Stanmodel(Sample(save_warmup=false, num_warmup=1000, num_samples=2000, thin=1), name="bernoulli", model=bernoullimodel, printsummary=false, tmpdir=tmpdir, output_format=:mcmcchains); rc, chns, cnames = stan(stanmodel, observeddata, ProjDir, diagnostics=false, CmdStanDir=CMDSTAN_HOME); if rc == 0 # Check if StatsPlots is available if isdefined(Main, :StatsPlots) p1 = plot(chns) savefig(p1, joinpath(tmpdir, "traceplot.pdf")) p2 = pooleddensity(chns) savefig(p2, joinpath(tmpdir, "pooleddensity.pdf")) end # Describe the results show(chns) println() # Ceate a ChainDataFrame sdf = read_summary(stanmodel) sdf[sdf.parameters .== :theta, [:mean, :ess]] end end # cd
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
871
using CmdStan ProjDir = @__DIR__ cd(ProjDir) bernoulli_model = " functions{ #include model_specific_funcs.stan #include shared_funcs.stan // a comment //#include shared_funcs.stan // a comment } data { int<lower=1> N; int<lower=0,upper=1> y[N]; } parameters { real<lower=0,upper=1> theta; } model { model_specific_function(); theta ~ beta(my_function(),1); y ~ bernoulli(theta); } "; observeddata = Dict("N" => 10, "y" => [0, 1, 0, 1, 0, 0, 0, 0, 0, 1]) stanmodel = Stanmodel(Sample(save_warmup=false, num_warmup=1000, num_samples=2000, thin=1), name="bernoulli", model=bernoulli_model, printsummary=false, tmpdir=mktempdir()); rc, a3d, cnames = stan(stanmodel, observeddata, ProjDir); if rc == 0 sdf = read_summary(stanmodel) @test sdf[sdf.parameters .== :theta, :mean][1] β‰ˆ 0.34 rtol=0.1 end
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
1474
using CmdStan wd = dirname(@__FILE__) if !isdefined(Main, :update_R_file) function update_R_file{T<:Any}(file::String, dct::Dict{String, T}; replaceNaNs::Bool=true) isfile(file) && rm(file) open(file, "w") do strmout str = "" for entry in dct str = "\""entry[1]"\""" <- " val = entry[2] if length(val)==1 && length(size(val))==0 # Scalar str = str*"$(val)\n" elseif length(val)==1 && length(size(val))==1 # Single element vector #str = str*"$(val[1])\n" elseif length(val)>1 && length(size(val))==1 # Vector str = str*"structure(c(" write(strmout, str) str = "" writecsv(strmout, val'); str = str*"), .Dim=c($(length(val))))\n" elseif length(val)>1 && length(size(val))>1 # Array str = str*"structure(c(" write(strmout, str) str = "" writecsv(strmout, val[:]'); dimstr = "c"*string(size(val)) str = str*"), .Dim=$(dimstr))\n" end write(strmout, str) end end end end dct = Dict[ Dict("theta" => 0.1), Dict("theta" => [0.4]), Dict("theta" => [0.1, 0.2, 0.4]), Dict("theta" => [0.4 0.5; 0.6 0.7]), ] for i in 1:length(dct) #for j in ["data", "init"] for j in ["data"] file = joinpath(wd, "test_r_$(i)_$(j).R") isfile(file) && rm(file) Stan.update_R_file(file, dct[i]) end end
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
266
using CmdStan, Test ProjDir = joinpath(dirname(@__FILE__), "..", "examples", "EightSchools") cd(ProjDir) do isdir("tmp") && rm("tmp", recursive=true); include(joinpath(ProjDir, "schools8.jl")) isdir("tmp") && rm("tmp", recursive=true); end # cd
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
372
struct Stop <: Exception end function run_task(f) try f() catch e if isa(e, Stop) println("Your program was gracefully terminated.") else rethrow() end end end function f() throw(Stop()) end function g() f() end run_task() do g() end println() run_task() do error("This is bad.") end println("Done!")
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
309
using CmdStan cmd1 = `echo` cmd2 = `2` sa = ["3", "4"] s = "5" #r1 = cmd1 * cmd2; println(r1) #r2 = cmd1 * sa; println(r2) #r3 = cmd1 * s; println(r3) cs = Base.AbstractCmd[] for i in 1:5 push!(cs, `echo $i`) end println() r = CmdStan.par(cs) run(r) println() r = CmdStan.par(`echo hello`, 6) run(r)
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
619
# Test script to test Stan on Windows try global CMDSTAN_HOME = @static Sys.iswindows() ? "C:\\cmdstan" : CMDSTAN_HOME Pkg.rm("Stan") Pkg.rm("Stan") Pkg.clone("Stan") catch e println(e) end # Go to the Stan.jl package directory ProjDir = joinpath(dirname(@__FILE__), "..", "examples", "Bernoulli") cd(ProjDir) do isdir("tmp") && rm("tmp", recursive=true); try include(joinpath(ProjDir, "bernoulli.jl")) catch e println(e) end println("After include('bernoulli.jl'), CMDSTAN_HOME is set to: $(CMDSTAN_HOME)") cd(stanmodel.tmpdir) run(`ls`) println() println(stanmodel.command) println() end # cd
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
595
using DelimitedFiles ProjDir = @__DIR__ x = [1.0; 2; 3; 4]; y = [5; 6; 7; 8.0]; open(joinpath(ProjDir, "test_delim_file.txt"), "w") do io writedlm(io, [x y], ',') end res = readdlm(joinpath(ProjDir, "test_delim_file.txt"), ',') println(res) dct1 = [ Dict("theta" => 0.1), Dict("theta" => [0.4]), Dict("theta" => [0.1, 0.2, 0.4]), Dict("theta" => [0.4 0.5; 0.6 0.7]), ] for entry in dct1 str = '"' * "$entry" * '"' * " <- " writedlm(joinpath(ProjDir, "test_delim_file_2.txt"), str, "") end strmin = open(joinpath(ProjDir, "test_delim_file_2.txt"), "r") readdlm(strmin, ',')
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
917
using CmdStan, Test, Statistics ProjDir = dirname(@__FILE__) cd(ProjDir) do isdir("tmp") && rm("tmp", recursive=true); bernoullimodel = " data { int<lower=1> N; int<lower=0,upper=1> y[N]; real empty[0]; } parameters { real<lower=0,upper=1> theta; } model { theta ~ beta(1,1); y ~ bernoulli(theta); } " observeddata = [ Dict("N" => 10, "y" => [0, 1, 0, 1, 0, 0, 0, 0, 0, 1],"empty"=>Float64[]), ] global stanmodel, rc, sim stanmodel = Stanmodel(num_samples=1200, thin=2, name="bernoulli", output_format=:array, model=bernoullimodel); rc, sim = stan(stanmodel, observeddata, ProjDir, diagnostics=false, CmdStanDir=CMDSTAN_HOME); if rc == 0 println() println("Test 0.2 < round(mean(theta), digits=1) < 0.4") @test 0.2 < round(mean(sim[:,8,:]), digits=1) < 0.4 end isdir("tmp") && rm("tmp", recursive=true); end # cd
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
716
using Mamba, Plots pyplot(size=(800,800)) if !isdefined(Main, :traceplot) function traceplot(c::AbstractChains; legend::Bool=false, na...) nrows, nvars, nchains = size(c.value) plts = Array{Plots.Plot{Plots.PyPlotBackend}}(nvars) for i in 1:nvars plts[i] = plot(1:nrows, c.value[:, i, :]) end plts end end if !isdefined(Main, :meanplot) function meanplot(c::AbstractChains; legend::Bool=false, na...) nrows, nvars, nchains = size(c.value) plts = Array{Plots.Plot{Plots.PyPlotBackend}}(nvars) val = Mamba.cummean(c.value) for i in 1:nvars plts[i] = plot(1:nrows, val[:, i, :], lab="Chain $i") end plts end end tp = traceplot(sim) mp = meanplot(sim)
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
643
abstract type Metrics end mutable struct Unit_e <: Metrics end mutable struct Diag_e <: Metrics end abstract type SamplingAlgorithm end mutable struct Hmc <: SamplingAlgorithm # ... metric::Metrics end mutable struct Fixed_param <: SamplingAlgorithm end Hmc() = Hmc(Diag_e()) Hmc(m::DataType) = ( m <: Metrics ? Hmc(m()) : "Error: $(m) not a subtype of Metrics" ) Hmc(m::Symbol) = ( eval(m) <: Metrics ? Hmc(eval(m)()) : "Error: $(m) not a subtype of Metrics" ) h = Hmc() l = Hmc(Diag_e) k = Hmc(:Unit_e) @assert isa(h.metric, Metrics) @assert isa(l.metric, Metrics) @assert isa(k.metric, Metrics) @assert typeof(k.metric) <: Metrics
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
docs
5018
# CmdStan | **Project Status** | **Documentation** | **Build Status** | |:-------------------------------------------------------------------------------:|:-------------------------------------------------------------------------------:|:-----------------------------------------------------------------------------------------------:| |![][project-status-img] | [![][docs-stable-img]][docs-stable-url] [![][docs-dev-img]][docs-dev-url] | ![][CI-build] | [docs-dev-img]: https://img.shields.io/badge/docs-dev-blue.svg [docs-dev-url]: https://stanjulia.github.io/CmdStan.jl/latest [docs-stable-img]: https://img.shields.io/badge/docs-stable-blue.svg [docs-stable-url]: https://stanjulia.github.io/CmdStan.jl/stable [CI-build]: https://github.com/stanjulia/CmdStan.jl/workflows/CI/badge.svg?branch=master [issues-url]: https://github.com/stanJulia/CmdStan.jl/issues [project-status-img]: https://img.shields.io/badge/lifecycle-deprecated-orange.svg ## Purpose *A package to run Stan's cmdstan executable from Julia.* ## Status CmdStan.jl will be deprecated in 2022. Please switch to StanSample.jl. Time permitting, Pull Requests will be merged if all tests pass and new fuctionality is tested. ## Prerequisites For more info on Stan, please go to <http://mc-stan.org>. The Julia package CmdStan.jl is based on Stan's command line interface, 'cmdstan'. The 'cmdstan' interface needs to be installed separatedly. Please see [cmdstan installation](https://github.com/StanJulia/CmdStan.jl/blob/master/docs/src/INSTALLATION.md) for further details. The location of the cmdstan executable and related programs is now obtained from the environment variable JULIA_CMDSTAN_HOME. This used to be CMDSTAN_HOME. Right now `versioninfo()` will show its setting (if defined). ## Versions Release 6.2.0 - Thanks to @Byrth. Switch from using ``` cd(dir) do # stuff run(cmd) end ``` to # stuff ```run(setenv(cmd, ENV; dir=dir))``` in main functions. Release 6.0.9 1. Switch to GitHub actions. Release 6.0.8 1. Thanks to @yiyuezhuo, a function `extract` has been added to simplify grouping variables into a NamedTuple. 2. Stanmodel's output_format argument has been extended with an option to request conversion to a NamedTuple. 3. Updated CSV.read to specify Dataframe argument Release 6.0.7 1. Compatibility updates 2. Cmdstan version updates. Release 6.0.2-6 1. Fixed an issue related to naming of created files. Thanks to mkshirazi. 2. Several bumps to deal with package versions. 3. Re-enabling Coverage. Release 6.0.2 1. Init files were not properly included in cmd. Thanks to ueliwechsler and andrstef. Release 6.0.1 1. Removed dependency on Documenter. Release 6.0.0 contains: 1. Revert back to output an array by default. 2. Switch to Requires.jl to delay/prevent loading of MCMCChains if not needed (thanks to suggestions by @Byrth and Stijn de Waele). 3. Updates to documentation. Release 6.0.0 is a breaking release. To revert back to v5.x behavior a script needs to include `using MCMCChains` (which thus must be installed) and specify `output_format=:mcmcchains` in the call to `stanmodel()`. This option is not tested on Travis. A sub-directory examples_mcmcchains has been added which demonstrate this usage pattern. CmdStan.jl tested on cmdstan v2.21.0. ## Documentation - [**STABLE**][docs-stable-url] &mdash; **documentation of the most recently tagged version.** - [**DEVEL**][docs-dev-url] &mdash; *documentation of the in-development version.* ## Questions and issues Question and contributions are very welcome, as are feature requests and suggestions. Please open an [issue][issues-url] if you encounter any problems or have a question. ## References There is no shortage of good books on Bayesian statistics. A few of my favorites are: 1. [Bolstad: Introduction to Bayesian statistics](http://www.wiley.com/WileyCDA/WileyTitle/productCd-1118593227.html) 2. [Bolstad: Understanding Computational Bayesian Statistics](http://www.wiley.com/WileyCDA/WileyTitle/productCd-0470046090.html) 3. [Gelman, Hill: Data Analysis using regression and multileve,/hierachical models](http://www.stat.columbia.edu/~gelman/arm/) 4. [McElreath: Statistical Rethinking](http://xcelab.net/rm/statistical-rethinking/) 5. [Gelman, Carlin, and others: Bayesian Data Analysis](http://www.stat.columbia.edu/~gelman/book/) 6. [Lee, Wagenmakers: Bayesian Cognitive Modeling](https://www.cambridge.org/us/academic/subjects/psychology/psychology-research-methods-and-statistics/bayesian-cognitive-modeling-practical-course?format=PB&isbn=9781107603578) 7. [Kruschke:Doing Bayesian Data Analysis](https://sites.google.com/site/doingbayesiandataanalysis/what-s-new-in-2nd-ed) 8. [Betancourt: A Conceptual Introduction to Hamiltonian Monte Carlo](https://arxiv.org/abs/1701.02434)
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
docs
826
# cmdstan installation ## Minimal requirement Note: CmdStan.jl and CmdStan refer to this Julia package. The executable C++ program is 'cmdstan'. To run this version of the CmdStan.jl package on your local machine, it assumes that the [cmdstan](http://mc-stan.org/interfaces/cmdstan) executable is properly installed. In order for CmdStan.jl to find the cmdstan you need to set the environment variable `JULIA_CMDSTAN_HOME` to point to the cmdstan directory, e.g. add ``` export JULIA_CMDSTAN_HOME=/Users/rob/Projects/Stan/cmdstan launchctl setenv JULIA_CMDSTAN_HOME /Users/rob/Projects/Stan/cmdstan ``` to `~/.bash_profile` or add `ENV["JULIA_CMDSTAN_HOME"]="./cmdstan"` to `./julia/etc/startup.jl`. I typically prefer cmdstan not to include the cmdstan version number so no update is needed when cmdstan is updated.
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
docs
3002
# A Julia interface to cmdstan ## CmdStan.jl [Stan](https://github.com/stan-dev/stan) is a system for statistical modeling, data analysis, and prediction. It is extensively used in social, biological, and physical sciences, engineering, and business. The Stan program language and interfaces are documented [here](http://mc-stan.org/documentation/). [cmdstan](http://mc-stan.org/interfaces/cmdstan.html) is the shell/command line interface to run Stan language programs. [CmdStan.jl](https://github.com/StanJulia/CmdStan.jl) wraps cmdstan and captures the samples for further processing. ## StanJulia CmdStan.jl is part of the [StanJulia Github organization](https://github.com/StanJulia) set of packages. It is one of two options in StanJulia to capture draws from a Stan language program. The other option is *under development* and is illustrated in Stan.jl and [StatisticalRethinking.jl](https://github.com/StatisticalRethinkingJulia/StatisticalRethinking.jl). These are not the only options to sample using Stan from Julia. Valid other options are PyCall.jl/PyStan and StanRun.jl. On a very high level, a typical workflow for using CmdStan.jl looks like: ``` using CmdStan # Define a Stan language program. bernoulli = "..." # Prepare for calling cmdstan. stanmodel = StanModel(...) # Compile and run Stan program, collect draws. rc, samples, cnames = stan(...) # Cmdstan summary of result sdf = read_summary(stanmodel) # Dsplay the summary sdf |> display # Show the draws samples |> display ``` This workflow creates an array of draws, the default value for the `output_format` argument in Stanmodel(). Other options are `:dataframes` and `:mcmcchains`. If at this point a vector of DataFrames (a DataFrame for each chain) is preferred: ``` df = CmdStan.convert_a3d(samples, cnames, Val(:dataframes)) ``` Or, if you know upfront a vector of DataFrames is what you want, you can specify that when creating the Stanmodel: ``` stanmodel = StanModel(..., output_format=:dataframes,...) ``` Version 5 of CmdStan.jl used `:mcmcchains` by default but the dependencies of MCMCChains.jl, including access to plotting features, can lead to long compile times. ## References There is no shortage of good books on Bayesian statistics. A few of my favorites are: 1. [Bolstad: Introduction to Bayesian statistics](http://www.wiley.com/WileyCDA/WileyTitle/productCd-1118593227.html) 2. [Bolstad: Understanding Computational Bayesian Statistics](http://www.wiley.com/WileyCDA/WileyTitle/productCd-0470046090.html) 3. [Gelman, Hill: Data Analysis using regression and multileve,/hierachical models](http://www.stat.columbia.edu/~gelman/arm/) 4. [McElreath: Statistical Rethinking](http://xcelab.net/rm/statistical-rethinking/) 5. [Gelman, Carlin, and others: Bayesian Data Analysis](http://www.stat.columbia.edu/~gelman/book/) and a great read (and implementation in DynamicHMC.jl): 5. [Betancourt: A Conceptual Introduction to Hamiltonian Monte Carlo](https://arxiv.org/abs/1701.02434)
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
docs
4524
# Version approach and history ## Approach A version of a Julia package is labeled (tagged) as v"major.minor.patch". My intention is to update the patch level whenever I make updates which are not visible to any of the existing examples. New functionality will be introduced in minor level updates. This includes adding new examples, tests and the introduction of new arguments if they default to previous behavior, e.g. in v"4.2.0" the `run_log_file` argument to stan(). Changes that require updates to some examples bump the major level. Updates for new releases of Julia and cmdstan bump the appropriate level. ## Testing Versions 6.x of the package has been developed and tested on Mac OSX 10.15.3, Julia 1.3+ and tested on cmdstan v2.21.0. ## Versions ### Release 6.0.2 1. Init files were not properly included in cmd. Thanks to ueliwechsler and andrstef. ### Release 6.0.1 1. Removed dependency on Documenter. ### Version 6.0.0 Release 6.0.0 is a breaking release. To revert back to v5.x behavior a script needs to include `using MCMCChains` (which thus must be installed) and specify `output_format=:mcmcchains` in the call to `stanmodel()`. This option is not tested on Travis, a sub-directory examples_mcmcchains has been added which demonstrate this usage pattern. 1. Revert back to output an array by default. 2. Switch to Requires.jl to delay/prevent loading of MCMCChains if not needed (thanks to suggestions by @Byrth and Stijn de Waele). 3. WIP: Redoing documentation. ### Version 5.6.0 1. Simplification were possible, removal of some older constructs. 2. Removal of NamedArrays. This is mildly breaking. If needed it can be brought back using Requires. ### Version 5.5.0 1. Upper bound fixes. ### Version 5.4.0 1. Removed init and data from Stanmodel. Data and init needs to be specified (if needed) in stan(). This is a breaking change although it wasn't handled properly. Thanks to Andrei R. Akhmetzhanov and Chris Fisher. ### Version 5.2.3 1. Fixed an issue in running read_samples from the REPL (thanks to Graydon Marz). ### Version 5.2.2 1. Made sure by default no files are created in Julia's `package` directory. 2. Removed some DataFrame update warnings. ### Version 5.2.1 contains: 1. Fixed an issue with read_diagnose.jl which failed on either linux or osx because of slightly different .csv file layout. ### Version 5.2.0 contains: 1. Specified Julia 1 dependency in Project 2. Updates from sdewaele to fix resource busy or locked error messages 3. Thanks to Daniel Coutinho an issue was fixed which made running CmdStan using Atom bothersome. 4. Contains a fix in diagnostics testing ### Version 5.1.1 contains: 1. Fixed an issue with ```save_warmup``` in Variational (thanks to fargolo). 2. Fixed a documentation issue in ```rel_path_cmdstan```. 3. Enabled specifying ```data``` and ```init``` using an existing file. 4. Support for Stan's include facility (thanks to Chris Fisher). CmdStan.jl tested on cmdstan v2.20.0. ### Version 5.1.0 contains: 1. Support for retrieving stansummary data (read_summary()). 2. Support for using mktempdir() (might improve issue #47). 3. Fixed handling of save_warmup. 4. Read all optimization iterations (thanks to sdewaele). 5. Several other minor documentation and type definition updates. 6. Fixeda bug related to Array{Dict} inputs to init and data (thanks to sdewaele). 7. Added a test to compare Stan's ESS values with MCMCChains ESS values. 8. Updated all examples to have a single Dict as data input (suggested by sdewaele). ### Version 4.5.2 1. Mostly minor (but important) fixes in documentation (thanks to Oliver Dechant). 2. Supports non-array versions of input data and inits. 3. Announcement v5.x.x will be based on MCMCChains.jl. StanMCMCChains.jl will also be renamed accordingly (StanMCMCChains.jl) once MCMCChains.jl is registered. ### Version 4.4.0 1. Pkg3 based. 2. Added the output_format option :namedarray which will return a NamesArrays object instead of the a3d array. ### Version 4.2.0/4.3.0 1. Added ability to reformat a3d_array to a TuringLang/MCMCChain object. 2. Added the ability to display the sample drawing progress in stdout (instead of storing these updated in the run_log_file) ### Version 4.1.0 1. Added ability to reformat a3d_array, e.g. to a DataFrame or a Mamba.Chains object using add-on packages such as StanDataFrames and StanMamba. 2. Allowed passing zero-length arrays as input. ### Version 4.0.0 1. Initial Julia 1.0 release of CmdStan.jl (based on Stan.jl). _
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
docs
5471
# A walk-through example ## Bernoulli example Make CmdStan.jl available: ``` using CmdStan ``` Define a variable, e.g. 'bernoullistanmodel', to hold the Stan model definition: ``` bernoullistanmodel = " data { int<lower=0> N; int<lower=0,upper=1> y[N]; } parameters { real<lower=0,upper=1> theta; } model { theta ~ beta(1,1); y ~ bernoulli(theta); } " ``` Create a Stanmodel object by giving the model a name and pass in the Stan model: ``` stanmodel = Stanmodel(name="bernoulli", model=bernoullistanmodel); ``` This creates a default model for sampling. A subsequent call to stan() will return an array of samples. Other arguments to Stanmodel() can be found in [`Stanmodel`](@ref) The observed input data is defined below. ``` bernoullidata = Dict("N" => 10, "y" => [0, 1, 0, 1, 0, 0, 0, 0, 0, 1]) ``` Each chain will use this data. If needed, an Array{Dict} can be defined with the same number of entries as the number of chains. This is also true for the optional `init` argument to stan(). Use these features with care, particularly providing different data as the chains are supposed to be from identical observed data. Run the simulation by calling stan(), passing in the data and the intended working directory. ``` ProjDir = @__DIR__ rc, chns, cnames = stan(stanmodel, bernoullidata, ProjDir, CmdStanDir=CMDSTAN_HOME) ``` More documentation on stan() can be found in [`stan`](@ref) If the return code rc indicated success (rc == 0), cmdstan execution completed succesfully. Next possible steps can be: ``` sdf = read_summary(stanmodel) ``` The first time (or when updates to the model have been made) stan() will compile the model and create the executable. On Windows, the CmdStanDir argument appears needed (this is still being investigated). On OSX/Unix CmdStanDir is obtained from an environment variable (see the Requirements section). By default stan() will run 4 chains and optionally display a combined summary. Some other CmdStan methods, e.g. optimize, return a dictionary. If `summary = true`, the default, the stan summary is also written to a .csv file and can be read in using: ``` csd = read_summary(stanmodel) csd[:theta, :mean] # Select mean as computed by the stansummary binary. ``` Stanmodel has an optional argument `printsummary=false` to have cmdstan create the summary .csv file but not display the stansummary. ## Output format options CmdStan.jl supports 3 output formats: 1. A 3 dimensional array ("a3d") where the first index refers to samples, the 2nd index to parameters and the 3rd index to chains. 2. A MCMCChains.Chains object, see the examples in subdirectory examples_mcmcchains. 3. A DataFrames object. The default output format is :array. To specify options 2 and 3 use: ``` stammodel= Stanmodel(..., output_format=:mcmcchains, ...) ``` or ``` stanmodel = Stanmodel(..., output_format=:dataframes, ...) ``` when creating the Stanmodel. It is very important that in order to use option 2 the package MCMCChains.jl needs to be installed and loaded in your script, e.g. see the `bernoulli.jl` example in the ```examples_mcmcchains``` directory. ## Running a CmdStan script, some details CmdStan.jl really only consists of 2 functions, Stanmodel() and stan(). ### [`Stanmodel`](@ref) Stanmodel() is used to define the basic attributes for a model: ``` monitor = ["theta", "lp__", "accept_stat__"] stanmodel = Stanmodel(name="bernoulli", model=bernoullistanmodel, monitors=monitor); stanmodel ``` Above script, in the Julia REPL, shows all parameters in the model, in this case (by default) a sample model. Compared to the call to Stanmodel() above, the keyword argument monitors has been added. This means that after the simulation is complete, only the monitored variables will be read in from the .csv file produced by Stan. This can be useful if many, e.g. 100s, nodes are being observed. If the requested result is an MCMCChains.Chains object, another option is available by using ```set_section(chain, section_map_dict)```, e.g. see the example in ```examples_mcmcchains/Dyes/dyes.jl```. If the samples are stored in a vector of DataFrames, the usual DataFrames selection options are available. Below an example of updating default model values when creating a model: ``` stanmodel2 = Stanmodel(Sample(adapt=CmdStan.Adapt(delta=0.9)), name="bernoulli2", nchains=6) ``` The format is slightly different from cmdstan, but the parameters are as described in the cmdstan Interface User's Guide. This is also the case for the Stanmodel() optional arguments random, init and output (refresh only). In the REPL, the stanmodel2 can be shown by: ``` stanmodel2 ``` After the Stanmodel object has been created fields can be updated, e.g. ``` stanmodel2.method.adapt.delta=0.85 ``` ### [`stan`](@ref) After a Stanmodel has been created, the workhorse function stan() is called to run the simulation. Note that some fields in the Stanmodel are updated by stan(). After the stan() call, the stanmodel.command contains an array of Cmd fields that contain the actual run commands for each chain. These are executed in parallel if that is possible. The call to stan() might update other info in the StanModel, e.g. the names of diagnostics files. The stan() call uses 'make' to create (or update when needed) an executable with the given model.name, e.g. bernoulli in the above example. If no model AbstractString (or of zero length) is found, a message will be shown.
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
docs
854
# Programs ## CMDSTAN_HOME ```@docs CMDSTAN_HOME ``` ## `set_cmdstan_home!` ```@docs CmdStan.set_cmdstan_home! CmdStan.rel_path_cmdstan ``` ## stanmodel() ```@docs Stanmodel CmdStan.update_model_file ``` ## stan() ```@docs stan ``` ## Types ```@docs CmdStan.Method CmdStan.Sample CmdStan.Adapt CmdStan.SamplingAlgorithm CmdStan.Hmc CmdStan.Metric CmdStan.Engine CmdStan.Nuts CmdStan.Static CmdStan.Diagnostics CmdStan.Gradient CmdStan.Diagnose CmdStan.OptimizeAlgorithm CmdStan.Optimize CmdStan.Lbfgs CmdStan.Bfgs CmdStan.Newton CmdStan.Variational ``` ## Utilities ```@docs CmdStan.cmdline CmdStan.check_dct_type CmdStan.convert_a3d CmdStan.Fixed_param CmdStan.par CmdStan.read_optimize CmdStan.read_samples CmdStan.read_variational CmdStan.read_diagnose CmdStan.stan_summary CmdStan.read_summary CmdStan.update_R_file ``` ## Index ```@index ```
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
docs
992
# LotkaVolterra example in Stan and DiffEqBayes formulations. This subdirectory contains 6 examples. 1. lv_benchmark is basically the benchmark as in DiffEqBayes 2. lv_benchmark_1 identified the lynx-hare coefficients using the lynx-hare data 3. lv_benchmark_2 uses the DiffEqBayes generated data 4. lv_benchmark_3 also runs a DynamicHMC example 5. diffeqbayes four parameter case 6. diffeqbayes one parameter case All simulations usually produce results close to the expected solution. All formulations occasionally have chains that do not converge. All simulations use a slightly updated stan_inference method (imported from DiffEqBayes). It records the u_hat estimates (in a generated_quantities section) and enables pre-compiling by stanc. Note that current benchmarking tools currently don't work well for CmdStan due to the forced compilation of the Stan language program. Notice that several additional (not normally required for CmdStan.jl) packages are needed in these scripts.
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
0.4.4
b8a399e95663485820000f26b6a43c794e166a49
code
223
using Documenter, RandomExtensions makedocs( sitename="RandomExtensions.jl", modules=[RandomExtensions], authors="Rafael Fourquet", ) deploydocs( repo = "github.com/JuliaRandom/RandomExtensions.jl.git", )
RandomExtensions
https://github.com/JuliaRandom/RandomExtensions.jl.git
[ "MIT" ]
0.4.4
b8a399e95663485820000f26b6a43c794e166a49
code
4797
module RandomExtensions export make, Uniform, Normal, Exponential, CloseOpen, OpenClose, OpenOpen, CloseClose, Rand, Bernoulli, Categorical, @rand # re-exports from Random, which don't overlap with new functionality and not from misc.jl export rand!, AbstractRNG, MersenneTwister, RandomDevice import Random: Sampler, rand, rand!, gentype using Random using Random: GLOBAL_RNG, SamplerTrivial, SamplerSimple, SamplerTag, SamplerType, Repetition using SparseArrays: sprand, sprandn, AbstractSparseArray, SparseVector, SparseMatrixCSC if isdefined(Random, :default_rng) using Random: default_rng else @inline default_rng() = GLOBAL_RNG end ## a dummy container type to take advangage of SamplerTag constructor struct Cont{T} end Base.eltype(::Type{Cont{T}}) where {T} = T ## some helper functions, not to be overloaded, except default_sampling default_sampling(::Type{X}) where {X} = error("default_sampling($X) not defined") default_sampling(::X) where {X} = default_sampling(X) default_gentype(::Type{T}) where {T} = val_gentype(default_sampling(T)) default_gentype(::X) where {X} = default_gentype(X) val_gentype(X) = gentype(X) val_gentype(::Type{X}) where {X} = X ## rand! for non-containers rand!(y, X) = rand!(default_rng(), y, X) rand!(y, ::Type{X}) where {X} = rand!(default_rng(), y, X) rand!(rng::AbstractRNG, y, X) = rand!(rng, y, Sampler(rng, X, Val(1))) rand!(rng::AbstractRNG, y, ::Type{X}) where {X} = rand!(rng, y, Sampler(rng, X, Val(1))) ## includes include("distributions.jl") include("sampling.jl") include("containers.jl") include("iteration.jl") include("macros.jl") ## updated rand docstring (TODO: replace Base's one) """ rand([rng=GLOBAL_RNG], [S], [C...]) # RandomExtensions Pick a random element or collection of random elements from the set of values specified by `S`; `S` can be * an indexable collection (for example `1:n` or `['x','y','z']`), * an `AbstractDict` or `AbstractSet` object, * a string (considered as a collection of characters), or * a type: the set of values to pick from is then equivalent to `typemin(S):typemax(S)` for integers (this is not applicable to `BigInt`, and to ``[0, 1)`` for floating point numbers; * a `Distribution` object, e.g. `Normal()` for a normal distribution (like `randn()`), or `CloseOpen(10.0, 20.0)` for uniform `Float64` numbers in the range ``[10.0, 20.0)``; * a `make` object, which can be e.g. `make(Pair, S1, S2)` or `make(Complex, S1, S2)`, where `S1` and `S2` are one of the specifications above; `Pair` or `Complex` can optionally be given as concrete types, e.g. `make(ComplexF64, 1:3, Int)` to generate `ComplexF64` instead of `Complex{Int}`. `S` usually defaults to `Float64`. If `C...` is not specified, `rand` produces a scalar. Otherwise, `C` can be: * a set of integers, or a tuple of `Int`, which specify the dimensions of an `Array` to generate; * `(Array, dims...)`: same as above, but with `Array` specified explicitely; * `(p::AbstractFloat, m::Integer, [n::Integer])`, which produces a sparse array of dimensions `(m, n)`, in which the probability of any element being nonzero is independently given by `p`; * `(String, [n=8])`, which produces a random `String` of length `n`; the generated string consists of `Char` taken from a predefined set like `randstring`, and can be specified with the `S` parameter; * `(Dict, n)`, which produces a `Dict` of length `n`; if `Dict` is given without type parameters, then `S` must be specified; * `(Set, n)` or `(BitSet, n)`, which produces a set of length `n`; * `(BitArray, dims...)`, which produces a `BitArray` with the specified dimensions. For `Array`, `Dict` and `Set`, a less abstract type can be specified, e.g. `Set{Float64}`, to force the type of the result regardless of the `S` parameter. In particular, in the absence of `S`, the type parameter(s) of the container play the role of `S`; for example, `rand(Dict{Int,Float64}, n)` is equivalent to `rand(make(Pair, Int, Float64), Dict, n)`. # Examples ```julia-repl julia> rand(Int, 2) 2-element Array{Int64,1}: 1339893410598768192 1575814717733606317 julia> rand(MersenneTwister(0), Dict(1=>2, 3=>4)) 1=>2 julia> rand("abc", String, 12) "bccaacaabaac" julia> rand(1:10, Set, 3) Set([3, 8, 6]) julia> rand(1:10, Set{Float64}, 3) Set([10.0, 5.0, 6.0]) ``` !!! note The complexity of `rand(rng, s::Union{AbstractDict,AbstractSet})` is linear in the length of `s`, unless an optimized method with constant complexity is available, which is the case for `Dict`, `Set` and `BitSet`. For more than a few calls, use `rand(rng, collect(s))` instead, or either `rand(rng, Dict(s))` or `rand(rng, Set(s))` as appropriate. """ rand end # module
RandomExtensions
https://github.com/JuliaRandom/RandomExtensions.jl.git
[ "MIT" ]
0.4.4
b8a399e95663485820000f26b6a43c794e166a49
code
5988
# generation of some containers filled with random values if VERSION < v"1.2.0-DEV.257" Base.:(!=)(x) = Base.Fix2(!=, x) end function make_argument(param) if param isa Symbol param else param::Expr @assert param.head == :(::) if param.args[1] isa Symbol param.args[1] else @assert param.args[1].head == :curly @assert param.args[1].args[1] == :Type @assert param.args[1].args[2] isa Symbol param.args[1].args[2] end end end # arg names must not be "rng" nor "X", already in use # (this is for nicer output of methods, to avoid cryptic names with gensym) macro make_container(margs...) definitions = [] argss = [] for a in margs push!(argss, a isa Expr && a.head == :vect ? # optional [nothing, a.args[1]] : a isa Expr && a.head == :call && a.args[1] == :(=>) ? # curly [a.args[2] => a.args[3]] : [a]) end pushfirst!(argss, [(), :X, :(::Type{X}) => :X]) # for Sampler for as0 in Iterators.product(argss...) as1 = filter(!=(nothing), collect(Any, as0)) curlys = [] replace!(as1) do a if a isa Pair push!(curlys, a[2]) a.first else a end end for def in (:(rand(rng::AbstractRNG) where {} = rand(rng, make())), :(rand() where {} = rand(default_rng(), make()))) append!(def.args[1].args[1].args, filter(!=(()), as1)) as2 = copy(as1) as2[1], as2[2] = as2[2], as2[1] filter!(!=(()), as2) append!(def.args[2].args[2].args[3].args, map(make_argument, as2)) append!(def.args[1].args, curlys) push!(definitions, def) end end esc(Expr(:block, definitions...)) end @make_container(::Type{String}, [n::Integer]) # we disable smthg like rand(String, 2, 3) because it looks to similar to, but is too different # than, rand(String, 2) (Array of String vs String) string_error() = throw(ArgumentError( "rand([rng], String, d1::Integer, d2::Integer, ...) is unsupported, use rand(rng, make(String), d1, d2, ...) or rand(rng, String, (d1, d2, ...)) instead")) rand(rng::AbstractRNG, ::Type{String}, n::Integer...) = string_error() rand( ::Type{String}, n::Integer...) = string_error() # sparse vectors & matrices @make_container(::Type{SparseVector}, p::AbstractFloat, m::Integer) @make_container(::Type{SparseVector}, p::AbstractFloat, d::Dims{1}) @make_container(::Type{SparseMatrixCSC}, p::AbstractFloat, m::Integer, n::Integer) @make_container(::Type{SparseMatrixCSC}, p::AbstractFloat, d::Dims{2}) # Tuple as a container @make_container(T::Type{<:Tuple}) @make_container(::Type{Tuple}, n::Integer) @make_container(T::Type{NTuple{N,TT} where N} => TT, n::Integer) @make_container(T::Type{<:NamedTuple{K}} => K) if VERSION < v"1.1.0" # disambiguate rand(rng::AbstractRNG, ::Type{NamedTuple}) = rand(rng, make(NamedTuple)) end ## arrays (same as in Random, but with explicit type specification, e.g. rand(Int, Array, 4) macro make_array_container(Cont) definitions = [ :(rand(rng::AbstractRNG, $Cont, dims::Dims) = rand(rng, _make_cont(t, dims))), :(rand( $Cont, dims::Dims) = rand(default_rng(), _make_cont(t, dims))), :(rand(rng::AbstractRNG, $Cont, dims::Integer...) = rand(rng, _make_cont(t, Dims(dims)))), :(rand( $Cont, dims::Integer...) = rand(default_rng(), _make_cont(t, Dims(dims)))), :(rand(rng::AbstractRNG, X, $Cont, dims::Dims) = rand(rng, _make_cont(t, X, dims))), :(rand( X, $Cont, dims::Dims) = rand(default_rng(), _make_cont(t, X, dims))), :(rand(rng::AbstractRNG, X, $Cont, dims::Integer...) = rand(rng, _make_cont(t, X, Dims(dims)))), :(rand( X, $Cont, dims::Integer...) = rand(default_rng(), _make_cont(t, X, Dims(dims)))), :(rand(rng::AbstractRNG, ::Type{X}, $Cont, dims::Dims) where {X} = rand(rng, _make_cont(t, X, dims))), :(rand( ::Type{X}, $Cont, dims::Dims) where {X} = rand(default_rng(), _make_cont(t, X, dims))), :(rand(rng::AbstractRNG, ::Type{X}, $Cont, dims::Integer...) where {X} = rand(rng, _make_cont(t, X, Dims(dims)))), :(rand( ::Type{X}, $Cont, dims::Integer...) where {X} = rand(default_rng(), _make_cont(t, X, Dims(dims)))), ] esc(Expr(:block, definitions...)) end _make_cont(args...) = make(args...) @make_array_container(t::Type{<:Array}) @make_array_container(t::Type{<:BitArray}) @make_array_container(t::AbstractFloat) _make_cont(t::AbstractFloat, x, dims::Dims{1}) = make(SparseVector, x, t, dims) _make_cont(t::AbstractFloat, dims::Dims{1}) = make(SparseVector, t, dims) _make_cont(t::AbstractFloat, x, dims::Dims{2}) = make(SparseMatrixCSC, x, t, dims) _make_cont(t::AbstractFloat, dims::Dims{2}) = make(SparseMatrixCSC, t, dims) ## sets/dicts function _rand!(rng::AbstractRNG, A::SetDict, n::Integer, sp::Sampler) empty!(A) while length(A) < n push!(A, rand(rng, sp)) end A end rand!( A::SetDict, X=default_sampling(A)) = rand!(default_rng(), A, X) rand!(rng::AbstractRNG, A::SetDict, X=default_sampling(A)) = _rand!(rng, A, length(A), sampler(rng, X)) rand!( A::SetDict, ::Type{X}) where {X} = rand!(default_rng(), A, X) rand!(rng::AbstractRNG, A::SetDict, ::Type{X}) where {X} = rand!(rng, A, Sampler(rng, X)) @make_container(T::Type{<:SetDict}, n::Integer)
RandomExtensions
https://github.com/JuliaRandom/RandomExtensions.jl.git
[ "MIT" ]
0.4.4
b8a399e95663485820000f26b6a43c794e166a49
code
8988
# definition of some distribution types ## Distribution & Make abstract type Distribution{T} end Base.eltype(::Type{<:Distribution{T}}) where {T} = T struct Make{T,X<:Tuple, XX<:Tuple} <: Distribution{T} # XX is X with Type{A} replaced by Nothing (otherwise, X (e.g. Tuple{Type{Int}}) can't have instances) x::XX end # @inline necessary for one @inferred test on arrays @inline function Base.getindex(m::Make{T,X}, i::Integer) where {T,X} i = Int(i) fieldtype(X, i) <: Type ? fieldtype(X, i).parameters[1] : m.x[i] end @inline Base.getindex(m::Make, idxs::AbstractVector{<:Integer}) = ntuple(i->m[idxs[i]], length(idxs)) # seems faster than `Tuple(m[i] for i in idxs)` Base.lastindex(m::Make) = lastindex(m.x) @generated function Make{T}(X...) where T XX = Tuple{(x <: Type ? Nothing : x for x in X)...} y = [x <: Type ? nothing : :(X[$i]) for (i, x) in enumerate(X)] :(Make{T,Tuple{$X...},$XX}(tuple($(y...)))) end Make0{T} = Make{T,Tuple{}} Make1{T} = Make{T,Tuple{X}} where X Make2{T} = Make{T,Tuple{X,Y}} where {X, Y} Make3{T} = Make{T,Tuple{X,Y,Z}} where {X, Y, Z} Make4{T} = Make{T,Tuple{X,Y,Z,U}} where {X, Y, Z, U} Make5{T} = Make{T,Tuple{X,Y,Z,U,V}} where {X, Y, Z, U, V} Make0{T}() where {T} = Make{T}() Make1{T}(x) where {T} = Make{T}(x) Make2{T}(x, y) where {T} = Make{T}(x, y) Make3{T}(x, y, z) where {T} = Make{T}(x, y, z) Make4{T}(x, y, z, u) where {T} = Make{T}(x, y, z, u) Make5{T}(x, y, z, u, v) where {T} = Make{T}(x, y, z, u, v) # default maketype & make & Make(...) # Make(...) is not meant to be specialized, i.e. Make(a, b, c) always create a Make3, # and is equal to the *default* make(...) # (it's a fall-back for client code which can help break recursivity) # TODO: add tests for Make(...) maketype(::Type{T}, x...) where {T} = T Make(::Type{T}, x...) where {T} = Make{maketype(T, x...)}(x...) make(::Type{T}, x...) where {T} = Make{maketype(T, x...)}(x...) # make(x) is defined in sampling.jl, and is a special case wrapping already valid # distributions (explicit or implicit) Make(x1, x2, xs...) = Make{maketype(x1, x2, xs...)}(x1, x2, xs...) make(x1, x2, xs...) = Make{maketype(x1, x2, xs...)}(x1, x2, xs...) find_deduced_type(::Type{T}, ::X, ) where {T,X} = deduce_type(T, gentype(X)) find_deduced_type(::Type{T}, ::Type{X}) where {T,X} = deduce_type(T, X) find_deduced_type(::Type{T}, ::X, ::Y) where {T,X,Y} = deduce_type(T, gentype(X), gentype(Y)) find_deduced_type(::Type{T}, ::Type{X}, ::Y) where {T,X,Y} = deduce_type(T, X, gentype(Y)) find_deduced_type(::Type{T}, ::X, ::Type{Y}) where {T,X,Y} = deduce_type(T, gentype(X), Y) find_deduced_type(::Type{T}, ::Type{X}, ::Type{Y}) where {T,X,Y} = deduce_type(T, X, Y) deduce_type(::Type{T}, ::Type{X}, ::Type{Y}) where {T,X,Y} = _deduce_type(T, Val(isconcretetype(T)), X, Y) deduce_type(::Type{T}, ::Type{X}) where {T,X} = _deduce_type(T, Val(isconcretetype(T)), X) _deduce_type(::Type{T}, ::Val{true}, ::Type{X}, ::Type{Y}) where {T,X,Y} = T _deduce_type(::Type{T}, ::Val{false}, ::Type{X}, ::Type{Y}) where {T,X,Y} = deduce_type(T{X}, Y) _deduce_type(::Type{T}, ::Val{true}, ::Type{X}) where {T,X} = T _deduce_type(::Type{T}, ::Val{false}, ::Type{X}) where {T,X} = T{X} # show(::Make) function Base.show(io::IO, m::Make{T}) where {T} M = typeof(m) P = M.parameters[2].parameters t = ntuple(length(m.x)) do i P[i] isa Type{<:Type} ? P[i].parameters[1] : m.x[i] end Base.show_type_name(io, M.name) print(io, "{", T, "}", t) end ## Uniform abstract type Uniform{T} <: Distribution{T} end struct UniformType{T} <: Uniform{T} end Uniform(::Type{T}) where {T} = UniformType{T}() Base.getindex(::UniformType{T}) where {T} = T struct UniformWrap{T,E} <: Uniform{E} val::T end Uniform(x::T) where {T} = UniformWrap{T,gentype(T)}(x) Base.getindex(x::UniformWrap) = x.val ## Normal & Exponential abstract type Normal{T} <: Distribution{T} end struct Normal01{T} <: Normal{T} end struct NormalΞΌΟƒ{T} <: Normal{T} ΞΌ::T Οƒ::T end const NormalTypes = Union{AbstractFloat,Complex{<:AbstractFloat}} Normal(::Type{T}=Float64) where {T<:NormalTypes} = Normal01{T}() Normal(ΞΌ::T, Οƒ::T) where {T<:NormalTypes} = NormalΞΌΟƒ(ΞΌ, Οƒ) Normal(ΞΌ::T, Οƒ::T) where {T<:Real} = NormalΞΌΟƒ(AbstractFloat(ΞΌ), AbstractFloat(Οƒ)) Normal(ΞΌ, Οƒ) = Normal(promote(ΞΌ, Οƒ)...) abstract type Exponential{T} <: Distribution{T} end struct Exponential1{T} <: Exponential{T} end struct ExponentialΞΈ{T} <: Exponential{T} ΞΈ::T end Exponential(::Type{T}=Float64) where {T<:AbstractFloat} = Exponential1{T}() Exponential(ΞΈ::T) where {T<:AbstractFloat} = ExponentialΞΈ(ΞΈ) Exponential(ΞΈ::Real) = ExponentialΞΈ(AbstractFloat(ΞΈ)) ## floats abstract type FloatInterval{T<:AbstractFloat} <: Uniform{T} end abstract type CloseOpen{ T<:AbstractFloat} <: FloatInterval{T} end abstract type OpenClose{ T<:AbstractFloat} <: FloatInterval{T} end abstract type CloseClose{T<:AbstractFloat} <: FloatInterval{T} end abstract type OpenOpen{ T<:AbstractFloat} <: FloatInterval{T} end struct CloseOpen12{T<:AbstractFloat} <: CloseOpen{T} end # interval [1,2) struct CloseOpen01{ T<:AbstractFloat} <: CloseOpen{T} end # interval [0,1) struct OpenClose01{ T<:AbstractFloat} <: OpenClose{T} end # interval (0,1] struct CloseClose01{T<:AbstractFloat} <: CloseClose{T} end # interval [0,1] struct OpenOpen01{ T<:AbstractFloat} <: OpenOpen{T} end # interval (0,1) struct CloseOpenAB{T<:AbstractFloat} <: CloseOpen{T} # interval [a,b) a::T b::T CloseOpenAB{T}(a::T, b::T) where {T} = (check_interval(a, b); new{T}(a, b)) end struct OpenCloseAB{T<:AbstractFloat} <: OpenClose{T} # interval (a,b] a::T b::T OpenCloseAB{T}(a::T, b::T) where {T} = (check_interval(a, b); new{T}(a, b)) end struct CloseCloseAB{T<:AbstractFloat} <: CloseClose{T} # interval [a,b] a::T b::T CloseCloseAB{T}(a::T, b::T) where {T} = (check_interval(a, b); new{T}(a, b)) end struct OpenOpenAB{T<:AbstractFloat} <: OpenOpen{T} # interval (a,b) a::T b::T OpenOpenAB{T}(a::T, b::T) where {T} = (check_interval(a, b); new{T}(a, b)) end check_interval(a, b) = a >= b && throw(ArgumentError("invalid interval specification")) const FloatInterval_64 = FloatInterval{Float64} const CloseOpen01_64 = CloseOpen01{Float64} const CloseOpen12_64 = CloseOpen12{Float64} CloseOpen01(::Type{T}=Float64) where {T<:AbstractFloat} = CloseOpen01{T}() CloseOpen12(::Type{T}=Float64) where {T<:AbstractFloat} = CloseOpen12{T}() CloseOpen(::Type{T}=Float64) where {T<:AbstractFloat} = CloseOpen01{T}() CloseOpen(a::T, b::T) where {T<:AbstractFloat} = CloseOpenAB{T}(a, b) OpenClose(::Type{T}=Float64) where {T<:AbstractFloat} = OpenClose01{T}() OpenClose(a::T, b::T) where {T<:AbstractFloat} = OpenCloseAB{T}(a, b) CloseClose(::Type{T}=Float64) where {T<:AbstractFloat} = CloseClose01{T}() CloseClose(a::T, b::T) where {T<:AbstractFloat} = CloseCloseAB{T}(a, b) OpenOpen(::Type{T}=Float64) where {T<:AbstractFloat} = OpenOpen01{T}() OpenOpen(a::T, b::T) where {T<:AbstractFloat} = OpenOpenAB{T}(a, b) # convenience functions CloseOpen(a, b) = CloseOpen(promote(a, b)...) CloseOpen(a::T, b::T) where {T} = CloseOpen(AbstractFloat(a), AbstractFloat(b)) OpenClose(a, b) = OpenClose(promote(a, b)...) OpenClose(a::T, b::T) where {T} = OpenClose(AbstractFloat(a), AbstractFloat(b)) CloseClose(a, b) = CloseClose(promote(a, b)...) CloseClose(a::T, b::T) where {T} = CloseClose(AbstractFloat(a), AbstractFloat(b)) OpenOpen(a, b) = OpenOpen(promote(a, b)...) OpenOpen(a::T, b::T) where {T} = OpenOpen(AbstractFloat(a), AbstractFloat(b)) ## Bernoulli struct Bernoulli{T<:Number} <: Distribution{T} p::Float64 Bernoulli{T}(p::Real) where {T} = let pf = Float64(p) 0.0 <= pf <= 1.0 ? new(pf) : throw(DomainError(p, "Bernoulli: parameter p must satisfy 0.0 <= p <= 1.0")) end end Bernoulli(p::Real=0.5) = Bernoulli(Int, p) Bernoulli(::Type{T}, p::Real=0.5) where {T<:Number} = Bernoulli{T}(p) ## Categorical struct Categorical{T<:Number} <: Distribution{T} cdf::Vector{Float64} function Categorical{T}(weigths) where T if !isa(weigths, AbstractArray) # necessary for accumulate # TODO: will not be necessary anymore in Julia 1.5 weigths = collect(weigths) end weigths = vec(weigths) isempty(weigths) && throw(ArgumentError("Categorical requires at least one category")) s = Float64(sum(weigths)) cdf = accumulate(weigths; init=0.0) do x, y x + Float64(y) / s end @assert isapprox(cdf[end], 1.0) # really? cdf[end] = 1.0 # to be sure the algo terminates new{T}(cdf) end end Categorical(weigths) = Categorical{Int}(weigths) Categorical(n::Number) = Categorical{typeof(n)}(Iterators.repeated(1.0 / Float64(n), Int(n)))
RandomExtensions
https://github.com/JuliaRandom/RandomExtensions.jl.git
[ "MIT" ]
0.4.4
b8a399e95663485820000f26b6a43c794e166a49
code
882
# iterating over on-the-fly generated random values ## Rand struct Rand{R<:AbstractRNG,S<:Sampler} rng::R sp::S end # X can be an explicit Distribution, or an implicit one like 1:10 Rand(rng::AbstractRNG, X) = Rand(rng, Sampler(rng, X)) Rand(rng::AbstractRNG, ::Type{X}=Float64) where {X} = Rand(rng, Sampler(rng, X)) Rand(X) = Rand(default_rng(), X) Rand(::Type{X}=Float64) where {X} = Rand(default_rng(), X) (R::Rand)(args...) = rand(R.rng, R.sp, args...) Base.iterate(iter::Union{Rand,Distribution}, R::Rand=iter) = R(), R Base.IteratorSize(::Type{<:Rand}) = Base.IsInfinite() Base.IteratorEltype(::Type{<:Rand}) = Base.HasEltype() Base.eltype(::Type{<:Rand{R, <:Sampler{T}}}) where {R,T} = T # convenience iteration over distributions Base.iterate(d::Distribution) = iterate(Rand(default_rng(), d)) Base.IteratorSize(::Type{<:Distribution}) = Base.IsInfinite()
RandomExtensions
https://github.com/JuliaRandom/RandomExtensions.jl.git
[ "MIT" ]
0.4.4
b8a399e95663485820000f26b6a43c794e166a49
code
3418
macro rand(exp) rand_macro(exp) end function rand_macro(ex) whereparams = [] ex isa Expr && ex.head ∈ (:(=), :function, :->) || throw(ArgumentError("@rand requires an expression defining `rand`")) sig = ex.args[1] body = ex.args[2] if sig.head == :where append!(whereparams, sig.args[2:end]) sig = sig.args[1] end if ex.head == :function && sig.head == :tuple # anonymous function sig = Expr(:call, :rand, sig.args...) end if ex.head == :-> # TODO: check that only one argument is passed sig = Expr(:call, :rand, sig) end sig.head == :call && sig.args[1] == :rand || throw(ArgumentError( "@rand requires a function expression defining `rand`")) argname = sig.args[2].args[1] # x namefull = sig.args[2] # x::X @assert namefull.head == :(::) # TODO: throw exception # sub-samplers; second argument true forces Val(Inf) for the sampler sps = Pair{<:Any,Bool}[] rng = gensym() body = samplerize!(sps, body, argname, rng) istrivial = isempty(sps) exsig = Expr(:call, :(Random.rand), :($(esc(rng))::AbstractRNG), esc(as_sampler(namefull, istrivial))) if !isempty(whereparams) exsig = Expr(:where, exsig, map(esc, whereparams)...) end ex = Expr(:function, exsig, esc(body)) sp = if istrivial # we explicitly define Sampler even in the trivial case to handle # redefinitions, where the old rand/sampler pair (for SamplerSimple) # is overwritten by a new one (for SamplerTrivial) quote Random.Sampler(::Type{RNG}, n::Repetition) where {RNG<:AbstractRNG} = SamplerTrivial($(esc(argname))) end else quote Random.Sampler(::Type{RNG}, n::Repetition) where {RNG<:AbstractRNG} = SamplerSimple($(esc(argname)), tuple(SP)) end end @assert sp.args[2].args[1].head == :where append!(sp.args[2].args[1].args, map(esc, whereparams)) # insert x::X in the argument list, between RNG and n::Repetition insert!(sp.args[2].args[1].args[1].args, 3, esc(namefull)) # insert inner samplers if !istrivial SP = [Expr(:call, :Sampler, :RNG, esc(x), many ? Val{Inf}() : :n) for (x, many) in sps] @assert :SP == pop!(sp.args[2].args[2].args[2].args[3].args) append!(sp.args[2].args[2].args[2].args[3].args, SP) end quote $ex $(sp.args[2]) # unwrap the quote/block around the definition end end function as_sampler(ex, istrivial) t = istrivial ? :(RandomExtensions.SamplerTrivial) : :(RandomExtensions.SamplerSimple) Expr(:(::), ex.args[1], Expr(:curly, t, Expr(:(<:), ex.args[2]))) end function samplerize!(sps, ex, name, rng) if ex == name # not within a rand() call return Expr(:ref, name) # name -> name[] end ex isa Expr || return ex if ex.head == :call && ex.args[1] == :rand # we assume that if rand has more than one arg, we want # a Val(Inf) sampler (e.g. rand(1:9, 2, 3) push!(sps, ex.args[2] => length(ex.args) > 2) i = length(sps) Expr(:call, :rand, rng, :($name.data[$i]), ex.args[3:end]...) else Expr(ex.head, map(e -> samplerize!(sps, e, name, rng), ex.args)...) end end
RandomExtensions
https://github.com/JuliaRandom/RandomExtensions.jl.git
[ "MIT" ]
0.4.4
b8a399e95663485820000f26b6a43c794e166a49
code
23298
# definition of samplers and random generation # allows to call `Sampler` only when the the arg isn't a Sampler itself sampler(::Type{RNG}, X, n::Repetition=Val(Inf)) where {RNG<:AbstractRNG} = Sampler(RNG, X, n) sampler(::Type{RNG}, ::Type{X}, n::Repetition=Val(Inf)) where {RNG<:AbstractRNG,X} = Sampler(RNG, X, n) sampler(::Type{RNG}, X::Sampler, n::Repetition=Val(Inf)) where {RNG<:AbstractRNG} = X sampler(rng::AbstractRNG, X, n::Repetition=Val(Inf)) = sampler(typeof(rng), X, n) ## defaults ### 0-arg make() = make(Float64) ### type: handles e.g. rand(make(Int)) # rand(rng, ::SamplerType{Make0{X}}) should not be overloaded, as make(T) # has this special pass-thru Sampler defined below Sampler(::Type{RNG}, ::Make0{X}, n::Repetition) where {RNG<:AbstractRNG,X} = Sampler(RNG, X, n) ### object: handles e.g. rand(make(1:3)) # make(x) where x isn't a type should create a distribution d such that rand(x) is # equivalent to rand(d); so we need to overload make(x) to give a different type # than Make1{gentype(x)}, as we can't simply define a generic pass-thru Sampler for # that Make1 type (because users expect the default to be a SamplerTrivial{<:Make1{...}}, # and might want to define only a rand method on this SamplerTrivial) # like Make1 struct MakeWrap{T,X} <: Distribution{T} x::X end # make(::Type) is intercepted in distribution.jl make(x) = MakeWrap{gentype(x),typeof(x)}(x) Sampler(::Type{RNG}, x::MakeWrap, n::Repetition) where {RNG<:AbstractRNG} = Sampler(RNG, x.x, n) ## Uniform Sampler(::Type{RNG}, d::Union{UniformWrap,UniformType}, n::Repetition ) where {RNG<:AbstractRNG} = Sampler(RNG, d[], n) ## floats ### fall-back on Random definitions for CO in (:CloseOpen01, :CloseOpen12) @eval begin Sampler(::Type{RNG}, ::$CO{T}, n::Repetition) where {RNG<:AbstractRNG,T} = Sampler(RNG, Random.$CO{T}(), n) Sampler(::Type{<:AbstractRNG}, ::$CO{BigFloat}, ::Repetition) = Random.SamplerBigFloat{Random.$CO{BigFloat}}(precision(BigFloat)) end end ### new intervals 01 # TODO: optimize for BigFloat for CO = (:OpenClose01, :OpenOpen01, :CloseClose01) @eval Sampler(::Type{RNG}, I::$CO{T}, n::Repetition) where {RNG<:AbstractRNG,T} = SamplerSimple(I, CloseOpen01(T)) end rand(r::AbstractRNG, sp::SamplerSimple{OpenClose01{T}}) where {T} = one(T) - rand(r, sp.data) rand(r::AbstractRNG, sp::SamplerSimple{OpenOpen01{T}}) where {T} = while true x = rand(r, sp.data) x != zero(T) && return x end # optimizations (TODO: optimize for BigFloat too) rand(r::AbstractRNG, sp::SamplerSimple{OpenOpen01{Float64}}) = reinterpret(Float64, reinterpret(UInt64, rand(r, sp.data)) | 0x0000000000000001) rand(r::AbstractRNG, sp::SamplerSimple{OpenOpen01{Float32}}) = reinterpret(Float32, reinterpret(UInt32, rand(r, sp.data)) | 0x00000001) rand(r::AbstractRNG, sp::SamplerSimple{OpenOpen01{Float16}}) = reinterpret(Float16, reinterpret(UInt16, rand(r, sp.data)) | 0x0001) # prevfloat(T(2)) - 1 for IEEEFloat upper01(::Type{Float64}) = 0.9999999999999998 upper01(::Type{Float32}) = 0.9999999f0 upper01(::Type{Float16}) = Float16(0.999) upper01(::Type{BigFloat}) = prevfloat(one(BigFloat)) rand(r::AbstractRNG, sp::SamplerSimple{CloseClose01{T}}) where {T} = rand(r, sp.data) / upper01(T) ### CloseOpenAB for (CO, CO01) = (CloseOpenAB => CloseOpen01, OpenCloseAB => OpenClose01, CloseCloseAB => CloseClose01, OpenOpenAB => OpenOpen01) @eval Sampler(::Type{RNG}, d::$CO{T}, n::Repetition) where {RNG<:AbstractRNG,T} = SamplerTag{$CO{T}}((a=d.a, d=d.b - d.a, sp=Sampler(RNG, $CO01{T}(), n))) @eval rand(rng::AbstractRNG, sp::SamplerTag{$CO{T}}) where {T} = sp.data.a + sp.data.d * rand(rng, sp.data.sp) end ## Normal & Exponential rand(rng::AbstractRNG, ::SamplerTrivial{Normal01{T}}) where {T<:NormalTypes} = randn(rng, T) Sampler(::Type{RNG}, d::NormalΞΌΟƒ{T}, n::Repetition) where {RNG<:AbstractRNG,T} = SamplerSimple(d, Sampler(RNG, Normal(T), n)) rand(rng::AbstractRNG, sp::SamplerSimple{NormalΞΌΟƒ{T},<:Sampler}) where {T} = sp[].ΞΌ + sp[].Οƒ * rand(rng, sp.data) rand(rng::AbstractRNG, ::SamplerTrivial{Exponential1{T}}) where {T<:AbstractFloat} = randexp(rng, T) Sampler(::Type{RNG}, d::ExponentialΞΈ{T}, n::Repetition) where {RNG<:AbstractRNG,T} = SamplerSimple(d, Sampler(RNG, Exponential(T), n)) rand(rng::AbstractRNG, sp::SamplerSimple{ExponentialΞΈ{T},<:Sampler}) where {T} = sp[].ΞΈ * rand(rng, sp.data) ## Bernoulli Sampler(::Type{RNG}, b::Bernoulli, n::Repetition) where {RNG<:AbstractRNG} = SamplerTag{typeof(b)}(b.p+1.0) rand(rng::AbstractRNG, sp::SamplerTag{Bernoulli{T}}) where {T} = ifelse(rand(rng, CloseOpen12()) < sp.data, one(T), zero(T)) ## Categorical Sampler(::Type{RNG}, c::Categorical, n::Repetition) where {RNG<:AbstractRNG} = SamplerSimple(c, Sampler(RNG, CloseOpen(), n)) # unfortunately requires @inline to avoid allocating @inline rand(rng::AbstractRNG, sp::SamplerSimple{Categorical{T}}) where {T} = let c = rand(rng, sp.data) T(findfirst(x -> x >= c, sp[].cdf)) end # NOTE: # if length(cdf) is somewhere between 150 and 200, the following gets faster: # T(searchsortedfirst(sp[].cdf, rand(rng, sp.data))) ## random elements from pairs #= disabled in favor of a special meaning for pairs Sampler(RNG::Type{<:AbstractRNG}, t::Pair, n::Repetition) = SamplerSimple(t, Sampler(RNG, Bool, n)) rand(rng::AbstractRNG, sp::SamplerSimple{<:Pair}) = @inbounds return sp[][1 + rand(rng, sp.data)] =# ## composite types ### sampler for pairs and complex numbers maketype(::Type{Pair}, x, y) = Pair{val_gentype(x), val_gentype(y)} maketype(::Type{Pair{X}}, _, y) where {X} = Pair{X, val_gentype(y)} maketype(::Type{Pair{X,Y} where X}, x, _) where {Y} = Pair{val_gentype(x), Y} maketype(::Type{Pair{X,Y}}, _, _) where {X,Y} = Pair{X,Y} maketype(::Type{Complex}, x) = Complex{val_gentype(x)} maketype(::Type{T}, _) where {T<:Complex} = T maketype(::Type{Complex}, x, y) = Complex{promote_type(val_gentype(x), val_gentype(y))} maketype(::Type{T}, _, _) where {T<:Complex} = T function Sampler(::Type{RNG}, u::Make2{T}, n::Repetition ) where RNG<:AbstractRNG where T <: Union{Pair,Complex} sp1 = sampler(RNG, u[1], n) sp2 = u[1] == u[2] ? sp1 : sampler(RNG, u[2], n) SamplerTag{Cont{T}}((sp1, sp2)) end rand(rng::AbstractRNG, sp::SamplerTag{Cont{T}}) where {T<:Union{Pair,Complex}} = T(rand(rng, sp.data[1]), rand(rng, sp.data[2])) #### additional convenience methods # rand(Pair{A,B}) => rand(make(Pair{A,B}, A, B)) if VERSION < v"1.11.0-DEV.618" # now implemented in `Random` Sampler(::Type{RNG}, ::Type{Pair{A,B}}, n::Repetition) where {RNG<:AbstractRNG,A,B} = Sampler(RNG, make(Pair{A,B}, A, B), n) end # rand(make(Complex, x)) => rand(make(Complex, x, x)) Sampler(::Type{RNG}, u::Make1{T}, n::Repetition) where {RNG<:AbstractRNG,T<:Complex} = Sampler(RNG, make(T, u[1], u[1]), n) # rand(Complex{T}) => rand(make(Complex{T}, T, T)) (redundant with implem in Random) Sampler(::Type{RNG}, ::Type{Complex{T}}, n::Repetition) where {RNG<:AbstractRNG,T<:Real} = Sampler(RNG, make(Complex{T}, T, T), n) ### sampler for tuples #### "simple scalar" (non-make) version Sampler(::Type{RNG}, ::Type{T}, n::Repetition ) where {RNG<:AbstractRNG,T<:Union{Tuple,NamedTuple}} = Sampler(RNG, make(T), n) if VERSION >= v"1.11.0-DEV.573" # now `Random` implements `rand(Tuple{...})`, so be more specific for # special stuff still not implemented by `Random` # TODO: we should probably remove this Sampler(::Type{RNG}, ::Type{Tuple}, n::Repetition) where {RNG <: AbstractRNG} = Sampler(RNG, make(Tuple), n) Sampler(::Type{RNG}, ::Type{NTuple{N}}, n::Repetition) where {RNG <: AbstractRNG, N} = Sampler(RNG, make(NTuple{N}), n) end #### make # implement make(Tuple, S1, S2...), e.g. for rand(make(Tuple, Int, 1:3)), # and make(NTuple{N}, S) _maketype(::Type{T}) where {T<:Tuple} = T === Tuple ? Tuple{} : T === NTuple ? Tuple{} : T isa UnionAll && Type{T} <: Type{NTuple{N}} where N ? T{default_gentype(Tuple)} : T function _maketype(::Type{T}, args...) where T <: Tuple types = [t <: Type ? t.parameters[1] : gentype(t) for t in args] TT = T === Tuple ? Tuple{types...} : _isNTuple(T, args...) ? (T isa UnionAll ? Tuple{fill(types[1], fieldcount(T))...} : T ) : T TT end _isNTuple(::Type{T}, args...) where {T<:Tuple} = length(args) == 1 && T !== Tuple && ( T <: NTuple || !isa(T, UnionAll)) # !isa(Tuple, UnionAll) !! @generated function _make(::Type{T}, args...) where T <: Tuple isempty(args) && return :(Make0{$(_maketype(T))}()) TT = _maketype(T, args...) samples = [t <: Type ? :(UniformType{$(t.parameters[1])}()) : :(args[$i]) for (i, t) in enumerate(args)] if _isNTuple(T, args...) :(Make1{$TT}($(samples[1]))) else quote if T !== Tuple && fieldcount(T) != length(args) throw(ArgumentError("wrong number of provided argument with $T (should be $(fieldcount(T)))")) else Make1{$TT}(tuple($(samples...))) end end end end make(::Type{T}, args...) where {T<:Tuple} = _make(T, args...) # make(Tuple, X, n::Integer) default_sampling(::Type{Tuple}) = Uniform(Float64) make(::Type{Tuple}, X, n::Integer) = make(NTuple{Int(n)}, X) make(::Type{Tuple}, ::Type{X}, n::Integer) where {X} = make(NTuple{Int(n)}, X) make(::Type{Tuple}, n::Integer) = make(Tuple, default_sampling(Tuple), Int(n)) # NTuple{N,T} where N make(::Type{NTuple{N,T} where N}, n::Integer) where {T} = make(NTuple{Int(n),T}) make(::Type{NTuple{N,T} where N}, X, n::Integer) where {T} = make(NTuple{Int(n),T}, X) make(::Type{NTuple{N,T} where N}, ::Type{X}, n::Integer) where {T,X} = make(NTuple{Int(n),T}, X) # disambiguate for Tupl = (Tuple, NamedTuple) @eval begin make(::Type{T}, X) where {T<:$Tupl} = _make(T, X) make(::Type{T}, ::Type{X}) where {T<:$Tupl,X} = _make(T, X) make(::Type{T}, X, Y) where {T<:$Tupl} = _make(T, X, Y) make(::Type{T}, ::Type{X}, Y) where {T<:$Tupl,X} = _make(T, X, Y) make(::Type{T}, X, ::Type{Y}) where {T<:$Tupl,Y} = _make(T, X, Y) make(::Type{T}, ::Type{X}, ::Type{Y}) where {T<:$Tupl,X,Y} = _make(T, X, Y) make(::Type{T}, X, Y, Z) where {T<:$Tupl} = _make(T, X, Y, Z) make(::Type{T}, ::Type{X}, Y, Z) where {T<:$Tupl,X} = _make(T, X, Y, Z) make(::Type{T}, X, ::Type{Y}, Z) where {T<:$Tupl,Y} = _make(T, X, Y, Z) make(::Type{T}, ::Type{X}, ::Type{Y}, Z) where {T<:$Tupl,X,Y} = _make(T, X, Y, Z) make(::Type{T}, X, Y, ::Type{Z}) where {T<:$Tupl,Z} = _make(T, X, Y, Z) make(::Type{T}, ::Type{X}, Y, ::Type{Z}) where {T<:$Tupl,X,Z} = _make(T, X, Y, Z) make(::Type{T}, X, ::Type{Y}, ::Type{Z}) where {T<:$Tupl,Y,Z} = _make(T, X, Y, Z) make(::Type{T}, ::Type{X}, ::Type{Y}, ::Type{Z}) where {T<:$Tupl,X,Y,Z} = _make(T, X, Y, Z) end end #### Sampler for general tuples @generated function Sampler(::Type{RNG}, c::Make1{T,X}, n::Repetition ) where {RNG<:AbstractRNG,T<:Tuple,X<:Tuple} @assert fieldcount(T) == fieldcount(X) sps = [:(sampler(RNG, c[1][$i], n)) for i in 1:length(T.parameters)] :(SamplerTag{Cont{T}}(tuple($(sps...)))) end @generated function Sampler(::Type{RNG}, ::Make0{T}, n::Repetition ) where {RNG<:AbstractRNG,T<:Tuple} d = Dict{DataType,Int}() sps = [] for t in T.parameters i = get(d, t, nothing) if i === nothing push!(sps, :(Sampler(RNG, $t, n))) d[t] = length(sps) else push!(sps, Val(i)) end end :(SamplerTag{Cont{T}}(tuple($(sps...)))) end @generated function rand(rng::AbstractRNG, sp::SamplerTag{Cont{T},S}) where {T<:Tuple,S<:Tuple} @assert fieldcount(T) == fieldcount(S) rands = [] for i = 1:fieldcount(T) j = fieldtype(S, i) <: Val ? fieldtype(S, i).parameters[1] : i push!(rands, :(convert($(fieldtype(T, i)), rand(rng, sp.data[$j])))) end :(tuple($(rands...))) end #### for "NTuple-like" # should catch Tuple{Integer,Integer} which is not NTuple, or even Tuple{Int,UInt}, when only one sampler was passed Sampler(::Type{RNG}, c::Make1{T,X}, n::Repetition) where {RNG<:AbstractRNG,T<:Tuple,X} = SamplerTag{Cont{T}}(sampler(RNG, c[1], n)) @generated function rand(rng::AbstractRNG, sp::SamplerTag{Cont{T},S}) where {T<:Tuple,S<:Sampler} rands = [:(convert($(T.parameters[i]), rand(rng, sp.data))) for i in 1:fieldcount(T)] :(tuple($(rands...))) end ### named tuples make(::Type{T}, args...) where {T<:NamedTuple} = _make(T, args...) _make(::Type{NamedTuple{}}) = Make0{NamedTuple{}}() @generated function _make(::Type{NamedTuple{K}}, X...) where {K} if length(X) <= 1 NT = NamedTuple{K,_maketype(NTuple{length(K)}, X...)} :(Make1{$NT}(make(NTuple{length(K)}, X...))) else NT = NamedTuple{K,_maketype(Tuple, X...)} :(Make1{$NT}(make(Tuple, X...))) end end function _make(::Type{NamedTuple{K,V}}, X...) where {K,V} Make1{NamedTuple{K,V}}(make(V, X...)) end # necessary to avoid circular defintions Sampler(::Type{RNG}, m::Make0{NamedTuple}, n::Repetition) where {RNG<:AbstractRNG} = SamplerType{NamedTuple}() Sampler(::Type{RNG}, m::Make1{T}, n::Repetition) where {RNG<:AbstractRNG, T <: NamedTuple} = SamplerTag{Cont{T}}(Sampler(RNG, m[1] , n)) rand(rng::AbstractRNG, sp::SamplerType{NamedTuple{}}) = NamedTuple() rand(rng::AbstractRNG, sp::SamplerTag{Cont{T}}) where T <: NamedTuple = T(rand(rng, sp.data)) ## collections ### sets/dicts const SetDict = Union{AbstractSet,AbstractDict} make(::Type{T}, X, n::Integer) where {T<:SetDict} = Make2{maketype(T, X, n)}(X , Int(n)) make(::Type{T}, ::Type{X}, n::Integer) where {T<:SetDict,X} = Make2{maketype(T, X, n)}(X , Int(n)) make(::Type{T}, n::Integer) where {T<:SetDict} = make(T, default_sampling(T), Int(n)) Sampler(::Type{RNG}, c::Make2{T}, n::Repetition) where {RNG<:AbstractRNG,T<:SetDict} = SamplerTag{Cont{T}}((sp = sampler(RNG, c[1], n), len = c[2])) function rand(rng::AbstractRNG, sp::SamplerTag{Cont{S}}) where {S<:SetDict} # assuming S() creates an empty set/dict s = sizehint!(S(), sp.data[2]) _rand!(rng, s, sp.data.len, sp.data.sp) end ### sets default_sampling(::Type{<:AbstractSet}) = Uniform(Float64) default_sampling(::Type{<:AbstractSet{T}}) where {T} = Uniform(T) #### Set maketype(::Type{Set}, X, _) = Set{val_gentype(X)} maketype(::Type{Set{T}}, _, _) where {T} = Set{T} ### BitSet default_sampling(::Type{BitSet}) = Uniform(Int8) # almost arbitrary, may change maketype(::Type{BitSet}, _, _) = BitSet ### dicts # K,V parameters are necessary here maketype(::Type{D}, _, ::Integer) where {K,V,D<:AbstractDict{K,V}} = D maketype(::Type{D}, ::Type, ::Integer) where {K,V,D<:AbstractDict{K,V}} = D #### Dict/ImmutableDict for D in (Dict, Base.ImmutableDict) @eval begin # again same inference bug # TODO: extend to AbstractDict ? (needs to work-around the inderence bug) default_sampling(::Type{$D{K,V}}) where {K,V} = Uniform(Pair{K,V}) default_sampling(D::Type{<:$D}) = throw(ArgumentError("under-specified scalar type for $D")) maketype(::Type{$D{K}}, X, ::Integer) where {K} = $D{K,fieldtype(val_gentype(X), 2)} maketype(::Type{$D{K,V} where K}, X, ::Integer) where {V} = $D{fieldtype(val_gentype(X), 1),V} maketype(::Type{$D}, X, ::Integer) = $D{fieldtype(val_gentype(X), 1),fieldtype(val_gentype(X), 2)} end end rand(rng::AbstractRNG, sp::SamplerTag{Cont{S}}) where {S<:Base.ImmutableDict} = foldl((d, _) -> Base.ImmutableDict(d, rand(rng, sp.data.sp)), 1:sp.data.len, init=S()) ### AbstractArray default_sampling(::Type{<:AbstractArray{T}}) where {T} = Uniform(T) default_sampling(::Type{<:AbstractArray}) = Uniform(Float64) make(::Type{A}, X, d1::Integer, dims::Integer...) where {A<:AbstractArray} = make(A, X, Dims((d1, dims...))) make(::Type{A}, ::Type{X}, d1::Integer, dims::Integer...) where {A<:AbstractArray,X} = make(A, X, Dims((d1, dims...))) make(::Type{A}, dims::Dims) where {A<:AbstractArray} = make(A, default_sampling(A), dims) make(::Type{A}, d1::Integer, dims::Integer...) where {A<:AbstractArray} = make(A, default_sampling(A), Dims((d1, dims...))) if VERSION < v"1.1.0" # to resolve ambiguity make(A::Type{<:AbstractArray}, X, d1::Integer) = make(A, X, Dims((d1,))) make(A::Type{<:AbstractArray}, X, d1::Integer, d2::Integer) = make(A, X, Dims((d1, d2))) end Sampler(::Type{RNG}, c::Make2{A}, n::Repetition) where {RNG<:AbstractRNG,A<:AbstractArray} = SamplerTag{A}((sampler(RNG, c[1], n), c[2])) rand(rng::AbstractRNG, sp::SamplerTag{A}) where {A<:AbstractArray} = rand!(rng, A(undef, sp.data[2]), sp.data[1]) #### Array # cf. inference bug https://github.com/JuliaLang/julia/issues/28762 # we have to write out all combinations for getting proper inference maketype(::Type{Array{T}}, _, ::Dims{N}) where {T, N} = Array{T, N} maketype(::Type{Array{T,N}}, _, ::Dims{N}) where {T, N} = Array{T, N} maketype(::Type{Array{T,N} where T}, X, ::Dims{N}) where {N} = Array{val_gentype(X), N} maketype(::Type{Array}, X, ::Dims{N}) where {N} = Array{val_gentype(X), N} #### BitArray default_sampling(::Type{<:BitArray}) = Uniform(Bool) maketype(::Type{BitArray{N}}, _, ::Dims{N}) where {N} = BitArray{N} maketype(::Type{BitArray}, _, ::Dims{N}) where {N} = BitArray{N} #### sparse vectors & matrices maketype(::Type{SparseVector}, X, p::AbstractFloat, dims::Dims{1}) = SparseVector{ val_gentype(X), Int} maketype(::Type{SparseMatrixCSC}, X, p::AbstractFloat, dims::Dims{2}) = SparseMatrixCSC{val_gentype(X), Int} maketype(::Type{SparseVector{X}}, _, p::AbstractFloat, dims::Dims{1}) where {X} = SparseVector{ X, Int} maketype(::Type{SparseMatrixCSC{X}}, _, p::AbstractFloat, dims::Dims{2}) where {X} = SparseMatrixCSC{X, Int} # need to be explicit and split these defs in 2 (or 4) to avoid ambiguities # TODO: check that using T instead of SparseVector in the RHS doesn't have perfs issues make(T::Type{SparseVector}, X, p::AbstractFloat, d1::Integer) = make(T, X, p, Dims((d1,))) make(T::Type{SparseVector}, ::Type{X}, p::AbstractFloat, d1::Integer) where {X} = make(T, X, p, Dims((d1,))) make(T::Type{SparseMatrixCSC}, X, p::AbstractFloat, d1::Integer, d2::Integer) = make(T, X, p, Dims((d1, d2))) make(T::Type{SparseMatrixCSC}, ::Type{X}, p::AbstractFloat, d1::Integer, d2::Integer) where {X} = make(T, X, p, Dims((d1, d2))) make(T::Type{SparseVector}, p::AbstractFloat, d1::Integer) = make(T, default_sampling(T), p, Dims((d1,))) make(T::Type{SparseMatrixCSC}, p::AbstractFloat, d1::Integer, d2::Integer) = make(T, default_sampling(T), p, Dims((d1, d2))) make(T::Type{SparseVector}, p::AbstractFloat, dims::Dims{1}) = make(T, default_sampling(T), p, dims) make(T::Type{SparseMatrixCSC}, p::AbstractFloat, dims::Dims{2}) = make(T, default_sampling(T), p, dims) Sampler(::Type{RNG}, c::Make3{A}, n::Repetition) where {RNG<:AbstractRNG,A<:AbstractSparseArray} = SamplerTag{Cont{A}}((sp = sampler(RNG, c[1], n), p = c[2], dims = c[3])) rand(rng::AbstractRNG, sp::SamplerTag{Cont{A}}) where {A<:SparseVector} = sprand(rng, sp.data.dims[1], sp.data.p, (r, n)->rand(r, sp.data.sp, n)) rand(rng::AbstractRNG, sp::SamplerTag{Cont{A}}) where {A<:SparseMatrixCSC} = sprand(rng, sp.data.dims[1], sp.data.dims[2], sp.data.p, (r, n)->rand(r, sp.data.sp, n), gentype(sp.data.sp)) #### StaticArrays function random_staticarrays() @eval using StaticArrays: tuple_length, tuple_prod, SArray, MArray for Arr = (:SArray, :MArray) @eval begin maketype(::Type{<:$Arr{S}} , X) where {S<:Tuple} = $Arr{S,val_gentype(X),tuple_length(S),tuple_prod(S)} maketype(::Type{<:$Arr{S,T}}, _) where {S<:Tuple,T} = $Arr{S,T,tuple_length(S),tuple_prod(S)} Sampler(::Type{RNG}, c::Make1{A}, n::Repetition) where {RNG<:AbstractRNG,A<:$Arr} = SamplerTag{Cont{A}}(Sampler(RNG, c[1], n)) rand(rng::AbstractRNG, sp::SamplerTag{Cont{$Arr{S,T,N,L}}}) where {S,T,N,L} = $Arr{S,T,N,L}(rand(rng, make(NTuple{L}, sp.data))) @make_container(T::Type{<:$Arr}) end end end ### String as a scalar let b = UInt8['0':'9';'A':'Z';'a':'z'], s = Sampler(MersenneTwister, b, Val(Inf)) # cache for the likely most common case global Sampler, rand, make make(::Type{String}) = Make2{String}(8, b) make(::Type{String}, chars) = Make2{String}(8, chars) make(::Type{String}, ::Type{C}) where C = Make2{String}(8, C) make(::Type{String}, n::Integer) = Make2{String}(Int(n), b) make(::Type{String}, chars, n::Integer) = Make2{String}(Int(n), chars) make(::Type{String}, ::Type{C}, n::Integer) where {C} = Make2{String}(Int(n), C) make(::Type{String}, n::Integer, chars) = Make2{String}(Int(n), chars) make(::Type{String}, n::Integer, ::Type{C}) where {C} = Make2{String}(Int(n), C) Sampler(::Type{RNG}, ::Type{String}, n::Repetition) where {RNG<:AbstractRNG} = SamplerTag{Cont{String}}((RNG === MersenneTwister ? s : Sampler(RNG, b, n)) => 8) function Sampler(::Type{RNG}, c::Make2{String}, n::Repetition) where {RNG<:AbstractRNG} sp = RNG === MersenneTwister && c[2] === b ? s : sampler(RNG, c[2], n) SamplerTag{Cont{String}}(sp => c[1]) end rand(rng::AbstractRNG, sp::SamplerTag{Cont{String}}) = String(rand(rng, sp.data.first, sp.data.second)) end ## X => a / X => (a, as...) syntax as an alternative to make(X, a) / make(X, a, as...) # this is experimental pair_to_make((a, b)::Pair) = b isa Tuple ? make(a, map(pair_to_make, b)...) : make(a, pair_to_make(b)) pair_to_make(x) = x @inline Sampler(::Type{RNG}, p::Pair, r::Repetition) where {RNG<:AbstractRNG} = Sampler(RNG, pair_to_make(p), r) # nothing can be inferred when only the pair type is available @inline gentype(::Type{<:Pair}) = Any @inline gentype(p::Pair) = gentype(pair_to_make(p))
RandomExtensions
https://github.com/JuliaRandom/RandomExtensions.jl.git
[ "MIT" ]
0.4.4
b8a399e95663485820000f26b6a43c794e166a49
code
68
module RandomExtensionsTests using ReTest include("tests.jl") end
RandomExtensions
https://github.com/JuliaRandom/RandomExtensions.jl.git
[ "MIT" ]
0.4.4
b8a399e95663485820000f26b6a43c794e166a49
code
66
module RandomExtensionsTests using Test include("tests.jl") end
RandomExtensions
https://github.com/JuliaRandom/RandomExtensions.jl.git
[ "MIT" ]
0.4.4
b8a399e95663485820000f26b6a43c794e166a49
code
25923
using RandomExtensions, Random, SparseArrays using Random: Sampler, gentype @testset "Distributions" begin # Normal/Exponential @test rand(Normal()) isa Float64 @test rand(Normal(0.0, 1.0)) isa Float64 @test rand(Normal(0, 1)) isa Float64 @test rand(Normal(0, 1.0)) isa Float64 @test rand(Exponential()) isa Float64 @test rand(Exponential(1.0)) isa Float64 @test rand(Exponential(1)) isa Float64 @test rand(Normal(Float32)) isa Float32 @test rand(Exponential(Float32)) isa Float32 @test rand(Normal(ComplexF64)) isa ComplexF64 # pairs/complexes @test rand(make(Pair, 1:3, Float64)) isa Pair{Int,Float64} @test rand(make(Pair{Int8}, 1:3, Float64)) isa Pair{Int8,Float64} @test rand(make(Pair{Int8,Float32}, 1:3, Float64)) isa Pair{Int8,Float32} @test rand(make(Pair{X,Float32} where X, 1:3, Float64)) isa Pair{Int,Float32} @test rand(Pair{Int,Float64}) isa Pair{Int,Float64} z = rand(make(Complex, 1:3, 6:9)) @test z.re ∈ 1:3 @test z.im ∈ 6:9 @test z isa Complex{Int} z = rand(make(ComplexF64, 1:3, 6:9)) @test z.re ∈ 1:3 @test z.im ∈ 6:9 @test z isa ComplexF64 for (C, R) in ((Complex, Int), (ComplexF64, Float64), (Complex{Int}, Int)) z = rand(make(C, 1:3)) @test z.re ∈ 1:3 @test z.im ∈ 1:3 @test z isa Complex{R} end @test rand(make(Complex, 1:3, Float64)) isa Complex{Float64} # promote_type should be used @test rand(ComplexF64) isa ComplexF64 @test rand(make(Complex,Int), 3) isa Vector{Complex{Int}} @test rand(make(Complex,1:3), 3) isa Vector{Complex{Int}} # Uniform @test rand(Uniform(Float64)) isa Float64 @test rand(Uniform(1:10)) isa Int @test rand(Uniform(1:10)) ∈ 1:10 @test rand(Uniform(Int)) isa Int # Bernoulli @test rand(Bernoulli()) ∈ (0, 1) @test rand(Bernoulli(1)) == 1 @test rand(Bernoulli(0)) == 0 # TODO: do the math to estimate proba of failure: @test 620 < count(rand(Bernoulli(Bool, 0.7), 1000)) < 780 for T = (Bool, Int, Float64, ComplexF64) r = rand(Bernoulli(T)) @test r isa T @test r ∈ (0, 1) r = rand(Bernoulli(T, 1)) @test r == 1 end # Categorical n = rand(1:9) @test rand(Categorical(n)) ∈ 1:9 @test all(∈(1:9), rand(Categorical(n), 10)) @test rand(Categorical(n)) isa Int c = Categorical(Float64(n)) @test rand(c) isa Float64 @test rand(c) ∈ 1:9 c = Categorical([1, 7, 2]) # cf. Bernoulli tests @test 620 < count(==(2), rand(c, 1000)) < 780 @test rand(c) isa Int @test rand(Categorical{Float64}((1, 2, 3, 4))) isa Float64 @test_throws ArgumentError Categorical(()) @test_throws ArgumentError Categorical([]) @test_throws ArgumentError Categorical(x for x in 1:0) end const rInt8 = typemin(Int8):typemax(Int8) const spString = Sampler(MersenneTwister, String) const RNGS = ([] => "global RNG", [MersenneTwister(0)] => "MersenneTwister", [RandomDevice()] => "RandomDevice") @testset "Containers $name" for (rng, name) in RNGS # Array for T = (Int, Int8) for (A, AT) = ((Array, Int8), (Array{T}, T), (Vector, Int8), (Vector{T}, T)) @inferred rand(rng..., Int8.(1:9), A, 10) a = rand(rng..., Int8.(1:9), A, 10) @test a isa Vector{AT} @test all(in(1:9), a) @inferred rand(rng..., Int8, A, 10) a = rand(rng..., Int8, A, 10) @test a isa Vector{AT} @test all(in(rInt8), a) end end # Set for S = (Set{Int}, Set, BitSet) s = rand(rng..., 1:99, S, 10) @test s isa (S === BitSet ? BitSet : Set{Int}) @test length(s) == 10 @test rand(s) ∈ 1:99 end for s = (Set([1, 2]), BitSet([1, 2])) @test s === rand!(s) @test s != Set([1, 2]) # very unlikely @test length(s) == 2 @test s === rand!(s, 3:9) <= Set(3:9) @test length(s) == 2 end @test rand(rng..., Pair{Int,Float64}, Set, 3) isa Set{Pair{Int,Float64}} @test rand(rng..., Pair{Int,Float64}, Set{Pair}, 3) isa Set{Pair} # BitSet s = rand(make(BitSet, 1:10, 3)) @test s isa BitSet @test length(s) == 3 @test s <= Set(1:10) @testset "default_sampling(::BitSet) == Int8" begin Random.seed!(0) rand!(s) @test s <= Set(rInt8) Random.seed!(0) @test s == rand(BitSet, 3) end # Dict for s = (rand(rng..., make(Pair, 1:99, 1:99), Dict, 10), rand(rng..., make(Pair, 1:99, 1:99), Dict{Int,Int}, 10)) @test s isa Dict{Int,Int} @test length(s) == 10 p = rand(s) @test p.first ∈ 1:99 @test p.second ∈ 1:99 end s = Dict(1=>2, 2=>1) @test s === rand!(s) @test length(s) == 2 @test first(s).first βˆ‰ (1, 2) # extremely unlikely rand!(s, make(Pair, 3:9, Int)) @test length(s) == 2 @test first(s).first ∈ 3:9 d = rand(rng..., Pair{Int,Float64}, Dict, 3) @test d isa Dict{Int,Float64} dd = rand!(rng..., d, Pair{Int,Int8}) @test dd === d delt = pop!(d) @test delt isa Pair{Int,Float64} @test delt[2] ∈ rInt8 @test rand(rng..., Pair{Int,Float64}, Dict{Any,Any}, 3) isa Dict{Any,Any} # sparse @test rand(rng..., Float64, .5, 10) isa SparseVector{Float64} @test rand(rng..., Float64, .5, (10,)) isa SparseVector{Float64} @test rand(rng..., Float64, SparseVector, .5, 10) isa SparseVector{Float64} @test rand(rng..., Float64, SparseVector, .5, (10,)) isa SparseVector{Float64} @test rand(rng..., .5, 10) isa SparseVector{Float64} @test rand(rng..., .5, (10,)) isa SparseVector{Float64} @test rand(rng..., SparseVector, .5, 10) isa SparseVector{Float64} @test rand(rng..., SparseVector, .5, (10,)) isa SparseVector{Float64} @test rand(rng..., Int, .5, 10) isa SparseVector{Int} @test rand(rng..., Int, .5, (10,)) isa SparseVector{Int} @test rand(rng..., Int, SparseVector, .5, 10) isa SparseVector{Int} @test rand(rng..., Int, SparseVector, .5, (10,)) isa SparseVector{Int} @test rand(rng..., Float64, .5, 10, 3) isa SparseMatrixCSC{Float64} @test rand(rng..., Float64, .5, (10, 3)) isa SparseMatrixCSC{Float64} @test rand(rng..., Float64, SparseMatrixCSC, .5, 10, 3) isa SparseMatrixCSC{Float64} @test rand(rng..., Float64, SparseMatrixCSC, .5, (10, 3)) isa SparseMatrixCSC{Float64} @test rand(rng..., .5, 10, 3) isa SparseMatrixCSC{Float64} @test rand(rng..., .5, (10, 3)) isa SparseMatrixCSC{Float64} @test rand(rng..., SparseMatrixCSC, .5, 10, 3) isa SparseMatrixCSC{Float64} @test rand(rng..., SparseMatrixCSC, .5, (10, 3)) isa SparseMatrixCSC{Float64} @test rand(rng..., Int, .5, 10, 3) isa SparseMatrixCSC{Int} @test rand(rng..., Int, .5, (10, 3)) isa SparseMatrixCSC{Int} @test rand(rng..., Int, SparseMatrixCSC, .5, 10, 3) isa SparseMatrixCSC{Int} @test rand(rng..., Int, SparseMatrixCSC, .5, (10, 3)) isa SparseMatrixCSC{Int} # BitArray for S = ([], [Bool], [Bernoulli()]) @test rand(rng..., S..., BitArray, 10) isa BitVector @test rand(rng..., S..., BitVector, 10) isa BitVector @test_throws MethodError rand(rng..., S..., BitVector, 10, 20) isa BitVector @test rand(rng..., S..., BitArray, 10, 3) isa BitMatrix @test rand(rng..., S..., BitMatrix, 10, 3) isa BitMatrix @test_throws MethodError rand(rng..., S..., BitVector, 10, 3) isa BitMatrix end # String s = rand(rng..., String) @test s isa String @test length(s) == 8 s = rand(rng..., String, 10) @test s isa String @test length(s) == 10 s = rand(rng..., "asd", String) @test length(s) == 8 @test Set(s) <= Set("asd") @test_throws ArgumentError rand(rng..., String, 2, 3) @test_throws ArgumentError rand(rng..., String, 2, 3, 4) @test_throws ArgumentError rand(rng..., String, 2, 3, 4, 5) # Tuple s = rand(rng..., Int, NTuple{3}) @test s isa NTuple{3,Int} s = rand(rng..., 1:3, NTuple{3}) @test s isa NTuple{3,Int} @test all(in(1:3), s) s = rand(rng..., 1:3, NTuple{3,Int8}) @test s isa NTuple{3,Int8} @test all(in(1:3), s) s = rand(rng..., NTuple{3, Int8}) @test s isa NTuple{3,Int8} s = rand(rng..., Tuple{Int8, UInt8}) @test s isa Tuple{Int8, UInt8} s = rand(rng..., 1:3, Tuple{Int8, UInt8}) @test s isa Tuple{Int8, UInt8} @test all(in(1:3), s) s = rand(rng..., 1:3, Tuple, 4) @test s isa NTuple{4,Int} @test all(in(1:3), s) s = rand(rng..., Tuple, 4) @test s isa NTuple{4,Float64} s = rand(rng..., NTuple{3}) @test s isa NTuple{3,Float64} s = rand(rng..., NTuple{N,UInt8} where N, 3) @test s isa NTuple{3,UInt8} s = rand(rng..., 1:3, NTuple{N,UInt8} where N, 3) @test s isa NTuple{3,UInt8} @test all(in(1:3), s) end @testset "Rand $name" for (rng, name) in RNGS for XT = zip(([Int], [1:3], []), (Int, Int, Float64)) X, T = XT r = Rand(rng..., X...) @test collect(Iterators.take(r, 10)) isa Vector{T} @test r() isa T @test r(2, 3) isa Matrix{T} @test r(.3, 2, 3) isa SparseMatrixCSC{T} end for d = (Uniform(1:10), Uniform(Int)) @test collect(Iterators.take(d, 10)) isa Vector{Int} end end struct PairDistrib <: RandomExtensions.Distribution{Pair} end Random.rand(rng::AbstractRNG, ::Random.SamplerTrivial{PairDistrib}) = 1=>2 @testset "allow abstract Pair when generating a Dict" begin d = rand(PairDistrib(), Dict, 1) @test d == Dict(1=>2) @test typeof(d) == Dict{Any,Any} end @testset "some tight typing" begin UI = Random.UInt52() @test eltype(rand(MersenneTwister(), Random.Sampler(MersenneTwister, UI), .6, 1, 0)) == UInt64 @test eltype(rand(UI, Set, 3)) == UInt64 @test eltype(rand(Uniform(UI), 3)) == UInt64 a = rand(make(Pair, Int, UI)) @test fieldtype(typeof(a), 2) == UInt64 end #= @testset "rand(::Pair)" begin @test rand(1=>3) ∈ (1, 3) @test rand(1=>2, 3) isa Vector{Int} @test rand(1=>'2', 3) isa Vector{Union{Char, Int}} end =# @testset "rand(::AbstractFloat)" begin # check that overridden methods still work m = MersenneTwister() for F in (Float16, Float32, Float64, BigFloat) @test rand(F) isa F sp = Random.Sampler(MersenneTwister, RandomExtensions.CloseOpen01(F)) @test rand(m, sp) isa F @test 0 <= rand(m, sp) < 1 for (CO, (l, r)) = (CloseOpen => (<=, <), CloseClose => (<=, <=), OpenOpen => (<, <), OpenClose => (<, <=)) f = rand(CO(F)) @test f isa F @test l(0, f) && r(f, 1) end F ∈ (Float64, BigFloat) || continue # only types implemented in Random sp = Random.Sampler(MersenneTwister, RandomExtensions.CloseOpen12(F)) @test rand(m, sp) isa F @test 1 <= rand(m, sp) < 2 end @test CloseOpen(1, 2) === CloseOpen(1.0, 2.0) @test CloseOpen(1.0, 2) === CloseOpen(1.0, 2.0) @test CloseOpen(1, 2.0) === CloseOpen(1.0, 2.0) @test CloseOpen(1.0, Float32(2)) === CloseOpen(1.0, 2.0) @test CloseOpen(big(1), 2) isa CloseOpen{BigFloat} for CO in (CloseOpen, CloseClose, OpenOpen, OpenClose) @test_throws ArgumentError CO(1, 1) @test_throws ArgumentError CO(2, 1) @test CO(Float16(1), 2) isa CO{Float16} @test CO(1, Float32(2)) isa CO{Float32} end end @testset "rand(::Type{<:Tuple})" begin for types in ([Base.BitInteger_types..., Float16, Float32, Float64, BigFloat, Char, Bool], [Int, UInt64, Char]) # more repetitions tlist = rand(types, rand(0:10)) T = Tuple{tlist...} @test rand(T) isa Tuple{tlist...} end @test rand(Tuple{}) === () sp = Sampler(MersenneTwister, Tuple) @test gentype(sp) == Tuple{} @test rand(sp) == () sp = Sampler(MersenneTwister, NTuple{3}) @test gentype(sp) == NTuple{3,Float64} @test rand(sp) isa NTuple{3,Float64} sp = Sampler(MersenneTwister, Tuple{Int8,UInt8}) @test gentype(sp) == Tuple{Int8,UInt8} @test rand(sp) isa Tuple{Int8,UInt8} end @testset "rand(make(Tuple, ...))" begin s = rand([Char, Int, Float64, Bool, 1:3, "abcd", Set([1, 2, 3])], rand(0:10)) @test rand(make(Tuple, s...)) isa Tuple{Random.gentype.(s)...} # explicit test for corner case: @test rand(make(Tuple)) == () @test rand(make(Tuple{})) == () t = rand(make(Tuple, 1:3, Char, Int)) @test t[1] ∈ 1:3 @test t[2] isa Char @test t[3] isa Int && t[3] βˆ‰ 1:3 # extremely unlikely t = rand(make(Tuple{Int8,Char,Int128}, 1:3, Char, Int8)) @test t[1] isa Int8 && t[1] ∈ 1:3 @test t[2] isa Char @test t[3] isa Int128 && t[3] ∈ rInt8 @test_throws ArgumentError make(Tuple{Int}, 1:3, 1:3) @test_throws ArgumentError make(Tuple{Int,Int,Int}, 1:3, 2:4) @test rand(make(Tuple, spString, String)) isa Tuple{String,String} @test rand(make(Tuple{Int8,Int8})) isa Tuple{Int8,Int8} @test rand(make(Tuple{Int8,UInt})) isa Tuple{Int8,UInt} # make(Tuple, s, n) s = rand(make(Tuple, 1:3, 4)) @test s isa NTuple{4,Int} @test all(in(1:3), s) s = rand(make(Tuple, Int8, 4)) @test s isa NTuple{4,Int8} s = rand(make(Tuple, 4)) @test s isa NTuple{4,Float64} end @testset "rand(make(NTuple{N}/Tuple{...}, x))" begin s, N = rand([Char, Int, Float64, Bool, 1:3, "abcd", Set([1, 2, 3])]), rand(0:10) T = Random.gentype(s) rand(make(NTuple{N}, s)) isa NTuple{N,T} @test rand(make(NTuple{3}, spString)) isa NTuple{3,String} @test rand(make(NTuple{3,UInt8}, 1:3)) isa NTuple{3,UInt8} @test rand(make(Tuple{Integer,Integer}, 1:3)) isa Tuple{Int,Int} r = rand(make(Tuple{AbstractFloat,AbstractFloat}, 1:3)) @test r isa Tuple{Float64,Float64} @test all(∈(1.0:3.0), r) r = rand(make(Tuple{AbstractFloat,Integer}, 1:3)) @test r isa Tuple{Float64,Int64} @test all(in(1:3), r) r = rand(make(NTuple{3})) @test r isa NTuple{3,Float64} r = rand(make(NTuple{N,UInt8} where N, 3)) @test r isa NTuple{3,UInt8} r = rand(make(NTuple{N,UInt8} where N, 1:3, 3)) @test r isa NTuple{3,UInt8} @test all(in(1:3), r) r = rand(make(NTuple{N,UInt8} where N, UInt8, 3)) @test r isa NTuple{3,UInt8} end @testset "NamedTuple" begin for t = (rand(make(NamedTuple)), rand(NamedTuple)) @test t == NamedTuple() end for t = (rand(make(NamedTuple{(:a,)})), rand(NamedTuple{(:a,)})) @test t isa NamedTuple{(:a,), Tuple{Float64}} end for t = (rand(make(NamedTuple{(:a,),Tuple{Int}})), rand(NamedTuple{(:a,),Tuple{Int}})) @test t isa NamedTuple{(:a,), Tuple{Int}} end t = rand(make(NamedTuple{(:a,)}, 1:3)) @test t isa NamedTuple{(:a,), Tuple{Int}} @test t.a ∈ 1:3 t = rand(make(NamedTuple{(:a,),Tuple{Float64}}, 1:3)) @test t isa NamedTuple{(:a,), Tuple{Float64}} @test t.a ∈ 1:3 for t = (rand(make(NamedTuple{(:a, :b)})), rand(NamedTuple{(:a, :b)})) @test t isa NamedTuple{(:a, :b), Tuple{Float64,Float64}} end for t = (rand(make(NamedTuple{(:a, :b),Tuple{Int,UInt8}})), rand(NamedTuple{(:a, :b),Tuple{Int,UInt8}})) @test t isa NamedTuple{(:a, :b), Tuple{Int,UInt8}} end t = rand(make(NamedTuple{(:a, :b)}, 1:3)) @test t isa NamedTuple{(:a, :b), Tuple{Int,Int}} @test t.a ∈ 1:3 && t.b ∈ 1:3 t = rand(make(NamedTuple{(:a, :b),Tuple{Float64,UInt8}}, 1:3)) @test t isa NamedTuple{(:a, :b), Tuple{Float64,UInt8}} @test t.a ∈ 1:3 && t.b ∈ 1:3 # as container @test rand(1:3, NamedTuple{(:a,)}) isa NamedTuple{(:a,), Tuple{Int}} @test rand(1:3, NamedTuple{(:a,), Tuple{Float64}}) isa NamedTuple{(:a,), Tuple{Float64}} @test rand(1:3, NamedTuple{(:a, :b)}) isa NamedTuple{(:a, :b), Tuple{Int,Int}} @test rand(1:3, NamedTuple{(:a, :b), Tuple{Float64,Float64}}) isa NamedTuple{(:a, :b), Tuple{Float64,Float64}} end @testset "rand(make(String, ...))" begin b = UInt8['0':'9';'A':'Z';'a':'z'] for (s, c, n) in [(rand(String), b, 8), (rand(make(String, 3)), b, 3), (rand(make(String, "asd")), "asd", 8), (rand(make(String, 3, "asd")), "asd", 3), (rand(make(String, "qwe", 3)), "qwe", 3)] @test s βŠ† map(Char, c) @test length(s) == n end @test rand(make(String, Char)) isa String @test rand(make(String, 3, Char)) isa String @test rand(make(String, Sampler(MersenneTwister, ['a', 'b', 'c']), 10)) isa String end @testset "rand(make(Set/BitSet, ...))" begin for (S, SS, (low, high)) = ((Set{Int}, Set{Int}, (typemin(Int), typemax(Int))), (Set, Set, (0, 1)), (BitSet, BitSet, (typemin(Int8), typemax(Int8)))) for (k, l) = ([1:9] => 1:9, [Int8] => rInt8, [] => ()) s = rand(make(S, k..., 3)) @test s isa (SS === Set ? (l == () ? Set{Float64} : Set{eltype(l)}) : SS) @test length(s) == 3 if l == () @test all(x -> low <= x <= high, s) else @test all(in(l), s) end end rand(make(S, Sampler(MersenneTwister, 1:99), 9)) isa Union{BitSet, Set{Int}} end end @testset "rand(make(Dict, ...))" begin for BD = (Dict, Base.ImmutableDict), (D, S) = (BD{Int16,Int16} => [], BD{Int16} => [Pair{Int8,Int16}], BD{K,Int16} where K => [Pair{Int16,Int8}], BD => [Pair{Int16,Int16}]) d = rand(make(D, S..., 3)) @test d isa BD{Int16,Int16} @test length(d) == 3 end end @testset "rand(make(Array/BitArray, ...))" begin for (T, Arr) = (Bool => BitArray, Float64 => Array{Float64}), k = ([], [T], [Bernoulli(T, 0.3)]), (d, dim) = ([(6,)] => 1, [(2,3)] => 2, [6] => 1, [2, 3] => 2, [Int8(2), Int16(3)] => 2), A = (T == Bool ? (BitArray, BitArray{dim}) : (Array, Array{Float64}, Array{Float64,dim}, Array{U,dim} where U)) s = rand(make(A, k..., d...)) @test s isa Arr{dim} @test length(s) == 6 end @test_throws MethodError rand(make(Matrix, 2)) @test_throws MethodError rand(make(Vector, 2, 3)) @test_throws MethodError rand(make(BitMatrix, 2)) @test_throws MethodError rand(make(BitVector, 2, 3)) @test rand(make(Array, spString, 9)) isa Array{String} @test rand(make(BitArray, Sampler(MersenneTwister, [0, 0, 0, 1]), 9)) isa BitArray # TODO: below was testing without explicit `Array` as 1st argument, so this test # may now be obsolete, redundant with tests above for dims = ((), (2, 3), (0x2, 3), (2,), (0x2,)), s = ([], [Int], [1:3]) T = s == [] ? Float64 : Int if dims != () a = rand(make(Array, s..., dims...)) @test a isa Array{T,length(dims)} if s == [1:3] @test all(in(1:3), a) end end if dims isa Dims a = rand(make(Array, s..., dims)) @test a isa Array{T,length(dims)} if s == [1:3] @test all(in(1:3), a) end end end end @testset "rand(make(Sparse...))" begin for k = ([], [Float64], [Bernoulli(Float64, 0.3)]), (d, dim) = ([(6,)] => 1, [(2,3)] => 2, [6] => 1, [2, 3] => 2, [Int8(2), Int16(3)] => 2) typ = dim == 1 ? SparseVector : SparseMatrixCSC s = rand(make(typ, k..., 0.3, d...)) @test s isa (dim == 1 ? SparseVector{Float64,Int} : SparseMatrixCSC{Float64,Int}) @test length(s) == 6 end @test rand(make(SparseVector, spString, 0.3, 9)) isa SparseVector{String} @test rand(make(SparseVector, make(SparseMatrixCSC, 1:9, 0.3, 2, 3), .1, 4)) isa SparseVector{SparseMatrixCSC{Int64,Int64},Int64} end @testset "rand(make(default))" begin @test rand(make()) isa Float64 @test rand(make(1:3)) isa Int @test rand(make(1:3)) ∈ 1:3 @test rand(make(Float64)) isa Float64 end @testset "rand(T => x) & rand(T => (x, y, ...))" begin @test rand(Complex => Int) isa Complex{Int} @test rand(Pair => (String, Int8)) isa Pair{String,Int8} @test_throws MethodError rand(1=>2) # calls rand(make(1, 2)) @test rand(Complex => Int, 3) isa Vector{Complex{Int}} @test rand(Pair => (String, Int8), Set, 3) isa Set{Pair{String,Int8}} nt = rand(NTuple{4} => Complex => 1:3) @test nt isa NTuple{4,Complex{Int64}} end ## make(x1, xs...) struct MyType x end RandomExtensions.maketype(x::MyType, y) = eltype(x.x:y) Base.rand(rng::AbstractRNG, x::Random.SamplerTrivial{<:RandomExtensions.Make2{<:Integer, MyType}}) = rand(rng, x[][1].x:x[][2]) @testset "rand(make(CustomType(), ...))" begin m = MyType(3) @test rand(make(m, 3)) == 3 @test rand(make(m, big(5))) isa BigInt @test rand(make(m, big(5))) ∈ 3:5 a = rand(make(m, big(6)), 5) @test a isa Vector{BigInt} @test length(a) == 5 @test all(∈(3:6), a) end ## Make getindex @testset "Make getindex" begin m = make(Pair, 1:2, Bool, make(String, 3)) @test m isa RandomExtensions.Make3 @test m[1] == 1:2 @test m[0x2] == Bool @test m[3] isa RandomExtensions.Make2 @test m[1:2] == (m[1], m[2]) @test m[[2, 3]] == m[2:end] == (m[2], m[3]) @test m[big(3)][1:end] == m[3][1:2] end ## @rand run_once = false struct Die n::Int end Base.eltype(::Type{Die}) = Int struct DieT{T} n::T end Base.eltype(::Type{DieT{T}}) where {T} = T @testset "@rand" begin must_run = !run_once global run_once = true if must_run # rng0 to be sure rng is not accessed in `esc`aped body of @rand rng0 = MersenneTwister() d = Die(6) @rand function rand(d::Die) 7 end @test rand(d) == 7 @rand function (d::Die) 7 end @test rand(d) == 7 @rand (d::Die) -> 7 @test rand(d) == 7 # redefinition @rand rand(d::Die) = rand(1:d.n) @test rand(d) ∈ 1:6 @test rand(rng0, d) ∈ 1:6 @test all(∈(1:6), rand(rng0, d, 10)) @test eltype(rand(d, 3)) == Int @rand function (d::Die) rand(1:d.n) end @test rand(d) ∈ 1:6 @test rand(rng0, d) ∈ 1:6 @test all(∈(1:6), rand(rng0, d, 10)) @test eltype(rand(d, 3)) == Int @rand (d::Die) -> rand(1:d.n) @test rand(d) ∈ 1:6 @test rand(rng0, d) ∈ 1:6 @test all(∈(1:6), rand(rng0, d, 10)) @test eltype(rand(d, 3)) == Int # redefinition (multiple inner samplers) @rand rand(d::Die) = rand(10:10) + rand(1:d.n) @test rand(d) ∈ 11:16 @test all(∈(11:16), rand(d, 10)) @rand function (d::Die) rand(10:10) + rand(1:d.n) end @test rand(d) ∈ 11:16 @test all(∈(11:16), rand(d, 10)) @rand (d::Die) -> rand(10:10) + rand(1:d.n) @test rand(d) ∈ 11:16 @test all(∈(11:16), rand(d, 10)) # redefinition access to argument not within rand call @rand rand(d::Die) = rand(1:1) + d.n @test all(==(7), rand(d, 10)) # redefinition back to SamplerTrivial @rand rand(d::Die) = d.n @test all(==(6), rand(d, 100)) # redefinition (Val(Inf) iff rand calls with 2+ arguments) @rand rand(d::Die) = (rand("asd") + rand("asd", 3)[1]; 1) s = Sampler(MersenneTwister, d, Val(1)) @test s.data[1] isa Random.SamplerSimple{String} @test s.data[2] isa Random.SamplerSimple{Vector{Char}} # "proof" of Val(Inf) s = Sampler(MersenneTwister, d, Val(Inf)) @test s.data[1] isa Random.SamplerSimple{Vector{Char}} @test s.data[2] isa Random.SamplerSimple{Vector{Char}} # test esc-correctness VAR = 100 @rand rand(d::Die) = rand(VAR+1:VAR+d.n) - VAR @test all(∈(1:6), rand(d, 100)) # with type parameters d = DieT(6) @rand rand(d::DieT{T}) where {T} = 1 @test rand(d) == 1 @rand function rand(d::DieT{T}) where {T} 2 end @test rand(d) == 2 @rand function (d::DieT{T}) where {T} 3 end @test rand(d) == 3 @rand ((d::DieT{T}) where {T}) -> 4 @test rand(d) == 4 @rand rand(d::DieT{Int}) = 0 @test rand(d) == 0 d = DieT(0x0) @rand rand(d::DieT{T}) where {T<:UInt8} = rand(typemin(T):typemax(T)) @test rand(d) isa UInt8 d = DieT(true) @rand rand(d::DieT{T}) where {T<:Bool} = T(typemin(T) + rand(typemin(T):typemax(T))) @test rand(d) isa Bool end end module TestAtRand # only using RandomExtensions, not Random, to check we don't depend on # some imported names like e.g. SamplerTrivial using RandomExtensions using ..RandomExtensionsTests: @test, @testset struct Die n end @testset "@rand in module" begin @rand rand(d::Die) = d.n # SamplerTrivial @test rand(Die(123)) == 123 @test rand(RandomDevice(), Die(123)) == 123 @rand rand(d::Die) = rand(1:d.n) # SamplerSimple @test rand(Die(1)) == 1 @test rand(RandomDevice(), Die(1)) == 1 end end # module TestAtRand
RandomExtensions
https://github.com/JuliaRandom/RandomExtensions.jl.git
[ "MIT" ]
0.4.4
b8a399e95663485820000f26b6a43c794e166a49
docs
11676
# RandomExtensions [![Tests Status](https://github.com/JuliaRandom/RandomExtensions.jl/workflows/CI/badge.svg)](https://github.com/JuliaRandom/RandomExtensions.jl/actions?query=workflow%3ACI) [![](https://img.shields.io/badge/docs-dev-blue.svg)](https://JuliaRandom.github.io/RandomExtensions.jl/dev) This package explores a possible extension of `rand`-related functionalities (from the `Random` module); the code is initially taken from https://github.com/JuliaLang/julia/pull/24912. Note that type piracy is committed! While hopefully useful, this package is still experimental, and hence unstable. User feedback, and design or implementation contributions are welcome. This does essentially 4 things: 1) define distribution objects, to give first-class status to features provided by `Random`; for example `rand(Normal(), 3)` is equivalent to `randn(3)`; other available distributions: `Exponential`, `CloseOpen` (for generation of floats in a close-open range) and friends, `Uniform` (which can wrap an implicit uniform distribution); 2) define `make` methods, which can combine distributions for objects made of multiple scalars, like `Pair`, `Tuple`, or `Complex`, or describe how to generate more complex objects, like containers; 3) extend the `rand([rng], [S], dims)` API to allow the generation of other containers than arrays (like `Set`, `Dict`, `SparseArray`, `String`, `BitArray`); 4) define a `Rand` iterator, which produces lazily random values. Point 1) defines a `Distribution` type which is incompatible with the "Distributions.jl" package. Input on how to unify the two approaches is welcome. Point 2) is really the core of this package. `make` provides a vocabulary to define the generation of "scalars" which require more than one argument to be described, e.g. pairs from `1:3` to `Int` (`rand(make(Pair, 1:3, Int))`) or regular containers (e.g. `make(Array, 2, 3)`). The point of calling `make` rather than putting all the arguments in `rand` directly is simplicity and composability: the `make` call always occurs as the second argument to `rand` (or first if the RNG is omitted). For example, `rand(make(Array, 2, 3), 3)` creates an array of matrices. Of course, `make` is not necessary, in that the same can be achieved with an ad hoc `struct`, which in some cases is clearer (e.g. `Normal(m, s)` rather than something like `make(Float64, Val(:Normal), m, s)`). As an experimental feature, the following alternative API is available: - `rand(T => x)` is equivalent to `rand(make(T, x))` - `rand(T => (x, y, ...))` is equivalent to `rand(make(T, x, y, ...))` This is for convenience only (it may be more readable), but may be less efficient due to the fact that the type of a pair containing a type doesn't know this exact type (e.g. `Pair => Int` has type `Pair{UnionAll,DataType}`), so `rand` can't infer the type of the generated value. Thanks to inlining, the inferred types can however be sufficiently tight in some cases (e.g. `rand(Complex => Int, 3)` is of type `Vector{Complex{Int64}}` instead of `Vector{Any}`). Point 3) allows something like `rand(1:30, Set, 10)` to produce a `Set` of length `10` with values from `1:30`. The idea is that `rand([rng], [S], Cont, etc...)` should always be equivalent to `rand([rng], make(Cont, [S], etc...))`. This design goes somewhat against the trend in `Base` to create containers using their constructors -- which by the way may be achieved via the `Rand` iterator from point 4). Still, I like the terse approach here, as it simply generalizes to other containers the _current_ `rand` API creating arrays. See the issue linked above for a discussion on these topics. For convenience, the following names from `Random` are re-exported in this package: `rand!`, `AbstractRNG`, `MersenneTwister`, `RandomDevice` (`rand` is in `Base`). Functions like `randn!` or `randstring` are considered to be obsoleted by this package so are not re-exported. It's still needed to import `Random` separately in order to use functions which don't extend the `rand` API, namely `randsubseq`, `shuffle`, `randperm`, `randcycle`, and their mutating variants. There is not much documentation for now: `rand`'s docstring is updated, and here are some examples: ```julia julia> rand(CloseOpen(Float64)) # equivalent to rand(Float64) 0.7678877639669386 julia> rand(CloseClose(1.0f0, 10)) # generation in [1.0f0, 10.0f0] 6.62467f0 julia> rand(OpenOpen(2.0^52, 2.0^52+1)) == 2.0^52 # exactness not guaranteed for "unreasonable" values! true julia> rand(Normal(0.0, 10.0)) # explicit ΞΌ and Οƒ parameters -8.473790458128912 julia> rand(Uniform(1:3)) # equivalent to rand(1:3) 2 julia> rand(make(Pair, 1:10, Normal())) # random Pair, where both members have distinct distributions 5 => 0.674375 julia> rand(make(Pair{Number,Any}, 1:10, Normal())) # specify the Pair type Pair{Number,Any}(1, -0.131617) julia> rand(Pair{Float64,Int}) # equivalent to rand(make(Pair, Float64, Int)) 0.321676 => -4583276276690463733 julia> rand(make(Tuple, 1:10, UInt8, OpenClose())) (9, 0x6b, 0.34900083923775505) julia> rand(Tuple{Float64,Int}) # equivalent to rand(make(Tuple, Float64, Int)) (0.9830769470405203, -6048436354564488035) julia> rand(make(NTuple{3}, 1:10)) # produces a 3-tuple with values from 1:10 (5, 9, 6) julia> rand(make(NTuple{N,UInt8} where N, 1:3, 5)) (0x02, 0x03, 0x02, 0x03, 0x02) julia> rand(make(NTuple{3}, make(Pair, 1:9, Bool))) # make calls can be nested (2 => false, 8 => true, 7 => false) julia> rand(make(Complex, Normal())) # each coordinate is drawn from the normal distribution 1.5112317924121632 + 0.723463453534426im julia> rand(make(Complex, Normal(), 1:10)) # distinct distributions 1.096731587266045 + 8.0im julia> rand(Normal(ComplexF64)) # equivalent to randn(ComplexF64) 0.9322376894079347 + 0.2812214248483498im julia> rand(Set, 3) Set([0.717172, 0.78481, 0.86901]) julia> rand!(ans, Exponential()) Set([0.7935073925105659, 2.593684878770254, 1.629181233597078]) julia> rand(1:9, Set, 3) # if you try `rand(1:3, Set, 9)`, it will take a while ;-) Set([3, 5, 8]) julia> rand(Dict{String,Int8}, 2) Dict{String,Int8} with 3 entries: "vxybIbae" => 42 "bO2fTwuq" => -13 julia> rand(make(Pair, 1:9, Normal()), Dict, 3) Dict{Int64,Float64} with 3 entries: 9 => 0.916406 3 => -2.44958 8 => -0.703348 julia> rand(SparseVector, 0.3, 9) # equivalent to sprand(9, 0.3) 9-element SparseVector{Float64,Int64} with 3 stored entries: [1] = 0.173858 [6] = 0.568631 [8] = 0.297207 julia> rand(Normal(), SparseMatrixCSC, 0.3, 2, 3) # equivalent to sprandn(2, 3, 0.3) 2Γ—3 SparseMatrixCSC{Float64,Int64} with 2 stored entries: [2, 1] = 0.448981 [1, 2] = 0.730103 # like for Array, sparse arrays enjoy to be special cased: `SparseVector` or `SparseMatrixCSC` # can be omitted in the `rand` call (not in the `make` call): julia> rand(make(SparseVector, 1:9, 0.3, 2), 0.1, 4, 3) # possible, bug ugly output when non-empty :-/ 4Γ—3 SparseMatrixCSC{SparseVector{Int64,Int64},Int64} with 0 stored entries julia> rand(String, 4) # equivalent to randstring(4) "5o75" julia> rand("123", String, 4) # like above, String creation with the "container" syntax ... "2131" julia> rand(make(String, 3, "123")) # ... which is as always equivalent to a call to make "211" julia> rand(String, Set, 3) # String considered as a scalar Set(["0Dfqj6Yr", "ILngfcRz", "HT5IEyK3"]) julia> rand(BitArray, 3) # equivalent to, but unfortunately more verbose than, bitrand(3) 3-element BitArray{1}: true true false julia> julia> rand(Bernoulli(0.2), BitVector, 10) # using the Bernoulli distribution 10-element BitArray{1}: false false false false true false true false false true julia> rand(1:3, NTuple{3}) # NTuple{3} considered as a container, equivalent to rand(make(NTuple{3}, 1:3)) (3, 3, 1) julia> rand(1:3, Tuple{Int,UInt8, BigFloat}) # works also with more general tuple types ... (3, 0x02, 2.0) julia> rand(1:3, NamedTuple{(:a, :b)}) # ... and with named tuples (a = 3, b = 2) julia> RandomExtensions.random_staticarrays() # poor man's conditional modules! # ugly warning julia> rand(make(MVector{2,AbstractString}, String), SMatrix{3, 2}) 3Γ—2 SArray{Tuple{3,2},MArray{Tuple{2},AbstractString,1,2},2,6} with indices SOneTo(3)Γ—SOneTo(2): ["SzPKXHFk", "1eFXaUiM"] ["RJnHwhb7", "jqfLcY8a"] ["FMTKcBY8", "eoYtNntD"] ["FzdD530L", "ux6sWGMU"] ["fFJuUtJQ", "H2mAQrIV"] ["pt0OYFJw", "O0fCfjjR"] julia> Set(Iterators.take(Rand(RandomDevice(), 1:10), 3)) # RNG defaults to Random.GLOBAL_RNG Set([9, 2, 6]) # note that the set could end up with less than 3 elements if `Rand` generates duplicates julia> collect(Iterators.take(Uniform(1:10), 3)) # distributions can be iterated over, using Random.GLOBAL_RNG implicitly 3-element Array{Int64,1}: 7 10 5 julia> rand(Complex => Int) # equivalent to rand(make(Complex, Int)) (experimental) 4610038282330316390 + 4899086469899572461im julia> rand(Pair => (String, Int8)) # equivalent to rand(make(Pair, String, Int8)) (experimental) "ODNXIePK" => 4 ``` In some cases, the `Rand` iterator can provide efficiency gains compared to repeated calls to `rand`, as it uses the same mechanism as array generation. For example, given `a = zeros(1000)` and `s = BitSet(1:1000)`, `a .+ Rand(s).()` is three times faster than `a .+ rand.(Ref(s))`. Note: as seen in the examples above, `String` can be considered as a scalar or as a container (in the `rand` API). In a call like `rand(String)`, both APIs coincide, but in `rand(String, 3)`, should we construct a `String` of length `3` (container API), or an array of strings of default length `8` ? Currently, the package chooses the first interpretation, partly because it was the first implemented, and also because it may actually be the one most useful (and offers the tersest API to compete with `randstring`). But as this package is still unstable, this choice may be revisited in the future. Note that it's easy to get the result of the second interpretation via either `rand(make(String), 3)`, `rand(String, (3,))` or `rand(String, Vector, 3)`. How to extend: the `make` function is meant to be extensible, and there are some helper functions which make it easy, but this is still experimental. By default, `make(T, args...)` will create a `Make{maketype(T, args...)}` object, say `m`, which contain `args...` as fields. For type stable code, the `rand` machinery likes to know the exact type of the object which will be generated by `rand(m)`, and `maketype(T, args...)` is supposed to return that type. For example, `maketype(Pair, 1:3, UInt) == Pair{Int,UInt}`. Then just define `rand` for `m` like documented in the `Random` module, e.g. `rand(rng::AbstractRNG, sp::SamplerTrivial{<:Make{P}}) where {P<:Pair} = P(rand(sp[][1]), rand(sp[][2]))`. For convenience, `maketype(T, ...)` defaults to `T`, which means that for simple cases, only the `rand` function has to be defined. But in cases like for `Pair` above, if `maketype` is not defined, the generated type will be assumed to be `Pair`, which is not a concrete type (and hence suboptimal). This package started out of frustration with the limitations of the `Random` module. Besides generating simple scalars and arrays, very little is supported out of the box. For example, generating a random `Dict` is too complex. Moreover, there are too many functions for my taste: `rand`, `randn`, `randexp`, `sprand` (with its exotic `rfn` parameter), `sprandn`, ~~`sprandexp`~~, `randstring`, `bitrand`, and mutating counterparts (but I believe `randn` will never go away, as it's so terse). I hope that this package can serve as a starting point towards improving `Random`.
RandomExtensions
https://github.com/JuliaRandom/RandomExtensions.jl.git
[ "MIT" ]
0.4.4
b8a399e95663485820000f26b6a43c794e166a49
docs
209
# RandomExtensions Most of the "documentation" is still in the [README](https://github.com/JuliaRandom/RandomExtensions.jl/blob/master/README.md). Here is the updated docstring for `rand`: ```@docs rand ```
RandomExtensions
https://github.com/JuliaRandom/RandomExtensions.jl.git
[ "MIT" ]
0.1.1
91e7a85ba7923e80f9a6bc359abb18b0fe437314
code
619
using MultiAgentPOMDPs using Documenter makedocs(; modules=[MultiAgentPOMDPs], authors="rejuvyesh <[email protected]>, Shushman <[email protected]> and contributors", repo="https://github.com/JuliaPOMDP/MultiAgentPOMDPs.jl/blob/{commit}{path}#L{line}", sitename="MultiAgentPOMDPs.jl", format=Documenter.HTML(; prettyurls=get(ENV, "CI", "false") == "true", canonical="https://juliapomdp.github.io/MultiAgentPOMDPs.jl", assets=String[], ), pages=[ "Home" => "index.md", ], ) deploydocs(; repo="github.com/JuliaPOMDP/MultiAgentPOMDPs.jl", )
MultiAgentPOMDPs
https://github.com/JuliaPOMDP/MultiAgentPOMDPs.jl.git