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" ]
7.10.1
fa6d92aa63d72f35adfbe99d79f60dd3f9604f0e
code
499
using StanSample, DataFrames, InferenceObjects, Test stan = " parameters { matrix[2, 3] x; } model { for (i in 1:2) x[i,:] ~ std_normal(); } "; sm = SampleModel("foo", stan); rc = stan_sample(sm); df = read_samples(sm, :dataframe) df |> display println() df2 = read_samples(sm, :nesteddataframe) df2 |> display println() idata = inferencedata(sm) display(idata) display(idata.posterior.x[15, 2, :, :]) display(df2.x[1015]) @test idata.posterior.x[15, 2, :, :] == df2.x[1015]
StanSample
https://github.com/StanJulia/StanSample.jl.git
[ "MIT" ]
7.10.1
fa6d92aa63d72f35adfbe99d79f60dd3f9604f0e
code
807
using StanSample, DataFrames, JSON, InferenceObjects, Test stan = " parameters { real r; matrix[2, 3] x; array[2, 2, 3] real<lower=0> z; } model { r ~ std_normal(); for (i in 1:2) { x[i,:] ~ std_normal(); for (j in 1:2) z[i, j, :] ~ std_normal(); } } "; tmpdir = joinpath(@__DIR__, "tmp") sm = SampleModel("tuple_model", stan, tmpdir) rc = stan_sample(sm) df2 = read_samples(sm, :nesteddataframe) display(df2) chns, col_names = read_samples(sm, :array; return_parameters=true) display(col_names) println() display(size(chns)) println() #ex = StanSample.extract(chns, col_names) idata = inferencedata(sm) display(idata) println() display(idata.posterior) println() @test reshape(Array(idata.posterior.z[1,1,1:2,1:2,3]), 4) == chns[1, 16:19, 1]
StanSample
https://github.com/StanJulia/StanSample.jl.git
[ "MIT" ]
7.10.1
fa6d92aa63d72f35adfbe99d79f60dd3f9604f0e
code
796
######### StanSample example ########### using StanSample, Test bernoulli_model = " data { int<lower=1> N; array[N] int<lower=0,upper=1> y; } parameters { real<lower=0,upper=1> theta; } model { theta ~ beta(1,1); y ~ bernoulli(theta); } "; bernoulli_data = [ Dict("N" => 10, "y" => [0, 1, 0, 1, 0, 0, 0, 0, 0, 1]), Dict("N" => 10, "y" => [0, 1, 0, 0, 1, 0, 0, 0, 0, 1]), Dict("N" => 10, "y" => [0, 1, 0, 1, 0, 0, 0, 0, 1, 0]), Dict("N" => 10, "y" => [0, 0, 0, 1, 0, 0, 1, 0, 0, 1]), ] sm = SampleModel("bernoulli", bernoulli_model) rc = stan_sample(sm; data=bernoulli_data, delta=0.85, num_threads=1) if success(rc) # Fetch the same output in the `sdf` ChainDataFrame sdf = read_summary(sm) @test sdf[sdf.parameters .== :theta, :mean][1] β‰ˆ 0.33 rtol=0.05 end
StanSample
https://github.com/StanJulia/StanSample.jl.git
[ "MIT" ]
7.10.1
fa6d92aa63d72f35adfbe99d79f60dd3f9604f0e
code
726
######### CmdStan sample example ########### using StanSample bernoulli_model = " data { int<lower=1> N; array[N] int<lower=0,upper=1> y; } parameters { real<lower=0,upper=1> theta; } model { theta ~ beta(1,1); y ~ bernoulli(theta); } "; bernoulli_data = [ Dict("N" => 10, "y" => [0, 1, 0, 1, 0, 0, 0, 0, 0, 1]), Dict("N" => 10, "y" => [0, 1, 0, 0, 1, 0, 0, 0, 0, 1]), Dict("N" => 10, "y" => [0, 1, 0, 1, 0, 0, 0, 0, 1, 0]) ] stanmodel = SampleModel("bernoulli", bernoulli_model) rc = stan_sample(stanmodel, data=bernoulli_data) # Fetch the same output in the `sdf` ChainDataFrame if success(rc) sdf = read_summary(stanmodel) @test sdf[sdf.parameters .== :theta, :mean][1] β‰ˆ 0.33 rtol=0.05 end
StanSample
https://github.com/StanJulia/StanSample.jl.git
[ "MIT" ]
7.10.1
fa6d92aa63d72f35adfbe99d79f60dd3f9604f0e
code
1669
######### StanSample example ########### using StanSample, Test bernoulli_model = " data { int<lower=1> N; array[N] int<lower=0,upper=1> y; } parameters { real<lower=0,upper=1> theta; } model { theta ~ beta(1,1); y ~ bernoulli(theta); } "; bernoulli_data = Dict("N" => 10, "y" => [0, 1, 0, 1, 0, 0, 0, 0, 0, 1]) sm = SampleModel("bernoulli", bernoulli_model) rc = stan_sample(sm, data=bernoulli_data, num_chains=4, delta=0.85) # Fetch the cmdstan summary in sdf` if success(rc) sdf = read_summary(sm) @test sdf[sdf.parameters .== :theta, :mean][1] β‰ˆ 0.33 rtol=0.05 # Included return formats samples = read_samples(sm) # Return KeyesArray object a3d = read_samples(sm, :array) # Return an a3d object df = read_samples(sm, :dataframe) # Return a DataFrame object # If (and only if) MCMCChains is loaded: # chns = read_samples(sm, :mcmcchains) # See examples in directory `examples_mcmcchains` df end isdir(tmpdir) && rm(tmpdir, recursive=true) sm = SampleModel("bernoulli", bernoulli_model, tmpdir) rc = stan_sample(sm, data=bernoulli_data, num_threads=4, num_cpp_chains=1, num_chains=4, delta=0.85) # Fetch the cmdstan summary in sdf` if success(rc) sdf = read_summary(sm) @test sdf[sdf.parameters .== :theta, :mean][1] β‰ˆ 0.33 rtol=0.05 # Included return formats samples = read_samples(sm) # Return Tables object a3d = read_samples(sm, :array) # Return an a3d object df = read_samples(sm, :dataframe) # Return a DataFrame object # If (and only if) MCMCChains is loaded: # chns = read_samples(sm, :mcmcchains) # See examples in directory `examples_mcmcchains` df end
StanSample
https://github.com/StanJulia/StanSample.jl.git
[ "MIT" ]
7.10.1
fa6d92aa63d72f35adfbe99d79f60dd3f9604f0e
code
1285
using StanSample, Test ProjDir = @__DIR__ cd(ProjDir) # do bernoulli_model = " data { int<lower=1> N; array[N] int<lower=0,upper=1> y; } parameters { real<lower=0,upper=1> theta; } model { theta ~ beta(1,1); y ~ bernoulli(theta); } "; sm = SampleModel("bernoulli", bernoulli_model) observeddata = Dict("N" => 10, "y" => [0, 1, 0, 1, 0, 0, 0, 0, 0, 1]) rc = stan_sample( sm; data=observeddata, num_samples=13, num_warmups=17, save_warmup=true, num_chains=1, sig_figs=2, stepsize=0.7, ) @test success(rc) samples = read_samples(sm, :array) shape = size(samples) # number of samples, number of chains, number of parameters @test shape == (30, 1, 1) # read the log file f = open(sm.log_file[1], "r") # remove leading whitespace and chop off the "(default)" suffix config = [chopsuffix(lstrip(x), r"\s+\(default\)$"i) for x in eachline(f) if length(x) > 0] close(f) # check that the config is as expected required_entries = [ "method = sample", "num_samples = 13", "num_warmup = 17", "save_warmup = true", "num_chains = 1", "sig_figs = 2", "stepsize = 0.7", ] for entry in required_entries @test entry in config end
StanSample
https://github.com/StanJulia/StanSample.jl.git
[ "MIT" ]
7.10.1
fa6d92aa63d72f35adfbe99d79f60dd3f9604f0e
code
864
using StanSample, Test #set_cmdstan_home!(homedir() * "/Projects/StanSupport/cmdstan_stanc3") ProjDir = @__DIR__ cd(ProjDir) # do 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; array[N] int<lower=0,upper=1> y; } parameters { real<lower=0,upper=1> theta; } model { model_specific_function(); theta ~ beta(my_function(),1); y ~ bernoulli(theta); } "; sm = SampleModel("bernoulli", bernoulli_model) observeddata = Dict("N" => 10, "y" => [0, 1, 0, 1, 0, 0, 0, 0, 0, 1]) rc = stan_sample(sm; data=observeddata) if success(rc) samples = read_samples(sm, :array) @test sum(samples)/length(samples) β‰ˆ 0.33 rtol=0.05 end #end
StanSample
https://github.com/StanJulia/StanSample.jl.git
[ "MIT" ]
7.10.1
fa6d92aa63d72f35adfbe99d79f60dd3f9604f0e
code
581
######### StanSample Bernoulli example ########### using AxisKeys, StanSample bernoulli_model = " data { int N; array[N] int y; } 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]) sm = SampleModel("bernoulli", bernoulli_model); rc = stan_sample(sm; data); if success(rc) (samples, cnames) = read_samples(sm, :array; return_parameters=true) ka = read_samples(sm, :keyedarray) ka |> display println() sdf = read_summary(sm) sdf |> display end
StanSample
https://github.com/StanJulia/StanSample.jl.git
[ "MIT" ]
7.10.1
fa6d92aa63d72f35adfbe99d79f60dd3f9604f0e
code
544
######### StanSample Bernoulli example ########### using StanSample bernoulli_model = " data { int<lower=1> N; array[N] int y; } 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]) sm = SampleModel("bernoulli", bernoulli_model); rc = stan_sample(sm; data, thin=4, delta=0.85); if success(rc) (samples, cnames) = read_samples(sm, :array; return_parameters=true) ka = read_samples(sm) ka |> display println() end
StanSample
https://github.com/StanJulia/StanSample.jl.git
[ "MIT" ]
7.10.1
fa6d92aa63d72f35adfbe99d79f60dd3f9604f0e
code
619
######### StanSample Bernoulli example ########### using StanSample bernoulli_model = " data { int<lower=1> N; array[N] int y; } parameters { real<lower=0,upper=1> theta; } model { theta ~ beta(1,1); y ~ bernoulli(theta); } "; bernoulli_data = Dict("N" => 10, "y" => [0, 1, 0, 1, 0, 0, 0, 0, 0, 1]) sm = SampleModel("bernoulli", bernoulli_model; method = StanSample.Sample( save_warmup=false, # Default thin=1, adapt = StanSample.Adapt(delta = 0.85)) ); rc = stan_sample(sm; data=bernoulli_data); if success(rc) (samples, cnames) = read_samples(sm, :array) end
StanSample
https://github.com/StanJulia/StanSample.jl.git
[ "MIT" ]
7.10.1
fa6d92aa63d72f35adfbe99d79f60dd3f9604f0e
code
630
######### StanSample Bernoulli example ########### using StanSample bernoulli_model = " 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); } "; bernoulli_data = Dict("N" => 10, "y" => [0, 1, 0, 1, 0, 0, 0, 0, 0, 1]) sm = SampleModel("bernoulli", bernoulli_model; method = StanSample.Sample( save_warmup=false, # Default thin=1, adapt = StanSample.Adapt(delta = 0.85)) ); rc = stan_sample(sm; data=bernoulli_data); if success(rc) (samples, cnames) = read_samples(sm, :array) end
StanSample
https://github.com/StanJulia/StanSample.jl.git
[ "MIT" ]
7.10.1
fa6d92aa63d72f35adfbe99d79f60dd3f9604f0e
code
492
######### StanSample Bernoulli example ########### using AxisKeys, StanSample bernoulli_model = " data { int<lower=1> N; array[N] int y; } parameters { real<lower=0,upper=1> theta; } model { theta ~ beta(1,1); y ~ bernoulli(theta); } "; bernoulli_data = Dict("N" => 10, "y" => [0, 1, 0, 1, 0, 0, 0, 0, 0, 1]) sm = SampleModel("bernoulli", bernoulli_model); rc = stan_sample(sm; data=bernoulli_data, num_chains=6); if success(rc) chns = read_samples(sm) end chns |> display
StanSample
https://github.com/StanJulia/StanSample.jl.git
[ "MIT" ]
7.10.1
fa6d92aa63d72f35adfbe99d79f60dd3f9604f0e
code
801
using StanSample stan_data_2 = Dict("N" => 3, "nu" => 13, "L_Psi" => [1.0 0.0 0.0; 2.0 3.0 0.0; 4.0 5.0 6.0]); stan_data = (N = 3, nu = 13, L_Psi = [1.0 0.0 0.0; 2.0 3.0 0.0; 4.0 5.0 6.0]); model_code = " data { int<lower=1> N; real<lower=N-1> nu; cholesky_factor_cov[N] L_Psi; } parameters { cholesky_factor_cov[N] L_X; } model { L_X ~ inv_wishart_cholesky(nu, L_Psi); } "; sm = SampleModel("test", model_code); stan_sample(sm; data=stan_data_2); ndf = read_samples(sm, :nesteddataframe) println(ndf.L_X[1]) println("\n") stan_sample(sm; data=stan_data_2); ndf = read_samples(sm, :nesteddataframe) println(ndf.L_X[1]) println("\n") for i in 1:5 stan_sample(sm; data=stan_data); ndf = read_samples(sm, :nesteddataframe) println(ndf.L_X[1]) println("\n") end
StanSample
https://github.com/StanJulia/StanSample.jl.git
[ "MIT" ]
7.10.1
fa6d92aa63d72f35adfbe99d79f60dd3f9604f0e
code
1061
cd(@__DIR__) using StanSample, Random, MCMCChains, Serialization tempdir = pwd() * "/tmp" # Generate Data seed = 350 Random.seed!(seed) n_obs = 50 y = randn(n_obs) stan_data = Dict( "y" => y, "n_obs" => n_obs) # Stan Language Model stan_01 = " data{ // total observations int n_obs; // observations vector[n_obs] y; } parameters { real mu; real<lower=0> sigma; } model { mu ~ normal(0, 1); sigma ~ gamma(1, 1); y ~ normal(mu, sigma); }" # Create SampleModel sm_01 = SampleModel("temp", stan_01) # Run the sampler rc_01 = stan_sample( sm_01; data = stan_data, seed, num_chains = 4, num_samples = 1000, num_warmups = 1000, save_warmup = false ) # Serialize after calling stan_sample! serialize(joinpath(sm_01.tmpdir, "sm_01"), sm_01) if success(rc_01) chn_01 = read_samples(sm_01, :mcmcchains) chn_01 |> display end sm_02 = deserialize(joinpath(sm_01.tmpdir, "sm_01")) if success(rc_01) chn_02 = read_samples(sm_02, :mcmcchains) chn_02 |> display end
StanSample
https://github.com/StanJulia/StanSample.jl.git
[ "MIT" ]
7.10.1
fa6d92aa63d72f35adfbe99d79f60dd3f9604f0e
code
576
using StanSample using MCMCChains using Random seed = 350 Random.seed!(seed) n_obs = 50 y = randn(n_obs) stan_data_2 = Dict("y" => y, "n_obs" => n_obs); stan_data= (y=y, n_obs=n_obs); model = " data{ // total observations int n_obs; // observations vector[n_obs] y; } parameters { real mu; real<lower=0> sigma; } model { mu ~ normal(0, 1); sigma ~ gamma(1, 1); y ~ normal(mu, sigma); }"; tmpdir = pwd()*"/tmp" sm = SampleModel("temp", model, tmpdir) rc = stan_sample(sm; data=stan_data_2) read_samples(sm, :mcmcchains) |> display
StanSample
https://github.com/StanJulia/StanSample.jl.git
[ "MIT" ]
7.10.1
fa6d92aa63d72f35adfbe99d79f60dd3f9604f0e
code
616
using StanSample using MCMCChains using Random seed = 350 Random.seed!(seed) n_obs = 50 y = randn(n_obs) stan_data_2 = Dict("y" => y, "n_obs" => n_obs); stan_data= (y=y, n_obs=n_obs); model = " data{ // total observations int n_obs; // observations vector[n_obs] y; } parameters { real mu; real<lower=0> sigma; } model { mu ~ normal(0, 1); sigma ~ gamma(1, 1); y ~ normal(mu, sigma); }"; tmpdir = pwd()*"/tmp" sm = SampleModel("temp", model, tmpdir) read_samples(sm, :mcmcchains) |> display rc = stan_sample(sm; data=stan_data) read_samples(sm, :mcmcchains) |> display
StanSample
https://github.com/StanJulia/StanSample.jl.git
[ "MIT" ]
7.10.1
fa6d92aa63d72f35adfbe99d79f60dd3f9604f0e
code
703
using StanSample, JSON, DataFrames stan = " data { int<lower=0> N; array[N] complex x; array[N] complex y; } parameters { complex alpha; complex beta; vector[2] sigma; } model { to_real(eps_n) ~ normal(0, sigma[1]); to_imag(eps_n) ~ normal(0, sigma[2]); sigma ~ //...hyperprior... for (n in 1:N) { complex eps_n = y[n] - (alpha + beta * x[n]); // error eps_n ~ // ...error distribution... } } "; w_max = 5 # Max extent of the independent values w = LinRange(-w_max, w_max, 11) tmp = Complex[] for i in w for j in w append!(tmp, Complex(i, j)) end end w = tmp df = DataFrame(w = filter(x -> sqrt(real(x)^2 + imag(x)^2) <= w_max, w)) n = length(w) display(df)
StanSample
https://github.com/StanJulia/StanSample.jl.git
[ "MIT" ]
7.10.1
fa6d92aa63d72f35adfbe99d79f60dd3f9604f0e
code
2625
using CSV, DataFrames using DimensionalData using StanSample using Statistics, Test df = CSV.read(joinpath(@__DIR__, "..", "..", "data", "chimpanzees.csv"), DataFrame); # Define the Stan language model stan10_4 = " data{ int N; int N_actors; int pulled_left[N]; int prosoc_left[N]; int condition[N]; int actor[N]; } parameters{ vector[N_actors] a; real bp; real bpC; } model{ vector[N] p; bpC ~ normal( 0 , 10 ); bp ~ normal( 0 , 10 ); a ~ normal( 0 , 10 ); for ( i in 1:504 ) { p[i] = a[actor[i]] + (bp + bpC * condition[i]) * prosoc_left[i]; p[i] = inv_logit(p[i]); } pulled_left ~ binomial( 1 , p ); } "; data10_4 = (N = size(df, 1), N_actors = length(unique(df.actor)), actor = df.actor, pulled_left = df.pulled_left, prosoc_left = df.prosoc_left, condition = df.condition); # Sample using cmdstan m10_4s = SampleModel("m10.4s", stan10_4) rc10_4s = stan_sample(m10_4s; data=data10_4); # Result rethinking rethinking = " mean sd 5.5% 94.5% n_eff Rhat bp 0.84 0.26 0.43 1.26 2271 1 bpC -0.13 0.29 -0.59 0.34 2949 1 a[1] -0.74 0.27 -1.16 -0.31 3310 1 a[2] 10.88 5.20 4.57 20.73 1634 1 a[3] -1.05 0.28 -1.52 -0.59 4206 1 a[4] -1.05 0.28 -1.50 -0.60 4133 1 a[5] -0.75 0.27 -1.18 -0.32 4049 1 a[6] 0.22 0.27 -0.22 0.65 3877 1 a[7] 1.81 0.39 1.22 2.48 3807 1 "; # Update sections @testset ":dimarrays tests" begin if success(rc10_4s) da = read_samples(m10_4s, :dimarrays) da1 = da[param=At(Symbol("a.1"))] # Other manipulations @test Tables.istable(da) == true # All of parameters dar = reshape(Array(da), 4000, 9); @test size(dar) == (4000, 9) # Check :param axis names @test dims(da, :param).val == vcat([Symbol("a.$i") for i in 1:7], :bp, :bpC) # Test combining vector param 'a' ma = matrix(da, "a"); rma = reshape(ma, 4000, size(ma, 3)) @test mean(rma, dims=1) β‰ˆ [-0.7 10.9 -1 -1 -0.7 0.2 1.8] atol=0.7 end end @testset ":dimarray tests" begin if success(rc10_4s) da = read_samples(m10_4s, :dimarray) da |> display da1 = da[param=At(Symbol("a.1"))] # Other manipulations @test Tables.istable(da) == true # Check :param axis names @test dims(da, :param).val == vcat([Symbol("a.$i") for i in 1:7], :bp, :bpC) # Test combining vector param 'a' ma = matrix(da, "a"); @test mean(ma, dims=1) β‰ˆ [-0.7 10.9 -1 -1 -0.7 0.2 1.8] atol=0.7 end end
StanSample
https://github.com/StanJulia/StanSample.jl.git
[ "MIT" ]
7.10.1
fa6d92aa63d72f35adfbe99d79f60dd3f9604f0e
code
568
using DataFrames using StanSample, Test ProjDir = @__DIR__ cd(ProjDir) gq = " data { int<lower=0> N; array[N] int<lower=0> y; } parameters { real<lower=0.00001> Theta; } model { Theta ~ gamma(4, 1000); for (n in 1:N) y[n] ~ exponential(Theta); } generated quantities{ real y_pred; y_pred = exponential_rng(Theta); } "; data = Dict( "N" => 3, "y" => [100, 950, 450] ); sm = SampleModel("Generate_quantities", gq); rc = stan_sample(sm; data) if success(rc) df = stan_generate_quantities(sm, 1, "1") df end
StanSample
https://github.com/StanJulia/StanSample.jl.git
[ "MIT" ]
7.10.1
fa6d92aa63d72f35adfbe99d79f60dd3f9604f0e
code
1681
using CSV, DataFrames, NamedTupleTools using InferenceObjects using StanSample stan_schools = """ data { int<lower=0> J; vector[J] y; vector[J] sigma; } parameters { real mu; real<lower=0> tau; vector[J] theta_tilde; } transformed parameters { vector[J] theta; for (j in 1:J) theta[j] = mu + tau * theta_tilde[j]; } model { mu ~ normal(0, 5); tau ~ cauchy(0, 5); theta_tilde ~ normal(0, 1); y ~ normal(theta, sigma); } generated quantities { vector[J] log_lik; vector[J] y_hat; for (j in 1:J) { log_lik[j] = normal_lpdf(y[j] | theta[j], sigma[j]); y_hat[j] = normal_rng(theta[j], sigma[j]); } } """; data = Dict( "J" => 8, "y" => [28.0, 8.0, -3.0, 7.0, -1.0, 1.0, 18.0, 12.0], "sigma" => [15.0, 10.0, 16.0, 11.0, 9.0, 11.0, 10.0, 18.0] ) m_schools = SampleModel("eight_schools", stan_schools) rc = stan_sample(m_schools; data, save_warmup=true) if success(rc) idata = StanSample.inferencedata( m_schools; posterior_predictive_var=:y_hat, log_likelihood_var=[:log_lik], dims=(; (k => [:school] for k in [:theta, :theta_tilde, :y_hat, :log_like])...), ) nt = namedtuple(data) idata = merge(idata, from_namedtuple(; observed_data = nt)) else @warn "Sampling failed." end if :observed_data in propertynames(idata) idata.observed_data end #DataFrame(idata.observed_data) keys(idata.posterior) post_schools = read_samples(m_schools, :dataframe) posterior_schools = DataFrame(idata.posterior) idata |> display sample_stats_schools = DataFrame(idata.sample_stats) sample_stats_schools[1:10, :] |> display
StanSample
https://github.com/StanJulia/StanSample.jl.git
[ "MIT" ]
7.10.1
fa6d92aa63d72f35adfbe99d79f60dd3f9604f0e
code
499
using StanSample, DataFrames, InferenceObjects, Test stan = " parameters { matrix[2, 3] x; } model { for (i in 1:2) x[i,:] ~ std_normal(); } "; sm = SampleModel("foo", stan); rc = stan_sample(sm); df = read_samples(sm, :dataframe) df |> display println() df2 = read_samples(sm, :nesteddataframe) df2 |> display println() idata = inferencedata(sm) display(idata) display(idata.posterior.x[15, 2, :, :]) display(df2.x[1015]) @test idata.posterior.x[15, 2, :, :] == df2.x[1015]
StanSample
https://github.com/StanJulia/StanSample.jl.git
[ "MIT" ]
7.10.1
fa6d92aa63d72f35adfbe99d79f60dd3f9604f0e
code
672
######### StanSample Bernoulli example ########### using AxisKeys using StanSample bernoulli_model = " 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); } "; bernoulli_data = Dict("N" => 10, "y" => [0, 1, 0, 1, 0, 0, 0, 0, 0, 1]) # Keep tmpdir across multiple runs to prevent re-compilation tmpdir = joinpath(@__DIR__, "tmp") sm = SampleModel("bernoulli_ka", bernoulli_model, tmpdir) rc = stan_sample(sm; data=bernoulli_data, num_threads=6, num_cpp_chains=6, num_chains=1, delta=0.85); if success(rc) ka = read_samples(sm, :keyedarray) ka |> display end
StanSample
https://github.com/StanJulia/StanSample.jl.git
[ "MIT" ]
7.10.1
fa6d92aa63d72f35adfbe99d79f60dd3f9604f0e
code
2500
using AxisKeys using DataFrames, CSV using StanSample using Statistics, Test df = CSV.read(joinpath(@__DIR__, "..", "..", "data", "chimpanzees.csv"), DataFrame); # Define the Stan language model stan10_4 = " data{ int N; int N_actors; int pulled_left[N]; int prosoc_left[N]; int condition[N]; int actor[N]; } parameters{ vector[N_actors] a; real bp; real bpC; } model{ vector[N] p; bpC ~ normal( 0 , 10 ); bp ~ normal( 0 , 10 ); a ~ normal( 0 , 10 ); for ( i in 1:504 ) { p[i] = a[actor[i]] + (bp + bpC * condition[i]) * prosoc_left[i]; p[i] = inv_logit(p[i]); } pulled_left ~ binomial( 1 , p ); } "; data = (N = size(df, 1), N_actors = length(unique(df.actor)), actor = df.actor, pulled_left = df.pulled_left, prosoc_left = df.prosoc_left, condition = df.condition); # Sample using cmdstan m10_4s = SampleModel("m10.4s", stan10_4) rc10_4s = stan_sample(m10_4s; data); # Result rethinking rethinking = " mean sd 5.5% 94.5% n_eff Rhat bp 0.84 0.26 0.43 1.26 2271 1 bpC -0.13 0.29 -0.59 0.34 2949 1 a[1] -0.74 0.27 -1.16 -0.31 3310 1 a[2] 10.88 5.20 4.57 20.73 1634 1 a[3] -1.05 0.28 -1.52 -0.59 4206 1 a[4] -1.05 0.28 -1.50 -0.60 4133 1 a[5] -0.75 0.27 -1.18 -0.32 4049 1 a[6] 0.22 0.27 -0.22 0.65 3877 1 a[7] 1.81 0.39 1.22 2.48 3807 1 "; # Update sections @testset "KeyedArray manipulations" begin if success(rc10_4s) ka = read_samples(m10_4s, :keyedarray) kb = ka(Symbol("a.1")) # Other manipulations @test Tables.istable(ka) == true # All draws of :a_1 @test size(vcat(kb...)) == (4000,) # All of parameters @testset "Basic HelpModel" begin kar = reshape(ka.data, 4000, 9); @test size(kar) == (4000, 9) # Axes ranges @test axes(ka) == (Base.OneTo(1000), Base.OneTo(4), Base.OneTo(9)) # Axes keys @test axiskeys(ka) == ( 1:1000, 1:4, [Symbol("a.1"), Symbol("a.2"), Symbol("a.3"), Symbol("a.4"), Symbol("a.5"), Symbol("a.6"), Symbol("a.7"), :bp, :bpC] ) # A single axis @test axiskeys(ka, :param) == vcat([Symbol("a.$i") for i in 1:7], :bp, :bpC) # Test combining vector param 'a' ma = matrix(ka, "a"); rma = reshape(ma.data, 4000, size(ma, 3)) @test mean(rma, dims=1) β‰ˆ [-0.7 10.9 -1 -1 -0.7 0.2 1.8] atol=0.7 end end
StanSample
https://github.com/StanJulia/StanSample.jl.git
[ "MIT" ]
7.10.1
fa6d92aa63d72f35adfbe99d79f60dd3f9604f0e
code
617
######### StanSample Bernoulli example ########### using AxisKeys using StanSample bernoulli_model = " data { int<lower=1> N; array[N] int<lower=0,upper=1> y; } parameters { real<lower=0,upper=1> theta; } model { theta ~ beta(1,1); y ~ bernoulli(theta); } "; bernoulli_data = Dict("N" => 10, "y" => [0, 1, 0, 1, 0, 0, 0, 0, 0, 1]) sm = SampleModel("bernoulli", bernoulli_model); rc = stan_sample(sm; data=bernoulli_data, save_metric=true, save_cmdstan_config=true, num_threads=6, num_cpp_chains=1, num_chains=6, seed=123); if success(rc) chns = read_samples(sm, :keyedarray) chns |> display end
StanSample
https://github.com/StanJulia/StanSample.jl.git
[ "MIT" ]
7.10.1
fa6d92aa63d72f35adfbe99d79f60dd3f9604f0e
code
576
######### StanSample Bernoulli example ########### using AxisKeys using StanSample bernoulli_model = " data { int<lower=1> N; array[N] int<lower=0,upper=1> y; } parameters { real<lower=0,upper=1> theta; } model { theta ~ beta(1,1); y ~ bernoulli(theta); } "; bernoulli_data = Dict("N" => 10, "y" => [0, 1, 0, 1, 0, 0, 0, 0, 0, 1]) sm = SampleModel("bernoulli", bernoulli_model) rc = stan_sample(sm; data=bernoulli_data, num_threads=6, num_cpp_chains=1, seed=123, num_chains=6, delta=0.85) if success(rc) chns = read_samples(sm) chns |> display end
StanSample
https://github.com/StanJulia/StanSample.jl.git
[ "MIT" ]
7.10.1
fa6d92aa63d72f35adfbe99d79f60dd3f9604f0e
code
561
######### StanSample Bernoulli example ########### using AxisKeys using StanSample bernoulli_model = " data { int<lower=1> N; array[N] int<lower=0,upper=1> y; } parameters { real<lower=0,upper=1> theta; } model { theta ~ beta(1,1); y ~ bernoulli(theta); } "; bernoulli_data = Dict("N" => 10, "y" => [0, 1, 0, 1, 0, 0, 0, 0, 0, 1]) sm = SampleModel("bernoulli", bernoulli_model); rc = stan_sample(sm; data=bernoulli_data, num_threads=6, num_cpp_chains=1, num_chains=6, seed=123); if success(rc) chns = read_samples(sm) chns = display end
StanSample
https://github.com/StanJulia/StanSample.jl.git
[ "MIT" ]
7.10.1
fa6d92aa63d72f35adfbe99d79f60dd3f9604f0e
code
637
using StanSample mwe_model = " parameters { real y; } model { y ~ normal(0.0, 1.0); } " sm = SampleModel("mwe_model", mwe_model) rc_1 = stan_sample(sm; num_chains=5, use_cpp_chains=true, show_logging=true) if success(rc_1) post = read_samples(sm, :dataframes) end display(available_chains(sm)) rc_2 = stan_sample(sm; num_chains=4, use_cpp_chains=true) if success(rc_2) post = read_samples(sm, :dataframes) end display(available_chains(sm)) rc_3 = stan_sample(sm; num_chains=4, use_cpp_chains=false, show_logging=true) if success(rc_3) post = read_samples(sm, :dataframes) end display(available_chains(sm))
StanSample
https://github.com/StanJulia/StanSample.jl.git
[ "MIT" ]
7.10.1
fa6d92aa63d72f35adfbe99d79f60dd3f9604f0e
code
863
######### Stan program example ########### using MCMCChains using StanSample #using StatsPlots bernoullimodel = " data { int<lower=1> N; array[N] int y; } parameters { real<lower=0,upper=1> theta; } model { theta ~ beta(1,1); y ~ bernoulli(theta); } "; observed_data = Dict("N" => 10, "y" => [0, 1, 0, 1, 0, 0, 0, 0, 0, 1]) # Default for tmpdir is to create a new tmpdir location # To prevent recompilation of a Stan progam, choose a fixed location, tmpdir=mktempdir() sm = SampleModel("bernoulli", bernoullimodel, tmpdir); rc = stan_sample(sm, data=observed_data); if success(rc) chns = read_samples(sm, :mcmcchains) # Describe the results chns |> display # Optionally, read samples as a a DataFrame df=read_samples(sm, :dataframe) first(df, 5) df = read_summary(sm) df[df.parameters .== :theta, [:mean, :ess]] end
StanSample
https://github.com/StanJulia/StanSample.jl.git
[ "MIT" ]
7.10.1
fa6d92aa63d72f35adfbe99d79f60dd3f9604f0e
code
1565
using StanSample, Test pure = " parameters { real r; real mu; real nu; matrix[2, 3] x; tuple(real, real) bar; tuple(real, tuple(real, real)) bar2; tuple(real, tuple(real, tuple(real, real))) bar3; } model { r ~ std_normal(); for (i in 1:2) { x[i,:] ~ std_normal(); } bar.1 ~ std_normal(); bar.2 ~ std_normal(); bar2.1 ~ std_normal(); bar2.2.1 ~ std_normal(); bar2.2.2 ~ std_normal(); bar3.1 ~ std_normal(); bar3.2.1 ~ std_normal(); bar3.2.2.1 ~ std_normal(); bar3.2.2.2 ~ std_normal(); mu ~ normal(0, 1); nu ~ normal(mu, 1); } generated quantities { complex z; complex_vector[2] zv; z = nu + nu * 2.0i; zv = to_complex([3 * nu, 5 * nu]', [nu * 4, nu * 6]'); } "; sm = SampleModel("pure_01", pure) rc = stan_sample(sm) df = read_samples(sm, :dataframe) ndf = read_samples(sm, :nesteddataframe) nnt = convert(NamedTuple, ndf) lr = 1:size(df, 1) @testset "Test arrays" begin for i in rand(lr, 5) @test ndf[i, :x] == reshape(Array(df[i, 4:9]), (2, 3)) @test nnt.x[i] == reshape(Array(df[i, 4:9]), (2, 3)) end end @testset "Complex values" begin for i in rand(lr, 5) @test ndf[i, :zv] == Array(df[i, ["zv.1", "zv.2"]]) @test nnt.zv[i] == Array(df[i, ["zv.1", "zv.2"]]) end end @testset "Tuples" begin for i in rand(lr, 5) @test ndf[i, :bar3] == (df[i, 15], (df[i, 16], (df[i, 17], df[i, 18]))) @test nnt.bar3[i] == (df[i, 15], (df[i, 16], (df[i, 17], df[i, 18]))) end end
StanSample
https://github.com/StanJulia/StanSample.jl.git
[ "MIT" ]
7.10.1
fa6d92aa63d72f35adfbe99d79f60dd3f9604f0e
code
3623
using StanSample, Test stan = " generated quantities { real base = normal_rng(0, 1); int base_i = to_int(normal_rng(10, 10)); tuple(real, real) pair = (base, base * 2); tuple(real, tuple(int, complex)) nested = (base * 3, (base_i, base * 4.0i)); array[2] tuple(real, real) arr_pair = {pair, (base * 5, base * 6)}; array[3] tuple(tuple(real, tuple(int, complex)), real) arr_very_nested = {(nested, base*7), ((base*8, (base_i*2, base*9.0i)), base * 10), (nested, base*11)}; array[3,2] tuple(real, real) arr_2d_pair = {{(base * 12, base * 13), (base * 14, base * 15)}, {(base * 16, base * 17), (base * 18, base * 19)}, {(base * 20, base * 21), (base * 22, base * 23)}}; real basep1 = base + 1, basep2 = base + 2; real basep3 = base + 3, basep4 = base + 4, basep5 = base + 5; array[2,3] tuple(array[2] tuple(real, vector[2]), matrix[4,5]) ultimate = { {( {(base, [base *2, base *3]'), (base *4, [base*5, base*6]')}, to_matrix(linspaced_vector(20, 7, 11), 4, 5) * base ), ( {(basep1, [basep1 *2, basep1 *3]'), (basep1 *4, [basep1*5, basep1*6]')}, to_matrix(linspaced_vector(20, 7, 11), 4, 5) * basep1 ), ( {(basep2, [basep2 *2, basep2 *3]'), (basep2 *4, [basep2*5, basep2*6]')}, to_matrix(linspaced_vector(20, 7, 11), 4, 5) * basep2 ) }, {( {(basep3, [basep3 *2, basep3 *3]'), (basep3 *4, [basep3*5, basep3*6]')}, to_matrix(linspaced_vector(20, 7, 11), 4, 5) * basep3 ), ( {(basep4, [basep4 *2, basep4 *3]'), (basep4 *4, [basep4*5, basep4*6]')}, to_matrix(linspaced_vector(20, 7, 11), 4, 5) * basep4 ), ( {(basep5, [basep5 *2, basep5 *3]'), (basep5 *4, [basep5*5, basep5*6]')}, to_matrix(linspaced_vector(20, 7, 11), 4, 5) * basep5 ) }}; } "; sm = SampleModel("brian_data", stan) rc = stan_sample(sm) df = read_samples(sm, :dataframe) ndf = read_samples(sm, :nesteddataframe) nnt = convert(NamedTuple, ndf) lr = 1:size(df, 1) pair_df = StanSample.select_nested_column(df, :pair) nested_df = StanSample.select_nested_column(df, :nested) arr_pair_df = StanSample.select_nested_column(df, :arr_pair) avn_df = StanSample.select_nested_column(df, :arr_very_nested) a2d_df = StanSample.select_nested_column(df, :arr_2d_pair) u_df = StanSample.select_nested_column(df, :ultimate) @testset "Pair" begin for i in rand(lr, 10) @test ndf.pair[i] == (pair_df[i, 1], pair_df[i, 2]) end end @testset "Nested" begin for i in rand(lr, 15) @test ndf.nested[i][1] == nested_df[i, 1] @test ndf.nested[i][2] == (nested_df[i, 2], nested_df[i, 3]) end end @testset "Arr_pair" begin for i in rand(lr, 15) @test ndf.arr_pair[i] == [(arr_pair_df[i, 1], arr_pair_df[i, 2]), (arr_pair_df[i, 3], arr_pair_df[i, 4])] end end @testset "Arr_very_nested" begin for i in rand(lr, 15) @test ndf.arr_very_nested[i][3][1][1] == avn_df[i, 1] @test ndf.arr_very_nested[i][3][1][2] == (avn_df[i, 2], avn_df[i, 3]) @test ndf.arr_very_nested[i][3][2] == avn_df[i, 12] end end @testset "Arr_2d_pair" begin for i in rand(lr, 15) @test ndf.arr_2d_pair[i][3, 2] == (a2d_df[i, 11], a2d_df[i, 12]) end end @testset "Ultimate" begin for i in rand(lr, 15) @test ndf.ultimate[i][2, 3][1][4] == Array(u_df[i, 135:136]) @test ndf.ultimate[i][2, 3][2] == reshape(Array(u_df[i, (end-19):end]), 4, 5) end end
StanSample
https://github.com/StanJulia/StanSample.jl.git
[ "MIT" ]
7.10.1
fa6d92aa63d72f35adfbe99d79f60dd3f9604f0e
code
584
######### StanSample Bernoulli example ########### using StanSample, DataFrames, Test ProjDir = @__DIR__ bernoulli_model = " data { int<lower=1> N; array[N] int y; } 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]) isdir(tmpdir) && rm(tmpdir; recursive=true) sm = SampleModel("bernoulli", bernoulli_model); rc1 = stan_sample(sm; data, sig_figs=18); if success(rc1) st = read_samples(sm) #display(DataFrame(st)) end @test size(DataFrame(st), 1) == 4000
StanSample
https://github.com/StanJulia/StanSample.jl.git
[ "MIT" ]
7.10.1
fa6d92aa63d72f35adfbe99d79f60dd3f9604f0e
code
608
using StanSample, DataFrames, JSON, InferenceObjects, NamedTupleTools stan = " parameters { real r; matrix[2, 2] x; tuple(real, real) bar; } model { r ~ std_normal(); for (i in 1:2) { x[i,:] ~ std_normal(); } bar.1 ~ std_normal(); bar.2 ~ std_normal(); } "; tmpdir = joinpath(@__DIR__, "tmp") sm = SampleModel("tuple_model", stan, tmpdir) rc = stan_sample(sm) chns, names = read_samples(sm, :array; return_parameters=true) display(names) println() display(size(chns)) println() ex = StanSample.extract(chns, names; permute_dims=true) println(ex[:bar][1:10])
StanSample
https://github.com/StanJulia/StanSample.jl.git
[ "MIT" ]
7.10.1
fa6d92aa63d72f35adfbe99d79f60dd3f9604f0e
code
682
using StanSample, DataFrames, JSON, InferenceObjects stan = " parameters { real r; matrix[2, 2] x; tuple(real, real) bar; } model { r ~ std_normal(); for (i in 1:2) { x[i,:] ~ std_normal(); } bar.1 ~ std_normal(); bar.2 ~ std_normal(); } "; tmpdir = joinpath(@__DIR__, "tmp") sm = SampleModel("tuple_model", stan, tmpdir) rc = stan_sample(sm) idata = inferencedata(sm) display(idata) println() display(idata.posterior) println() display(idata.posterior.x) df2 = read_samples(sm, :nesteddataframe) display(df2) chns, names = read_samples(sm, :array; return_parameters=true) display(names) println() display(size(chns)) println()
StanSample
https://github.com/StanJulia/StanSample.jl.git
[ "MIT" ]
7.10.1
fa6d92aa63d72f35adfbe99d79f60dd3f9604f0e
code
1468
using StanSample, DataFrames, JSON, InferenceObjects, Test stan = " parameters { real r; matrix[2, 3] x; tuple(real, real) bar; tuple(real, tuple(real, real)) bar2; tuple(real, tuple(real, tuple(real, real))) bar3; } model { r ~ std_normal(); for (i in 1:2) { x[i,:] ~ std_normal(); } bar.1 ~ std_normal(); bar.2 ~ std_normal(); bar2.1 ~ std_normal(); bar2.2.1 ~ std_normal(); bar2.2.2 ~ std_normal(); bar3.1 ~ std_normal(); bar3.2.1 ~ std_normal(); bar3.2.2.1 ~ std_normal(); bar3.2.2.2 ~ std_normal(); } "; tmpdir = joinpath(@__DIR__, "tmp") sm = SampleModel("tuple_model_2", stan, tmpdir) rc = stan_sample(sm) chns, col_names = read_samples(sm, :array; return_parameters=true) display(col_names) println() display(size(chns)) println() ex = StanSample.extract(chns, col_names; permute_dims=true) println(size(ex[:bar])) println() println(ex[:bar][1:5]) println() println(ex[:bar3][1:5]) println() println(size(ex[:x])) println() display(ex[:x][1, 1, :, :]) println() df = read_samples(sm, :dataframe) df |> display idata = inferencedata(sm) display(idata) println() display(idata.posterior) println() display(idata.posterior.x) df2 = read_samples(sm, :nesteddataframe) #display(df2) chns, col_names = read_samples(sm, :array; return_parameters=true) display(col_names) println() display(size(chns)) println() @test idata.posterior.bar3[1, 1, 1, :] == chns[1, 13:16, 1]
StanSample
https://github.com/StanJulia/StanSample.jl.git
[ "MIT" ]
7.10.1
fa6d92aa63d72f35adfbe99d79f60dd3f9604f0e
docs
2404
# Installing cmdstan. ## Clone the cmdstan.git repo. Big! Takes a while, by far the longest step. ``` git clone https://github.com/stan-dev/cmdstan.git --recursive cmdstan # or e.g. # git clone -b v2.29.1 https://github.com/stan-dev/cmdstan.git --recursive cmdstan ``` If you plan to use BridgeStan, I suggest to also clone BridgeStan at this time: ``` git clone --recurse-submodules https://github.com/roualdes/bridgestan.git ``` Both cmdstan and bridgestan a fairly big! If bridgestan is installed in the same directory as cmdstan, StanSample will automatically set up some support. ## Customize cmdstan. ``` cd cmdstan # Create ./make/local from ./make/local.example or copy from a previous install # ls -lia ./make/local #ls: ./make/local: No such file or directory # If you want to customize the ./make/local.example file # ls -lia ./make/local.example # cp -R ./make/local.example ./make/local # ls -lia ./make/local # Now un-comment the CXX=clang++ and STAN_THREADS=true lines in ./make/local. # Or do: touch ./make/local echo "CXX=clang++\nSTAN_THREADS=true" > ./make/local ``` ## Build cmdstan. ``` # If a previous install has been compiled in this directory: # make clean-all # or # make -B -j9 build make -j9 build ``` ## Test cmdstan was built correctly. ``` make examples/bernoulli/bernoulli ./examples/bernoulli/bernoulli num_threads=6 sample num_chains=4 data file=examples/bernoulli/bernoulli.data.json bin/stansummary output_*.csv ``` ## For Stan.jl etc. to find cmdstan, export CMDSTAN ``` export CMDSTAN=`pwd` # Use value of `pwd` here ``` ## Below an example of the `make/local` file mentioned above with the CXX and STAN_THREADS lines enabled. ``` # To use this template, make a copy from make/local.example to make/local # and uncomment options as needed. # Be sure to run `make clean-all` before compiling a model to make sure # everything gets rebuilt. # Change the C++ compiler if needed CXX=clang++ # Only needed on macOS if clang++ is preferred. # Enable threading STAN_THREADS=true # Enable the MPI backend (requires also setting (replace gcc with clang on Mac) # STAN_MPI=true # CXX=mpicxx # TBB_CXX_TYPE=gcc ``` If you have enabled BridgeStan you can test this with: ``` cd bridgestan # Also install above `make/local` in the bridgestan directory cp ../cmdstand/make.local . make test_models/multi/multi_model.so ```
StanSample
https://github.com/StanJulia/StanSample.jl.git
[ "MIT" ]
7.10.1
fa6d92aa63d72f35adfbe99d79f60dd3f9604f0e
docs
14307
# StanSample v7.10 | **Project Status** | **Build Status** | |:---------------------------:|:-----------------:| |![][project-status-img] | ![][CI-build] | [docs-dev-img]: https://img.shields.io/badge/docs-dev-blue.svg [docs-dev-url]: https://stanjulia.github.io/StanSample.jl/latest [docs-stable-img]: https://img.shields.io/badge/docs-stable-blue.svg [docs-stable-url]: https://stanjulia.github.io/StanSample.jl/stable [CI-build]: https://github.com/stanjulia/StanSample.jl/workflows/CI/badge.svg?branch=master [issues-url]: https://github.com/stanjulia/StanSample.jl/issues [project-status-img]: https://img.shields.io/badge/lifecycle-active-green.svg ## Note After many years I have decided to step away from my work with Stan and Julia. My plan is to be around until the end of 2024 for support if someone decides to step in and take over further development and maintenance work. At the end of 2024 I'll archive the different packages and projects included in the Github organisations StanJulia, StatisticalRethingJulia and RegressionAndOtherStoriesJulia if no one is interested (and time-wise able!) to take on this work. I have thoroughly enjoyed working on both Julia and Stan and see both projects mature during the last 15 or so years. And I will always be grateful for the many folks who have helped me on numerous occasions. Both the Julia and the Stan community are awesome to work with! Thanks a lot! ## Purpose StanSample.jl wraps `cmdstan`'s `sample` method to generate draws from a Stan Language Program. It is the primary workhorse in the StanJulia ecosystem. StanSample.jl v7.8.0 supports the new save_metric and save_cmdstan_config command keywords. StanSample.jl v7.6 supports recent enhancements to the Stan Language visible in the output files (.csv files). It supports array, tuples and complex values in `output_format=:nesteddataframe`. StanSample.jl v7 supports InferenceObjects.jl as a package extension. Use `inferencedata(model)` to create an InferenceData object. See also note 1 below. An example Pluto notebook can be found [here](https://github.com/StanJulia/StanExampleNotebooks.jl/blob/main/notebooks/DimensionalData/dimensionaldata.jl) ## Notes 1. Use of both InferenceObjects.jl and the `read_samples()` output_format options :dimarray and :dimarrays (based on DimensionalData.jl) creates a conflict. Hence these output_format options are no longer included. See the example Pluto notebook `test_dimarray.jl`in [StanExampleNotebooks.jl](https://github.com/StanJulia/StanExampleNotebooks.jl) for an example how to still use that option. At some point in time InferenceObjects.jl might provide an alternative way to create a stacked DataFrame and/or DimensionalData object. 2. I've removed BridgeStan.jl from StanSample.jl. Two example Pluto notebooks, `test_bridgestan.jl` and `bridgestan_stansample_example.jl` in [StanExampleNotebooks.jl](https://github.com/StanJulia/StanExampleNotebooks.jl/tree/main/notebooks/BridgeStan) demonstrate how BridgeStan can be used. ## Prerequisites You need a working installation of [Stan's cmdstan](https://mc-stan.org/users/interfaces/cmdstan.html), the path of which you should specify in either `CMDSTAN` or `JULIA_CMDSTAN_HOME`, e.g. in your `~/.julia/config/startup.jl` include a line like: ```Julia # CmdStan setup ENV["CMDSTAN"] = expanduser("~/.../cmdstan/") # replace with your path ``` Or you can define and export CMDSTAN in your .profile, .bashrc, .zshrc, etc. For more details see [this file](https://github.com/StanJulia/StanSample.jl/blob/master/INSTALLING_CMDSTAN.md). See the `example/bernoulli.jl` for a basic example. Many more examples and test scripts are available in this package and also in Stan.jl. ## Multi-threading and multi-chaining behavior. From StanSample.jl v6 onwards 2 mechanisms for in paralel drawing samples for chains are supported, i.e. on C++ level (using threads) and on Julia level (by spawning a Julia process for each chain). The `use_cpp_chains` keyword argument in the call to `stan_sample()` determines if chains are executed on C++ level or on Julia level. By default, `use_cpp_chains = false`. From cmdstan-2.28.0 onwards it is possible to use C++ threads to run multiple chains by setting `use_cpp_chains=true` in the call to `stan_sample()`: ``` rc = stan_sample(_your_model_; use_cpp_chains=true, [ data | init | ...]) ``` To enable multithreading in `cmdstan` specify this before the build process of `cmdstan`, i.e. before running `make -j9 build`. I typically create a `path_to_my_cmdstan_directory/make/local` file containing `STAN_THREADS=true`. You can see an example in `.github/CI.yml` script. By default in either case `num_chains=4`. See `??stan_sample` for all keyword arguments. Internally, `num_chains` will be copied to either `num_cpp_chains` or `num_julia_chains`. Currently I do not suggest to use both C++ and Julia level chains. Based on the value of `use_cpp_chains` (true or false) the `stan_sample()` method will set either `num_cpp_chains=num_chains; num_julia_chains=1` or `num_julia_chains=num_chains;num_cpp_chain=1`. This default behavior can be disabled by setting the postional `check_num_chains` argument in the call to `stan_sample()` to `false`. Threads on C++ level can be used in multiple ways, e.g. to run separate chains and to speed up certain operations. By default StanSample.jl's SampleModel sets the C++ num_threads to 4. See the (updated for cmdstan-2.29.0) RedCardsStudy example [graphs](https://github.com/StanJulia/Stan.jl/tree/master/Examples/RedCardsStudy/graphs) in Stan.jl and [here](https://discourse.mc-stan.org/t/stan-num-threads-and-num-threads/25780/5?u=rob_j_goedman) for more details, in particular with respect to just enabling threads and including TBB or not on Intel, and also some indications of the performance on an Apple's M1/ARM processor running native (not using Rosetta and without Intel's TBB). In some cases I have seen performance advantages using both Julia threads and C++ threads but too many combined threads certainly doesn't help. Note that if you only want 1000 draws (using 1000 warmup samples for tuning), multiple chains (C++ or Julia) do not help. ## Installation This package is registered. It can be installed with: ```Julia pkg> add StanSample.jl ``` ## Usage Use this package like this: ```Julia using StanSample ``` See the docstrings (in particular `??StanSample`) for more help. ## Versions ### Version 7.9-7.10 1. Fix by zeyus for cmdstan options ### Versions 7.5-7.8 1. Switching to cmdstan v2.35.0 2. Support for new command keywords settings `save_metric1` and `save_cmdstan_config` 3. Support for Stan .csv file extensions in output format :nesteddataframe. ### Version 7.1-4.0 1. Switch to cmdstan.2.32.0 for testing 2. Removed BridgeStan extension ### Version 7.0.1 1. Updated column types for sample_stats (NamedTuples and DataFrames) ### Version 7.0.0 1. InferenceObjects.jl support. 2. Conditional support for BridgeStan. 3. Reduced support for :dimarray and :dimarrays option in `read_samples()`. ### Version 6.13.8 1. Support for InferenceObjects v0.3. 2. Many `tmp` directories created during testing have been removed from the repo. 3. Support for BridgeStan v1.0 has been dropped. ### Version 6.13.7 1. Moved InferenceObjects behind Requires 2. Method `inferencedata()` is using `inferencedata3()` currently ### Version 6.13.6 1. Added inferencedata3() 2. Added option to enable logging in the terminal (thanks to @FelixNoessler) ### Version 6.13.0 - 6.13.5 1. Many more (minor and a bit more) updates to `inferencedata()` 2. Updates to BridgeStan (more to be expected soon) 3. Fix for chain numbering when using CPP threads (thanks to @apinter) 4. Switched to use cmdstan-2.32.0 for testing 5. Updates to Examples_Notebooks (in particular now using both `inferencedata()` and `inferencedata2()`) 6. Dropped support for read_samples(m, :dimarray) as this conflicted with InferenceData ### Version 6.12.0 1. Added experimental version of inferencedata(). See example in ./test/test_inferencedata.jl 2. Added InferenceObjects.jl as a dependency 3. Dropped MonteCarloMeasurements.jl as a dependency (still supported using Requires) 4. Dropped MCMCChains.jl as a dependency (still supported using Requires) 5. Dropped AxisKeys.jl as a dependency ### Version 6.11.5 1. Add sig_figs field to SampleModel (thanks to Andrew Radcliffe). This change enables the user to control the number of significant digits which are preserved in the output. sig_figs=6 is the default cmdstan option, which is what StanSample has been defaulting to. Typically, a user should prefer to generate outputs with sig_figs=18 so that the f64's are uniquely identified. It might be wise to make such a recommendation in the documentation, but I suppose that casual users would complain about the correspondingly increased .csv sizes (and subsequent read times). ### Version 6.11.4 1. Dropped conversion to Symbols in `read_csv_files()` if internals are requested (`include_internals=true`) 2. Added InferenceObjects as a dependency. This is part of the work with Set Haxen to enable working with InferenceData objects in a future release (probably v6.12). ### Version 6.11.1 1. Fix bridge_path in SampleModel. ### Version 6.11.0 1. Support for BridgeStan as a dependency of StanSample.jl (Thanks to Seth Axen) ### Version 6.10.0 1. Support for the updated version of BridgeStan. ### Version 6.9.3 1. A much better test has been added for multidimensional input arrays thanks to Andy Pohl (`test/test_JSON`). ### Version 6.9.2 1. More general handling of Array input data to cmdstan if the Array has more than 2 dimensions. ### Version 6.9.2 1. Experimental support for [BridgeStan](https://gitlab.com/roualdes/bridgestan). ### Version 6.9.0-1 1. For chains read in as either a :dataframe or a :nesteddataframe the function matrix(...) has been replaced by array(...). Depending on the the eltype of the requested column, array will return a Vector, a Matrix or an Array with 3 dimensions. 2. The function describe() has been added which returns a df with results based on Stan's stansummary executable. 3. A new method has been added to DataFrames.getindex to extract cells in stansummary DataFrame, e.g. ss1_1[:a, :ess]. ### Version 6.8.0 (nesteddataframe is experimental!) 1. Added :nesteddataframe option to read_samples(). Maybe useful if cmdstan returns vectors or matrices. 2. Extended the matrix() function to matrix(df, Symbol). ### Version 6.7.0 1. Drops support for creating R files. 2. Requires StanBase 4.7.0 ### Version 6.4.0 1. Introduced `available_chains("your model")` 2. Updated Redcardsstudy results for cmdstan-2.29.0 ### Version 6.3.0-1 1. Switch to cmdstan-2.29.0 testing. ### Version 6.2.1 1. Better handling of .csv chain retrieval in read_csv_files. ### Version 6.2.0 1. Revert back to by default use Julia level chains. ### Version 6.1.1-2 1. Documentation improvements. ### version 6.1.0 1. Modified (simplified?) use of `num_chains` to define either number of chains on C++ or Julia level based on `use_cpp_chains` keyword argument to `stan_sample()`. ### Version 6.0.0 1. Switch to C++ threads by default. 2. Use JSON3.jl for data.json and init.json as replacement for data.r and init.r files. 3. The function `read_generated_quantities()` has been dropped. 4. The function `stan_generate_quantites()` now returns a DataFrame. ### Version 5.4 - 5.6 1. Full usage of num_threads and num_cpp_threads ### Version 5.3.1 & 5.3.2 1. Drop the use of the STAN_NUM_THREADS environment variable in favor of the keyword num_threads in stan_sample(). Default value is 4. ### Version 5.3 1. Enable local multithreading. Local as cmdstan needs to be built with STAN_THREADS=true (see make/local examples). ### Version 5.2 1. Switch use CMDSTAN environment variable ### version 5.1 1. Testing with conda based install (Windows, but also other platforms) ### Versions 5.0 1. Docs updates. 2. Fix for DimensionalData v0.19.1 (@dim no longer exported) 3. Added DataFrame parameter blocking option. ### Version 5.0.0 1. Keyword based SampleModel and stan_sample(). 2. Dropped dependency on StanBase. 3. Needs cmdstan 2.28.1 (for num_threads). 4. `tmpdir` now positional argument in SampleZModel. 5. Refactor src dir (add `common` subdir). 6. stan_sample() is now an alias for stan_run(). ### Version 4.3.0 1. Added keywords seed and n_chains to stan_sample(). 2. SampleModel no longer uses shared fields (prep work for v5). ### version 4.2.0 1. Minor updates 2. Added test for MCMCChains ### Version 4.1.0 1. The addition of :dimarray and :dimarrays output_format (see ?read_samples). 2. No longer re-exporting many previously exported packages. 3. The use of Requires.jl to enable most output_format options. 4. All example scripts have been moved to Stan.jl (because of item 3). ### Version 4.0.0 (**BREAKING RELEASE!**) 1. Make KeyedArray chains the read_samples() default output. 2. Drop the output_format kwarg, e.g.: `read_samples(model, :dataframe)`. 3. Default output format is KeyedArray chains, i.e.: `chns = read_samples(model)`. ### Version 3.1.0 1. Introduction of Tables.jl interface as an output_format option (`:table`). 2. Overloading Tables.matrix to group a variable in Stan's output file as a matrix. 3. Re-used code in read_csv_files() for generated_quantities. 4. The read_samples() method now consistently applies keyword arguments start and chains. 5. The table for each chain output_format is :tables. 6. ### Version 3.0.1 1. Thanks to the help of John Wright (@jwright11) all StanJulia packages have been tested on Windows. Most functionality work, with one exception. Stansummary.exe fails on Windows if warmup samples have been saved. ### Version 3.0.0 1. By default read_samples(model) will return a NamedTuple with all chains appended. 2. `output_format=:namedtuples` will provide a NamedTuple with separate chains. ### Version 2.2.5 1. Thanks to @yiyuezhuo, a function `extract` has been added to simplify grouping variables into a NamedTuple. 2. read_sample() output_format argument has been extended with an option to request conversion to a NamedTuple. ### Version 2.2.4 1. Dropped the use of pmap in StanBase
StanSample
https://github.com/StanJulia/StanSample.jl.git
[ "MIT" ]
0.2.2
dbcb0d532975547a973fc334c76338e397850709
code
643
using VoronoiGraph using Documenter DocMeta.setdocmeta!(VoronoiGraph, :DocTestSetup, :(using VoronoiGraph); recursive=true) makedocs(; modules=[VoronoiGraph], authors="Sikorski <[email protected]> and contributors", repo="https://github.com/axsk/VoronoiGraph.jl/blob/{commit}{path}#{line}", sitename="VoronoiGraph.jl", format=Documenter.HTML(; prettyurls=get(ENV, "CI", "false") == "true", canonical="https://axsk.github.io/VoronoiGraph.jl", assets=String[], ), pages=[ "Home" => "index.md", ], ) deploydocs(; repo="github.com/axsk/VoronoiGraph.jl", devbranch="main", )
VoronoiGraph
https://github.com/axsk/VoronoiGraph.jl.git
[ "MIT" ]
0.2.2
dbcb0d532975547a973fc334c76338e397850709
code
1069
using BenchmarkTools using VoronoiGraph using Random function bsuite( dims = 2:5, ns = [100, 1000]) suite = BenchmarkGroup() for d in dims suite[d] = BenchmarkGroup() for n in ns Random.seed!(1) x = rand(d,n) suite[d][n] = @benchmarkable voronoi($x) seconds=1 end end return suite end const parameterfile = "../cache/params.json" function autotune!(suite, load=true) if load && isfile(parameterfile) try println("Loading benchmark parameters") loadparams!(suite, BenchmarkTools.load(parameterfile)[1], :evals, :samples); return catch end end println("Tuning benchmark parameters") tune!(suite) BenchmarkTools.save("params.json", params(suite)) end function autorun() s = bsuite() autotune!(s) println("Running benchmark") results = run(s, verbose = true) println("Saving benchmark results") BenchmarkTools.save("output.json", median(results)) return s, results end
VoronoiGraph
https://github.com/axsk/VoronoiGraph.jl.git
[ "MIT" ]
0.2.2
dbcb0d532975547a973fc334c76338e397850709
code
425
module VoronoiGraph using LinearAlgebra using NearestNeighbors using Polyhedra using ProgressMeter using SparseArrays using StaticArrays using RecipesBase include("voronoi.jl") include("raycast.jl") include("volume.jl") include("plot.jl") include("montecarlo.jl") export voronoi, voronoi_random export volumes export mc_volumes, mc_integrate for i in 1:10 precompile(voronoi, (Vector{SVector{i, Float64}},)) end end
VoronoiGraph
https://github.com/axsk/VoronoiGraph.jl.git
[ "MIT" ]
0.2.2
dbcb0d532975547a973fc334c76338e397850709
code
4643
using SpecialFunctions """ mc_volume(i, xs, nmc, searcher) Estimate the area and volume of the `i`-th Voronoi cell from the Voronoi Diagram generated by `xs` by a Monte Carlo estimate from random rays """ function mc_volume(i, xs, nmc=1000, searcher = Raycast(xs)) y, Ξ΄y, V, A = mc_integrate(x->1, i, xs, nmc, 0, searcher) A, V end """ mc_volumes(xs::Points, nmc=1000) Estimate the areas and volumes of the Voronoi Cells generated by `xs` using `nmc` Monte Carlo samples. # Returns - `SparseMatrix`: the areas of the common boundaries of two cells - `Vector`: the volumes of each cell """ function mc_volumes(xs::Points, nmc=1000, symmetrized=true) V = zeros(length(xs)) A = spzeros(length(xs), length(xs)) searcher = Raycast(xs) for i in 1:length(xs) a, v = mc_volume(i, xs, nmc, searcher) V[i] = v A[:, i] = a end #A = (A + A') / 2 if symmetrized A = (A + A') / 2 end A, V end """ mc_volumes(sig::Vertices, xs::Points, nmc=1000) In the case when the simplicial complex is already known this information can be used to speed up the Monte-Carlo sampling by restricting the search space """ function mc_volumes(Οƒ::Vertices, xs::Points, nmc=1000) V = zeros(length(xs)) A = spzeros(length(xs), length(xs)) searcher = Raycast(xs) neigh = neighbors(Οƒ) for i in 1:length(xs) ix = [i; neigh[i]] a, v = mc_volume(1, xs[ix], nmc, RaycastBruteforce()) V[i] = v A[ix, i] = a end #A = (A + A') / 2 A, V end # TODO: this belongs in its own file, something like topology.jl or so """ neighbors(sig::Vertices) --> Dict{Int, Vector{Int}} Compute the neighbors of all generators. """ neighbors(Οƒ::Vertices) = neighbors(keys(Οƒ)) function neighbors(Οƒ) d = Dict{Int, Vector{Int}}() for s in Οƒ for i in s v = get!(d, i, Vector{Int}()) append!(v, s) end end for i in keys(d) unique!(d[i]) filter!(x->x != i, d[i]) end return d end """ mc_integrate(f::Function, i::Int, xs::Points, nmc=1000, nmc2=1000, searcher=Raycast(xs)) Integrate function `f` over cell `i` and its boundary using `nmc` rays per cell and `nmc2` points per ray for the volume integral. # Returns: - `Vf::Real`: the volume integral of `f` - `Af::SparseVector`: Af[j] is the surface integral of `f` over the intersection between cells i and j. - `V::Real`: the volume of cell `i` - `A::SparseVector`: A[j] is the surface area of the intersection between cells i and j. """ function mc_integrate(f::Function, i::Int, xs::Vector, nmc=1000, nmc2=1000, searcher = Raycast(xs)) x = xs[i] d = length(x) # volume/area computations are basically for free, leaving them commented for now V = 0. A = spzeros(length(xs)) y = 0. Ξ΄y = spzeros(length(xs)) for _ in 1:nmc u = normalize(randn(d)) (j, t) = raycast([i], x, u, xs, searcher) V += t^d if t < Inf for _ in 1:nmc2 r = t * rand() xβ€² = x + u * r y += f(xβ€²) * r^(d-1) * t end j = j[1] == i ? j[2] : j[1] # choose the other generator (the one we didnt start with) normal = normalize(xs[j] - xs[i]) dA = t ^ (d-1) / abs(dot(normal, u)) A[j] += dA Ξ΄y[j] += dA * f(x + t*u) end end c_vol = pi^(d/2) / gamma(d/2 + 1) c_area = d * c_vol V *= c_vol / nmc A *= c_area / nmc y *= c_area / nmc / nmc2 Ξ΄y *= c_area / nmc y, Ξ΄y, V, A end function mc_integrate(f, Οƒ::Vertices, xs::Points, nmc, nmc2) return mc_integrate_i((x,i)->f(x), Οƒ, xs, nmc, nmc2) end # MC integration using f(x, i) function which is also passed the index of the cell function mc_integrate_i(f, Οƒ::Vertices, xs::Points, nmc, nmc2) n = length(xs) ys = zeros(n) βˆ‚ys = zeros(n) neigh = neighbors(Οƒ) for i in 1:n ix = [i; neigh[i]] y, βˆ‚y, V, A = mc_integrate(x->f(x, i), 1, xs[ix], nmc, nmc2, RaycastBruteforce()) ys[i] = y βˆ‚ys[i] = sum(βˆ‚y) end return ys, βˆ‚ys end function mc_integrate(f, xs::Vector, nmc, nmc2=1, symmetrized=true) V = zeros(length(xs)) Y = zeros(length(xs)) A = spzeros(length(xs), length(xs)) dY = spzeros(length(xs), length(xs)) for i in 1:length(xs) y, dy, v, a = mc_integrate(f, i, xs, nmc, nmc2) Y[i] = y dY[i,:] = dy V[i] = v A[i,:] = a end if symmetrized A = (A + A') / 2 dY = (A + A') / 2 end Y, dY, V, A end
VoronoiGraph
https://github.com/axsk/VoronoiGraph.jl.git
[ "MIT" ]
0.2.2
dbcb0d532975547a973fc334c76338e397850709
code
1061
@userplot VoronoiPlot @recipe function f(p::VoronoiPlot; fill_z=nothing) v, P = p.args fs = faces(v, P) xs = reduce(hcat, P) lims = extrema(xs, dims=2) label --> "" xlims --> lims[1] .* 1.1 ylims --> lims[2] .* 1.1 for (i, f) in enumerate(fs) @series begin if !isnothing(fill_z) fill_z := fill_z[i] end if !hasallrays(f) f else [] end end end @series begin seriestype := :scatter xs[1,:], xs[2,:] end end function faces(vertices, P::AbstractVector) dim = length(P[1]) conns = Dict{Int, Set{Int}}() for (sig, _) in vertices for x in sig v = get!(conns, x, Set{Int}()) union!(v, sig) end end faces = [face(i, conns[i], P) for i in 1:length(P)] #conns end function face(i, js, P) halfspaces = [] A = P[i] for j in js i == j && continue B = P[j] u = B-A b = dot(u, (A+B)/2) hf = HalfSpace(u, b) push!(halfspaces, hf) end halfspaces = [h for h in halfspaces] return polyhedron(hrep(halfspaces)) end
VoronoiGraph
https://github.com/axsk/VoronoiGraph.jl.git
[ "MIT" ]
0.2.2
dbcb0d532975547a973fc334c76338e397850709
code
5756
## Implementations of different raycasting search algorithms # default raycast Raycast(xs) = RaycastIncircleSkip(KDTree(xs)) struct RaycastBruteforce end """ shooting a ray in the given direction, find the next connecting point. This is the bruteforce variant, using a linear search to find the closest point """ function raycast(sig::Sigma, r, u, xs, searcher::RaycastBruteforce) (tau, ts) = [0; sig], Inf x0 = xs[sig[1]] c = maximum(dot(xs[g], u) for g in sig) skip(i) = (dot(xs[i], u) <= c) || i ∈ sig for i in 1:length(xs) skip(i) && continue x = xs[i] t = (sum(abs2, r .- x) - sum(abs2, r .- x0)) / (2 * u' * (x-x0)) if 0 < t < ts (tau, ts) = vcat(sig, [i]), t end end return sort(tau), ts end struct RaycastBisection{T} tree::T tmax eps::Float64 end """ shooting a ray in the given direction, find the next connecting point. This variant (by Poliaski, Pokorny) uses a binary search """ function raycast(sig::Sigma, r::Point, u::Point, xs::Points, searcher::RaycastBisection) tau, tl, tr = [], 0, searcher.tmax x0 = xs[sig[1]] while tr-tl > searcher.eps tm = (tl+tr)/2 i, _ = nn(searcher.tree, r+tm*u) x = xs[i] if i in sig tl = tm else tr = (sum(abs2, r .- x) - sum(abs2, r .- x0)) / (2 * u' * (x-x0)) tau = vcat(sig, [i]) # early stopping idxs, _ = knn(searcher.tree, r+tr*u, length(sig)+1, true) length(intersect(idxs, [sig; i])) == length(sig)+1 && break end end if tau == [] tau = [0; sig] tr = Inf end return sort(tau), tr end struct RaycastIncircle{T} tree::T tmax::Float64 end """ Shooting a ray in the given direction, find the next connecting point. This variant uses an iterative NN search """ function raycast(sig::Sigma, r::Point, u::Point, xs::Points, searcher::RaycastIncircle) i = 0 t = 1 x0 = xs[sig[1]] local d, n # find a t large enough to include a non-boundary (sig) point while t < searcher.tmax n, d = nn(searcher.tree, r+t*u) if d==Inf warn("d==Inf in raycast expansion, this should never happen") return [0; sig], Inf end if n in sig t = t * 2 else i = n break end end if i == 0 return [0; sig], Inf end # sucessively reduce incircles unless nothing new is found while true x = xs[i] t = (sum(abs2, r - x) - sum(abs2, r - x0)) / (2 * u' * (x-x0)) j, _ = nn(searcher.tree, r+t*u) if j in [sig; i] break else i = j end end tau = sort([i; sig]) return tau, t end struct RaycastIncircleSkip{T} tree::T end """ raycast(sig::Sigma, r::Point, u::Point, xs::Points, seacher::RaycastIncircleSkip) Return `(tau, t)` where `tau = [sig..., i]` are the new generators and `t` the distance to walk from `r` to find the new representative. `::RaycastIncircleSkip` uses the nearest-neighbours skip predicate to find the initial candidate on the right half plane. Resumes with successive incircle searches until convergence (just as in ``::RaycastIncircle`). Q: Why is this routine split in these two parts instead of only iterating on the right half plane? A: The first might find no generator in case of a ray. This is handled explicitly here. """ function raycast(sig::Sigma, r::Point, u::Point, xs::Points, searcher::RaycastIncircleSkip) x0 = xs[sig[1]] # only consider points on the right side of the hyperplane c = maximum(dot(xs[g], u) for g in sig) skip(i) = (dot(xs[i], u) <= c) || i ∈ sig # shift candidate onto the plane spanned by the generators candidate = r + u * (u' * (x0-r)) # compute heuristic t assuming the resulting delauney simplex was regular # this reduces number of extra searches by about 10% if length(sig) > 1 n = length(sig) radius = norm(candidate-x0) #radius = sum(norm(candidate-xs[s]) for s in sig) / n # better but slower t = radius / sqrt((n+1)*(n-1)) candidate += t * u end is, _ = knn(searcher.tree, candidate, 1, false, skip) (length(is) == 0) && return [0; sig], Inf # no point was found i = is[1] # sucessively reduce incircles unless nothing new is found while true x = xs[i] t = (sum(abs2, r - x) - sum(abs2, r - x0)) / (2 * u' * (x-x0)) candidate = r + t*u j, d = nn(searcher.tree, candidate) (j in sig || j == i) && break # converged to the smallest circle dold = sqrt(sum(abs2, x0-candidate)) isapprox(d, dold) && @warn "degenerate vertex at $sig + [$i] ($d $dold)" i = j end tau = sort([i; sig]) return tau, t end struct RaycastCompare tree::KDTree tmax eps timings end RaycastCompare(xs) = RaycastCompare(KDTree(xs), 1_000., 1e-8, zeros(4)) function raycast(sig::Sigma, r::Point, u::Point, xs::Points, searcher::RaycastCompare) s1 = RaycastBruteforce() s2 = RaycastBisection(searcher.tree, searcher.tmax, searcher.eps) s3 = RaycastIncircle(searcher.tree, searcher.tmax) s4 = RaycastIncircleSkip(searcher.tree) t1 = @elapsed r1 = raycast(sig, r, u, xs, s1) t2 = @elapsed r2 = raycast(sig, r, u, xs, s2) t3 = @elapsed r3 = raycast(sig, r, u, xs, s3) t4 = @elapsed r4 = raycast(sig, r, u, xs, s4) searcher.timings .+= [t1, t2, t3, t4] if !(r1[1]==r2[1]==r3[1]==r4[1]) && r3[2] < searcher.tmax @warn "raycast algorithms return different results" r1 r2 r3 r4 tuple(r...) end return r4 end
VoronoiGraph
https://github.com/axsk/VoronoiGraph.jl.git
[ "MIT" ]
0.2.2
dbcb0d532975547a973fc334c76338e397850709
code
3677
""" given two generators `g1`, `g2`, `vertices` of their common boundary (in generator representation) and the list of all generators, compute the boundary volume. It works by constructing a polytope from halfspaces between the generators of the boundary vertices. We use an affine transformation to get rid of the dimension in direction g1->g2 """ function boundary_area(g1::Int, g2::Int, vertices::AbstractVector{<:Sigma}, generators) length(generators[1]) == 1 && return 1 A = generators[g1] B = generators[g2] transform = transformation(A, B) A = transform(A) gen_inds = unique!(sort!(reduce(vcat,vertices))) halfspaces = [] for gen_ind in gen_inds gen_ind in (g1,g2) && continue B = transform(generators[gen_ind]) u = normalize(B-A) b = dot(u, (A+B)/2) hf = HalfSpace(u[2:end], b) push!(halfspaces, hf) end halfspaces = [h for h in halfspaces] # Performance with different libraries on random 6x100 data: # nolib: 30 mins # CDDLib: 40 mins # QHull: 5h (with warnings about not affine polyhedron using a solver) poly = polyhedron(hrep(halfspaces)) local vol try vol = hasrays(poly) ? Inf : volume(poly) catch e if isa(e, AssertionError) @warn e vol = NaN else rethrow(e) end end return vol end """ affine transformation rotatinig and translating such that the boundary is aligned with the first dimension. A->B will be mapped to const*[1,0,0,...] and (A+B)/2 to [0,0,...] """ function transformation(A, B) R = diagm(ones(length(A))) R[:,1] = B-A R = collect(inv(qr(R).Q)) # Shortcut for Gram-Schmidt orthogonalization. t = R*(A+B)/2 transform(x) = R*x - t return transform end function transformation(A::SVector{N, T}, B::SVector{N, T}) where {N, T} R = MMatrix{N,N,T}(I) R[:,1] = B-A R = inv(qr(R).Q) t = R * (A+B)/2 transform(x) = R*x - t end """ build the connectivity matrix for the SQRA from adjacency and boundary information """ function volumes(vertices, P::AbstractVector) dim = length(P[1]) conns = adjacency(vertices) I = Int[] J = Int[] As = Float64[] Vs = zeros(length(P)) #=@showprogress 1 "Voronoi volumes "=# for ((g1,g2), sigs) in conns a = boundary_area(g1, g2, sigs, P) h = norm(P[g1] - P[g2]) / 2 v = a * h / dim # Volume computation push!(I, g1) push!(J, g2) push!(As, a) Vs[g1] += v Vs[g2] += v end A = sparse(I, J, As, length(P), length(P)) A = A + A' return A, Vs end """ given vertices in generator-coordinates, collect the verts belonging to generator pairs, i.e. boundary vertices """ function adjacency(v::Vertices) conns = Dict{Tuple{Int,Int}, Vector{Vector{Int}}}() for (sig, r) in v for a in sig for b in sig a >= b && continue v = get!(conns, (a,b), []) push!(v, sig) end end end return conns end """ similar to `boundary_area`, however uses a vector representation and is slower """ function boundary_area_vrep(g1::Int, g2::Int, inds::AbstractVector{<:Sigma}, vertices::Vertices, generators) A = generators[g1] B = generators[g2] dim = length(A) vertex_coords = map(i->vertices[i], inds) push!(vertex_coords, A) # Append one Voronoi center for full-dimensional volume. poly = polyhedron(vrep(vertex_coords), QHull.Library()) vol = hasrays(poly) ? Inf : volume(poly) h = norm(B - A) / 2 A = dim * vol / h return A, h, vol end
VoronoiGraph
https://github.com/axsk/VoronoiGraph.jl.git
[ "MIT" ]
0.2.2
dbcb0d532975547a973fc334c76338e397850709
code
7806
const Point{T} = AbstractVector{T} where T<:Real const Points = AbstractVector{<:Point} const Sigma = AbstractVector{<:Integer} # Encoded the vertex by the ids of its generators. const Vertex = Tuple{<:Sigma, <: Point} const Vertices = Dict{<:Sigma, <:Point} dim(xs::Points) = length(xs[1]) voronoi(x; kwargs...) = voronoi(vecvec(x); kwargs...) """ construct the voronoi diagram from `x` through breadth-first search """ function voronoi(xs::Points, searcher = Raycast(xs)) sig, r = descent(xs, searcher) verts, rays = explore(sig, r, xs, searcher) return verts::Vertices, xs, rays end voronoi_random(x, args...; kwargs...) = voronoi_random(vecvec(x), args...; kwargs...) """ construct a (partial) voronoi diagram from `x` through a random walk """ function voronoi_random(xs::Points, iter=1000; maxstuck=typemax(Int)) searcher = Raycast(xs) sig, r = descent(xs, searcher) verts = walk(sig, r, iter, xs, searcher, maxstuck) return verts::Vertices, xs end vecvec(x::Matrix) = map(SVector{size(x,1)}, eachcol(x)) vecvec(x::Vector{<:SVector}) = x """ starting at given points, run the ray shooting descent to find vertices """ function descent(xs::Points, searcher, start = 1) :: Vertex sig = [start] r = xs[start] d = length(r) for k in d:-1:1 # find an additional generator for each dimension u = randray(xs[sig]) (tau, t) = raycast(sig, r, u, xs, searcher) if t == Inf u = -u (tau, t) = raycast(sig, r, u, xs, searcher) end if t == Inf error("Could not find a vertex in both directions of current point." * "Consider increasing search range (tmax)") end sig = tau r = r + t*u end sig = SVector{dim(xs)+1}(sig) return (sig, r) end """ starting at vertices, walk nsteps along the voronoi graph to find new vertices """ function walk(sig::Sigma, r::Point, nsteps::Int, xs::Points, searcher, maxstuck::Int) :: Vertices verts = Dict(sig => r) nonew = 0 prog = Progress(maxstuck, 1, "Voronoi walk") progmax = 0 for s in 1:nsteps nonew += 1 progmax = max(progmax, nonew) ProgressMeter.update!(prog, progmax) randdir = rand(1:length(sig)) sig, r = walkray(sig, r, xs, searcher, randdir) r == Inf && continue # we encountered an infinite ray get!(verts, sig) do nonew = 0 return r end nonew > maxstuck && break end return verts end """ find the vertex connected to `v` by moving away from its `i`-th generator """ function walkray(sig::Sigma, r::Point, xs::Points, searcher, i) sig_del = deleteat(sig, i) u = u_default(sig, xs, i) sigβ€², t = raycast(sig_del, r, u, xs, searcher) if t < Inf rβ€² = r + t*u return sigβ€², rβ€² else return sig, r # if the vertex has an unbounded ray, return the same vertex end end function u_compare(sig, xs, i) u1 = u_randray(sig, xs, i) u2 = u_qr(sig, xs, i) #u3 = u_qr_short(deleteat(sig, i), xs, sig[i]) u3=u2 if !(isapprox(u1, u2) && isapprox(u1, u2)) @warn "Not approx" u1 u2 u3 end return u1 end function u_randray(sig, xs, i) sig_del = deleteat(sig, i) u = randray_modified(xs[sig_del]) if (u' * (xs[sig[i]] - xs[sig_del[1]])) > 0 u = -u end return u end # replace gram-schmidt of randray by qr function u_qr(sig, xs, i) n = length(sig) d = length(xs[1]) X = MMatrix{d, n-1, eltype(xs[1])}(undef) for j in 1:i-1 X[:, j] = xs[sig[j]] end for j in i:n-1 X[:, j] = xs[sig[j+1]] end origin = X[:, end] X[:, end] = xs[sig[i]] X .-= origin X = SMatrix(X) Q, R = qr(X) u = -Q[:,end] * sign(R[end,end]) return u end # same as u_qr, shorter and slower function u_qr_short(sig_del, xs, opposing) sig = vcat(sig_del[2:end], [opposing]) origin = xs[sig_del[1]] X = mapreduce(i->xs[i] - origin,hcat, sig) X = Array(X) #@show t q = qr(X) u = q.Q[:,end] u *= -sign(q.R[end,end]) return u end """ BFS of vertices starting from `S0` """ function explore(sig, r, xs::Points, searcher) # :: Vertices verts = Dict(sig=>r) queue = [sig=>r] edgecount = Dict{SVector{dim(xs), Int64}, Int}() sizehint!(edgecount, round(Int, expected_edges(xs))) sizehint!(verts, round(Int, expected_vertices(xs))) rays = Pair{Vector{Int64}, Int}[] cache = true # Caches if both points along an edge are known. Trades memory for runtime. hit = 0 miss = 0 new = 0 unbounded = 0 while length(queue) > 0 yield() (sig,r) = pop!(queue) for i in 1:length(sig) if cache && get(edgecount, deleteat(sig, i), 0) == 2 hit += 1 continue end sigβ€², rβ€² = walkray(sig, r, xs, searcher, i) if sigβ€² == sig push!(rays, sig => i) unbounded += 1 continue end if !haskey(verts, sigβ€²) push!(queue, sigβ€² => rβ€²) push!(verts, sigβ€² => rβ€²) if cache for j in 1:length(sigβ€²) edge = deleteat(sigβ€², j) edgecount[edge] = get(edgecount, edge, 0) + 1 end end new += 1 else miss += 1 end end end #@show hit, miss, new, unbounded return verts, rays end u_default = u_qr deleteat(sig::Vector, i) = deleteat!(copy(sig), i) deleteat(x,y) = StaticArrays.deleteat(x,y) """ generate a random ray orthogonal to the subspace spanned by the given points """ function randray(xs::Points) k = length(xs) d = length(xs[1]) v = similar(xs, k-1) # Gram Schmidt for i in 1:k-1 v[i] = xs[i] .- xs[k] for j in 1:(i-1) v[i] = v[i] .- dot(v[i], v[j]) .* v[j] end v[i] = normalize(v[i]) end u = randn(d) for i in 1:k-1 u = u - dot(u, v[i]) * v[i] end u = normalize(u) return u end """ generate a random ray orthogonal to the subspace spanned by the given points """ function randray_modified(xs::Points) k = length(xs) v = collect(xs) for i in 1:k v[i] -= v[k] # subtract origin end v[k] = randn(dim(xs)) # modified Gram-Schmidt (for better stability) for i in 1:k v[i] = normalize(v[i]) for j in i+1:k v[j] -= dot(v[i], v[j]) * v[i] end end u = v[k] return u end """ vertexheuristic(d, n) expected number of vertices for `n` points in `d` dimensions c.f. [Dwyer, The expected number of k-faces of a Voronoi Diagram (1993)] """ function expected_vertices(d, n) # from the previous work, only good for d>5 # 2^((d+1)/2) * exp(1/4) * pi^((d-1)/2) * d^((d-2)/2) / (d+1) * n # lower and upperbound coincide for k==d lowerbound(d, d) * n end function expected_edges(d, n) expected_vertices(d, n) * (d+1) / 2 end expected_edges(xs::Points) = expected_edges(dim(xs), length(xs)) expected_vertices(xs::Points) = expected_vertices(dim(xs), length(xs)) # Theorem 1 # For fixed k and d as n grow without bound, EF(k,d) Μƒ C(k,d)n with C(k,d) β‰₯ lowerbound(k,d) function lowerbound(k, d) 2 * pi^(k/2) * d^(k-1) / (k*(k+1)) * beta(d*k/2, (d-k+1)/2) ^ (-1) * (gamma(d/2) / gamma((d+1)/2))^k end # Theorem 1 # For fixed k and d as n grow without bound, EF(k,d) Μƒ C(k,d)n with C(k,d) ≀ upperbound(k,d) function upperbound(k, d) 2 * d^(d-2) * pi^((d-1)/2) * gamma((d^2+1)/2) * gamma(d/2)^d / ((d+1) * (d+2) * gamma(d^2/2) * gamma((d+1)/2)^d) * binomial(d+2, k+1) end
VoronoiGraph
https://github.com/axsk/VoronoiGraph.jl.git
[ "MIT" ]
0.2.2
dbcb0d532975547a973fc334c76338e397850709
code
1596
function test_volume(npoints = 100, dim = 3) x = rand(dim, npoints) @time v, p = voronoi_random(x, 10000) @time a = adjacency(v) @time av = [boundary_area_verts(a, v, p) for a in a] @time ae = [boundary_area_edges(a, p) for a in a] delta = filter(isfinite, ae - av) quota = sum(delta .< 1e-6) / length(delta) @assert quota > 2/3 @assert length(delta) / length(av) > 2/3 end function test_random(d=6, n=200) x = rand(d, n) @time v,p = voronoi_random(rand(d,n), 10_000_000; maxstuck=100_000); @show length(v) a = adjacency(v) println("avg. no. of neighbors: ", length(a)/n) println("avg. no. of vertices per face: ", mean(length.(values(a)))) @time c = connectivity_matrix(v, p) v,p,c end function test_grid(n=5, iter=10000) plot(legend=false); x = hcat(hexgrid(n)...) x .+= randn(2,n*n) .* 0.01 @time v, P = voronoi_random(x, iter) v = Dict(filter(collect(v)) do (k,v) norm(v) < 10 end) #c = extractconn(v) @time A, Vs = connectivity_matrix(v, P) AA = map(x->x>.0, A) plot_connectivity!(AA .* 2, P) scatter!(eachrow(hcat(values(v)...))...) xlims!(1,6); ylims!(0,5) end #= function benchmark(n=100, d=6, iter=100, particles=10) x = rand(d, n) @benchmark voronoi($x, $iter, $particles) end =# function hexgrid(n) P = [] for i in 1:n for j in 1:n x = i + j/2 y = j * sqrt(3) / 2 push!(P, [x,y]) end end P end function tests() test_volume() test_random() test_grid() end
VoronoiGraph
https://github.com/axsk/VoronoiGraph.jl.git
[ "MIT" ]
0.2.2
dbcb0d532975547a973fc334c76338e397850709
code
3143
using Test using VoronoiGraph using BenchmarkTools using LinearAlgebra using Random using RecipesBase using Statistics using VoronoiCells using VoronoiCells.GeometryBasics # nice to have if tests dont pass seed = rand(UInt) @show seed Random.seed!(seed) # necessary condition for the voronoi diagram to be correct function test_equidistance(verts, xs) allsame(x) = all(y -> y β‰ˆ first(x), x) for (sig, v) in verts dists = [norm(xs[s] - v) for s in sig] relerr = maximum(abs, 1 .- dists ./ dists[1]) if relerr > 1e-5 @show dists return false end end return true end bigdata = [rand(2, 10000), rand(4,1000), rand(6,200), rand(8,100)] smalldata = [rand(2, 1000), rand(3, 1000), rand(4,100)] @testset "VoronoiGraph.jl" begin @testset "Equidistance" begin for data in bigdata @time verts, xs = voronoi(data) @test test_equidistance(verts, xs) vrand, xs = voronoi_random(data, 1000) @test test_equidistance(vrand, xs) @test issubset(keys(vrand), keys(verts)) end end @testset "Raycast" begin for data in smalldata data = VoronoiGraph.vecvec(data) search = VoronoiGraph.RaycastCompare(data) @test_nowarn voronoi(data, search) end end @testset "Area computation" begin data = rand(2,1000) rect = Rectangle(Point2(-1000., -1000.), Point2(1000., 1000)) tess = voronoicells(data[1,:], data[2,:], rect) area = voronoiarea(tess) |> sort v, P = VoronoiGraph.voronoi(data) _, A = VoronoiGraph.volumes(v, P) A = sort(A) # the larger areas lie at the boundary and are computed differently small = A .< 1 #println("comparing areas on $(sum(small)) out of $(length(small)) cells") @test β‰ˆ(A[small], area[small], rtol=1e-8) end @testset "Monte Carlo Volumes" begin x = rand(2,20) v, xs = voronoi(x) A, V = volumes(v, xs) # exact reference volumes Am, Vm = mc_volumes(xs, 10_000) err = std(filter(isfinite, (Am-A)./A)) @test err < 0.2 Am, Vm = mc_volumes(v, xs, 10_000) err = std(filter(isfinite, (Am-A)./A)) @test err < 0.2 end @testset "Plot recipe" begin verts, xs = voronoi(rand(2,20)) p = VoronoiGraph.VoronoiPlot((verts, xs)) # this is broken without `using Plots`, but works with iter # however we dont want to require Plots for testing, so accepting this as broken @test_broken RecipesBase.apply_recipe(Dict{Symbol, Any}(), p) end end function benchmark(n=1000) data = rand(2,n) rect = Rectangle(Point2(-1000., -1000.), Point2(1000., 1000)) tess = voronoicells(data[1,:], data[2,:], rect) @show @benchmark VoronoiCells.voronoicells($data[1,:], $data[2,:], $rect) @show @benchmark VoronoiCells.voronoiarea($tess) v, P = VoronoiGraph.voronoi(data) @show @benchmark VoronoiGraph.voronoi($data) @show @benchmark VoronoiGraph.volumes($v, $P) return nothing end
VoronoiGraph
https://github.com/axsk/VoronoiGraph.jl.git
[ "MIT" ]
0.2.2
dbcb0d532975547a973fc334c76338e397850709
docs
2967
# VoronoiGraph [![DOI](https://zenodo.org/badge/417525067.svg)](https://zenodo.org/badge/latestdoi/417525067) [![Dev](https://img.shields.io/badge/docs-dev-blue.svg)](https://axsk.github.io/VoronoiGraph.jl/dev) [![Build Status](https://github.com/axsk/VoronoiGraph.jl/workflows/CI/badge.svg)](https://github.com/axsk/VoronoiGraph.jl/actions) [![codecov](https://codecov.io/gh/axsk/VoronoiGraph.jl/branch/main/graph/badge.svg?token=OYHZKYOE2H)](https://codecov.io/gh/axsk/VoronoiGraph.jl) This Package implements a variation of the Voronoi Graph Traversal algorithm by Polianskii and Pokorny [\[1\]](https://dl.acm.org/doi/10.1145/3394486.3403266). It constructs a [Voronoi Diagram](https://en.wikipedia.org/wiki/Voronoi_diagram) from a set of points by performing a random walk on the graph of the vertices of the diagram. Unlike many other Voronoi implementations this algorithm is not limited to 2 or 3 dimensions and promises good performance even in higher dimensions. ## Usage We can compute the Voronoi diagram with a simple call of `voronoi` ```julia julia> data = rand(4, 100) # 100 points in 4D space julia> v, P = voronoi(data) ``` which returns the vertices `v::Dict`. `keys(v)` returns the simplicial complex of the diagram, wheras `v[xs]` returns the coordinates of the vertex inbetween the generators `data[xs]`. Additionally `P` contains the data in a vector-of-vectors format, used for further computations. It also exports the random walk variant (returning only a subset of vertices): ```julia julia> v, P = voronoi_random(data, 1000) # perform 1000 iterations of the random walk ``` ## Area / Volume computation ```julia julia> A,V = volumes(v, P) ``` computes the (deterministic) areas of the boundaries of neighbouring cells (as sparse array `A`) as well as the volume of the cells themselves (vector `V`) by falling back onto the Polyhedra.jl volume computation. ## Monte Carlo Combining the raycasting approach with Monte Carlo estimates we can approximate the areas and volumes effectively: ```julia julia> A, V = mc_volumes(P, 1000) # cast 1000 Monte Carlo rays per cell ``` If the simplicial complex of vertices is already known we can speed up the process: ```julia julia> A, V = mc_volumes(v, P, 1000) # use the neighbourhood infromation contained in v ``` We furthermore can integrate any function `f` over a cell `i` and its boundaries: ```julia julia> y, Ξ΄y, V, A = mc_integrate(x->x^2, 1, P, 100, 10) # integrate cell 1 with 100 boundary and 100*10 volume samples ``` Here `y` and the vector `Ξ΄y` contain the integrals over the cell and its boundaries. V and A get computed as a byproduct. ## References [\[1\]](https://dl.acm.org/doi/10.1145/3394486.3403266) V. Polianskii, F. T. Pokorny - Voronoi Graph Traversal in High Dimensions with Applications to Topological Data Analysis and Piecewise Linear Interpolation (2020, Proceedings of the 26th ACM SIGKDD International Conference on Knowledge Discovery & Data Mining)
VoronoiGraph
https://github.com/axsk/VoronoiGraph.jl.git
[ "MIT" ]
0.2.2
dbcb0d532975547a973fc334c76338e397850709
docs
192
```@meta CurrentModule = VoronoiGraph ``` # VoronoiGraph Documentation for [VoronoiGraph](https://github.com/axsk/VoronoiGraph.jl). ```@index ``` ```@autodocs Modules = [VoronoiGraph] ```
VoronoiGraph
https://github.com/axsk/VoronoiGraph.jl.git
[ "MIT" ]
0.1.1
5c0857f7a0b5f313b86e521613858a70c948cd95
code
473
using SDLCanvas window = create_window("SDLCanvas", 800, 600) function main() clock = Clock(60) RUNNING = true while RUNNING while events_exist() event = pop_event() if event.type == QUIT || is_key_pressed(event, K_ESCAPE) RUNNING = false break end end splash(window, BLACK) update_display(window) tick(clock) end quit(window) end main()
SDLCanvas
https://github.com/Noremac11800/SDLCanvas.jl.git
[ "MIT" ]
0.1.1
5c0857f7a0b5f313b86e521613858a70c948cd95
code
1017
using SDLCanvas function draw_ring(window::Window; n_circles=100, ring_radius = 200, circle_radius=10) cx = window.w / 2 cy = window.h / 2 for n in 1:n_circles theta = n/n_circles*2pi x, y = round(Int, ring_radius*cos(theta) + cx), round(Int, ring_radius*sin(theta) + cy) colour = random_colour(150) draw_filled_circle(window, x, y, circle_radius, colour) end end window = create_window("SDLCanvas", 800, 600) function main() r = 200 speed = 3 direction = -1 clock = Clock(60) RUNNING = true while RUNNING while events_exist() event = pop_event() if event.type == QUIT RUNNING = false break end end direction = r < 50 || r > 200 ? -direction : direction r += direction * speed splash(window, WHITE) draw_ring(window, ring_radius=r) update_display(window) tick(clock) end quit(window) end main()
SDLCanvas
https://github.com/Noremac11800/SDLCanvas.jl.git
[ "MIT" ]
0.1.1
5c0857f7a0b5f313b86e521613858a70c948cd95
code
2849
using SDLCanvas window = create_window("SDLCanvas", 800, 600) shape_func = draw_circle shapes = [] function change_shape(func::Function) global shape_func = func end function main() gui_manager = GUI_Manager(window) circle_button = Button("", 20, 20; w = 50, h = 50, on_clicked = (_) -> change_shape(draw_circle), colour=LIGHTBLUE) filled_circle_button = Button("", 90, 20; w = 50, h = 50, on_clicked = (_) -> change_shape(draw_filled_circle), colour=LIGHTBLUE) square_button = Button("", 160, 20; w = 50, h = 50, on_clicked = (_) -> change_shape(draw_rect), colour=LIGHTBLUE) filled_square_button = Button("", 230, 20; w = 50, h = 50, on_clicked = (_) -> change_shape(draw_filled_rect), colour=LIGHTBLUE) undo_button = Button("UNDO", 800-70, 20; on_clicked = (_) -> if !isempty(shapes) pop!(shapes) end, colour=LIGHTRED) add_element(gui_manager, circle_button) add_element(gui_manager, filled_circle_button) add_element(gui_manager, square_button) add_element(gui_manager, filled_square_button) add_element(gui_manager, undo_button) clock = Clock(60) RUNNING = true while RUNNING splash(window, WHITE) while events_exist() event = pop_event() if event.type == QUIT RUNNING = false break end event_occurred = process_events(gui_manager, event) if mouse_clicked(event) && !event_occurred mx, my = get_mouse_pos() if shape_func == draw_circle push!(shapes, ("circle", mx, my)) end if shape_func == draw_filled_circle push!(shapes, ("filled_circle", mx, my)) end if shape_func == draw_rect push!(shapes, ("rect", mx, my)) end if shape_func == draw_filled_rect push!(shapes, ("filled_rect", mx, my)) end end end for (shape, x, y) in shapes if shape == "circle" draw_circle(window, x, y, 20, BLACK) end if shape == "filled_circle" draw_filled_circle(window, x, y, 20, BLACK) end if shape == "rect" draw_rect(window, x, y, 40, 40, BLACK) end if shape == "filled_rect" draw_filled_rect(window, x, y, 40, 40, BLACK) end end draw(gui_manager) draw_circle(window, 45, 45, 20, BLACK) draw_filled_circle(window, 115, 45, 20, BLACK) draw_rect(window, 170, 30, 30, 30, BLACK) draw_filled_rect(window, 240, 30, 30, 30, BLACK) update_display(window) tick(clock) end quit(window) end main()
SDLCanvas
https://github.com/Noremac11800/SDLCanvas.jl.git
[ "MIT" ]
0.1.1
5c0857f7a0b5f313b86e521613858a70c948cd95
code
961
using SDLCanvas window = create_window("SDLCanvas", 800, 600) function main() font = Font(joinpath(dirname(@__DIR__), "assets", "swansea.ttf"), 24) display_text = "This is some slow printing text... Pretty cool!" time_to_display = 5.0 frame_count = 0 clock = Clock(60) RUNNING = true while RUNNING while events_exist() event = pop_event() if event.type == QUIT || is_key_pressed(event, K_ESCAPE) RUNNING = false break end end frame_count += 1 percent_to_show = clamp(frame_count / (time_to_display * 60), 0, 1) end_index = round(Int, percent_to_show * length(display_text)) splash(window, WHITE) surface = render_font(font, display_text[1:end_index], BLACK) blit(window, surface, 400, 300; centered=true) update_display(window) tick(clock) end quit(window) end main()
SDLCanvas
https://github.com/Noremac11800/SDLCanvas.jl.git
[ "MIT" ]
0.1.1
5c0857f7a0b5f313b86e521613858a70c948cd95
code
919
using SDLCanvas STARS = [(rand(0:800), rand(0:600)) for _ in 1:300]; window = create_window("SDLCanvas", 800, 600) function draw_starfield() for (i, (x, y)) in enumerate(STARS) if i % 4 == 0 speed = 1 elseif i % 3 == 0 speed = 2 elseif i % 2 == 0 speed = 3 elseif i % 1 == 0 speed = 4 end new_x = x + speed > 800 ? 0 : x + speed STARS[i] = (new_x, y) draw_pixel(window, new_x, y, WHITE) end end function main() clock = Clock(60) RUNNING = true while RUNNING while events_exist() event = pop_event() if event.type == QUIT RUNNING = false break end end splash(window, BLACK) draw_starfield() update_display(window) tick(clock) end quit(window) end main()
SDLCanvas
https://github.com/Noremac11800/SDLCanvas.jl.git
[ "MIT" ]
0.1.1
5c0857f7a0b5f313b86e521613858a70c948cd95
code
807
using SDLCanvas window = create_window("SDLCanvas", 800, 600) function main() da = 0 db = 0 clock = Clock(60) RUNNING = true while RUNNING while events_exist() event = pop_event() if event.type == QUIT RUNNING = false break end end da += 0.1 if da > 2pi da = 0 db = 0 end if db < 2pi db += 0.1 end splash(window, WHITE) draw_filled_circle(window, 400, 300, 50, DARKGREY) draw_filled_circle(window, 400, 300, 45, WHITE) draw_filled_arc(window, 400, 300, 45, da, da+db, lighter(YELLOW, 100)) update_display(window) tick(clock) end quit(window) end main()
SDLCanvas
https://github.com/Noremac11800/SDLCanvas.jl.git
[ "MIT" ]
0.1.1
5c0857f7a0b5f313b86e521613858a70c948cd95
code
870
using SDLCanvas window = create_window("SDLCanvas", 800, 600) function handle_events(x, y, speed) if is_key_held(K_W) y -= speed end if is_key_held(K_A) x -= speed end if is_key_held(K_S) y += speed end if is_key_held(K_D) x += speed end return x, y end function main() x, y = 400, 300 speed = 3 clock = Clock(60) RUNNING = true while RUNNING while events_exist() event = pop_event() if event.type == QUIT || is_key_pressed(event, K_ESCAPE) RUNNING = false break end end x, y = handle_events(x, y, speed) splash(window, BLACK) draw_filled_rect(window, x, y, 30, 30, LIGHTGREY) update_display(window) tick(clock) end quit(window) end main()
SDLCanvas
https://github.com/Noremac11800/SDLCanvas.jl.git
[ "MIT" ]
0.1.1
5c0857f7a0b5f313b86e521613858a70c948cd95
code
734
using SDLCanvas window = create_window("SDLCanvas", 800, 600) function main() a = 0 b = 0 clock = Clock(60) RUNNING = true while RUNNING while events_exist() event = pop_event() if event.type == QUIT RUNNING = false break end end a += 0.05 if a > 2pi a = 0 end b += 0.02 if b > 2pi b = 0 end splash(window, WHITE) draw_ellipse(window, 400, 300, 60, 100, RED; rotation=a) draw_filled_ellipse(window, 600, 300, 60, 100, GREEN; rotation=b) update_display(window) tick(clock) end quit(window) end main()
SDLCanvas
https://github.com/Noremac11800/SDLCanvas.jl.git
[ "MIT" ]
0.1.1
5c0857f7a0b5f313b86e521613858a70c948cd95
code
734
using SDLCanvas window = create_window("SDLCanvas", 800, 600) function main() font = Font(joinpath(dirname(@__DIR__), "assets", "sunnyspells.ttf"), 20) surface = render_font(font, "This is some text", BLACK) clock = Clock(60) RUNNING = true while RUNNING while events_exist() event = pop_event() if event.type == QUIT RUNNING = false break end end splash(window, WHITE) draw_circle(window, 400, 300, 100, BLACK) blit(window, surface, 400, 300; centered=true) # Draw the surface relative to its center update_display(window) tick(clock) end quit(window) end main()
SDLCanvas
https://github.com/Noremac11800/SDLCanvas.jl.git
[ "MIT" ]
0.1.1
5c0857f7a0b5f313b86e521613858a70c948cd95
code
560
using SDLCanvas window = create_window("SDLCanvas", 800, 600) function main() image = load_image(joinpath(dirname(@__DIR__), "assets", "ship.png")) clock = Clock(60) RUNNING = true while RUNNING while events_exist() event = pop_event() if event.type == QUIT RUNNING = false break end end splash(window, WHITE) blit(window, image, 400, 300) update_display(window) tick(clock) end quit(window) end main()
SDLCanvas
https://github.com/Noremac11800/SDLCanvas.jl.git
[ "MIT" ]
0.1.1
5c0857f7a0b5f313b86e521613858a70c948cd95
code
963
using SDLCanvas window = create_window("SDLCanvas", 800, 600) circles1 = [] circles2 = [] function main() gui_manager = GUI_Manager(window; show_fps = true) clock = Clock(60) RUNNING = true while RUNNING while events_exist() event = pop_event() if event.type == QUIT RUNNING = false break end if mouse_clicked(event) push!(circles1, get_mouse_pos()) end if is_mouse_held(MOUSE_RIGHT) push!(circles2, get_mouse_pos()) end end splash(window, WHITE) for (x, y) in circles1 draw_filled_circle(window, x, y, 20, RED) end for (x, y) in circles2 draw_filled_circle(window, x, y, 20, GREEN) end draw(gui_manager) update_display(window) tick(clock) end quit(window) end main()
SDLCanvas
https://github.com/Noremac11800/SDLCanvas.jl.git
[ "MIT" ]
0.1.1
5c0857f7a0b5f313b86e521613858a70c948cd95
code
1266
using SDLCanvas window = create_window("SDLCanvas", 800, 600) bg_colour = WHITE function change_bg_colour(button::Button) global bg_colour if bg_colour == button.hover_colour bg_colour = WHITE else bg_colour = button.hover_colour end end function main() gui_manager = GUI_Manager(window; show_fps=true) red_button = Button("Press Me", 100, 200; font_size = 30, on_clicked = change_bg_colour, colour=LIGHTRED) green_button = Button("No Press Me!", 300, 200; font_size = 30, on_clicked = change_bg_colour, colour=LIGHTGREEN) blue_button = Button("I Want To Be Pressed!", 500, 200; font_size = 30, on_clicked = change_bg_colour, colour=LIGHTBLUE) add_element(gui_manager, red_button) add_element(gui_manager, green_button) add_element(gui_manager, blue_button) clock = Clock(60) RUNNING = true while RUNNING while events_exist() event = pop_event() if event.type == QUIT RUNNING = false break end process_events(gui_manager, event) end splash(window, bg_colour) draw(gui_manager) update_display(window) tick(clock) end quit(window) end main()
SDLCanvas
https://github.com/Noremac11800/SDLCanvas.jl.git
[ "MIT" ]
0.1.1
5c0857f7a0b5f313b86e521613858a70c948cd95
code
1405
using Pkg; Pkg.activate(".") using SDLCanvas using SimpleDirectMediaLayer using SimpleDirectMediaLayer.LibSDL2 window = create_window("SDLCanvas", 800, 600) function main() SDL_StartTextInput() text = "" font = Font("/Users/cam/Documents/GitBucket/Development/SDLCanvas-Github/SDLCanvas/assets/swansea.ttf", 24) surface = render_font(font, "Stuff", BLACK) clock = Clock(60) RUNNING = true while RUNNING while events_exist() event = pop_event() if event.type == QUIT || is_key_pressed(event, K_ESCAPE) RUNNING = false break end if is_key_pressed(event, K_BACKSPACE) if length(text) != 0 text = text[1:end-1] surface = render_font(font, text, BLACK) end end if event.type == SDL_TEXTINPUT text *= string(Char(event.text.text[1])) surface = render_font(font, text, BLACK) end if event.type == SDL_TEXTEDITING composition = event.edit.text cursor = event.edit.start selection_len = event.edit.length end end splash(window, WHITE) blit(window, surface, 200, 200) update_display(window) tick(clock) end quit(window) end main()
SDLCanvas
https://github.com/Noremac11800/SDLCanvas.jl.git
[ "MIT" ]
0.1.1
5c0857f7a0b5f313b86e521613858a70c948cd95
code
2117
module SDLCanvas include("common.jl") export ColourRGBA include("colour.jl") export NAMED_COLOURS export BLACK export WHITE export RED export LIGHTRED export GREEN export LIGHTGREEN export BLUE export LIGHTBLUE export GREY export LIGHTGREY export DARKGREY export YELLOW export random_colour export random_named_colour export lighter export darker include("colours.jl") export SCREEN_CENTER_X export SCREEN_CENTER_Y export Window export create_window export quit export splash export update_display include("display.jl") export Surface export get_size export get_center export blit include("surface.jl") export draw_pixel export draw_line export draw_arc export draw_filled_arc export draw_circle export draw_filled_circle export draw_ellipse export draw_filled_ellipse export draw_rect export draw_filled_rect include("draw.jl") export Clock export tick include("clock.jl") export Font export render_font include("font.jl") export Image export load_image export blit include("images.jl") export events_exist export pop_event export get_mouse_pos export mouse_clicked export is_mouse_held export is_key_pressed export is_key_held export QUIT export MOUSE_LEFT export MOUSE_RIGHT export K_ESCAPE export K_SPACE export K_ENTER export K_RETURN export K_BACKSPACE export K_A export K_B export K_C export K_D export K_E export K_F export K_G export K_H export K_I export K_J export K_K export K_L export K_N export K_O export K_P export K_Q export K_R export K_S export K_T export K_U export K_V export K_W export K_X export K_Y export K_Z include("events.jl") using .Colour using .Colours using .Display using .Surfaces using .Draw using .Time using .Events using .Fonts using .Images ########################################################### export GLOBALS export GUI_Manager export AbstractGUIElement export process_events export add_element export draw include("GUI/gui_manager.jl") export MouseRegion export RectRegion export CircleRegion export is_contained include("GUI/utils/utils.jl") export Button export signals export draw include("GUI/button.jl") using .GUI using .Utils using .Buttons end
SDLCanvas
https://github.com/Noremac11800/SDLCanvas.jl.git
[ "MIT" ]
0.1.1
5c0857f7a0b5f313b86e521613858a70c948cd95
code
187
module Time include("common.jl") export Clock export tick struct Clock fps::Int Clock(fps) = new(fps) end function tick(clock::Clock) SDL_Delay(1000 Γ· clock.fps) end end
SDLCanvas
https://github.com/Noremac11800/SDLCanvas.jl.git
[ "MIT" ]
0.1.1
5c0857f7a0b5f313b86e521613858a70c948cd95
code
216
module Colour include("common.jl") export ColourRGBA struct ColourRGBA r::Int g::Int b::Int a::Int ColourRGBA(r, g, b) = new(r, g, b, 255) ColourRGBA(r, g, b, a) = new(r, g, b, a) end end
SDLCanvas
https://github.com/Noremac11800/SDLCanvas.jl.git
[ "MIT" ]
0.1.1
5c0857f7a0b5f313b86e521613858a70c948cd95
code
1503
module Colours using ..Colour export NAMED_COLOURS export BLACK export WHITE export RED export LIGHTRED export GREEN export LIGHTGREEN export BLUE export LIGHTBLUE export GREY export LIGHTGREY export DARKGREY export YELLOW export random_colour export random_named_colour export lighter export darker BLACK = ColourRGBA(0, 0, 0) WHITE = ColourRGBA(255, 255, 255) RED = ColourRGBA(255, 0, 0) LIGHTRED = ColourRGBA(252, 106, 106, 255) GREEN = ColourRGBA(0, 255, 0) LIGHTGREEN = ColourRGBA(106, 252, 113, 255) BLUE = ColourRGBA(0, 0, 255) LIGHTBLUE = ColourRGBA(106, 186, 252, 255) GREY = ColourRGBA(150, 150, 150) LIGHTGREY = ColourRGBA(200, 200, 200) DARKGREY = ColourRGBA(100, 100, 100) YELLOW = ColourRGBA(242, 189, 41) NAMED_COLOURS = [ BLACK, WHITE, RED, LIGHTRED, GREEN, LIGHTGREEN, BLUE, LIGHTBLUE, GREY, LIGHTGREY, DARKGREY, YELLOW, ] function random_colour(a::Int=255)::ColourRGBA return ColourRGBA(rand(0:255), rand(0:255), rand(0:255), a) end function random_named_colour()::ColourRGBA return rand(NAMED_COLOURS) end function lighter(colour::ColourRGBA, a::Int)::ColourRGBA r = colour.r + a <= 255 ? colour.r + a : 255 g = colour.g + a <= 255 ? colour.g + a : 255 b = colour.b + a <= 255 ? colour.b + a : 255 if r < 0 r = 0 end if g < 0 g = 0 end if b < 0 b = 0 end return ColourRGBA(r, g, b, colour.a) end function darker(colour::ColourRGBA, a::Int)::ColourRGBA return lighter(colour, -a) end end
SDLCanvas
https://github.com/Noremac11800/SDLCanvas.jl.git
[ "MIT" ]
0.1.1
5c0857f7a0b5f313b86e521613858a70c948cd95
code
66
using SimpleDirectMediaLayer using SimpleDirectMediaLayer.LibSDL2
SDLCanvas
https://github.com/Noremac11800/SDLCanvas.jl.git
[ "MIT" ]
0.1.1
5c0857f7a0b5f313b86e521613858a70c948cd95
code
1570
module Display include("common.jl") using ..Colour export SCREEN_CENTER_X export SCREEN_CENTER_Y export Window export create_window export quit export splash export update_display SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 16) SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 16) @assert SDL_Init(SDL_INIT_EVERYTHING) == 0 "Error initialising SDL: $(unsafe_string(SDL_GetError()))" const SCREEN_CENTER_X = SDL_WINDOWPOS_CENTERED const SCREEN_CENTER_Y = SDL_WINDOWPOS_CENTERED struct Window sdl_window::Ptr{SDL_Window} renderer::Ptr{SDL_Renderer} title::String w::Int h::Int x::Int y::Int flags::Dict{Any, Any} end function create_window(title::String, w::Int, h::Int, x::Int=SCREEN_CENTER_X, y::Int=SCREEN_CENTER_Y; flags...)::Window window = SDL_CreateWindow(title, x, y, w, h, SDL_WINDOW_SHOWN) SDL_SetWindowResizable(window, SDL_TRUE) renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC) return Window(window, renderer, title, w, h, x, y, flags) end function quit(window::Window) SDL_DestroyRenderer(window.renderer) SDL_DestroyWindow(window.sdl_window) SDL_Quit() exit() end function splash(window::Window, r::Int, g::Int, b::Int, a::Int=255) SDL_SetRenderDrawColor(window.renderer, r, g, b, a); SDL_RenderClear(window.renderer); end function splash(window::Window, colour::ColourRGBA) splash(window, colour.r, colour.g, colour.b, colour.a) end function update_display(window::Window) SDL_RenderPresent(window.renderer) end end
SDLCanvas
https://github.com/Noremac11800/SDLCanvas.jl.git
[ "MIT" ]
0.1.1
5c0857f7a0b5f313b86e521613858a70c948cd95
code
8622
module Draw include("common.jl") # Colour and Display modules are already brought into scope in SDLCanvas.jl. # Re-including them with include() is unnecessary. Just use the .. using syntax. using ..Colour using ..Display export draw_pixel export draw_line export draw_arc export draw_filled_arc export draw_circle export draw_filled_circle export draw_ellipse export draw_filled_ellipse export draw_rect export draw_filled_rect function draw_pixel(window::Window, x::Int, y::Int, colour::Tuple{Int,Int,Int,Int}) SDL_SetRenderDrawColor(window.renderer, colour...) SDL_SetRenderDrawBlendMode(window.renderer, SDL_BLENDMODE_BLEND) SDL_RenderDrawPoint(window.renderer, x, y) end function draw_pixel(window::Window, x::Int, y::Int, colour::Tuple{Int,Int,Int}) draw_pixel(window, x, y, (colour..., 255)) end function draw_pixel(window::Window, x::Int, y::Int, colour::ColourRGBA) draw_pixel(window, x, y, (colour.r, colour.g, colour.b, colour.a)) end function draw_line(window::Window, x1::Int, y1::Int, x2::Int, y2::Int, colour::Tuple{Int, Int, Int, Int}; thickness::Int=1) angle = SDL_atan2(y2-y1, x2-x1) dx = floor(Int, sin(angle) * thickness / 2.0) dy = floor(Int, -cos(angle) * thickness / 2.0) SDL_SetRenderDrawColor(window.renderer, colour...) SDL_SetRenderDrawBlendMode(window.renderer, SDL_BLENDMODE_BLEND) for i in 0:thickness-1 SDL_RenderDrawLine(window.renderer, x1 + i*dx, y1 + i*dy, x2 + i*dx, y2 + i*dy) end end function draw_line(window::Window, x1::Int, y1::Int, x2::Int, y2::Int, colour::Tuple{Int, Int, Int}; kwargs...) draw_line(window, x1, y1, x2, y2, (colour..., 255); kwargs...) end function draw_line(window::Window, x1::Int, y1::Int, x2::Int, y2::Int, colour::ColourRGBA; kwargs...) draw_line(window, x1, y1, x2, y2, (colour.r, colour.g, colour.b, colour.a); kwargs...) end function draw_arc(window::Window, x::Int, y::Int, r::Int, start_angle::Real, end_angle::Real, colour::Tuple{Int, Int, Int, Int}) SDL_SetRenderDrawColor(window.renderer, colour...) SDL_SetRenderDrawBlendMode(window.renderer, SDL_BLENDMODE_BLEND) for theta in start_angle:0.01:end_angle px, py = r*cos(theta) + x, -r*sin(theta) + y SDL_RenderDrawPoint(window.renderer, round(Int, px), round(Int, py)) end end function draw_arc(window::Window, x::Int, y::Int, r::Int, start_angle::Real, end_angle::Real, colour::Tuple{Int, Int, Int}) draw_arc(window, x, y, r, start_angle, end_angle, (colour..., 255)) end function draw_arc(window::Window, x::Int, y::Int, r::Int, start_angle::Real, end_angle::Real, colour::ColourRGBA) draw_arc(window, x, y, r, start_angle, end_angle, (colour.r, colour.g, colour.b, colour.a)) end function draw_filled_arc(window::Window, x::Int, y::Int, r::Int, start_angle::Real, end_angle::Real, colour::Tuple{Int, Int, Int, Int}) SDL_SetRenderDrawColor(window.renderer, colour...) SDL_SetRenderDrawBlendMode(window.renderer, SDL_BLENDMODE_BLEND) for dx in -r:r for dy in -r:r if dx^2 + dy^2 <= r^2 angle_to_x_axis = atan(-dy, dx) angle_to_x_axis = angle_to_x_axis < 0 ? angle_to_x_axis + 2pi : angle_to_x_axis if start_angle <= angle_to_x_axis <= end_angle SDL_RenderDrawPoint(window.renderer, x+dx, y+dy) end end end end end function draw_filled_arc(window::Window, x::Int, y::Int, r::Int, start_angle::Real, end_angle::Real, colour::Tuple{Int, Int, Int}) draw_filled_arc(window, x, y, r, start_angle, end_angle, (colour..., 255)) end function draw_filled_arc(window::Window, x::Int, y::Int, r::Int, start_angle::Real, end_angle::Real, colour::ColourRGBA) draw_filled_arc(window, x, y, r, start_angle, end_angle, (colour.r, colour.g, colour.b, colour.a)) end function draw_circle(window::Window, x::Int, y::Int, r::Int, colour::Tuple{Int, Int, Int, Int}) SDL_SetRenderDrawColor(window.renderer, colour...) SDL_SetRenderDrawBlendMode(window.renderer, SDL_BLENDMODE_BLEND) draw_arc(window, x, y, r, 0, 2pi, colour) end function draw_circle(window::Window, x::Int, y::Int, r::Int, colour::Tuple{Int, Int, Int}) draw_circle(window, x, y, r, (colour..., 255)) end function draw_circle(window::Window, x::Int, y::Int, r::Int, colour::ColourRGBA) draw_circle(window, x, y, r, (colour.r, colour.g, colour.b, colour.a)) end function draw_filled_circle(window::Window, x::Int, y::Int, r::Int, colour::Tuple{Int, Int, Int, Int}) SDL_SetRenderDrawColor(window.renderer, colour...) SDL_SetRenderDrawBlendMode(window.renderer, SDL_BLENDMODE_BLEND) for dy in -r:r for dx in -r:r if (dx^2 + dy^2 <= r^2) SDL_RenderDrawPoint(window.renderer, x+dx, y+dy) end end end end function draw_filled_circle(window::Window, x::Int, y::Int, r::Int, colour::Tuple{Int, Int, Int}) draw_filled_circle(window, x, y, r, (colour..., 255)) end function draw_filled_circle(window::Window, x::Int, y::Int, r::Int, colour::ColourRGBA) draw_filled_circle(window, x, y, r, (colour.r, colour.g, colour.b, colour.a)) end function draw_ellipse(window::Window, x::Int, y::Int, major::Int, minor::Int, colour::Tuple{Int, Int, Int, Int}; rotation::Real=0) SDL_SetRenderDrawColor(window.renderer, colour...) SDL_SetRenderDrawBlendMode(window.renderer, SDL_BLENDMODE_BLEND) for theta in 0:0.01:2pi px = major*cos(theta)*cos(rotation) - minor*sin(theta)*sin(rotation) + x py = major*cos(theta)*sin(rotation) + minor*sin(theta)*cos(rotation) + y SDL_RenderDrawPoint(window.renderer, round(Int, px), round(Int, py)) end end function draw_ellipse(window::Window, x::Int, y::Int, major::Int, minor::Int, colour::Tuple{Int, Int, Int}; kwargs...) draw_ellipse(window, x, y, major, minor, (colour..., 255); kwargs...) end function draw_ellipse(window::Window, x::Int, y::Int, major::Int, minor::Int, colour::ColourRGBA; kwargs...) draw_ellipse(window, x, y, major, minor, (colour.r, colour.g, colour.b, colour.a); kwargs...) end function draw_filled_ellipse(window::Window, x::Int, y::Int, major::Int, minor::Int, colour::Tuple{Int, Int, Int, Int}; rotation::Real=0) SDL_SetRenderDrawColor(window.renderer, colour...) SDL_SetRenderDrawBlendMode(window.renderer, SDL_BLENDMODE_BLEND) r = max(major, minor) for dx in -r:r for dy in -r:r ddx = dx*cos(rotation) + dy*sin(rotation) ddy = dy*cos(rotation) - dx*sin(rotation) if (ddx/major)^2 + (ddy/minor)^2 <= 1 SDL_RenderDrawPoint(window.renderer, round(Int, x + dx), round(Int, y + dy)) end end end end function draw_filled_ellipse(window::Window, x::Int, y::Int, major::Int, minor::Int, colour::Tuple{Int, Int, Int}; kwargs...) draw_filled_ellipse(window, x, y, major, minor, (colour..., 255); kwargs...) end function draw_filled_ellipse(window::Window, x::Int, y::Int, major::Int, minor::Int, colour::ColourRGBA; kwargs...) draw_filled_ellipse(window, x, y, major, minor, (colour.r, colour.g, colour.b, colour.a); kwargs...) end function draw_rect(window::Window, x::Int, y::Int, w::Int, h::Int, colour::Tuple{Int, Int, Int, Int}) SDL_SetRenderDrawColor(window.renderer, colour...) SDL_SetRenderDrawBlendMode(window.renderer, SDL_BLENDMODE_BLEND) draw_line(window, x, y, x+w, y, colour) draw_line(window, x+w, y, x+w, y+h, colour) draw_line(window, x, y+h, x+w, y+h, colour) draw_line(window, x, y, x, y+h, colour) end function draw_rect(window::Window, x::Int, y::Int, w::Int, h::Int, colour::Tuple{Int, Int, Int}) draw_rect(window, x, y, w, h, (colour..., 255)) end function draw_rect(window::Window, x::Int, y::Int, w::Int, h::Int, colour::ColourRGBA) draw_rect(window, x, y, w, h, (colour.r, colour.g, colour.b, colour.a)) end function draw_filled_rect(window::Window, x::Int, y::Int, w::Int, h::Int, colour::Tuple{Int, Int, Int, Int}) SDL_SetRenderDrawColor(window.renderer, colour...) SDL_SetRenderDrawBlendMode(window.renderer, SDL_BLENDMODE_BLEND) for px in x:x+w for py in y:y+h SDL_RenderDrawPoint(window.renderer, px, py) end end end function draw_filled_rect(window::Window, x::Int, y::Int, w::Int, h::Int, colour::Tuple{Int, Int, Int}) draw_filled_rect(window, x, y, w, h, (colour..., 255)) end function draw_filled_rect(window::Window, x::Int, y::Int, w::Int, h::Int, colour::ColourRGBA) draw_filled_rect(window, x, y, w, h, (colour.r, colour.g, colour.b, colour.a)) end end
SDLCanvas
https://github.com/Noremac11800/SDLCanvas.jl.git
[ "MIT" ]
0.1.1
5c0857f7a0b5f313b86e521613858a70c948cd95
code
2522
module Events include("common.jl") export events_exist export pop_event export get_mouse_pos export mouse_clicked export is_mouse_held export is_key_pressed export is_key_held export QUIT export MOUSE_LEFT export MOUSE_RIGHT export K_ESCAPE export K_SPACE export K_ENTER export K_RETURN export K_BACKSPACE export K_A export K_B export K_C export K_D export K_E export K_F export K_G export K_H export K_I export K_J export K_K export K_L export K_N export K_O export K_P export K_Q export K_R export K_S export K_T export K_U export K_V export K_W export K_X export K_Y export K_Z const QUIT = SDL_QUIT EVENTS_REF = Ref{SDL_Event}() MOUSE_LEFT = SDL_BUTTON_LEFT MOUSE_RIGHT = SDL_BUTTON_RIGHT K_SPACE = SDL_SCANCODE_SPACE K_ENTER = SDL_SCANCODE_RETURN K_RETURN = SDL_SCANCODE_RETURN K_BACKSPACE = SDL_SCANCODE_BACKSPACE K_ESCAPE = SDL_SCANCODE_ESCAPE K_A = SDL_SCANCODE_A K_B = SDL_SCANCODE_B K_C = SDL_SCANCODE_C K_D = SDL_SCANCODE_D K_E = SDL_SCANCODE_E K_F = SDL_SCANCODE_F K_G = SDL_SCANCODE_G K_H = SDL_SCANCODE_H K_I = SDL_SCANCODE_I K_J = SDL_SCANCODE_J K_K = SDL_SCANCODE_K K_L = SDL_SCANCODE_L K_M = SDL_SCANCODE_M K_N = SDL_SCANCODE_N K_O = SDL_SCANCODE_O K_P = SDL_SCANCODE_P K_Q = SDL_SCANCODE_Q K_R = SDL_SCANCODE_R K_S = SDL_SCANCODE_S K_T = SDL_SCANCODE_T K_U = SDL_SCANCODE_U K_V = SDL_SCANCODE_V K_W = SDL_SCANCODE_W K_X = SDL_SCANCODE_X K_Y = SDL_SCANCODE_Y K_Z = SDL_SCANCODE_Z function get_mouse_pos()::Tuple{Int, Int} x, y = Ref{Int32}(), Ref{Int32}() SDL_GetMouseState(x, y) return Int(x[]), Int(y[]) end function mouse_clicked(event::SDL_Event, mouse_button::Int=MOUSE_LEFT)::Bool if event.type == SDL_MOUSEBUTTONDOWN return event.button.button == mouse_button end return false end function is_mouse_held(mouse_button::Int=MOUSE_LEFT)::Bool mouse_button_states = SDL_GetMouseState(C_NULL, C_NULL) & SDL_BUTTON(mouse_button) return Bool(parse(Int, reverse(bitstring(mouse_button_states))[mouse_button])) end function is_key_pressed(event::SDL_Event, key::SDL_Scancode)::Bool if event.type == SDL_KEYDOWN return event.key.keysym.scancode == key end return false end function is_key_held(key::SDL_Scancode)::Bool keystate = SDL_GetKeyboardState(C_NULL) return unsafe_load(keystate, Int(key)+1) end function update_key_states() SDL_PumpEvents() end function events_exist()::Bool update_key_states() return Bool(SDL_PollEvent(EVENTS_REF)) end function pop_event()::SDL_Event return EVENTS_REF[] end end
SDLCanvas
https://github.com/Noremac11800/SDLCanvas.jl.git
[ "MIT" ]
0.1.1
5c0857f7a0b5f313b86e521613858a70c948cd95
code
873
module Fonts include("common.jl") export Font export render_font using ..Colour using ..Display using ..Surfaces struct Font font::Ptr{TTF_Font} size::Int Font(fontname, size) = new(get_font(fontname, size), size) end function get_font(path::String, size::Int)::Ptr{TTF_Font} @assert TTF_Init() == 0 "Error initialising font backend" font::Ptr{TTF_Font} = TTF_OpenFont(path, size) if font == C_NULL throw(error("font was null and couldn't be found at: $(path)")) end return font end function render_font(font::Font, text::String, colour::ColourRGBA; antialiased=true)::Surface colour = SDL_Color(colour.r, colour.g, colour.b, colour.a) if antialiased return Surface(TTF_RenderText_Blended(font.font, text, colour)) else return Surface(TTF_RenderText_Solid(font.font, text, colour)) end end end
SDLCanvas
https://github.com/Noremac11800/SDLCanvas.jl.git
[ "MIT" ]
0.1.1
5c0857f7a0b5f313b86e521613858a70c948cd95
code
664
module Images include("common.jl") export Image export load_image export blit using ..Display using ..Surfaces # This is necessary when two different modules export the same function name import ..Surfaces: blit struct Image surface::Surface Image(path::String) = load_image(path) Image(surface::Surface) = new(surface) end function load_image(path::String)::Image surface = IMG_Load(path) if surface == C_NULL throw(error("Image could not be loaded")) end return Image(Surface(surface)) end function blit(window::Window, image::Image, x::Int, y::Int; kwargs...) blit(window, image.surface, x, y; kwargs...) end end
SDLCanvas
https://github.com/Noremac11800/SDLCanvas.jl.git
[ "MIT" ]
0.1.1
5c0857f7a0b5f313b86e521613858a70c948cd95
code
1024
module Surfaces include("common.jl") export Surface export get_size export get_center export blit using ..Display struct Surface surface::Ptr{SDL_Surface} Surface(surface) = new(surface) end function get_size(window::Window, surface::Surface) texture = SDL_CreateTextureFromSurface(window.renderer, surface.surface) w, h = Ref{Int32}(), Ref{Int32}() SDL_QueryTexture(texture, C_NULL, C_NULL, w, h) return w[], h[] end function get_center(window::Window, surface::Surface) w, h = get_size(window, surface) return w Γ· 2, h Γ· 2 end function blit(window::Window, surface::Surface, x::Int, y::Int; centered=false) texture = SDL_CreateTextureFromSurface(window.renderer, surface.surface) w, h = Ref{Int32}(), Ref{Int32}() SDL_QueryTexture(texture, C_NULL, C_NULL, w, h) w, h = w[], h[] if centered rect = SDL_Rect(x - wΓ·2, y - hΓ·2, w, h) else rect = SDL_Rect(x, y, w, h) end SDL_RenderCopy(window.renderer, texture, C_NULL, Ref(rect)) end end
SDLCanvas
https://github.com/Noremac11800/SDLCanvas.jl.git
[ "MIT" ]
0.1.1
5c0857f7a0b5f313b86e521613858a70c948cd95
code
3523
module Buttons include("../common.jl") export Button export signals export draw using ..Colour using ..Colours using ..Display using ..Fonts using ..Draw using ..Surfaces using ..Events using ..GUI using ..Utils import ..GUI: draw mutable struct Button <: AbstractGUIElement label::String x::Int y::Int w::Int h::Int on_clicked::Function colour::ColourRGBA hover_colour::ColourRGBA pressed_colour::ColourRGBA border::Int border_colour::ColourRGBA visible::Bool active::Bool font_size::Int font::Font padding::Int pressed::Bool hovered::Bool _mouse_region::RectRegion _signals::Dict{String, Function} _draw::Function end function pressed(button::Button, event::SDL_Event)::Bool mx, my = get_mouse_pos() if is_contained(button._mouse_region) button.hovered = true else button.hovered = false end if is_mouse_held() if is_contained(button._mouse_region) && is_contained(button._mouse_region; pos=GLOBALS[].mouse_last_clicked_position) button.pressed = true end else if is_contained(button._mouse_region) && button.pressed && is_contained(button._mouse_region; pos=GLOBALS[].mouse_last_clicked_position) button.on_clicked(button) end button.pressed = false end return button.pressed end signals = Dict( "pressed" => pressed, ) function Button(label::String, x::Int, y::Int; w::Int = 0, h::Int = 0, on_clicked::Function = (button::Button) -> (), colour::ColourRGBA = WHITE, hover_colour::ColourRGBA = LIGHTGREY, pressed_colour::ColourRGBA = DARKGREY, border::Int = 1, border_colour::ColourRGBA = BLACK, visible::Bool = true, active::Bool = true, font_size::Int = 20, font::Font = Font(joinpath(dirname(dirname(@__DIR__)), "assets", "sunnyspells.ttf"), font_size), padding::Int=10, pressed::Bool=false, hovered::Bool=false) return Button(label, x, y, w, h, on_clicked, colour, lighter(colour, 30), darker(colour, 30), border, border_colour, visible, active, font_size, font, padding, pressed, hovered, RectRegion(x, y, w, h), signals, draw) end function draw(window::Window, button::Button) text_surface = render_font(button.font, button.label, BLACK) if button.w == 0 || button.h == 0 button.w, button.h = get_size(window, text_surface) .+ (button.padding*2, button.padding*2) button._mouse_region.x = button.x - button.padding button._mouse_region.y = button.y - button.padding button._mouse_region.w = button.w button._mouse_region.h = button.h end if button.label == "" button.padding = 0 end if button.pressed draw_filled_rect(window, button.x-button.padding, button.y-button.padding, button.w, button.h, button.pressed_colour) elseif button.hovered draw_filled_rect(window, button.x-button.padding, button.y-button.padding, button.w, button.h, button.hover_colour) else draw_filled_rect(window, button.x-button.padding, button.y-button.padding, button.w, button.h, button.colour) end draw_rect(window, button.x-button.padding, button.y-button.padding, button.w, button.h, button.border_colour) blit(window, text_surface, button.x, button.y) end end
SDLCanvas
https://github.com/Noremac11800/SDLCanvas.jl.git
[ "MIT" ]
0.1.1
5c0857f7a0b5f313b86e521613858a70c948cd95
code
1800
module GUI include("../common.jl") export GLOBALS export GUI_Manager export AbstractGUIElement export process_events export add_element export draw using ..Display using ..Events using ..Fonts using ..Colours using ..Surfaces abstract type AbstractGUIElement end mutable struct Globals last_frame_time::Float64 time_since_last_frame::Float64 mouse_last_clicked_position::Tuple{Int, Int} Globals() = new(time(), 0.0, (0, 0)) end global const GLOBALS = Ref{Globals}(Globals()) struct GUI_Manager window::Window elements::Vector{AbstractGUIElement} show_fps::Bool GUI_Manager(window; show_fps=false) = new(window, Vector{AbstractGUIElement}(), show_fps) end function process_events(manager::GUI_Manager, event::SDL_Event)::Bool if mouse_clicked(event) GLOBALS[].mouse_last_clicked_position = get_mouse_pos() end signal_fired = false for element in manager.elements sigs = element._signals for (sig_name, sig) in pairs(sigs) if sig(element, event) signal_fired = true end end end return signal_fired end function add_element(manager::GUI_Manager, element::AbstractGUIElement) push!(manager.elements, element) end function draw(manager::GUI_Manager) GLOBALS[].time_since_last_frame = time() - GLOBALS[].last_frame_time GLOBALS[].last_frame_time = time() fps = round(Int, 1/GLOBALS[].time_since_last_frame) for element in manager.elements element._draw(manager.window, element) end if manager.show_fps font = Font(joinpath(dirname(dirname(@__DIR__)), "assets", "swansea.ttf"), 20) surface = render_font(font, "FPS = $fps", BLACK) blit(manager.window, surface, manager.window.w - 100, 20) end end end
SDLCanvas
https://github.com/Noremac11800/SDLCanvas.jl.git
[ "MIT" ]
0.1.1
5c0857f7a0b5f313b86e521613858a70c948cd95
code
722
module TextInputs include("../common.jl") export TextInput export draw using ..Colour using ..Colours using ..Display using ..Fonts using ..Draw using ..Surfaces using ..Events using ..GUI import ..GUI: draw struct TextInput <: AbstractGUIElement text::String x::Int y::Int w::Int h::Int _signals::Dict{String, Function} _draw::Function end signals = Dict( "confirmed" => confirmed, ) function TextInput(text::String, x::Int, y::Int; w::Int, h::Int) return TextInput(text, x, y, w, h, signals, draw) end function confirmed(textInput::TextInput, event::SDL_Event)::Bool end function draw(window::Window, textInput::TextInput) end end
SDLCanvas
https://github.com/Noremac11800/SDLCanvas.jl.git
[ "MIT" ]
0.1.1
5c0857f7a0b5f313b86e521613858a70c948cd95
code
884
module Utils export MouseRegion export RectRegion export CircleRegion export is_contained using ..Events abstract type MouseRegion end mutable struct RectRegion <: MouseRegion x::Int y::Int w::Int h::Int RectRegion(x, y, w, h) = new(x, y, w, h) end mutable struct CircleRegion <: MouseRegion x::Int y::Int r::Int CircleRegion(x, y, r) = new(x, y, r) end function is_contained(region::RectRegion; pos=(-1, -1)) mx, my = pos if mx == -1 || my == -1 mx, my = get_mouse_pos() end x, y, w, h = region.x, region.y, region.w, region.h return (x <= mx <= x + w) && (y <= my <= y + h) end function is_contained(region::CircleRegion; pos=(-1, -1)) mx, my = pos if mx == -1 || my == -1 mx, my = get_mouse_pos() end x, y, r = region.x, region.y, region.r return (mx-x)^2 + (my-y)^2 <= r^2 end end
SDLCanvas
https://github.com/Noremac11800/SDLCanvas.jl.git
[ "MIT" ]
0.1.1
5c0857f7a0b5f313b86e521613858a70c948cd95
code
80
using SDLCanvas using Test @testset "SDLCanvas.jl" begin @assert 1 < 2 end
SDLCanvas
https://github.com/Noremac11800/SDLCanvas.jl.git
[ "MIT" ]
0.1.1
5c0857f7a0b5f313b86e521613858a70c948cd95
docs
3228
[![Build Status](https://github.com/cam/SDLCanvas.jl/actions/workflows/CI.yml/badge.svg?branch=main)](https://github.com/cam/SDLCanvas.jl/actions/workflows/CI.yml?query=branch%3Amain) # Welcome to SDLCanvas.jl! Please see the [wiki](https://github.com/Noremac11800/SDLCanvas.jl/wiki) for a more detailed explanation of what SDLCanvas has to offer, and some very basic documentation for its API. SDLCanvas is completely inspired by the [pygame](https://www.pygame.org/docs/) C/Python library which is designed for creating 2D (and sometimes 3D) games using SDL2. Despite the confusing name, SDLCanvas is not designed for creating video games, although there's nothing stopping you from trying! I originally designed the library as a higher level interface into the [SDL2](https://github.com/JuliaMultimedia/SimpleDirectMediaLayer.jl) bindings for Julia to create basic graphics, image rendering, and font rendering. The library is extremely bare-bones and lacks MOST of the features a developer would expect from a modern graphics library (anti-aliasing being one of the sore spots). It doesn't have collision detection, clipping, lighting, occlusion, cameras, or any of the bells and whistles of a game engine (because it isn't one)! What it can do is draw shape primitives like lines, circles, and rectangles, render text and images, and comes with a GUI manager which currently only has a simple button implemented. The "examples/" directory in the root of the repo has a series of strangely organised examples of how to use most of the features that already exist in the library. ## Installation Using Julia's package manager, SDLCanvas and its dependencies can be installed via: ``` using Pkg; Pkg.add("SDLCanvas") ``` , or alternatively in the Julia REPL: ``` julia> ] pkg> add SDLCanvas ``` ## Getting Started The "examples/" directory in the repo contains a `SDLCanvas_template.jl` which is a bare-bones program designed to display an empty black window. However for convenience, the template code is below: ```Julia using SDLCanvas window = create_window("SDLCanvas", 800, 600) function main() clock = Clock(60) RUNNING = true while RUNNING while events_exist() event = pop_event() if event.type == QUIT || is_key_pressed(event, K_ESCAPE) RUNNING = false break end end splash(window, BLACK) update_display(window) tick(clock) end quit(window) end main() ``` ## Examples ### examples/example1.jl Drawing animated circles ### examples/example2.jl Animated scrolling starfield ### examples/example3.jl Spinning loading circle ### examples/example4.jl WASD-player-controlled square ### examples/example5.jl Animated, rotating ellipses ### examples/example6.jl Displaying text centered relative to the surface's center ### examples/example7.jl Displaying a PNG ### examples/example8.jl Drawing circles according to mouse position and button clicked. Left click = Draw single filled red circle Hold right click = Draw filled green circle every frame ### examples/example9.jl GUI manager and button demo ### examples/example10.jl Very simple shape-painting app demo
SDLCanvas
https://github.com/Noremac11800/SDLCanvas.jl.git
[ "MIT" ]
0.1.1
b7424b1abc9ca95b5ac266676c81ec316f44cc18
code
194
using Documenter using RenoiseOSC makedocs(sitename="RenoiseOSC.jl", modules=[RenoiseOSC], pages=["index.md", "api.md", "config.md"]) deploydocs(repo="github.com/stellartux/RenoiseOSC.jl.git")
RenoiseOSC
https://github.com/stellartux/RenoiseOSC.jl.git
[ "MIT" ]
0.1.1
b7424b1abc9ca95b5ac266676c81ec316f44cc18
code
17981
""" RenoiseOSC.jl is a collection of wrappers around the [Renoise OSC API functions](https://tutorials.renoise.com/wiki/Open_Sound_Control) """ module RenoiseOSC export luaeval, tempo, editmode, octave, patternfollow, editstep, setmacroparam, monophonic, monophonicglide, phraseplayback, phraseprogram, quantizationmode, scalekey, scalemode, transpose, volume, volumedb, linesperbeat, metronome, metronomeprecount, quantization, quantizationstep, scheduleadd, scheduleset, slotmute, slotunmute, trigger, ticksperline, bypass, setparam, mute, unmute, solo, outputdelay, postfxpanning, postfxvolume, postfxvolumedb, prefxpanning, prefxvolume, prefxvolumedb, prefxwidth, loopblock, loopblockmovebackwards, loopblockmoveforwards, looppattern, start, stop, resume, midievent, noteon, noteoff, sethost!, setport! using OpenSoundControl using Sockets const settings = Dict{String,Union{Sockets.InetAddr,UDPSocket}}("server" => Sockets.InetAddr(ip"127.0.0.1", 8000)) """ sethost!(host::Union{AbstractString,Sockets.IPAddr}) Set the host of the Renoise OSC server. Default value is `ip"127.0.0.1"`. !!! compat "Julia 1.3" Setting the host by passing an AbstractString requires at least Julia 1.3. # Example ```jldoctest; setup=:(using Sockets: @ip_str; using RenoiseOSC: sethost!) julia> sethost!(ip"127.0.0.1") Sockets.InetAddr{Sockets.IPv4}(ip"127.0.0.1", 8000) ``` """ sethost!(host::Union{AbstractString,IPAddr}) = settings["server"] = Sockets.InetAddr(host, settings["server"].port) """ setport!(port::Integer) Set the port of the Renoise OSC server. Default value is `8000`. """ setport!(port::Integer) = settings["server"] = Sockets.InetAddr(settings["server"].host, port) """ setaddress!(host::Union{AbstractString,Sockets.IPAddr}, port::Integer) Set the host and the port of the OSC Server. """ setaddress!(host::Union{AbstractString,IPAddr}, port::Integer) = settings["server"] = Sockets.InetAddr(host, port) function postmessage(path::AbstractString, argtypes::AbstractString="", args...) send( get!(UDPSocket, settings, "socket"), settings["server"].host, settings["server"].port, OpenSoundControl.message("/renoise/" * path, argtypes, args...).data ) end """ luaeval(expr::AbstractString) Evaluate a Lua expression inside Renoise's scripting environment. # Example ```julia luaeval("renoise.song().transport.bpm = 132") ``` """ luaeval(expr::AbstractString) = postmessage("evaluate", "s", expr) """ tempo(bpm::Integer) Set the song's current bpm `[32:999]` """ function tempo(bpm::Integer) if 32 <= bpm <= 999 postmessage("song/bpm", "i", Int32(bpm)) else @warn "Can't set bpm to $(bpm), bpm must be in 32:999" end end """ editmode(on::Bool) Set the song's global edit mode on or off """ editmode(on::Bool) = postmessage("song/edit/mode", on ? "T" : "F") """ octave(oct::Integer) Sets the song's current octave [0:8] """ function octave(oct::Integer) if oct in 0:8 postmessage("song/edit/octave", "i", Int32(oct)) else @warn "Can't set octave to $(oct), octave must be in 0:8" end end """ patternfollow(on::Bool) Enable or disable global pattern follow mode """ patternfollow(on::Bool) = postmessage("song/edit/pattern_follow", on ? "T" : "F") """ editstep(step::Integer) Set the song's current edit step `[0:8]` """ function editstep(step::Integer) if step in 0:8 postmessage("song/edit/step", "i", Int32(step)) else @warn "Can't set edit step to $(step), edit step must be in 0:8" end end """ setmacroparam(param::Integer, value::Real; instrument::Integer = -1) Set `instrument`'s macro parameter value `[0.0:1.0]`. Default to the currently selected instrument. """ function setmacroparam(param::Integer, value::Real; instrument::Integer=-1) postmessage("song/instrument/$(instrument)/$(param)", "d", Float64(value)) end """ monophonic(mono::Bool; instrument::Integer=-1) Enable or disable `instrument`'s mono mode. Default to the currently selected instrument. """ monophonic(mono::Bool; instrument::Integer=-1) = postmessage("song/instrument/$(instrument)/monophonic", mono ? "T" : "F") """ monophonicglide(glide::Integer; instrument::Integer=-1) Set `instrument`'s glide amount `[0:255]`. Default to the currently selected instrument. """ function monophonicglide(glide::Integer; instrument::Integer=-1) if glide in 0:255 postmessage("song/instrument/$(instrument)/monophonic_glide", "i", Int32(glide)) else @warn "Can't set monophonic glide to $(glide), glide must be in 0:255" end end """ phraseplayback(mode::AbstractString; instrument::Integer=-1) Set `instrument`'s phraseplayback mode `["Off", "Program", "Keymap"]` Default to the currently selected instrument. """ function phraseplayback(mode::AbstractString; instrument::Integer=-1) if mode in Set(["Off", "Program", "Keymap"]) postmessage("song/instrument/$(instrument)/phrase_playback", "s", mode) else @warn "Can't set phrase playback mode to \"$(mode)\", mode must be one of `[\"Off\", \"Program\", \"Keymap\"]`" end end """ phraseprogram(program::Integer; instrument::Integer=-1) Set `instrument`'s phrase program number [0:127] Default to the currently selected instrument. """ function phraseprogram(program::Integer; instrument::Integer=-1) if program in 0:127 postmessage("song/instrument/$(instrument)/phrase_playback", "i", Int32(program)) else @warn "Can't set phrase program to $(program), program must be in 0:127" end end """ quantizationmode(mode::AbstractString; instrument::Integer=-1) Set `instrument`'s quantization method, one of `"None"`, `"Line"`, `"Beat"`, `"Bar"`. Default to the currently selected instrument. """ function quantizationmode(mode::AbstractString; instrument::Integer=-1) if mode in Set(["None", "Line", "Beat", "Bar"]) postmessage("song/instrument/$(instrument)/quantize", "s", mode) else @warn "Can't set quantization mode to \"$(mode)\", mode must be one of `[\"None\", \"Line\", \"Beat\", \"Bar\"]`" end end """ scalekey(key::AbstractString; instrument::Integer=-1) Set `instrument`'s note scaling key. Default to the currently selected instrument. """ function scalekey(key::AbstractString; instrument::Integer=-1) if key in Set(["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"]) postmessage("song/instrument/$(instrument)/scale_key", "s", key) else @warn "Can't set scale key to \"$(key)\", key must be one of [\"C\", \"C#\", \"D\", \"D#\", \"E\", \"F\", \"F#\", \"G\", \"G#\", \"A\", \"A#\", \"B\"]" end end """ scalemode(mode::AbstractString; instrument::Integer=-1) Set `instrument`'s note scaling mode. Default to the currently selected instrument. """ function scalemode(mode::AbstractString; instrument::Integer=-1) postmessage("song/instrument/$(instrument)/scale_mode", "s", mode) end """ transpose(pitch::Integer; instrument::Integer=-1) Set `instrument`'s global pitch transpose `[-120:120]``. Default to the currently selected instrument. """ function transpose(pitch::Integer; instrument::Integer=-1) if pitch in -120:120 postmessage("song/instrument/$(instrument)/transpose", "i", pitch) else @warn "Can't transpose by $(pitch), `pitch` must be in `-120:120`" end end """ volume(level::Real; instrument::Integer=-1) Set `instrument`'s global volume to `level` `[0.0:db2lin(6)]β‰ˆ[0.0:2.0]`. Default to the currently selected instrument. """ function volume(level::Real; instrument::Integer=-1) postmessage("song/instrument/$(instrument)/volume", "d", clamp(Float64(level), 0.0, 1.9952623149688795)) end """ volumedb(level::Real; instrument::Integer=-1) Set `instrument`'s global volume to `level` in decibels `[0.0:6.0]`. Default to the currently selected instrument. """ function volumedb(level::Real; instrument::Integer=-1) postmessage("song/instrument/$(instrument)/volume_db", "d", clamp(Float64(level), 0.0, 6.0)) end """ linesperbeat(lpb::Integer) Set the song's current lines per beat [1:255] """ function linesperbeat(lpb::Integer) if lpb in 1:255 postmessage("song/lpb", "i", Int32(lpb)) else @warn "Can't set lines per beat to $(lpb), `lpb` must be in `1:255`" end end """ metronome(on::Bool) Enable or disable the global metronome """ metronome(on::Bool) = postmessage("song/record/metronome", on ? "T" : "F") """ metronomeprecount(on::Bool) Enable or disable the global metronome precount """ metronomeprecount(on::Bool) = postmessage("song/record/metronome_precount", on ? "T" : "F") """ quantization(on::Bool) Enable or disable the global record quantization """ quantization(on::Bool) = postmessage("song/record/quantization", on ? "T" : "F") """ quantizationstep(step::Integer) Set the global record quantization step [1:32] """ function quantizationstep(step::Integer) if step in 1:32 postmessage("song/record/quantization_step", b ? "T" : "F") else @warn "Can't set quantization step to $(step), `step` must be in `1:32`" end end """ scheduleadd(sequence::Integer) Add a scheduled sequence playback pos """ scheduleadd(sequence::Integer) = postmessage("song/sequence/schedule_add", "i", Int32(sequence)) """ scheduleset(sequence::Integer) Replace the current sequence playback pos """ scheduleset(sequence::Integer) = postmessage("song/sequence/schedule_set", "i", Int32(sequence)) """ slotmute(track::Integer, sequence::Integer) slotmute(mute::Bool, track::Integer, sequence::Integer) Mute the given track, sequence slot in the matrix. """ slotmute(track::Integer, sequence::Integer) = postmessage("song/sequence/slot_mute", "ii", Int32(track), Int32(sequence)) slotmute(mute::Bool, track::Integer, sequence::Integer) = postmessage("song/sequence/slot_$(mute ? "" : "un")mute", "ii", Int32(track), Int32(sequence)) """ slotunmute(track::Integer, sequence::Integer) Mute the given track, sequence slot in the matrix. """ slotunmute(track::Integer, sequence::Integer) = postmessage("song/sequence/slot_unmute", "ii", Int32(track), Int32(sequence)) """ trigger(sequence::Integer) Set playback pos to the specified sequence pos """ trigger(sequence::Integer) = postmessage("song/sequence/trigger", "i", Int32(sequence)) """ ticksperline(tpl::Integer) Set the song's current ticks per line [1:16] """ function ticksperline(tpl::Integer) if tpl in 1:16 postmessage("song/tpl", "i", Int32(tpl)) else @warn "Can't set ticks per line to $(tpl), ticks per line must be in `1:16`" end end """ bypass(bypassed::Bool; track::Integer=-1, device::Integer=-1) Set the bypass status of a device, set `true` to bypass the device. When unspecified, `track` and `device` default to the currently selected track and device. """ function bypass(bypassed::Bool; track::Integer=-1, device::Integer=-1) postmessage("song/track/$(track)/device/$(device)/bypass", bypassed ? "T" : "F") end """ setparam(key::Union{AbstractString,Integer}, value::Real; track::Integer=-1, device::Integer=-1) Set the parameter of any device by its name or index. `value` is clamped between `0.0` and `1.0`. When unspecified, track and device default to the currently selected track and device. """ function setparam(key::Integer, value::Real; track::Integer=-1, device::Integer=-1) postmessage("song/track/$(track)/device/$(device)/set_parameter_by_index", "id", Int32(key), Float64(clamp(value, 0.0, 1.0))) end function setparam(key::AbstractString, value::Real; track::Integer=-1, device::Integer=-1) postmessage("song/track/$(track)/device/$(device)/set_parameter_by_name", "sd", key, Float64(clamp(value, 0.0, 1.0))) end """ mute(muted::Bool = true; track::Integer = -1) Mute or unmute the given track. Default to the currently selected track. """ mute(muted::Bool=true; track::Integer=-1) = postmessage("song/track/$(track)/$(muted ? "" : "un")mute") """ unmute(; track::Integer=-1) mute(false; track::Integer=-1) Unmute the given track. Default to the currently selected track. """ unmute(; track::Integer=-1) = postmessage("song/track/$(track)/unmute") """ solo(; track::Integer) Toggle solo for the given track. Default to the currently selected track. """ solo(; track::Integer=-1) = postmessage("song/track/$(track)/solo") """ outputdelay(Ξ΄t::Real; track::Integer) Set the given track's output delay in milliseconds [-100:100]. Default to the currently selected track. """ function outputdelay(Ξ΄t::Real; track::Integer=-1) if -100.0 <= Ξ΄t <= 100.0 postmessage("song/track/$(track)/output_delay", "d", Float64(Ξ΄t)) else @warn "Can't set output delay to `$(Ξ΄t)`. The output delay time must be between `-100.0` and `100.0`" end end """ postfxpanning(pan::Integer; track::Integer=-1) Set `track`'s post-FX panning, `[-50:50]` left to right. Default to the currently selected track. """ function postfxpanning(pan::Integer; track::Integer=-1) if -50 <= pan <= 50 postmessage("song/track/$(track)/postfx_panning", "i", Int32(pan)) else @warn "Can't set post-FX panning to $(pan), `pan` must be in `-50:50`" end end """ postfxvolume(level::Real; track::Integer=-1) Set `track`s post-FX volume, `[0.0:db2lin(6.0)]`, -Inf:+6dB. Default to the currently selected track. """ function postfxvolume(level::Real; track::Integer=-1) postmessage("song/track/$(track)/postfx_volume", "d", clamp(Float64(level), 0.0, 1.9952623149688795)) end """ postfxvolumedb(level::Real; track::Integer=-1) Set `track`s post-FX volume in decibels, `[-200.0:3.0]`. Default to the currently selected track. """ function postfxvolumedb(level::Real; track::Integer=-1) postmessage("song/track/$(track)/postfx_volume_db", "d", clamp(Float64(level), -200.0, 3.0)) end """ prefxpanning(pan::Integer; track::Integer=-1) Set `track`'s pre-FX panning, `[-50:50]` left to right. Default to the currently selected track. """ function prefxpanning(pan::Integer; track::Integer=-1) if -50 <= pan <= 50 postmessage("song/track/$(track)/prefx_panning", "i", Int32(pan)) else @warn "Can't set pre-FX panning to $(pan), `pan` must be in `-50:50`" end end """ prefxvolume(level::Real; track::Integer=-1) Set `track`s pre-FX volume, `[0.0:db2lin(6.0)]`, -Inf:+6dB. Default to the currently selected track. """ function prefxvolume(level::Real; track::Integer=-1) postmessage("song/track/$(track)/prefx_volume", "d", clamp(Float64(level), 0.0, 1.9952623149688795)) end """ prefxvolumedb(level::Real; track::Integer=-1) Set `track`s pre-FX volume in decibels, `[-200.0:3.0]`. Default to the currently selected track. """ prefxvolumedb(level::Real; track::Integer=-1) = postmessage("song/track/$(track)/prefx_volume_db", "d", clamp(Float64(level), -200.0, 3.0)) """ prefxwidth(width::Real; track::Integer=-1) Set `track`'s pre-FX width `[0.0:1.0]`. Default to the currently selected track. """ prefxwidth(width::Real; track::Integer=-1) = postmessage("song/track/$(track)/prefx_width", "d", clamp(Float64(width), 0.0, 1.0)) """ loopblock(loop::Bool) Enable or disable pattern block loop. """ loopblock(loop::Bool) = postmessage("/transport/loop/block", loop ? "T" : "F") """ loopblockmovebackwards() Move the block loop one segment backwards """ loopblockmovebackwards() = postmessage("transport/loop/block_move_backwards") """ loopblockmoveforwards() Move the block loop one segment forwards """ loopblockmoveforwards() = postmessage("transport/loop/block_move_forwards") """ looppattern(loop::Bool) Enable or disable looping the current pattern. """ looppattern(loop::Bool) = postmessage("transport/loop/pattern", loop ? "T" : "F") """ start() Start playback or restart playing the current pattern """ start() = postmessage("transport/start") """ stop() Stop playback """ stop() = postmessage("transport/stop") """ panic() Stop playback and reset all playing instruments and DSPs """ panic() = postmessage("transport/panic") """ resume() Continue playback """ resume() = postmessage("transport/continue") """ midievent(portid::UInt8, status::UInt8, data1::UInt8, data2::UInt8) midievent(event::Union{UInt32,UInt64,Array{<:Integer},NTuple{4,<:Integer}}) Fire a raw MIDI event. """ midievent(portid::UInt8, status::UInt8, data1::UInt8, data2::UInt8) = postmessage("trigger/midi", "m", [portid, status, data1, data2]) function midievent(event::Union{Array{<:Integer},NTuple{4,<:Integer}}) if all(<=(255), event) postmessage("trigger/midi", "m", UInt8.(event)) else @warn "Can't send MIDI event" end end midievent(portid::Integer, status::Integer, data1::Integer, data2::Integer) = midievent([portid, status, data1, data2]) midievent(event::UInt64) = postmessage("trigger/midi", "h", event) midievent(event::UInt32) = postmessage("trigger/midi", "i", event) """ noteon(pitch::Integer, velocity::Integer; instrument::Integer=-1, track::Integer=-1) Turn on the note with the velocity. Default to the currently selected instrument and track. """ function noteon(pitch::Integer, velocity::Integer; instrument::Integer=-1, track::Integer=-1) postmessage("trigger/note_on", "iiii", Int32.((instrument, track, pitch, velocity))...) end """ noteoff(pitch::Integer, velocity::Integer; instrument::Integer=-1, track::Integer=-1) Turn off the note """ function noteoff(pitch::Integer; instrument::Integer=-1, track::Integer=-1) postmessage("trigger/note_off", "iii", Int32.((instrument, track, pitch))...) end end # module
RenoiseOSC
https://github.com/stellartux/RenoiseOSC.jl.git
[ "MIT" ]
0.1.1
b7424b1abc9ca95b5ac266676c81ec316f44cc18
docs
543
# RenoiseOSC.jl [![Docs](https://img.shields.io/badge/docs-dev-blue.svg)](https://stellartux.github.io/RenoiseOSC.jl/dev/) [![GitHub license](https://img.shields.io/github/license/stellartux/RenoiseOSC.jl)](https://github.com/stellartux/RenoiseOSC.jl/blob/master/LICENSE) RenoiseOSC.jl wraps the [Renoise OpenSoundControl API](https://tutorials.renoise.com/wiki/Open_Sound_Control). See [the docs](https://stellartux.github.io/RenoiseOSC.jl/dev/) for more details. ## Quickstart ```julia using Pkg Pkg.add(RenoiseOSC) using RenoiseOSC ```
RenoiseOSC
https://github.com/stellartux/RenoiseOSC.jl.git
[ "MIT" ]
0.1.1
b7424b1abc9ca95b5ac266676c81ec316f44cc18
docs
805
# Renoise OSC API This file documents the API exposed in Renoise `^3.0.1`. ```@meta CurrentModule = RenoiseOSC ``` ## v3.0 ```@docs luaeval tempo editmode octave patternfollow editstep linesperbeat metronome metronomeprecount quantization quantizationstep scheduleadd scheduleset slotmute slotunmute trigger bypass setparam outputdelay postfxpanning postfxvolume postfxvolumedb prefxpanning prefxvolume prefxvolumedb prefxwidth solo mute unmute panic resume start stop midievent noteon noteoff ``` ## v3.3 Below are the functions added between Renoise `3.0.1` and `3.3.0`. ```@docs setmacroparam monophonic monophonicglide phraseplayback phraseprogram quantizationmode scalekey scalemode transpose volume volumedb ticksperline loopblock loopblockmovebackwards loopblockmoveforwards looppattern ```
RenoiseOSC
https://github.com/stellartux/RenoiseOSC.jl.git
[ "MIT" ]
0.1.1
b7424b1abc9ca95b5ac266676c81ec316f44cc18
docs
322
# Configuration ```@meta CurrentModule = RenoiseOSC ``` RenoiseOSC defaults to sending events to `localhost` at port `8000`, the default port which Renoise hosts its OSC server on. To use a different address, use the functions below. Only communication over UDP is supported. ```@docs setaddress! sethost! setport! ```
RenoiseOSC
https://github.com/stellartux/RenoiseOSC.jl.git
[ "MIT" ]
0.1.1
b7424b1abc9ca95b5ac266676c81ec316f44cc18
docs
626
# RenoiseOSC.jl ```@meta CurrentModule = RenoiseOSC ``` ```@docs RenoiseOSC ``` ## Install Run the following commands in Julia to install RenoiseOSC. ```julia using Pkg Pkg.add(RenoiseOSC) ``` ## Use Open Renoise. The OSC server must be enabled for RenoiseOSC.jl to be able to communicate with it. To enable the OSC server, select the Edit menu, then open the Preferences menu. Open the OSC tab and check the Enable Server checkbox. You should see `*** Server is up and running` in the Incoming Messages panel. ```julia using RenoiseOSC start() ``` If everything is working correctly, Renoise should now be playing.
RenoiseOSC
https://github.com/stellartux/RenoiseOSC.jl.git
[ "MIT" ]
0.1.0
6e0e59cf030ff08603780c7595a52748e1e68014
code
1511
using Documenter using UniqueKronecker using DocumenterCitations ENV["JULIA_DEBUG"] = "Documenter" PAGES = [ "Home" => "index.md", "Unique Kronecker Products" => [ "Basics" => "uniquekronecker/basics.md", "Higher Order" => "uniquekronecker/higherorder.md", ], "Circulant Kronecker Products" => "circulantkronecker/basics.md", "Matrix Conversions" => [ "Polynomial Dynamical System" => "matrices/dynamicalsystem.md", "Elimination Matrix" => "matrices/elimination.md", "Duplication Matrix" => "matrices/duplication.md", "Commutation Matrix" => "matrices/commutation.md", "Symmetrizer Matrix" => "matrices/symmetrizer.md" ], "API Reference" => "api.md", "Paper Reference" => "paper.md", ] bib = CitationBibliography(joinpath(@__DIR__, "src", "refs.bib")) makedocs( sitename = "UniqueKronecker.jl", clean = true, doctest = false, linkcheck = false, format = Documenter.HTML( prettyurls = get(ENV, "CI", nothing) == "true", edit_link = "https://github.com/smallpondtom/UniqueKronecker.jl", assets=String[ "assets/citations.css", "assets/favicon.ico", ], # analytics = "G-B2FEJZ9J99", ), modules = [ UniqueKronecker, ], pages = PAGES, plugins=[bib], ) deploydocs( repo = "github.com/smallpondtom/UniqueKronecker.jl.git", branch = "gh-pages", devbranch = "main", # Add other deployment options as needed )
UniqueKronecker
https://github.com/smallpondtom/UniqueKronecker.jl.git
[ "MIT" ]
0.1.0
6e0e59cf030ff08603780c7595a52748e1e68014
code
359
module UniqueKronecker using LinearAlgebra using SparseArrays using Kronecker: βŠ— using StatsBase: countmap using Combinatorics: permutations, factorial, binomial, with_replacement_combinations include("unique_kronecker.jl") include("circulant_kronecker.jl") include("polytools.jl") include("vectorize.jl") include("legacy.jl") end # module UniqueKronecker
UniqueKronecker
https://github.com/smallpondtom/UniqueKronecker.jl.git
[ "MIT" ]
0.1.0
6e0e59cf030ff08603780c7595a52748e1e68014
code
3217
export circulant_kronecker, βŠ›, circulant_kron_snapshot_matrix """ circulant_kronecker(args::AbstractArray...) Circulant Kronecker product operation for multiple Kronecker products. ## Arguments - `args::AbstractArray...`: Vectors or matrices to perform the circulant Kronecker product. ## Returns - `result`: The circulant Kronecker product. """ function circulant_kronecker(args::AbstractArray...) n = length(args) if n == 2 return args[1] βŠ— args[2] + args[2] βŠ— args[1] elseif n == 3 return args[1] βŠ— args[2] βŠ— args[3] + args[2] βŠ— args[3] βŠ— args[1] + args[3] βŠ— args[1] βŠ— args[2] else # Compute one Kronecker product to get the correct size and type initial_kp = βŠ—(args...) # Initialize result as a zero array of the same type and size as initial_kp result = zero(initial_kp) @inbounds for k in 0:(n - 1) # Generate cyclic permutation of arguments permuted_args = ntuple(i -> args[mod1(i + k, n)], n) # Compute Kronecker product of permuted arguments kp = βŠ—(permuted_args...) result += kp end return result end end # Helper function to flatten arguments function flatten_args(args...) result = [] for arg in args if isa(arg, AbstractArray{<:Number}) push!(result, arg) elseif isa(arg, Tuple) || isa(arg, Array) append!(result, flatten_args(arg...)) else error("Unsupported argument type: ", typeof(arg)) end end return result end """ βŠ›(args::AbstractArray...) Circulant Kronecker product operator for multiple arguments. ## Arguments - `args::AbstractArray...`: Vectors or matrices to perform the circulant Kronecker product. ## Returns - `result`: The circulant Kronecker product. """ function βŠ›(args...) flat_args = flatten_args(args...) return circulant_kronecker(flat_args...) end """ circulant_kron_snapshot_matrix(Xmat::AbstractArray{T}...) where {T<:Number} Compute the circulant Kronecker product of a set of matrices, where each matrix is a snapshot matrix. ## Arguments - `Xmat::AbstractArray{T}...`: Snapshot matrices to compute the circulant Kronecker product. ## Returns - `result`: The circulant Kronecker product of the snapshot matrices. """ function circulant_kron_snapshot_matrix(Xmat::AbstractArray{T}...) where {T<:Number} # Ensure all matrices have the same number of columns ncols = size(Xmat[1], 2) for X in Xmat[2:end] if size(X, 2) != ncols throw(ArgumentError("All input matrices must have the same number of columns")) end end # Inner function to compute circulant Kronecker product for a set of vectors function circulant_kron_timestep(x...) return circulant_kronecker(x...) end # Collect columns from each matrix col_iterators = map(eachcol, Xmat) # Zip the columns together to align them zipped_columns = zip(col_iterators...) # Apply circulant_kron_timestep to each set of columns tmp = [circulant_kron_timestep(cols...) for cols in zipped_columns] # Concatenate the results horizontally return reduce(hcat, tmp) end
UniqueKronecker
https://github.com/smallpondtom/UniqueKronecker.jl.git
[ "MIT" ]
0.1.0
6e0e59cf030ff08603780c7595a52748e1e68014
code
10833
""" makeQuadOp(n::Int, inds::AbstractArray{Tuple{Int,Int,Int}}, vals::AbstractArray{Real}, which_quad_term::Union{String,Char}="H") β†’ H or F or Q Helper function to construct the quadratic operator from the indices and values. The indices must be a 1-dimensional array of tuples of the form `(i,j,k)` where `i,j,k` are the indices of the quadratic term. For example, for the quadratic term ``2.5x_1x_2`` for ``\\dot{x}_3`` would have an index of `(1,2,3)` with a value of `2.5`. The `which_quad_term` argument specifies which quadratic term to construct. Note that the values must be a 1-dimensional array of the same length as the indices. ## Arguments - `n::Int`: dimension of the quadratic operator - `inds::AbstractArray{Tuple{Int,Int,Int}}`: indices of the quadratic term - `vals::AbstractArray{Real}`: values of the quadratic term - `which_quad_term::Union{String,Char}="H"`: which quadratic term to construct - `symmetric::Bool=true`: whether to construct the symmetric `H` or `Q` matrix ## Returns - the quadratic operator """ function makeQuadOp(n::Int, inds::AbstractArray{Tuple{Int,Int,Int}}, vals::AbstractArray{<:Real}; which_quad_term::Union{String,Char}="H", symmetric::Bool=true) @assert length(inds) == length(vals) "The length of indices and values must be the same." Q = zeros(n, n, n) for (ind,val) in zip(inds, vals) if symmetric i, j, k = ind if i == j Q[ind...] = val else Q[i,j,k] = val/2 Q[j,i,k] = val/2 end else Q[ind...] = val end end if which_quad_term == "H" || which_quad_term == 'H' return Q2H(Q) elseif which_quad_term == "F" || which_quad_term == 'F' return eliminate(Q2H(Q), 2) elseif which_quad_term == "Q" || which_quad_term == 'Q' return Q else error("The quad term must be either H, F, or Q.") end end """ makeCubicOp(n::Int, inds::AbstractArray{Tuple{Int,Int,Int,Int}}, vals::AbstractArray{Real}, which_cubic_term::Union{String,Char}="G") β†’ G or E Helper function to construct the cubic operator from the indices and values. The indices must be a 1-dimensional array of tuples of the form `(i,j,k,l)` where `i,j,k,l` are the indices of the cubic term. For example, for the cubic term ``2.5x_1x_2x_3`` for ``\\dot{x}_4`` would have an index of `(1,2,3,4)` with a value of `2.5`. The `which_cubic_term` argument specifies which cubic term to construct (the redundant or non-redundant operator). Note that the values must be a 1-dimensional array of the same length as the indices. ## Arguments - `n::Int`: dimension of the cubic operator - `inds::AbstractArray{Tuple{Int,Int,Int,Int}}`: indices of the cubic term - `vals::AbstractArray{Real}`: values of the cubic term - `which_cubic_term::Union{String,Char}="G"`: which cubic term to construct "G" or "E" - `symmetric::Bool=true`: whether to construct the symmetric `G` matrix ## Returns - the cubic operator """ function makeCubicOp(n::Int, inds::AbstractArray{Tuple{Int,Int,Int,Int}}, vals::AbstractArray{<:Real}; which_cubic_term::Union{String,Char}="G", symmetric::Bool=true) @assert length(inds) == length(vals) "The length of indices and values must be the same." S = zeros(n, n, n, n) for (ind,val) in zip(inds, vals) if symmetric i, j, k, l = ind if i == j == k S[ind...] = val elseif (i == j) && (j != k) S[i,j,k,l] = val/3 S[i,k,j,l] = val/3 S[k,i,j,l] = val/3 elseif (i != j) && (j == k) S[i,j,k,l] = val/3 S[j,i,k,l] = val/3 S[j,k,i,l] = val/3 elseif (i == k) && (j != k) S[i,j,k,l] = val/3 S[j,i,k,l] = val/3 S[i,k,j,l] = val/3 else S[i,j,k,l] = val/6 S[i,k,j,l] = val/6 S[j,i,k,l] = val/6 S[j,k,i,l] = val/6 S[k,i,j,l] = val/6 S[k,j,i,l] = val/6 end else S[ind...] = val end end G = spzeros(n, n^3) for i in 1:n G[i, :] = vec(S[:, :, :, i]) end if which_cubic_term == "G" || which_cubic_term == 'G' return G elseif which_cubic_term == "E" || which_cubic_term == 'E' return eliminate(G, 3) else error("The cubic term must be either G or E.") end end """ extractF(F::Union{SparseMatrixCSC,VecOrMat}, r::Int) β†’ F Extracting the `F` matrix for POD basis of dimensions `(N, r)` ## Arguments - `F`: F matrix - `r`: reduced order ## Returns - extracted `F` matrix """ function extractF(F, r) N = size(F, 1) if 0 < r < N xsq_idx = [1 + (N + 1) * (n - 1) - n * (n - 1) / 2 for n in 1:N] extract_idx = [collect(x:x+(r-i)) for (i, x) in enumerate(xsq_idx[1:r])] idx = Int.(reduce(vcat, extract_idx)) return F[1:r, idx] elseif r <= 0 || N < r error("Incorrect dimensions for extraction") else return F end end """ insertF(Fi::Union{SparseMatrixCSC,VecOrMat}, N::Int) β†’ F Inserting values into the `F` matrix for higher dimensions ## Arguments - `Fi`: F matrix to insert - `N`: the larger order ## Returns - inserted `F` matrix """ function insert2F(Fi, N) F = spzeros(N, Int(N * (N + 1) / 2)) Ni = size(Fi, 1) xsq_idx = [1 + (N + 1) * (n - 1) - n * (n - 1) / 2 for n in 1:N] insert_idx = [collect(x:x+(Ni-i)) for (i, x) in enumerate(xsq_idx[1:Ni])] idx = Int.(reduce(vcat, insert_idx)) F[1:Ni, idx] = Fi return F end """ insert2randF(Fi::Union{SparseMatrixCSC,VecOrMat}, N::Int) β†’ F Inserting values into the `F` matrix for higher dimensions ## Arguments - `Fi`: F matrix to insert - `N`: the larger order ## Returns - inserted `F` matrix """ function insert2randF(Fi, N) F = sprandn(N, Int(N * (N + 1) / 2), 0.8) Ni = size(Fi, 1) xsq_idx = [1 + (N + 1) * (n - 1) - n * (n - 1) / 2 for n in 1:N] insert_idx = [collect(x:x+(Ni-i)) for (i, x) in enumerate(xsq_idx[1:Ni])] idx = Int.(reduce(vcat, insert_idx)) F[1:Ni, idx] = Fi return F end """ extractH(H::Union{SparseMatrixCSC,VecOrMat}, r::Int) β†’ H Extracting the `H` matrix for POD basis of dimensions `(N, r)` ## Arguments - `H`: H matrix - `r`: reduced order ## Returns - extracted `H` matrix """ function extractH(H, r) N = size(H, 1) if 0 < r < N tmp = [(N*i-N+1):(N*i-N+r) for i in 1:r] idx = Int.(reduce(vcat, tmp)) return H[1:r, idx] elseif r <= 0 || N < r error("Incorrect dimensions for extraction.") else return H end end """ insertH(Hi::Union{SparseMatrixCSC,VecOrMat}, N::Int) β†’ H Inserting values into the `H` matrix for higher dimensions ## Arguments - `Hi`: H matrix to insert - `N`: the larger order ## Returns - inserted `H` matrix """ function insert2H(Hi, N) H = spzeros(N, Int(N^2)) Ni = size(Hi, 1) tmp = [(N*i-N+1):(N*i-N+Ni) for i in 1:Ni] idx = Int.(reduce(vcat, tmp)) H[1:Ni, idx] = Hi return H end """ insert2bilin(X::Union{SparseMatrixCSC,VecOrMat}, N::Int, p::Int) β†’ BL Inserting the values into the bilinear matrix (`N`) for higher dimensions ## Arguments - `X`: bilinear matrix to insert - `N`: the larger order ## Returns - Inserted bilinear matrix """ function insert2bilin(X, N, p) Ni = size(X, 1) BL = zeros(N, N*p) for i in 1:p idx = (i-1)*N+1 BL[1:Ni, idx:(idx+Ni-1)] = X[:, (i-1)*Ni+1:i*Ni] end return BL end """ Q2H(Q::AbstractArray) β†’ H Convert the quadratic `Q` operator into the `H` operator. The `Q` matrix is a 3-dim tensor with dimensions `(n x n x n)`. Thus, ```math \\mathbf{Q} = \\begin{bmatrix} \\mathbf{Q}_1 \\\\ \\mathbf{Q}_2 \\\\ \\vdots \\\\ \\mathbf{Q}_n \\end{bmatrix} \\quad \\text{where }~~ \\mathbf{Q}_i \\in \\mathbb{R}^{n \\times n} ``` ## Arguments - `Q::AbstractArray`: Quadratic matrix in the 3-dim tensor form with dimensions `(n x n x n)` ## Returns - the `H` quadratic matrix """ function Q2H(Q::AbstractArray) # The Q matrix should be a 3-dim tensor with dim n n = size(Q, 1) # Preallocate the sparse matrix of H H = spzeros(n, n^2) for i in 1:n H[i, :] = vec(Q[:, :, i]) end return H end """ H2Q(H::AbstractArray) β†’ Q Convert the quadratic `H` operator into the `Q` operator ## Arguments - `H::AbstractArray`: Quadratic matrix of dimensions `(n x n^2)` ## Returns - the `Q` quadratic matrix of 3-dim tensor """ function H2Q(H::AbstractArray) # The Q matrix should be a 3-dim tensor with dim n n = size(H, 1) # Preallocate the sparse matrix of H Q = Array{Float64}(undef, n, n, n) for i in 1:n Q[:,:,i] = reshape(H[i, :], n, n) end return Q end """ makeIdentityCubicOp(n::Int, which_cubic_term::Union{String,Char}="G") β†’ G or E Helper function to construct the identity cubic operator. ## Arguments - `n::Int`: dimension of the cubic operator - `which_cubic_term::Union{String,Char}="G"`: which cubic term to construct "G" or "E" ## Returns - the identity cubic operator """ function makeIdentityCubicOp(n::Int; which_cubic_term::Union{String,Char}="G") # Create the index and value tuples inds = [] vals = [] for i in 1:n # Cubic term push!(inds, (i,i,i,i)) push!(vals, 1.0) for j in 1:n if i != j # Quadratic term times linear term push!(inds, (j,j,i,i)) push!(vals, 0.5) end end end S = zeros(n, n, n, n) for (ind,val) in zip(inds, vals) i, j, k, l = ind if i == j == k S[ind...] = val elseif (i == j) && (j != k) S[i,j,k,l] = val/3 S[i,k,j,l] = val/3 S[k,i,j,l] = val/3 elseif (i != j) && (j == k) S[i,j,k,l] = val/3 S[j,i,k,l] = val/3 S[j,k,i,l] = val/3 elseif (i == k) && (j != k) S[i,j,k,l] = val/3 S[j,i,k,l] = val/3 S[i,k,j,l] = val/3 else S[i,j,k,l] = val/6 S[i,k,j,l] = val/6 S[j,i,k,l] = val/6 S[j,k,i,l] = val/6 S[k,i,j,l] = val/6 S[k,j,i,l] = val/6 end end G = zeros(n, n^3) for i in 1:n G[i, :] = vec(S[:, :, :, i]) end if which_cubic_term == "G" || which_cubic_term == 'G' return G elseif which_cubic_term == "E" || which_cubic_term == 'E' return eliminate(G,3) else error("The cubic term must be either G or E.") end end
UniqueKronecker
https://github.com/smallpondtom/UniqueKronecker.jl.git
[ "MIT" ]
0.1.0
6e0e59cf030ff08603780c7595a52748e1e68014
code
14661
export dupmat, symmtzrmat, elimat, commat, eliminate, duplicate, duplicate_symmetric export makePolyOp export kron_snapshot_matrix, unique_kron_snapshot_matrix """ dupmat(n::Int, p::Int) -> Dp::SparseMatrixCSC{Int} Create a duplication matrix of order `p` for a vector of length `n` [MagnusEML1980](@citet). ## Arguments - `n::Int`: The length of the vector. - `p::Int`: The order of the duplication matrix, e.g., `p = 2` for x βŠ— x. ## Output - `Dp::SparseMatrixCSC{Int}`: The duplication matrix of order `p`. ## Example ```julia-repl julia> dupmat(2,2) 4Γ—3 SparseMatrixCSC{Int64, Int64} with 4 stored entries: 1 β‹… β‹… β‹… 1 β‹… β‹… 1 β‹… β‹… β‹… 1 ``` """ function dupmat(n::Int, p::Int) if p == 2 # fast algorithm for quadratic case m = n * (n + 1) / 2 nsq = n^2 r = 1 a = 1 v = zeros(nsq) cn = cumsum(n:-1:2) for i = 1:n v[r:(r+i-2)] = (i - n) .+ cn[1:(i-1)] r = r + i - 1 v[r:r+n-i] = a:a.+(n-i) r = r + n - i + 1 a = a + n - i + 1 end D = sparse(1:nsq, v, ones(length(v)), nsq, m) return D else # general algorithm for any order p # Calculate the number of unique elements in a symmetric tensor of order p num_unique_elements = binomial(n + p - 1, p) # Create the duplication matrix with appropriate size Dp = spzeros(Int, n^p, num_unique_elements) function elements!(D, l, indices) perms = unique([sum((indices[Οƒ[i]] - 1) * n^(p - i) for i in 1:p) + 1 for Οƒ in permutations(1:p)]) @inbounds for p in perms D[p, l] = 1 end end elements!(D, l, indices...) = elements!(D, l, indices) # function generate_nonredundant_combinations(n::Int, p::Int) # if p == 1 # return [[i] for i in 1:n] # else # lower_combs = generate_nonredundant_combinations(n, p - 1) # return [vcat(comb, [i]) for comb in lower_combs for i in comb[end]:n] # end # end # Generate all combinations (i1, i2, ..., ip) with i1 ≀ i2 ≀ ... ≀ ip # combs = generate_nonredundant_combinations(n, p) combs = with_replacement_combinations(1:n, p) combs = reduce(hcat, combs) combs = Vector{eltype(combs)}[eachrow(combs)...] # # Fill in the duplication matrix using the computed combinations elements!.(Ref(Dp), 1:num_unique_elements, combs...) return Dp end end """ symmtzrmat(n::Int, p::Int) -> Sp::SparseMatrixCSC{Float64} Create a symmetrizer matrix of order `p` for a vector of length `n` [MagnusEML1980](@citet). ## Arguments - `n::Int`: The length of the vector. - `p::Int`: The order of the symmetrizer matrix, e.g., `p = 2` for x βŠ— x. ## Output - `Sp::SparseMatrixCSC{Float64}`: The symmetrizer matrix of order `p`. ## Example ```julia-repl julia> symmtzrmat(2,2) 4Γ—4 SparseMatrixCSC{Float64, Int64} with 6 stored entries: 1.0 β‹… β‹… β‹… β‹… 0.5 0.5 β‹… β‹… 0.5 0.5 β‹… β‹… β‹… β‹… 1.0 ``` """ function symmtzrmat(n::Int, p::Int) if p == 2 # fast algorithm for quadratic case np = n^p return 0.5 * (sparse(1.0I, np, np) + commat(n, n)) else # Create the symmetrizer matrix with appropriate size np = Int(n^p) Sp = spzeros(Float64, np, np) function elements!(N, l, indices) perms = [sum((indices[Οƒ[i]] - 1) * n^(p - i) for i in 1:p) + 1 for Οƒ in permutations(1:p)] # For cases where two or all indices are the same, # we should not count permutations more than once. unique_perms = countmap(perms) # Assign the column to the matrix N @inbounds for (perm, count) in unique_perms N[perm, l] = count / factorial(p) end end elements!(N, l, indices...) = elements!(N, l, indices) function generate_redundant_combinations(n::Int, p::Int) iterators = ntuple(_ -> 1:n, p) return [collect(product) for product in Iterators.product(iterators...)] end # Generate all combinations (i1, i2, ..., ip) with i1 ≀ i2 ≀ ... ≀ ip combs = generate_redundant_combinations(n, p) combs = reduce(hcat, combs) combs = Vector{eltype(combs)}[eachrow(combs)...] # Fill in the duplication matrix using the computed combinations elements!.(Ref(Sp), 1:np, combs...) return Sp end end """ elimat(n::Int, p::Int) -> Lp::SparseMatrixCSC{Int} Create an elimination matrix of order `p` for a vector of length `n` [MagnusEML1980](@citet). ## Arguments - `n::Int`: The length of the vector. - `p::Int`: The order of the elimination matrix, e.g., `p = 2` for x βŠ— x. ## Output - `Lp::SparseMatrixCSC{Int}`: The elimination matrix of order `p`. ## Example ```julia-repl julia> elimat(2,2) 3Γ—4 SparseMatrixCSC{Int64, Int64} with 3 stored entries: 1 β‹… β‹… β‹… β‹… 1 β‹… β‹… β‹… β‹… β‹… 1 ``` """ function elimat(n::Int, p::Int) if p == 2 # fast algorithm for quadratic case T = tril(ones(n, n)) # Lower triangle of 1's f = findall(x -> x == 1, T[:]) # Get linear indexes of 1's k = n * (n + 1) / 2 # Row size of L n2 = n * n # Colunm size of L x = f + n2 * (0:k-1) # Linear indexes of the 1's within L' row = [mod(a, n2) != 0 ? mod(a, n2) : n2 for a in x] col = [mod(a, n2) != 0 ? div(a, n2) + 1 : div(a, n2) for a in x] L = sparse(row, col, ones(length(x)), n2, k) L = L' # Now transpose to actual L return L else # general algorithm for any order p # Calculate the number of rows in L num_rows = binomial(n + p - 1, p) # Initialize the output matrix L Lp = spzeros(Int, num_rows, n^p) # Generate all combinations with repetition of n elements from {1, 2, ..., n} combs = with_replacement_combinations(1:n, p) # Fill the matrix L for (l, comb) in enumerate(combs) v = [1] # Start with a scalar 1 @inbounds for d in 1:p e = collect(1:n .== comb[d]) # Create the indicator vector v = v βŠ— e # Build the Kronecker product end Lp[l, :] = v # Assign the row end return Lp end end """ commat(m::Int, n::Int) β†’ K Create commutation matrix `K` of dimension `m x n` [MagnusEML1980](@citet). ## Arguments - `m::Int`: row dimension of the commutation matrix - `n::Int`: column dimension of the commutation matrix ## Returns - `K`: commutation matrix ## Example ```julia-repl julia> commat(2,2) 4Γ—4 SparseMatrixCSC{Float64, Int64} with 4 stored entries: 1.0 β‹… β‹… β‹… β‹… β‹… 1.0 β‹… β‹… 1.0 β‹… β‹… β‹… β‹… β‹… 1.0 ``` """ function commat(m::Int, n::Int) mn = Int(m * n) A = reshape(1:mn, m, n) v = vec(A') K = sparse(1.0I, mn, mn) K = K[v, :] return K end """ commat(m::Int) β†’ K Dispatch for the commutation matrix of dimensions (m, m) ## Arguments - `m::Int`: row and column dimension of the commutation matrix ## Returns - `K`: commutation matrix """ commat(m::Int) = commat(m, m) # dispatch """ eliminate(A::AbstractArray, p::Int) Eliminate the redundant polynomial coefficients in the matrix `A` and return the matrix with unique coefficients. ## Arguments - `A::AbstractArray`: A matrix - `p::Int`: The order of the polynomial, e.g., `p = 2` for x βŠ— x. ## Returns - matrix with unique coefficients ## Example ```julia-repl julia> n = 2; P = rand(n,n); P *= P'; p = vec(P) 4-element Vector{Float64}: 0.5085988756090203 0.7704767970682769 0.7704767970682769 1.310279680309927 julia> Q = rand(n,n); Q *= Q'; q = vec(Q) 4-element Vector{Float64}: 0.40940214810208353 0.2295272821417254 0.2295272821417254 0.25503767587483905 julia> A2 = [p'; q'] 2Γ—4 Matrix{Float64}: 0.257622 0.44721 0.0202203 0.247649 1.55077 0.871029 0.958499 0.650717 julia> eliminate(A2, 2) 2Γ—3 Matrix{Float64}: 0.508599 1.54095 1.31028 0.409402 0.459055 0.255038 ``` """ function eliminate(A::AbstractArray, p::Int) n = size(A, 1) Dp = dupmat(n, p) return A * Dp end """ duplicate(A::AbstractArray) Duplicate the redundant polynomial coefficients in the matrix `A` with a unique set of coefficients and return the matrix with redundant coefficients. ## Arguments - `A::AbstractArray`: A matrix - `p::Int`: The order of the polynomial, e.g., `p = 2` for x βŠ— x. ## Returns - matrix with redundant coefficients ## Example ```julia-repl julia> n = 2; P = rand(n,n); P *= P'; p = vec(P) 4-element Vector{Float64}: 0.5085988756090203 0.7704767970682769 0.7704767970682769 1.310279680309927 julia> Q = rand(n,n); Q *= Q'; q = vec(Q) 4-element Vector{Float64}: 0.40940214810208353 0.2295272821417254 0.2295272821417254 0.25503767587483905 julia> A2 = [p'; q'] 2Γ—4 Matrix{Float64}: 0.257622 0.44721 0.0202203 0.247649 1.55077 0.871029 0.958499 0.650717 julia> D2 = dupmat(2,2) 4Γ—3 SparseMatrixCSC{Int64, Int64} with 4 stored entries: 1 β‹… β‹… β‹… 1 β‹… β‹… 1 β‹… β‹… β‹… 1 julia> A2 * D2 2Γ—3 Matrix{Float64}: 0.508599 1.54095 1.31028 0.409402 0.459055 0.255038 julia> duplicate(A2 * D2, 2) 2Γ—4 Matrix{Float64}: 0.508599 1.54095 0.0 1.31028 0.409402 0.459055 0.0 0.255038 ```` """ function duplicate(A::AbstractArray, p::Int) n = size(A, 1) Lp = elimat(n, p) return A * Lp end """ duplicate_symmetric(A::AbstractArray, p::Int) Duplicate the redundant polynomial coefficients in the matrix `A` with a unique set of coefficients and return the matrix with redundant coefficients which are duplicated symmetrically. This guarantees that the operator is symmetric. The difference from `duplicate` is that we use the elimination matrix `Lp` and the symmetric commutation matrix `Sp` to multiply the `A` matrix. ## Arguments - `A::AbstractArray`: A matrix - `p::Int`: The order of the polynomial, e.g., `p = 2` for x βŠ— x. ## Returns - matrix with redundant coefficients duplicated symmetrically ## Example ```julia-repl julia> n = 2; P = rand(n,n); P *= P'; p = vec(P) 4-element Vector{Float64}: 0.5085988756090203 0.7704767970682769 0.7704767970682769 1.310279680309927 julia> Q = rand(n,n); Q *= Q'; q = vec(Q) 4-element Vector{Float64}: 0.40940214810208353 0.2295272821417254 0.2295272821417254 0.25503767587483905 julia> A2 = [p'; q'] 2Γ—4 Matrix{Float64}: 0.257622 0.44721 0.0202203 0.247649 1.55077 0.871029 0.958499 0.650717 julia> D2 = dupmat(2,2) 4Γ—3 SparseMatrixCSC{Int64, Int64} with 4 stored entries: 1 β‹… β‹… β‹… 1 β‹… β‹… 1 β‹… β‹… β‹… 1 julia> A2 * D2 2Γ—3 Matrix{Float64}: 0.508599 1.54095 1.31028 0.409402 0.459055 0.255038 julia> duplicate_symmetric(A2 * D2, 2) 2Γ—4 Matrix{Float64}: 0.508599 0.770477 0.770477 1.31028 0.409402 0.229527 0.229527 0.255038 ```` """ function duplicate_symmetric(A::AbstractArray, p::Int) n = size(A, 1) Lp = elimat(n, p) Sp = symmtzrmat(n, p) return A * Lp * Sp end """ makePolyOp(n::Int, inds::AbstractArray{<:NTuple{P,<:Int}}, vals::AbstractArray{<:Real}; nonredundant::Bool=true, symmetric::Bool=true) where P Helper function to construct the polynomial operator from the indices and values. The indices must be a 1-dimensional array of, e.g., tuples of the form `(i,j)` where `i,j` are the indices of the polynomial term. For example, for the polynomial term ``2.5x_1x_2`` for ``\\dot{x}_3`` would have an index of `(1,2,3)` with a value of `2.5`. The `nonredundant` argument specifies which polynomial operator to construct (the redundant or non-redundant operator). Note that the values must be a 1-dimensional array of the same length as the indices. The `symmetric` argument specifies whether to construct the operator with symmetric coefficients. ## Arguments - `n::Int`: dimension of the polynomial operator - `inds::AbstractArray{<:NTuple{P,<:Int}}`: indices of the polynomial term - `vals::AbstractArray{<:Real}`: values of the polynomial term - `nonredundant::Bool=true`: whether to construct the non-redundant operator - `symmetric::Bool=true`: whether to construct the symmetric operator ## Returns - the polynomial operator """ function makePolyOp(n::Int, inds::AbstractArray{<:NTuple{P,<:Int}}, vals::AbstractArray{<:Real}; nonredundant::Bool=true, symmetric::Bool=true) where P p = P - 1 @assert length(inds) == length(vals) "The length of indices and values must be the same." # Initialize a p-order tensor of size n^p S = zeros(ntuple(_ -> n, p+1)) # Iterate over indices and assign values considering symmetry for (ind, val) in zip(inds, vals) if symmetric element_idx = ind[1:end-1] last_idx = ind[end] perms = unique(permutations(element_idx)) contribution = val / length(perms) for perm in perms S[perm...,last_idx] = contribution end else S[ind...] = val end end # Flatten the p-order tensor into a matrix form with non-unique coefficients A = spzeros(n, n^p) for i in 1:n A[i, :] = vec(S[ntuple(_ -> :, p)..., i]) end if nonredundant return eliminate(A, p) else return A end end """ kron_snapshot_matrix(Xmat::AbstractArray{T}, p::Int) where {T<:Number} Take the `p`-order Kronecker product of each state of the snapshot matrix `Xmat`. ## Arguments - `Xmat::AbstractArray{T}`: state snapshot matrix - `p::Int`: order of the Kronecker product ## Returns - kronecker product state snapshot matrix """ function kron_snapshot_matrix(Xmat::AbstractArray{T}, p::Int) where {T<:Number} function kron_timestep(x) return x[:,:] βŠ— p # x has to be AbstractMatrix (Kronecker.jl) end tmp = kron_timestep.(eachcol(Xmat)) return reduce(hcat, tmp) end """ unique_kron_snapshot_matrix(Xmat::AbstractArray{T}, p::Int) where {T<:Number} Take the `p`-order unique Kronecker product of each state of the snapshot matrix `Xmat`. ## Arguments - `Xmat::AbstractArray{T}`: state snapshot matrix - `p::Int`: order of the Kronecker product ## Returns - unique kronecker product state snapshot matrix """ function unique_kron_snapshot_matrix(Xmat::AbstractArray{T}, p::Int) where {T<:Number} function unique_kron_timestep(x) return ⊘(x, p) end tmp = unique_kron_timestep.(eachcol(Xmat)) return reduce(hcat, tmp) end
UniqueKronecker
https://github.com/smallpondtom/UniqueKronecker.jl.git
[ "MIT" ]
0.1.0
6e0e59cf030ff08603780c7595a52748e1e68014
code
7414
export unique_kronecker, ⊘ """ CombinationIterator(n::Int, p::Int) Iterator for generating all combinations with repetition of `n` elements from {1, 2, ..., n}. ## Fields - `n::Int`: number of elements - `p::Int`: number of elements in each combination """ struct UniqueCombinationIterator n::Int p::Int end """ Base.iterate(it::UniqueCombinationIterator, comb::Vector{Int}) Iterate over all combinations with repetition of `n` elements from {1, 2, ..., n}. """ function Base.iterate(it::UniqueCombinationIterator, comb::Vector{Int}) p = it.p n = it.n # Find the rightmost element that can be incremented i = p while i > 0 if comb[i] < n comb[i] += 1 # Fill subsequent positions with the incremented value to # maintain non-decreasing order for j in i+1:p comb[j] = comb[i] end return comb, comb end i -= 1 end # Termination: if we can't increment, we stop return nothing end function Base.iterate(it::UniqueCombinationIterator) # Start with the first combination [1, 1, ..., 1] comb = ones(Int, it.p) return comb, comb end Base.length(it::UniqueCombinationIterator) = binomial(it.n + it.p - 1, it.p) Base.eltype(it::UniqueCombinationIterator) = Vector{Int} Base.IteratorSize(::UniqueCombinationIterator) = Base.SizeUnknown() """ unique_kronecker(x::AbstractVector{T}, y::AbstractVector{T}) where T Unique Kronecker product operation. For example, if ```math x = y = \\begin{bmatrix} 1 \\\\ 2 \\end{bmatrix} ``` then ```math \\mathrm{unique_kronecker}(x, x) = \\begin{bmatrix} 1 \\\\ 2 \\\\ 4 \\end{bmatrix} ``` ## Arguments - `x::AbstractVector{T}`: vector to perform the unique Kronecker product - `y::AbstractVector{T}`: vector to perform the unique Kronecker product ## Returns - `result`: unique Kronecker product ## Note This implementation is faster than `unique_kronecker_power` for `p = 2`. """ @inline function unique_kronecker(x::AbstractArray{T}, y::AbstractArray{T}) where {T} n = length(x) m = length(y) result = Array{T}(undef, n*(n+1) ÷ 2) k = 1 @inbounds for i in 1:n for j in i:m result[k] = x[i] * y[j] k += 1 end end return result end """ unique_kronecker(x::AbstractVector{T}, y::AbstractVector{T}, z::AbstractVector{T}) where T Unique Kronecker product operation for triple Kronecker product. ## Arguments - `x::AbstractVector{T}`: vector to perform the unique Kronecker product - `y::AbstractVector{T}`: vector to perform the unique Kronecker product - `z::AbstractVector{T}`: vector to perform the unique Kronecker product ## Returns - `result`: unique Kronecker product ## Note This implementation is faster than `unique_kronecker_power` for `p = 3`. """ @inline function unique_kronecker(x::AbstractArray{T}, y::AbstractArray{T}, z::AbstractArray{T}) where {T} n = length(x) result = Array{T}(undef, n*(n+1)*(n+2) ÷ 6) l = 1 @inbounds for i in 1:n for j in i:n for k in j:n result[l] = x[i] * y[j] * z[k] l += 1 end end end return result end """ unique_kronecker(x::AbstractVector{T}, y::AbstractVector{T}, z::AbstractVector{T}, w::AbstractVector{T}) where T Unique Kronecker product operation for quadruple Kronecker product. ## Arguments - `x::AbstractVector{T}`: vector to perform the unique Kronecker product - `y::AbstractVector{T}`: vector to perform the unique Kronecker product - `z::AbstractVector{T}`: vector to perform the unique Kronecker product - `w::AbstractVector{T}`: vector to perform the unique Kronecker product ## Returns - `result`: unique Kronecker product ## Note This implementation is faster than `unique_kronecker_power` for `p = 4`. """ @inline function unique_kronecker(x::AbstractArray{T}, y::AbstractArray{T}, z::AbstractArray{T}, w::AbstractArray{T}) where {T} n = length(x) result = Array{T}(undef, n*(n+1)*(n+2)*(n+3) ÷ 24) d = 1 @inbounds for i in 1:n for j in i:n for k in j:n for l in k:n result[d] = x[i] * y[j] * z[k] * w[l] d += 1 end end end end return result end # """ # unique_kronecker(x::AbstractVector{T}) where T # Unique Kronecker product operation (dispatch) # ## Arguments # - `x::AbstractVector{T}`: vector to perform the unique Kronecker product # ## Returns # - `result`: unique Kronecker product # """ # @inline function unique_kronecker(x::AbstractArray{T}) where {T} # n = length(x) # result = Array{T}(undef, n*(n+1) ÷ 2) # k = 1 # @inbounds for i in 1:n # for j in i:n # result[k] = x[i] * x[j] # k += 1 # end # end # return result # end """ unique_kronecker_power(x::AbstractArray{T}, p::Int) where T Unique Kronecker product operation generalized for power `p`. ## Arguments - `x::Union{T,AbstractArray{T}}`: vector (or scalar) to perform the unique Kronecker product - `p::Int`: power of the unique Kronecker product ## Returns - `result`: unique Kronecker product """ @inline function unique_kronecker_power(x::Union{T,AbstractArray{T}}, p::Int) where {T<:Number} n = length(x) if n == 1 # If x is a scalar return x^p end # Calculate the correct number of unique elements num_unique_elements = binomial(n + p - 1, p) result = Array{T}(undef, num_unique_elements) idx = 1 @inbounds for comb in UniqueCombinationIterator(n, p) product = one(T) @simd for j in comb product *= x[j] end result[idx] = product idx += 1 end if idx != num_unique_elements + 1 error("Mismatch in expected and actual number of elements filled") end return result end """ ⊘(x::AbstractVector{T}, y::AbstractVector{T}) where T Unique Kronecker product operation ## Arguments - `x::AbstractVector{T}`: vector to perform the unique Kronecker product - `y::AbstractVector{T}`: vector to perform the unique Kronecker product ## Returns - unique Kronecker product """ ⊘(x::AbstractArray{T}, y::AbstractArray{T}) where {T} = unique_kronecker(x, y) ⊘(x::AbstractArray{T}, y::AbstractArray{T}, z::AbstractArray{T}) where {T} = unique_kronecker(x,y,z) ⊘(x::AbstractArray{T}, y::AbstractArray{T}, z::AbstractArray{T}, w::AbstractArray{T}) where {T} = unique_kronecker(x,y,z,w) # Scalars unique_kronecker(x::Number, y::Number) = x * y unique_kronecker(x::Number, y::Number, z::Number) = x * y * z unique_kronecker(x::Number, y::Number, z::Number, w::Number) = x * y * z * w ⊘(x::Number, y::Number, z::Number) = unique_kronecker(x, y, z) ⊘(x::Number, y::Number, z::Number, w::Number) = unique_kronecker(x, y, z, w) """ ⊘(x::AbstractArray{T}...) where {T<:Number} Generalized Kronecker product operator for multiple vectors. ## Arguments - `x::AbstractArray{T}...`: one or more vectors to perform the unique Kronecker product ## Returns - unique Kronecker product of all vectors """ ⊘(x::AbstractArray{T}, p::Int) where {T<:Number} = p == 1 ? x : p == 2 ? unique_kronecker(x, x) : p == 3 ? unique_kronecker(x, x, x) : p == 4 ? unique_kronecker(x, x, x, x) : unique_kronecker_power(x, p)
UniqueKronecker
https://github.com/smallpondtom/UniqueKronecker.jl.git
[ "MIT" ]
0.1.0
6e0e59cf030ff08603780c7595a52748e1e68014
code
1029
""" vech(A::AbstractMatrix{T}) β†’ v Half-vectorization operation. For example half-vectorzation of ```math A = \\begin{bmatrix} a_{11} & a_{12} \\\\ a_{21} & a_{22} \\end{bmatrix} ``` becomes ```math v = \\begin{bmatrix} a_{11} \\\\ a_{21} \\\\ a_{22} \\end{bmatrix} ``` ## Arguments - `A`: matrix to half-vectorize ## Returns - `v`: half-vectorized form """ function vech(A::AbstractMatrix{T}) where {T} m = LinearAlgebra.checksquare(A) v = Vector{T}(undef, (m * (m + 1)) >> 1) k = 0 for j = 1:m, i = j:m @inbounds v[k+=1] = A[i, j] end return v end """ invec(r::AbstractArray, m::Int, n::Int) β†’ r Inverse vectorization. ## Arguments - `r::AbstractArray`: the input vector - `m::Int`: the row dimension - `n::Int`: the column dimension ## Returns - the inverse vectorized matrix """ function invec(r::AbstractArray, m::Int, n::Int)::AbstractArray tmp = sparse(reshape(1.0I(n), 1, :)) return kron(tmp, sparse(1.0I,m,m)) * kron(sparse(1.0I,n,n), r) end
UniqueKronecker
https://github.com/smallpondtom/UniqueKronecker.jl.git
[ "MIT" ]
0.1.0
6e0e59cf030ff08603780c7595a52748e1e68014
code
1612
@testset "circulant Kronecker" begin # Example usage # Two vectors x = [1, 2] y = [3, 4] result_xy = x βŠ› y result_xy2 = circulant_kronecker(x, y) @test result_xy β‰ˆ [6, 10, 10, 16] @test result_xy2 β‰ˆ [6, 10, 10, 16] # Three vectors z = [5, 6] result_xyz = βŠ›(x, y, z) result_xyz2 = circulant_kronecker(x, y, z) @test result_xyz β‰ˆ [45, 68, 68, 100, 68, 100, 100, 144] @test result_xyz2 β‰ˆ [45, 68, 68, 100, 68, 100, 100, 144] # Matrices A = [1 2; 3 4] B = [5 6; 7 8] C = [9 10; 11 12] result_ABC = βŠ›(A, B, C) result_ABC2 = circulant_kronecker(A, B, C) @test result_ABC β‰ˆ [ 135 194 194 268 194 268 268 360 253 312 342 416 342 416 452 544 253 342 312 416 342 452 416 544 431 520 520 624 562 672 672 800 253 342 342 452 312 416 416 544 431 520 562 672 520 624 672 800 431 562 520 672 520 672 624 800 693 824 824 976 824 976 976 1152 ] @test result_ABC2 β‰ˆ [ 135 194 194 268 194 268 268 360 253 312 342 416 342 416 452 544 253 342 312 416 342 452 416 544 431 520 520 624 562 672 672 800 253 342 342 452 312 416 416 544 431 520 562 672 520 624 672 800 431 562 520 672 520 672 624 800 693 824 824 976 824 976 976 1152 ] x = [1,2] y = [3,4] z = [5,6] w = [7,8] result_xyzw = circulant_kronecker(x, y, z, w) @test size(result_xyzw) == (16,1) end
UniqueKronecker
https://github.com/smallpondtom/UniqueKronecker.jl.git
[ "MIT" ]
0.1.0
6e0e59cf030ff08603780c7595a52748e1e68014
code
1517
@testset "Quadratic matrix conversion" begin # Settings for the KS equation N = 4 H = zeros(N, N^2) for i in 1:N x = rand(N) H[i, :] = x βŠ— x end F = UniqueKronecker.eliminate(H, 2) @test all(F .== UniqueKronecker.eliminate(UniqueKronecker.duplicate(F, 2), 2)) @test all(F .== UniqueKronecker.eliminate(UniqueKronecker.duplicate_symmetric(F, 2), 2)) H = UniqueKronecker.duplicate(F,2) Q = UniqueKronecker.H2Q(H) Hnew = Matrix(UniqueKronecker.Q2H(Q)) @test all(H .== Hnew) end @testset "3rd order matrix conversions" begin for n in [2, 3, 4, 5, 6, 10] x = 1:n # Julia creates Double by default x3e = zeros(Int, div(n*(n+1)*(n+2), 6)) l = 1 for i = 1:n for j = i:n for k = j:n x3e[l] = x[i] * x[j] * x[k] l += 1 end end end L = UniqueKronecker.elimat(n, 3) x3 = (x βŠ— x βŠ— x) x3e_2 = L * x3 @test all(x3e_2 .== x3e) D = UniqueKronecker.dupmat(n, 3) x3_2 = D * x3e @test all(x3_2 .== x3) G = zeros(n, n^3) for i = 1:n y = rand(n) G[i, :] = y βŠ— y βŠ— y end E = UniqueKronecker.eliminate(G, 3) @test E * x3e β‰ˆ G * x3 Gs = UniqueKronecker.duplicate_symmetric(E, 3) @test Gs * x3 β‰ˆ G * x3 G2 = UniqueKronecker.duplicate(E, 3) @test G2 * x3_2 β‰ˆ G * x3 end end
UniqueKronecker
https://github.com/smallpondtom/UniqueKronecker.jl.git
[ "MIT" ]
0.1.0
6e0e59cf030ff08603780c7595a52748e1e68014
code
494
@testset "Making polynomial operator" begin idx = [(1, 1, 1), (1, 1, 2)] val = [1.0, 2.0] H = UniqueKronecker.makeQuadOp(3, idx, val, which_quad_term="H", symmetric=true) F = UniqueKronecker.makeQuadOp(3, idx, val, which_quad_term="F", symmetric=false) A2 = UniqueKronecker.makePolyOp(3, idx, val, nonredundant=false, symmetric=true) A2u = UniqueKronecker.makePolyOp(3, idx, val, nonredundant=true, symmetric=false) @test all(H .== A2) @test all(F .== A2u) end
UniqueKronecker
https://github.com/smallpondtom/UniqueKronecker.jl.git
[ "MIT" ]
0.1.0
6e0e59cf030ff08603780c7595a52748e1e68014
code
2392
@testset "Run legacy code 1" begin H = [ 0.0 1.0 0.0 0.0 1.0 0.0 0.0 0.0 1.0 0.0 0.0 1.0 0.0 1.0 0.0 0.0 0.0 1.0 1.0 0.0 0.0 0.0 1.0 1.0 0.0 0.0 0.0 ] H2 = UniqueKronecker.insert2H(H, 4) H2test = [ 0.0 1.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 1.0 1.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 ] @test all(H2 .== H2test) @test all(H .== UniqueKronecker.extractH(H2, 3)) F = UniqueKronecker.eliminate(H, 2) F2 = UniqueKronecker.insert2F(F, 4) F2test = [ 0.0 1.0 0.0 0.0 1.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 1.0 0.0 1.0 0.0 0.0 1.0 0.0 0.0 1.0 0.0 0.0 0.0 1.0 1.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 ] @test all(F2 .== F2test) @test all(F .== UniqueKronecker.extractF(F2, 3)) end @testset "Run legacy code 2" begin n, j, k = 4, 2, 3 X = rand(2,2) BL = UniqueKronecker.insert2bilin(X, 3, 1) idx = [(1, 1, 1), (1, 1, 2)] val = [1.0, 2.0] H = UniqueKronecker.makeQuadOp(3, idx, val, which_quad_term="H", symmetric=true) F = UniqueKronecker.makeQuadOp(3, idx, val, which_quad_term="F", symmetric=false) Q = UniqueKronecker.makeQuadOp(3, idx, val, which_quad_term="Q", symmetric=false) @test all(H .== UniqueKronecker.duplicate_symmetric(F, 2)) @test all(H .== UniqueKronecker.Q2H(Q)) idx = [(2, 1, 1, 1), (1, 1, 3, 2), (1, 2, 3, 1), (1, 2, 1, 3)] val = [1.0, 2.0, -1.0, 2.0] G = UniqueKronecker.makeCubicOp(3, idx, val, which_cubic_term="G", symmetric=true) E = UniqueKronecker.makeCubicOp(3, idx, val, which_cubic_term="E", symmetric=false) @test all(G .== UniqueKronecker.duplicate_symmetric(E, 3)) G = UniqueKronecker.makeIdentityCubicOp(3, which_cubic_term="G") E = UniqueKronecker.makeIdentityCubicOp(3, which_cubic_term="E") @test size(G) == (3, 27) @test size(E) == (3, 10) G = UniqueKronecker.makeIdentityCubicOp(4, which_cubic_term="G") E = UniqueKronecker.makeIdentityCubicOp(4, which_cubic_term="E") @test size(G) == (4, 64) @test size(E) == (4, 20) end
UniqueKronecker
https://github.com/smallpondtom/UniqueKronecker.jl.git
[ "MIT" ]
0.1.0
6e0e59cf030ff08603780c7595a52748e1e68014
code
600
using UniqueKronecker using Test using Kronecker using Random function testfile(file, testname=defaultname(file)) println("running test file $(file)") @testset "$testname" begin; include(file); end return end defaultname(file) = uppercasefirst(replace(splitext(basename(file))[1], '_' => ' ')) @testset "UniqueKronecker" begin testfile("unique_kronecker.jl") testfile("circulant_kronecker.jl") testfile("special_matrices.jl") testfile("create_poly.jl") testfile("conversion.jl") testfile("snapshot.jl") testfile("vectorize.jl") testfile("legacy.jl") end
UniqueKronecker
https://github.com/smallpondtom/UniqueKronecker.jl.git
[ "MIT" ]
0.1.0
6e0e59cf030ff08603780c7595a52748e1e68014
code
558
@testset "Creating polynomial snapshot matrices" begin n = 3 K = 10 X = rand(n, K) X2 = kron_snapshot_matrix(X, 2) X2u = unique_kron_snapshot_matrix(X, 2) @test all(elimat(n,2) * X2 .== X2u) end @testset "Circulant Kronecker snapshot matrix" begin X1 = [1 2; 3 4] X2 = [5 6; 7 8] X3 = [9 10; 11 12] X = circulant_kron_snapshot_matrix(X1, X2, X3) for i in 1:2 x1 = X1[:,i] x2 = X2[:,i] x3 = X3[:,i] x = circulant_kronecker(x1, x2, x3) @test X[:,i] == vec(x) end end
UniqueKronecker
https://github.com/smallpondtom/UniqueKronecker.jl.git
[ "MIT" ]
0.1.0
6e0e59cf030ff08603780c7595a52748e1e68014
code
609
@testset "Duplication Matrix" begin n = 2 D = UniqueKronecker.dupmat(n, 2) @test all(D .== [1 0 0; 0 1 0; 0 1 0; 0 0 1]) end @testset "Elimination Matrix" begin n = 2 L = UniqueKronecker.elimat(n, 2) @test all(L .== [1 0 0 0; 0 1 0 0; 0 0 0 1]) end @testset "Symmetric Elimination Matrix" begin n = 2 L = UniqueKronecker.elimat(n, 2) * UniqueKronecker.symmtzrmat(n, 2) @test all(L .== [1 0 0 0; 0 0.5 0.5 0; 0 0 0 1]) end @testset "Commutation matrix" begin n = 2 K = UniqueKronecker.commat(n, 2) @test all(K .== [1 0 0 0; 0 0 1 0; 0 1 0 0; 0 0 0 1]) end
UniqueKronecker
https://github.com/smallpondtom/UniqueKronecker.jl.git
[ "MIT" ]
0.1.0
6e0e59cf030ff08603780c7595a52748e1e68014
code
639
@testset "Unique Kronecker" begin n = 2 x = rand(n) y = x βŠ— x z = x ⊘ x @test all(dupmat(n, 2) * z .== y) w = ⊘(x, 3) y = x βŠ— x βŠ— x @test all(dupmat(n, 3) * w β‰ˆ y) x = rand(2) y = unique_kronecker(x,x) z = unique_kronecker(x,x,x) w = unique_kronecker(x,x,x,x) @test all(⊘(x, x) β‰ˆ y) @test all(⊘(x, x, x) β‰ˆ z) @test all(⊘(x, x, x, x) β‰ˆ w) x = rand(3) y = UniqueKronecker.unique_kronecker_power(x,2) @test all(⊘(x, 2) β‰ˆ y) it = UniqueKronecker.UniqueCombinationIterator(3, 2) comb = [1, 1] result, _ = iterate(it, comb) @test result == [1, 2] end
UniqueKronecker
https://github.com/smallpondtom/UniqueKronecker.jl.git
[ "MIT" ]
0.1.0
6e0e59cf030ff08603780c7595a52748e1e68014
code
239
@testset "vech" begin A = [1 2; 3 4] a = [1; 3; 4] @test all(a .== UniqueKronecker.vech(A)) end @testset "inverse vectorization" begin A = [1 2; 3 4] a = vec(A) @test all(A .== UniqueKronecker.invec(a, 2, 2)) end
UniqueKronecker
https://github.com/smallpondtom/UniqueKronecker.jl.git