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" ]
0.4.0
fc6c301b221ae65a75ac85cc7fe1fc52bfd0a338
code
2522
export SpikedWishart, covspikedist struct SpikedWishart <: ContinuousMatrixDistribution beta::Integer n::Integer p::Integer spikes::Array{Float64, 1} scaled::Bool end SpikedWishart(beta, n, p, spikes; scaled=false) = SpikedWishart(beta, n, p, spikes, scaled) SpikedWishart(beta, n, p; scaled=false) = SpikedWishart(beta, n, p, [], scaled) # SAMPLERS function scaling(d::SpikedWishart) d.scaled ? 1/d.n : 1 end function randreduced(d::SpikedWishart) if length(d.spikes) <= 1 return randtridiagonal(d) else return randbanded(d) end end function randtridiagonal(d::SpikedWishart) a = d.beta * d.n/2 # diagonal and superdiagonal of B Bdv = [rand(Chi(2*a - d.beta*k))/sqrt(d.beta) for k in 0:(d.p-1)] Bev = [rand(Chi(d.beta*(d.p-k)))/sqrt(d.beta) for k in 1:(d.p-1)] if length(d.spikes) == 1 Bdv[1] *= sqrt(1 + d.spikes[1]) end # diagonal and off-diagonals of BB' dv = Bdv.^2 + [0; Bev.^2] ev = Bdv[1:end-1] .* Bev SymTridiagonal(dv, ev) * scaling(d) end # Multi-spike version only implemented for beta=1 function randbanded(d::SpikedWishart) @assert d.beta in [1, 2] r = length(d.spikes) if d.beta == 1 U = BandedMatrix{Float64}(undef, (d.p, d.p), (0, r)) elseif d.beta == 2 U = BandedMatrix{Complex{Float64}}(undef, (d.p, d.p), (0, r)) end dv = [rand(Chi(d.beta*(d.n - k + 1)))/sqrt(d.beta) for k in 1:d.p] @. dv[1:r] *= sqrt(1 + d.spikes) U[band(0)] .= dv for k = 1:(r-1) if d.beta == 1 ev = randn(d.p - k) elseif d.beta == 2 ev = (randn(d.p - k) + im * randn(d.p-k))/sqrt(2) end @. ev[1:(r-k)] *= sqrt(1 + d.spikes[(k+1):end]) U[band(k)] .= ev end U[band(r)] .= [rand(Chi(d.beta*(d.p - k)))/sqrt(d.beta) for k in r:(d.p-1)] if d.beta == 1 Symmetric(U' * U) * scaling(d) elseif d.beta == 2 # The conjugate transpose is done like this rather than with ' because # U'U is not automatically a banded matrix Hermitian(transpose(conj(U)) * U) * scaling(d) end end function critspikes(d::SpikedWishart) gamma = d.p/d.n d.spikes[d.spikes .> sqrt(gamma)] end function covspikedist(d::SpikedWishart) gamma = d.p/d.n cspikes = critspikes(d) l = 1 .+ cspikes mu = @. l * (1 + gamma/cspikes) sigma = @. l * sqrt(gamma * 2 * (1 - gamma/cspikes^2)) MvNormal(mu, sigma) end
RandomMatrixDistributions
https://github.com/damian-t-p/RandomMatrixDistributions.jl.git
[ "MIT" ]
0.4.0
fc6c301b221ae65a75ac85cc7fe1fc52bfd0a338
code
578
export MarchenkoPastur struct MarchenkoPastur <: ContinuousUnivariateDistribution gamma::Real MarchenkoPastur(gamma) = 0 < gamma <= 1 ? new(gamma) : error("Gamma must be in (0, 1]") end function minimum(d::MarchenkoPastur) (1 - sqrt(d.gamma))^2 end function maximum(d::MarchenkoPastur) (1 + sqrt(d.gamma))^2 end function pdf(d::MarchenkoPastur, x::Real) lambdamin = minimum(d) lambdamax = maximum(d) if lambdamin < x < lambdamax return sqrt((lambdamax - x) * (x - lambdamin))/(d.gamma * x * 2 * pi) else return 0 end end
RandomMatrixDistributions
https://github.com/damian-t-p/RandomMatrixDistributions.jl.git
[ "MIT" ]
0.4.0
fc6c301b221ae65a75ac85cc7fe1fc52bfd0a338
code
2991
using FastGaussQuadrature using SpecialFunctions using ApproxFun using Interpolations export TracyWidom struct TracyWidom <: ContinuousUnivariateDistribution beta::Integer end function cdf(d::TracyWidom, x::Real) if d.beta == 1 _fredholm_det(_V_airy_kernel, x, 100) elseif d.beta == 2 _fredholm_det(_airy_kernel, x, 100) elseif d.beta == 4 (_fredholm_det(_V_airy_kernel, x * sqrt(2), 100) + _fredholm_det(_V_airy_kernel, x * sqrt(2), 100, -1))/2 else throw(DomainError(d.beta)) end end _TWfs = Dict() function _TWf(x, beta) if !(beta in keys(_TWfs)) dom = Chebyshev(-5..5) D = Derivative(dom) _TWfs[beta] = D * Fun(x -> cdf(TracyWidom(beta), x), dom) end _TWfs[beta](x) end function pdf(d::TracyWidom, x::Real) _TWf(x, d.beta) end _TWinvs = Dict() function _TWinv(t, beta) (0 < t < 1) || throw(DomainError(t)) if !(beta in keys(_TWinvs)) # bounds outside which we use limiting representation u = 4 l = -5 # TODO: make a more principled grid using tail behaviour n = 1000 y = range(l, u, length=n) x = cdf.(TracyWidom(beta), y) # Transform limiting ends to maintain differentiability righta = pdf(TracyWidom(beta), u)/(beta * sqrt(u) * exp(-beta * u^(3/2)*2/3)) rightb = x[end] - righta * (1 - exp(-beta * u^(3/2) * 2/3)) lefta = pdf(TracyWidom(beta), l)/(beta * l^2/8 * exp(beta * l^3/24)) leftb = x[1] - lefta * exp(-beta * abs(l)^3/24) itp = interpolate((x,), y, Gridded(Linear())) _TWinvs[beta] = [righta, rightb, x[end], lefta, leftb, x[1], itp] end # TODO: make the indexing less terrible if t > _TWinvs[beta][3] s = (t - _TWinvs[beta][2])/_TWinvs[beta][1] return (log(1/(1 - s)) * 3/(2 * beta))^(2/3) elseif t < _TWinvs[beta][6] s = (t - _TWinvs[beta][5])/_TWinvs[beta][4] return -(log(1/s) * 24/beta)^(1/3) else return _TWinvs[beta][end](t) end end function quantile(d::TracyWidom, q::Real) _TWinv(q, d.beta) end function _phi(s, xi) s + 10 * tan(pi * (xi + 1)/4) end function _Dphi(s, xi) pi * 5/2 * sec(pi * (xi + 1)/4)^2 end """ Transform a kernel on L_2(s, infinity) to one on L_2(-1, 1) """ function _transform_kernel(kernel, s) (x, y) -> sqrt(_Dphi(s, x) * _Dphi(s, y)) * kernel(_phi(s, x), _phi(s, y)) end """ Approximate fredholm determinant of a kernel on (s, infinity) """ function _fredholm_det(kernel, s, N, z=1) (nodes, weights) = gausslegendre(N) trans_kernel = _transform_kernel(kernel, s) M = I - z * sqrt.(weights * weights') .* trans_kernel.(nodes', nodes) det(M) end function _airy_kernel(x, y) if x == y airyaiprime(x)^2 - x * airyai(x)^2 else (airyai(x) * airyaiprime(y) - airyaiprime(x) * airyai(y))/(x - y) end end function _V_airy_kernel(x, y) airyai((x + y)/2)/2 end
RandomMatrixDistributions
https://github.com/damian-t-p/RandomMatrixDistributions.jl.git
[ "MIT" ]
0.4.0
fc6c301b221ae65a75ac85cc7fe1fc52bfd0a338
code
1021
export Wachter """ Wachter Distribution Let Σ<sub>1</sub> be Σ<sub>2</sub> pxp covariance matrices of n<sub>1</sub> and n<sub>2</sub> standard normal observations respectively. If p/n<sub>1</sub> → γ<sub>1</sub> and p/n<sub>2</sub> → γ<sub>2</sub>, then Σ<sub>1</sub>Σ<sub>2</sub><sup>-1</sup> has a limiting spectral distribution of Wachter(γ<sub>1</sub>, γ<sub>2</sub>). """ struct Wachter <: ContinuousUnivariateDistribution gamma1::Real gamma2::Real Wachter(gamma1, gamma2) = 0 <= gamma2 < 1 ? new(gamma1, gamma2) : error("Gamma2 must be in [0, 1)") end function minimum(d::Wachter) ((1 - sqrt(d.gamma1 + d.gamma2 - d.gamma1 * d.gamma2))/(1 - d.gamma2))^2 end function maximum(d::Wachter) ((1 + sqrt(d.gamma1 + d.gamma2 - d.gamma1 * d.gamma2))/(1 - d.gamma2))^2 end function pdf(d::Wachter, x::Real) a = minimum(d) b = maximum(d) if a < x < b return (1 - d.gamma2) * sqrt((b - x) * (x - a))/(2 * pi * x * (d.gamma1 + d.gamma2 * x)) else return 0 end end
RandomMatrixDistributions
https://github.com/damian-t-p/RandomMatrixDistributions.jl.git
[ "MIT" ]
0.4.0
fc6c301b221ae65a75ac85cc7fe1fc52bfd0a338
code
587
using RandomMatrixDistributions using Test @testset "MarchenkoPastur" begin @test_throws ErrorException MarchenkoPastur(5) dist = MarchenkoPastur(1) @test minimum(dist) == 0 @test maximum(dist) == 4 @test pdf(dist, -1) == pdf(dist, 5) == 0 @test pdf(dist, 2) ≈ 1/(2*pi) end @testset "Wachter" begin @test_throws ErrorException Wachter(10, 10) dist = Wachter(1, 0.5) @test minimum(dist) == 0 @test maximum(dist) == 16 @test pdf(dist, -1) == pdf(dist, 17) == 0 @test pdf(Wachter(0.5, 0), 1) ≈ pdf(MarchenkoPastur(0.5), 1) end
RandomMatrixDistributions
https://github.com/damian-t-p/RandomMatrixDistributions.jl.git
[ "MIT" ]
0.4.0
fc6c301b221ae65a75ac85cc7fe1fc52bfd0a338
code
1183
using RandomMatrixDistributions using Distributions using Test @testset "MatrixSamplers" begin n = 1000 p = 400 γ = p/n # test white Wishart for beta in [1, 4, 8] #println("Testing white Wishart with β = ", beta) λs = randeigvals(SpikedWishart(beta, n, p)) @test length(λs) == p @test eltype(λs) <: Real @test minimum(λs) > 0 #println("Testing Jacobi with β = ", beta) λs = randeigvals(Jacobi(beta, n, n, p)) @test length(λs) == p @test eltype(λs) <: Real @test minimum(λs) > 0 end #println("Testing Spiked Wishart with β = 1") s = 8 W = SpikedWishart(1, n, p, [0.1, 2, 4, s]) λs = randeigvals(W)/n @test length(λs) == p @test eltype(λs) <: Real # Check if the maximum spike is reasonable # This tests can fail in principle, but only with negligible probability #μ = (1 + s) * (1 + γ/s) #σ = (1 + s) * sqrt(γ * 2 * (1 - γ/s^2)) spikedist = covspikedist(W) μ = mean(spikedist)[end] σ = sqrt(var(spikedist)[end]) @test abs(maximum(λs) - μ)/σ < 4 @test all(randeigstat(W, eigmax, 10) .> 0) end
RandomMatrixDistributions
https://github.com/damian-t-p/RandomMatrixDistributions.jl.git
[ "MIT" ]
0.4.0
fc6c301b221ae65a75ac85cc7fe1fc52bfd0a338
code
185
using RandomMatrixDistributions using Random: seed! using Test @testset "RandomMatrixDistributions" begin seed!(1) include("MatrixSamplers.jl") include("Densities.jl") end
RandomMatrixDistributions
https://github.com/damian-t-p/RandomMatrixDistributions.jl.git
[ "MIT" ]
0.4.0
fc6c301b221ae65a75ac85cc7fe1fc52bfd0a338
docs
3056
RandomMatrixDistributions.jl ============================ [![Build Status](https://github.com/damian-t-p/RandomMatrixDistributions.jl/actions/workflows/ci.yml/badge.svg)](https://github.com/damian-t-p/RandomMatrixDistributions.jl/actions?query=workflow) [![codecov](https://codecov.io/gh/damian-t-p/RandomMatrixDistributions.jl/branch/master/graph/badge.svg)](https://codecov.io/gh/damian-t-p/RandomMatrixDistributions.jl) A Julia package containing `Distribution.jl`-type specifications for various distributions arising from random matrix theory. # Currently implemented distributions ## Matrix distributions * `SpikedWigner(beta, n, spikes; scaled=false)`: Wigner distribution with an added rank-*r* matrix with eigenvalues (*s*<sub>1</sub>, ... , *s*<sub>r</sub>) * sqrt(*n*). `spikes` is an array `[s1, ..., sr]` such that the diagonal matrix with diagonal sqrt(n)(*s*<sub>1</sub>, ... , *s*<sub>r</sub>, 0, ..., 0) is added to a white Wigner matrix. * `SpikedWishart(beta, n, p, spikes; scaled=false)`: Wishart distribution with spiked covariance [1] `spikes` is an array `[s1, ..., sr]` such that the Wishart covariance is diagonal with entries 1 + *s*<sub>1</sub>, ... , 1 + *s*<sub>r</sub>, 1, ..., 1. * `Jacobi(beta, n1, n2, p)`: Random matrices of the form *E*(*E*+*H*)<sup>-1</sup>. Here *E* and *H* are (*n*<sub>1</sub>, *p*) and (*n*<sub>2</sub>, *p*) white Wisharts respectively. [2] Specifying `scaled=true` in `SpikedWigner` and `SpikedWishart` scales the matrices by an appropriate function of *n* so that the corresponding bulks converge to the semicircle and Marchenko-Pastur laws respectively. Due to the inverse in the definition of the Jacobi ensemble, no scaling is necessary for `Jacobi`, Normal entries in Gaussian ensembles are scaled to have variance 1. ## Limiting eigenvalue distributions * `MarchenkoPastur(gamma)`: Limiting empirical spectral density of a real white Wishart matrix with *p*/*n* -> *gamma* as long as 0 < *gamma* < 1. * `TracyWidom(beta)`: Limiting distribution of the maximum eigenvalue of many random matrix ensembles with Dyson parameter beta. * `Wachter(gamma1, gamma2)`: Limiting empirical spectral density of *S*<sub>1</sub> *S*<sub>2</sub><sup>-1</sup>. Here *S*<sub>1</sub> and *S*<sub>2</sub>$ are sample covariance matrices with *n*<sub>1</sub>/*p* -> *gamma*<sub>1</sub> and *n*<sub>2</sub>/*p* -> *gamma*<sub>2</sub>. # Efficient samplers The function `randeigvals` efficiently samples from the distribution of eigenvalues of the implemented random matrix distributions. It does this by generating a tridiagonal or banded matrix with eigenvalue equal in distribution to the specified model. # Examples An Jupyter notebook demonstrating all of the implemented eigenvalue samplers is provided in `/examples/eigenvalue-simulation.ipynb`. # References [1] Dumitriu & Edelman, Matrix Models for beta ensembles, Journal of Mathematical Physics, (11), (2002). [2] Killip & Nenciu, Matrix Models for Circular Ensembles, International Mathematics Research Notices, 50, (2004).
RandomMatrixDistributions
https://github.com/damian-t-p/RandomMatrixDistributions.jl.git
[ "MIT" ]
0.1.4
9f929d662ab4ca057a58504146bd12cc91b1b6f8
code
5561
# # GridapMakie # # [![Stable](https://img.shields.io/badge/docs-stable-blue.svg)](https://gridap.github.io/GridapMakie.jl/stable) # [![Dev](https://img.shields.io/badge/docs-dev-blue.svg)](https://gridap.github.io/GridapMakie.jl/dev) # [![Build Status](https://github.com/gridap/GridapMakie.jl/workflows/CI/badge.svg?branch=master)](https://github.com/gridap/GridapMakie.jl/actions) # [![Coverage](https://codecov.io/gh/gridap/GridapMakie.jl/branch/master/graph/badge.svg)](https://codecov.io/gh/gridap/GridapMakie.jl) # ## Overview # The visualization of numerical results is an important part of finite element (FE) computations. However, before the inception of GridapMakie.jl, the # only approach available to data visualization of [Gridap.jl](https://github.com/gridap/Gridap.jl) computations was to write simulation # data to data files (e.g., in vtu format) for later visualization with, e.g., Paraview or VisIt. From the idea of visually inspecting # data from Julia code directly or to manipulate it with packages of the Julia # open-source package ecosystem, [GridapMakie.jl](https://github.com/gridap/GridapMakie.jl) is born. As a part of the Google Summer of # Code 2021 program, GridapMakie adopts [Makie.jl](https://github.com/JuliaPlots/Makie.jl) as a second visualization back-end for # Gridap.jl simulations. This package is thought as a built-in tool to assess the user in their FE calculations with a smoother workflow # in a highly intuitive API. # # ## Installation # According to Makie's guidelines, it is enough to install one of its backends, e.g. GLMakie. Additionally, Gridap provides the plot objects # to be visualized and `FileIO` allows to save the figures plotted. # ```julia # julia> ] # pkg> add Gridap, GridapMakie, GLMakie, FileIO # ``` # # ## Examples # First things first, we shall be using the three packages as well as `FileIO`. # We may as well create directories to store downloaded meshes and output files using Gridap, GridapMakie, GLMakie using FileIO mkdir("models") mkdir("images") # ### 2D Plots # Then, let us consider a simple, 2D simplexified cartesian triangulation Ω domain = (0, 1, 0, 1) cell_nums = (10, 10) model = CartesianDiscreteModel(domain, cell_nums) |> simplexify Ω = Triangulation(model) # The visualization of the vertices, edges, and faces of Ω can be achieved as follows fig = plot(Ω) wireframe!(Ω, color=:black, linewidth=2) scatter!(Ω, marker=:star8, markersize=20, color=:blue) save("images/2d_Fig1.png", fig) # <p align="center"> # <img src="_readme/images/2d_Fig1.png" width="500"/> # </p> # We now consider a FE function `uh` constructed with Gridap reffe = ReferenceFE(lagrangian, Float64, 1) V = FESpace(model, reffe) uh = interpolate(x->sin(π*(x[1]+x[2])), V) # and plot it over Ω, adding a colorbar fig, _ , plt = plot(Ω, uh) Colorbar(fig[1,2], plt) save("images/2d_Fig11.png", fig) # <p align="center"> # <img src="_readme/images/2d_Fig11.png" width="500"/> # </p> # On the other hand, we may as well plot cell values celldata = π*rand(num_cells(Ω)) .-1 fig, _ , plt = plot(Ω, color=celldata, colormap=:heat) Colorbar(fig[2,1], plt, vertical=false) save("images/2d_Fig13.png", fig) # <p align="center"> # <img src="_readme/images/2d_Fig13.png" width="500"/> # </p> # If we are only interested in the boundary of Ω, namely Γ Γ = BoundaryTriangulation(model) fig, _ , plt = plot(Γ, uh, colormap=:algae, linewidth=10) Colorbar(fig[1,2], plt) save("images/2d_Fig111.png", fig) # <p align="center"> # <img src="_readme/images/2d_Fig111.png" width="500"/> # </p> # ### 3D Plots # In addition to the 2D plots, GridapMakie is able to handle more complex geometries. For example, # take the mesh from the [first Gridap tutorial](https://gridap.github.io/Tutorials/stable/pages/t001_poisson/#Tutorial-1:-Poisson-equation-1), # which can be downloaded using url = "https://github.com/gridap/GridapMakie.jl/raw/d5d74190e68bd310483fead8a4154235a61815c5/_readme/model.json" download(url,"models/model.json") # Therefore, we may as well visualize such mesh model = DiscreteModelFromFile("models/model.json") Ω = Triangulation(model) ∂Ω = BoundaryTriangulation(model) fig = plot(Ω, shading=true) wireframe!(∂Ω, color=:black) save("images/3d_Fig1.png", fig) # <p align="center"> # <img src="_readme/images/3d_Fig1.png" width="500"/> # </p> v(x) = sin(π*(x[1]+x[2]+x[3])) fig, ax, plt = plot(Ω, v, shading=true) Colorbar(fig[1,2], plt) save("images/3d_Fig2.png", fig) # <p align="center"> # <img src="_readme/images/3d_Fig2.png" width="500"/> # </p> # we can even plot functions in certain subdomains, e.g. Γ = BoundaryTriangulation(model, tags=["square", "triangle", "circle"]) fig = plot(Γ, v, colormap=:rainbow, shading=true) wireframe!(∂Ω, linewidth=0.5, color=:gray) save("images/3d_Fig3.png", fig) # <p align="center"> # <img src="_readme/images/3d_Fig3.png" width="500"/> # </p> # ### Animations and interactivity # Finally, by using Makie [Observables](https://makie.juliaplots.org/stable/interaction/nodes.html), we # can create animations or interactive plots. For example, if the nodal field has a time dependence t = Observable(0.0) u = lift(t) do t x->sin(π*(x[1]+x[2]+x[3]))*cos(π*t) end fig = plot(Ω, u, colormap=:rainbow, shading=true, colorrange=(-1,1)) wireframe!(∂Ω, color=:black, linewidth=0.5) framerate = 30 timestamps = range(0, 2, step=1/framerate) record(fig, "images/animation.gif", timestamps; framerate=framerate) do this_t t[] = this_t end # <p align="center"> # <img src="_readme/images/animation.gif" width="500"/> # </p>
GridapMakie
https://github.com/gridap/GridapMakie.jl.git
[ "MIT" ]
0.1.4
9f929d662ab4ca057a58504146bd12cc91b1b6f8
code
192
rm("images", force=true, recursive=true) rm("models", force=true, recursive=true) module README; include("README.jl"); end using Literate Literate.markdown("README.jl", "..", documenter=false)
GridapMakie
https://github.com/gridap/GridapMakie.jl.git
[ "MIT" ]
0.1.4
9f929d662ab4ca057a58504146bd12cc91b1b6f8
code
375
using Documenter, GridapMakie makedocs(; modules=[GridapMakie], format=Documenter.HTML(), pages=[ "Home" => "index.md", ], repo="https://github.com/gridap/GridapMakie.jl/blob/{commit}{path}#L{line}", sitename="GridapMakie.jl", authors="The GridapMakie project contributors", ) deploydocs(; repo="github.com/gridap/GridapMakie.jl", )
GridapMakie
https://github.com/gridap/GridapMakie.jl.git
[ "MIT" ]
0.1.4
9f929d662ab4ca057a58504146bd12cc91b1b6f8
code
287
module GridapMakie using Gridap using Gridap.Helpers using Gridap.Arrays using Gridap.CellData using Gridap.Geometry using Gridap.ReferenceFEs using Gridap.Visualization using FillArrays import Makie import GeometryBasics include("conversions.jl") include("recipes.jl") end #module
GridapMakie
https://github.com/gridap/GridapMakie.jl.git
[ "MIT" ]
0.1.4
9f929d662ab4ca057a58504146bd12cc91b1b6f8
code
5490
# Two different plot functions depending on the need of having a continuous or discontinuous mesh. function to_plot_dg_mesh(grid::Grid) UnstructuredGrid(grid) |> to_plot_dg_mesh end function to_plot_dg_mesh(grid::UnstructuredGrid) to_simplex_grid(grid) |> to_dg_mesh end function to_plot_mesh(grid::Grid) UnstructuredGrid(grid) |> to_plot_mesh end function to_plot_mesh(grid::UnstructuredGrid) to_simplex_grid(grid) |> to_mesh end # For the moment, we simplexify all grids (missing support for quads or general polytopes). function to_simplex_grid(grid::UnstructuredGrid) reffes = get_reffes(grid) polys = map(get_polytope,reffes) all(is_simplex,polys) ? grid : simplexify(grid) end # Create continuous GeometryBasics mesh equivalent of our grid. function to_mesh(grid::UnstructuredGrid) reffes = get_reffes(grid) @assert all(reffe->get_order(reffe)==1,reffes) @assert all(reffe->is_simplex(get_polytope(reffe)),reffes) xs = get_node_coordinates(grid) Tp = eltype(eltype(xs)) Dp = length(eltype(xs)) ps = collect(reinterpret(GeometryBasics.Point{Dp,Tp},xs)) cns = get_cell_node_ids(grid) Tc = eltype(eltype(cns)) Dc = num_cell_dims(grid) fs = collect(lazy_map(GeometryBasics.NgonFace{Dc+1,Tc},cns)) GeometryBasics.Mesh(GeometryBasics.connect(ps,fs)) end # Create discontinuous grid with the corresponding handling of nodal or cell fields. function to_point(x::VectorValue{D,T}) where {D,T} GeometryBasics.Point{D,T}(Tuple(x)) end function to_dg_points(grid::UnstructuredGrid) node_x = get_node_coordinates(grid) coords = to_dg_node_values(grid, node_x) [to_point(x) for x in coords] end function to_dg_mesh(grid::UnstructuredGrid) ps = to_dg_points(grid) Dc = num_cell_dims(grid) Tc = Int32 cns = Vector{Vector{Tc}}(undef, num_cells(grid)) i = 1 for cell in 1:num_cells(grid) cn = zeros(Tc, Dc+1) for lnode in 1:(Dc+1) cn[lnode] = i i += one(Tc) end cns[cell] = cn end fs = lazy_map(GeometryBasics.NgonFace{Dc+1,Tc}, cns) |> collect GeometryBasics.connect(ps, fs) |> GeometryBasics.Mesh end function to_dg_node_values(grid::Grid, node_value::Vector) cell_nodes = get_cell_node_ids(grid) i = 0 cache = array_cache(cell_nodes) for cell in 1:length(cell_nodes) nodes = getindex!(cache, cell_nodes, cell) for node in nodes i += 1 end end T = eltype(node_value) values = zeros(T,i) i = 0 for cell in 1:length(cell_nodes) nodes = getindex!(cache, cell_nodes, cell) for node in nodes i += 1 values[i] = node_value[node] end end values end function to_dg_cell_values(grid::Grid, cell_value::Vector) cell_nodes = get_cell_node_ids(grid) i = 0 cache = array_cache(cell_nodes) for cell in 1:length(cell_nodes) nodes = getindex!(cache, cell_nodes, cell) for node in nodes i += 1 end end T = eltype(cell_value) values = zeros(T,i) i = 0 for cell in 1:length(cell_nodes) nodes = getindex!(cache, cell_nodes, cell) for node in nodes i += 1 values[i] = cell_value[cell] end end values end # Obtain edge and vertex skeletons: function to_lowdim_grid(grid::Grid, ::Val{D}) where D topo = GridTopology(grid) labels = FaceLabeling(topo) model = DiscreteModel(grid, topo, labels) Grid(ReferenceFE{D}, model) end to_lowdim_grid(grid::Grid{D}, ::Val{D}) where D = grid to_face_grid(grid::Grid) = to_lowdim_grid(grid, Val(2)) to_edge_grid(grid::Grid) = to_lowdim_grid(grid, Val(1)) to_vertex_grid(grid::Grid) = to_lowdim_grid(grid, Val(0)) function to_face_grid_with_map(grid::Grid) function _fixnodeids!(face_to_nodes,face_to_m,face_to_n) for face in 1:length(face_to_nodes) m = face_to_m[face] n = face_to_n[face] p = face_to_nodes.ptrs[face] if m⋅n < 0 a = face_to_nodes.data[p] face_to_nodes.data[p] = face_to_nodes.data[p+1] face_to_nodes.data[p+1] = a end end end D = 2 topo = GridTopology(grid) labels = FaceLabeling(topo) model = DiscreteModel(grid, topo, labels) nfaces = num_faces(model,D) Γ = BoundaryTriangulation(model,IdentityVector(nfaces)) n_Γ = get_normal_vector(Γ) x_Γ = CellPoint(Fill(VectorValue(0.0,0.0),nfaces),Γ,ReferenceDomain()) face_to_n = collect(n_Γ(x_Γ)) face_to_ϕ = get_cell_map(Γ) face_to_Jt = lazy_map(∇,face_to_ϕ) Jt = GenericCellField(face_to_Jt,Γ,ReferenceDomain()) m_Γ = Operation(a->VectorValue(a[1],a[3],a[5])×VectorValue(a[2],a[4],a[6]))(Jt) face_to_m = collect(m_Γ(x_Γ)) g = UnstructuredGrid(Grid(ReferenceFE{D}, model)) face_to_nodes = get_cell_node_ids(g) _fixnodeids!(face_to_nodes,face_to_m,face_to_n) face_to_cells = get_faces(topo,D,num_cell_dims(grid)) face_to_cell = lazy_map(getindex,face_to_cells,Fill(1,nfaces)) g,face_to_cell end # Obtain grid and cellfield from triangulation: function to_grid(trian::Triangulation) vds = visualization_data(trian,"") first(vds).grid end function to_grid(trian::Triangulation, uh::Any) vds = visualization_data(trian, "", cellfields=[""=>uh]) grid = first(vds).grid nodaldata = first(first(vds).nodaldata)[2] scalarnodaldata = map(to_scalar, nodaldata) grid, scalarnodaldata end to_scalar(x) = x to_scalar(x::VectorValue) = norm(x) function to_point1D(trian::Triangulation{Dc,1}, uh::Any) where Dc vds = first(visualization_data(trian, "", cellfields=["uh"=>uh])) y = vds.nodaldata["uh"] x = map(y->y[1], get_node_coordinates(vds.grid)) x, y end
GridapMakie
https://github.com/gridap/GridapMakie.jl.git
[ "MIT" ]
0.1.4
9f929d662ab4ca057a58504146bd12cc91b1b6f8
code
6484
struct PlotGrid{G<:Grid} grid::G end Gridap.Geometry.get_grid(pg::PlotGrid) = pg.grid setup_color(color::Union{Symbol, Makie.Colorant}, ::Grid) = color function setup_color(color::AbstractArray, grid::Grid) color = if length(color) == num_nodes(grid) to_dg_node_values(grid, color) elseif length(color) == num_cells(grid) to_dg_cell_values(grid, color) else @unreachable end end setup_face_color(color::Union{Symbol, Makie.Colorant}, ::Grid, ::Any) = color function setup_face_color(color::AbstractArray, grid::Grid, face_to_cell) color = if length(color) == num_nodes(grid) color elseif length(color) == num_cells(grid) color[face_to_cell] else @unreachable end end mesh_theme = Makie.Theme( color = :pink, colormap = :bluesreds, shading = Makie.NoShading, cycle = nothing ) # By merging the default theme for the Mesh type and some attributes whose values we want to impose from mesh_theme # (in this case: color, colormap, etc.), we may override the current default theme and use our settings. # Note: Makie.Theme() returns an Attributes type. @Makie.recipe(PlotGridMesh) do scene merge!( mesh_theme, Makie.default_theme(scene, Makie.Mesh) ) end # The lift function is necessary when dealing with reactive attributes or Observables. #function Makie.plot!(plot::Makie.Mesh{<:Tuple{PlotGrid}}) function Makie.plot!(plot::PlotGridMesh{<:Tuple{PlotGrid}}) grid = Makie.lift(get_grid, plot[1]) D = num_cell_dims(grid[]) if D in (0,1,2) color = Makie.lift(setup_color, plot[:color], grid) mesh = Makie.lift(to_plot_dg_mesh, grid) elseif D == 3 face_grid_and_map = Makie.lift(to_face_grid_with_map, grid) face_grid = Makie.lift(first, face_grid_and_map) face_to_cell = Makie.lift(i->i[2], face_grid_and_map) face_color = Makie.lift(setup_face_color, plot[:color], grid, face_to_cell) mesh = Makie.lift(m->m|>to_plot_dg_mesh|>GeometryBasics.normal_mesh, face_grid) color = Makie.lift(setup_color, face_color, face_grid) else @unreachable end # plot.attributes.attributes returns a Dict{Symbol, Observable} to be called by any function. # plot.attributes returns an Attributes type. if D in (2,3) valid_attributes = Makie.shared_attributes(plot,Makie.Mesh) valid_attributes[:color] = color Makie.mesh!(plot, valid_attributes, mesh) elseif D == 1 valid_attributes = Makie.shared_attributes(plot,Makie.LineSegments) valid_attributes[:color] = color Makie.linesegments!(plot, valid_attributes, mesh ) elseif D == 0 valid_attributes = Makie.shared_attributes(plot,Makie.Scatter) valid_attributes[:color] = color Makie.scatter!(plot, valid_attributes, mesh ) else @unreachable end end # No need to create discontinuous meshes for wireframe and scatter. function Makie.convert_arguments(::Type{<:Makie.Wireframe}, pg::PlotGrid) grid = get_grid(pg) mesh = to_plot_mesh(grid) (mesh, ) end function Makie.convert_arguments(::Type{<:Makie.Scatter}, pg::PlotGrid) grid = get_grid(pg) node_coords = get_node_coordinates(grid) x = map(to_point, node_coords) (x, ) end function Makie.convert_arguments(::Type{PlotGridMesh}, trian::Triangulation) grid = to_grid(trian) (PlotGrid(grid), ) end function Makie.convert_arguments(t::Type{<:Union{Makie.Wireframe, Makie.Scatter}}, trian::Triangulation) grid = to_grid(trian) Makie.convert_arguments(t, PlotGrid(grid)) end # Set default plottype as mesh if argument is type Triangulation, i.e., mesh(Ω) == plot(Ω). Makie.plottype(::Triangulation{Dc,1}) where Dc = Makie.Scatter Makie.plottype(::Triangulation{Dc,Dp}) where {Dc,Dp} = PlotGridMesh Makie.args_preferred_axis(t::Triangulation)= num_point_dims(t)<=2 ? Makie.Axis : Makie.LScene Makie.plottype(::PlotGrid) = PlotGridMesh Makie.args_preferred_axis(pg::PlotGrid)= num_point_dims(pg.Grid)<=2 ? Makie.Axis : Makie.LScene @Makie.recipe(MeshField) do scene merge!( mesh_theme, Makie.default_theme(scene, Makie.Mesh) ) end # We explicitly set the colorrange property of p to (min, max) of the color provided. Here, when we use mesh(), # Makie fills the attribute plots of p (p.plots) with the given attributes. Hence, p.plots[1] inherits the colorrange # of p (this is just to draw colorbars). Another way would be using $ Colorbar(fig[1,2], plt.plots[1]), but quite less # appealing from the point of view of the user. function Makie.plot!(p::MeshField{<:Tuple{Triangulation, Any}}) trian, uh = p[1:2] grid_and_data = Makie.lift(to_grid, trian, uh) pg = Makie.lift(i->PlotGrid(i[1]), grid_and_data) p[:color] = Makie.lift(i->i[2], grid_and_data) if p[:colorrange][] === Makie.automatic p[:colorrange] = Makie.lift(extrema, p[:color]) end Makie.plot!(p, pg; p.attributes.attributes... ) end Makie.plottype(::Triangulation{Dc,1}, ::Any) where Dc = Makie.Scatter Makie.plottype(::Triangulation{Dc,Dp}, ::Any) where {Dc,Dp} = MeshField function Makie.plot!(p::MeshField{<:Tuple{CellField}}) uh = p[1] trian = Makie.lift(get_triangulation, uh) grid_and_data = Makie.lift(to_grid, trian, uh) pg = Makie.lift(i->PlotGrid(i[1]), grid_and_data) p[:color] = Makie.lift(i->i[2], grid_and_data) if p[:colorrange][] === Makie.automatic p[:colorrange] = Makie.lift(extrema, p[:color]) end Makie.plot!(p, pg; p.attributes.attributes... ) end function Makie.convert_arguments(::Union{Type{Makie.Lines},Type{Makie.ScatterLines},Type{Makie.Scatter}}, c::CellField) trian=get_triangulation(c) if num_point_dims(trian)==1 return to_point1D(trian, c) else ArgumentError("This function requires a 1D CellField") end end function Makie.convert_arguments(::Union{Type{Makie.Lines},Type{Makie.ScatterLines},Type{Makie.Scatter}}, trian::Triangulation{Dc,1}, uh::Any=x->0.0) where Dc return to_point1D(trian, uh) end Makie.plottype(c::CellField) = Makie.plottype(get_triangulation(c),c) Makie.args_preferred_axis(c::CellField)= Makie.args_preferred_axis(get_triangulation(c)) function Makie.point_iterator(pg::PlotGrid) UnstructuredGrid(pg.grid) |> to_dg_points end
GridapMakie
https://github.com/gridap/GridapMakie.jl.git
[ "MIT" ]
0.1.4
9f929d662ab4ca057a58504146bd12cc91b1b6f8
code
3799
module TestGridapMakie using GridapMakie using Gridap using GLMakie using Test import FileIO const OUTDIR = joinpath(@__DIR__, "output") rm(OUTDIR, force=true, recursive=true) mkpath(OUTDIR) function savefig(f, suffix::String) fig = f() println("*"^80) filename = "$(suffix).png" @show filename path = joinpath(OUTDIR, filename) FileIO.save(path, fig) return true end @testset "Tests 1D" begin model = CartesianDiscreteModel((0,15),90) Ω = Triangulation(model) reffe = ReferenceFE(lagrangian, Float64, 1) V = FESpace(model, reffe) u=x->cos(π*x[1])*exp(-x[1]/10) uh = interpolate(u, V) Γ = BoundaryTriangulation(model) @test savefig("1d_Fig1") do fig = lines(Ω,u) scatter!(uh,color=:red) fig end @test savefig("1d_Fig2") do fig=scatterlines(uh) plot!(Γ,uh,color=:red) fig end end @testset "Tests 2D" begin domain = (0,1,0,1) cell_nums = (10,10) model = CartesianDiscreteModel(domain,cell_nums) |> simplexify Ω = Triangulation(model) Γ = BoundaryTriangulation(model) Λ = SkeletonTriangulation(model) n_Λ = get_normal_vector(Λ) reffe = ReferenceFE(lagrangian,Float64,1) V = FESpace(model,reffe) uh = interpolate(x->sin(π*(x[1]+x[2])),V) celldata = rand(num_cells(Ω)) @test savefig("2d_Fig1") do fig = plot(Ω) wireframe!(Ω, linestyle=:dash, color=:black) scatter!(Ω, markersize=10, marker=:diamond, color=:brown2) fig end @test savefig("2d_Fig11") do fig, _ , sc = plot(Ω, uh) Colorbar(fig[1,2], sc) fig end @test savefig("2d_Fig111") do fig,_,sc = plot(Γ, uh, colormap=:algae, linewidth=10) Colorbar(fig[1,2],sc) fig end @test savefig("2d_Fig12") do fig = plot(Ω, color=:green) wireframe!(Ω, color=:red, linewidth=2.5) fig end @test savefig("2d_Fig13") do fig, _ , plt = plot(Ω, color=3*celldata, colormap=:heat) Colorbar(fig[1,2], plt) fig end @test savefig("2d_Fig14") do fig, _ , plt = plot(Λ, jump(n_Λ⋅∇(uh)),linewidth=4) Colorbar(fig[1,2], plt) fig end @test savefig("2d_fig15") do fig, _ , plt = plot(uh, colormap=:Spectral) Colorbar(fig[1,2], plt) fig end end @testset "Tests 3D" begin domain = (0,1,0,1,0,1) cell_nums = (10,10,10) model = CartesianDiscreteModel(domain,cell_nums) |> simplexify Ω = Triangulation(model) Γ = BoundaryTriangulation(model) Λ = SkeletonTriangulation(model) n_Λ = get_normal_vector(Λ) reffe = ReferenceFE(lagrangian,Float64,1) V = FESpace(model,reffe) uh = interpolate(x->sin(π*(x[1]+x[2]+x[3])),V) celldata = rand(num_cells(Ω)) @test savefig("3d_Fig1") do fig = plot(Ω) wireframe!(Ω) scatter!(Ω) fig end @test savefig("3d_Fig11") do fig, _ , sc = plot(Ω, uh, colorrange=(0,1)) Colorbar(fig[1,2],sc) fig end @test savefig("3d_Fig111") do fig, _ , sc = plot(Γ, uh, colormap=:algae) Colorbar(fig[1,2],sc) fig end @test savefig("3d_Fig12") do fig = plot(Ω, color=:green) wireframe!(Ω, color=:red, linewidth=2.5) fig end @test savefig("3d_Fig13") do fig, _ , plt = plot(Ω, color=3*celldata, colormap=:heat) Colorbar(fig[1,2], plt) fig end @test savefig("3d_Fig14") do fig, _ , plt = plot(Λ, jump(n_Λ⋅∇(uh))) Colorbar(fig[1,2],plt) fig end @test savefig("3d_fig15") do fig, _ , plt = plot(uh, colormap=:Spectral, colorrange=(0,1)) Colorbar(fig[1,2], plt) fig end end end #module
GridapMakie
https://github.com/gridap/GridapMakie.jl.git
[ "MIT" ]
0.1.4
9f929d662ab4ca057a58504146bd12cc91b1b6f8
docs
2130
Contributing to `GridapMakie` == By contributing to `GridapMakie`, you accept and agree to the following *Developer Certificate of Origin Version 1.1* (see below) for all your contributions. ``` Developer Certificate of Origin Version 1.1 Copyright (C) 2004, 2006 The Linux Foundation and its contributors. 1 Letterman Drive Suite D4700 San Francisco, CA, 94129 Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Developer's Certificate of Origin 1.1 By making a contribution to this project, I certify that: (a) The contribution was created in whole or in part by me and I have the right to submit it under the open source license indicated in the file; or (b) The contribution is based upon previous work that, to the best of my knowledge, is covered under an appropriate open source license and I have the right under that license to submit that work with modifications, whether created in whole or in part by me, under the same open source license (unless I am permitted to submit under a different license), as indicated in the file; or (c) The contribution was provided directly to me by some other person who certified (a), (b) or (c) and I have not modified it. (d) I understand and agree that this project and the contribution are public and that a record of the contribution (including all personal information I submit with it, including my sign-off) is maintained indefinitely and may be redistributed consistent with this project or the open source license(s) involved. ``` GridapMakie Style Guides === * 2 spaces for indentation level * No trailing white spaces * CamelCase for typenames * Pluralized CamelCase for files that implement a type * CamelCasesTests for CamelCase type test file * Use lowercase for methods, with underscores only when necessary * Use whitespace for readability * 80 characterl line length limit * Use method! for muting methods See [the Julia CONTRIBUTING.md](https://github.com/JuliaLang/julia/blob/master/CONTRIBUTING.md) for further information.
GridapMakie
https://github.com/gridap/GridapMakie.jl.git
[ "MIT" ]
0.1.4
9f929d662ab4ca057a58504146bd12cc91b1b6f8
docs
725
# Changelog All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [0.1.3] - 2024-09-06 ### Added - Updated to support Gridap v0.18, together with Makie v0.21. ## [0.1.2] - 2022-08-24 ### Added - Support for Makie 0.17. ## [0.1.1] - 2021-11-10 ### Added - Support for Gridap v0.17. ## [0.1.0] - 2021-08-23 ### Added - Visualization of vertices, edges, and faces of Gridap `Triangulation` objects made of simplices. - Visualization of scalar-valued `CellField` and related objects on `Triangulation` objects made of simplices.
GridapMakie
https://github.com/gridap/GridapMakie.jl.git
[ "MIT" ]
0.1.4
9f929d662ab4ca057a58504146bd12cc91b1b6f8
docs
7268
# GridapMakie | **Documentation** | |:------------ | | [![Stable](https://img.shields.io/badge/docs-stable-blue.svg)](https://gridap.github.io/GridapMakie.jl/stable) [![Dev](https://img.shields.io/badge/docs-dev-blue.svg)](https://gridap.github.io/GridapMakie.jl/dev) | |**Build Status** | | [![Build Status](https://github.com/gridap/GridapMakie.jl/workflows/CI/badge.svg?branch=master)](https://github.com/gridap/GridapMakie.jl/actions) [![Coverage](https://codecov.io/gh/gridap/GridapMakie.jl/branch/master/graph/badge.svg)](https://codecov.io/gh/gridap/GridapMakie.jl) | | **Community** | | [![Join the chat at https://gitter.im/Gridap-jl/community](https://badges.gitter.im/Gridap-jl/community.svg)](https://gitter.im/Gridap-jl/community?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) | | **Acknowledgement** | | [<img src="https://developers.google.com/open-source/gsoc/resources/downloads/GSoC-logo-horizontal.svg" alt="GSoC" width="220"/>](https://summerofcode.withgoogle.com/projects/#6231266174697472) | ## Overview The visualization of numerical results is an important part of finite element (FE) computations. However, before the inception of GridapMakie.jl, the only approach available to data visualization of [Gridap.jl](https://github.com/gridap/Gridap.jl) computations was to write simulation data to data files (e.g., in vtu format) for later visualization with, e.g., Paraview or VisIt. From the idea of visually inspecting data from Julia code directly or to manipulate it with packages of the Julia open-source package ecosystem, [GridapMakie.jl](https://github.com/gridap/GridapMakie.jl) is born. As a part of the Google Summer of Code 2021 program, GridapMakie adopts [Makie.jl](https://github.com/JuliaPlots/Makie.jl) as a second visualization back-end for Gridap.jl simulations. This package is thought as a built-in tool to assess the user in their FE calculations with a smoother workflow in a highly intuitive API. ## Acknowledgement A significant part of this package has been developed in the framework of the Google Summer of Code 2021 project [[Gridap] Visualizing PDE approximations in Julia with Gridap.jl and Makie.jl](https://summerofcode.withgoogle.com/projects/#6231266174697472). ## Installation According to Makie's guidelines, it is enough to install one of its backends, e.g. GLMakie. Additionally, Gridap provides the plot objects to be visualized and `FileIO` allows to save the figures plotted. ```julia julia> ] pkg> add Gridap, GridapMakie, GLMakie, FileIO ``` ## Examples First things first, we shall be using the three packages as well as `FileIO`. We may as well create directories to store downloaded meshes and output files ````julia using Gridap, GridapMakie, GLMakie using FileIO mkdir("models") mkdir("images") ```` ### 1D Plots Let us consider a 1D triangulation Ω, a function `u` and the corresponding FE function `uh` constructed with Gridap ````julia model = CartesianDiscreteModel((0,15),150) Ω = Triangulation(model) reffe = ReferenceFE(lagrangian, Float64, 1) V = FESpace(model, reffe) u=x->cos(π*x[1])*exp(-x[1]/10) uh = interpolate(u, V) ```` The visualization of the function can be achieved as follows ````julia fig=plot(uh) save("images/1d_Fig1.png", fig) ```` <p align="center"> <img src="_readme/images/1d_Fig1.png" width="500"/> </p> We may also plot the function with a line and its value at the boundaries ````julia Γ = BoundaryTriangulation(model) fig=lines(Ω,u) plot!(Γ,uh,color=:red) save("images/1d_Fig2.png", fig) ```` <p align="center"> <img src="_readme/images/1d_Fig2.png" width="500"/> </p> ### 2D Plots Then, let us consider a simple, 2D simplexified cartesian triangulation Ω ````julia domain = (0, 1, 0, 1) cell_nums = (10, 10) model = CartesianDiscreteModel(domain, cell_nums) |> simplexify Ω = Triangulation(model) ```` The visualization of the vertices, edges, and faces of Ω can be achieved as follows ````julia fig = plot(Ω) wireframe!(Ω, color=:black, linewidth=2) scatter!(Ω, marker=:star8, markersize=20, color=:blue) save("images/2d_Fig1.png", fig) ```` <p align="center"> <img src="_readme/images/2d_Fig1.png" width="500"/> </p> We now consider a FE function `uh` constructed with Gridap ````julia reffe = ReferenceFE(lagrangian, Float64, 1) V = FESpace(model, reffe) uh = interpolate(x->sin(π*(x[1]+x[2])), V) ```` and plot it over Ω, adding a colorbar ````julia fig, _ , plt = plot(Ω, uh) Colorbar(fig[1,2], plt) save("images/2d_Fig11.png", fig) ```` <p align="center"> <img src="_readme/images/2d_Fig11.png" width="500"/> </p> On the other hand, we may as well plot cell values ````julia celldata = π*rand(num_cells(Ω)) .-1 fig, _ , plt = plot(Ω, color=celldata, colormap=:heat) Colorbar(fig[2,1], plt, vertical=false) save("images/2d_Fig13.png", fig) ```` <p align="center"> <img src="_readme/images/2d_Fig13.png" width="500"/> </p> If we are only interested in the boundary of Ω, namely Γ ````julia Γ = BoundaryTriangulation(model) fig, _ , plt = plot(Γ, uh, colormap=:algae, linewidth=10) Colorbar(fig[1,2], plt) save("images/2d_Fig111.png", fig) ```` <p align="center"> <img src="_readme/images/2d_Fig111.png" width="500"/> </p> ### 3D Plots In addition to the 2D plots, GridapMakie is able to handle more complex geometries. For example, take the mesh from the [first Gridap tutorial](https://gridap.github.io/Tutorials/stable/pages/t001_poisson/#Tutorial-1:-Poisson-equation-1), which can be downloaded using ````julia url = "https://github.com/gridap/GridapMakie.jl/raw/d5d74190e68bd310483fead8a4154235a61815c5/_readme/model.json" download(url,"models/model.json") ```` Therefore, we may as well visualize such mesh ````julia model = DiscreteModelFromFile("models/model.json") Ω = Triangulation(model) ∂Ω = BoundaryTriangulation(model) fig = plot(Ω) wireframe!(∂Ω, color=:black) save("images/3d_Fig1.png", fig) ```` <p align="center"> <img src="_readme/images/3d_Fig1.png" width="500"/> </p> ````julia v(x) = sin(π*(x[1]+x[2]+x[3])) fig, ax, plt = plot(Ω, v) Colorbar(fig[1,2], plt) save("images/3d_Fig2.png", fig) ```` <p align="center"> <img src="_readme/images/3d_Fig2.png" width="500"/> </p> we can even plot functions in certain subdomains, e.g. ````julia Γ = BoundaryTriangulation(model, tags=["square", "triangle", "circle"]) fig = plot(Γ, v, colormap=:rainbow) wireframe!(∂Ω, linewidth=0.5, color=:gray) save("images/3d_Fig3.png", fig) ```` <p align="center"> <img src="_readme/images/3d_Fig3.png" width="500"/> </p> ### Animations and interactivity Finally, by using Makie [Observables](https://makie.juliaplots.org/stable/interaction/nodes.html), we can create animations or interactive plots. For example, if the nodal field has a time dependence ````julia t = Observable(0.0) u = lift(t) do t x->sin(π*(x[1]+x[2]+x[3]))*cos(π*t) end fig = plot(Ω, u, colormap=:rainbow, colorrange=(-1,1)) wireframe!(∂Ω, color=:black, linewidth=0.5) framerate = 30 timestamps = range(0, 2, step=1/framerate) record(fig, "images/animation.gif", timestamps; framerate=framerate) do this_t t[] = this_t end ```` <p align="center"> <img src="_readme/images/animation.gif" width="500"/> </p> --- *This page was generated using [Literate.jl](https://github.com/fredrikekre/Literate.jl).*
GridapMakie
https://github.com/gridap/GridapMakie.jl.git
[ "MIT" ]
0.1.4
9f929d662ab4ca057a58504146bd12cc91b1b6f8
docs
286
```@meta CurrentModule = GridapMakie ``` # GridapMakie The documentation of this package is under construction. For further information read the [README.md](https://github.com/gridap/GridapMakie.jl/blob/master/README.md) file. ```@index ``` ```@autodocs Modules = [GridapMakie] ```
GridapMakie
https://github.com/gridap/GridapMakie.jl.git
[ "MIT" ]
1.0.2
c8760444248aef64bc728b340ebc50df13148c93
code
880
using TinyHugeNumbers using Documenter DocMeta.setdocmeta!(TinyHugeNumbers, :DocTestSetup, :(using TinyHugeNumbers); recursive=true) makedocs(; modules = [ TinyHugeNumbers ], strict = [ :doctest, :eval_block, :example_block, :meta_block, :parse_error, :setup_block ], authors = "Bagaev Dmitry <[email protected]> and contributors", repo = "https://github.com/reactivebayes/TinyHugeNumbers.jl/blob/{commit}{path}#{line}", sitename = "TinyHugeNumbers.jl", format = Documenter.HTML(; prettyurls = get(ENV, "CI", "false") == "true", canonical = "https://reactivebayes.github.io/TinyHugeNumbers.jl", edit_link = "main", assets = String[], ), pages = [ "Documentation" => "index.md", ], ) deploydocs(; repo="github.com/ReactiveBayes/TinyHugeNumbers.jl", devbranch="main", forcepush = true)
TinyHugeNumbers
https://github.com/ReactiveBayes/TinyHugeNumbers.jl.git
[ "MIT" ]
1.0.2
c8760444248aef64bc728b340ebc50df13148c93
code
4474
module TinyHugeNumbers export tiny, huge import Base: show, convert, promote_rule """ See [`tiny`](@ref) """ struct TinyNumber <: Real end Base.show(io::IO, ::TinyNumber) = print(io, "tiny") Base.convert(::Type{F}, ::TinyNumber) where {F<:AbstractFloat} = 10eps(F) Base.convert(::Type{Float32}, ::TinyNumber) = 1.0f-6 Base.convert(::Type{Float64}, ::TinyNumber) = 1e-12 Base.convert(::Type{BigFloat}, ::TinyNumber) = big"1e-24" Base.promote_rule(::Type{TinyNumber}, ::Type{I}) where {I<:Integer} = promote_type(TinyNumber, promote_type(I, Float64)) Base.promote_rule(::Type{TinyNumber}, ::Type{F}) where {F<:AbstractFloat} = F (::Type{T})(::TinyNumber) where {T<:AbstractFloat} = convert(T, tiny) (::TinyNumber)(::Type{T}) where {T} = convert(T, TinyNumber()) (::TinyNumber)(something) = convert(typeof(something), TinyNumber()) """ tiny `tiny` represents a (wow!) tiny number that can be used in a various computations without unnecessary type promotions. `tiny` is defined as: - `1.0f-6` for `Float32` - `1e-12` for `Float64` - `big"1e-24"` for `BigFloat` - `10 * eps(F)` for an arbitrary type `F <: AbstractFloat` # Example ```jldoctest julia> tiny tiny julia> 1 + tiny 1.000000000001 julia> tiny + 1 1.000000000001 julia> 1f0 + tiny 1.000001f0 julia> big"1.0" + tiny 1.000000000000000000000001 julia> big"1" + tiny 1.000000000000000000000001 ``` See also: [`huge`](@ref) """ const tiny = TinyNumber() ## ------------------------------------------------------------------------------------ ## """ See [`huge`](@ref) """ struct HugeNumber <: Real end Base.show(io::IO, ::HugeNumber) = print(io, "huge") Base.convert(::Type{F}, ::HugeNumber) where {F<:AbstractFloat} = inv(tiny(F)) Base.convert(::Type{Float32}, ::HugeNumber) = 1.0f+6 Base.convert(::Type{Float64}, ::HugeNumber) = 1e+12 Base.convert(::Type{BigFloat}, ::HugeNumber) = big"1e+24" Base.promote_rule(::Type{HugeNumber}, ::Type{I}) where {I<:Integer} = promote_type(HugeNumber, promote_type(I, Float64)) Base.promote_rule(::Type{HugeNumber}, ::Type{F}) where {F<:AbstractFloat} = F (::Type{T})(::HugeNumber) where {T<:AbstractFloat} = convert(T, huge) (::HugeNumber)(::Type{T}) where {T} = convert(T, HugeNumber()) (::HugeNumber)(something) = convert(typeof(something), HugeNumber()) """ huge `huge` represents a (wow!) huge number that can be used in a various computations without unnecessary type promotions. `huge` is defined as: - `1.0f+6` for `Float32` - `1e+12` for `Float64` - `big"1e+24"` for `BigFloat` - `inv(tiny(F))` for an arbitrary type `F <: AbstractFloat` # Example ```jldoctest julia> huge huge julia> 1 + huge 1.000000000001e12 julia> huge + 1 1.000000000001e12 julia> 1f0 + huge 1.000001f6 julia> big"1.0" + huge 1.000000000000000000000001e+24 julia> big"1" + huge 1.000000000000000000000001e+24 ``` See also: [`tiny`](@ref) """ const huge = HugeNumber() ## ------------------------------------------------------------------------------------ ## # A special structure that is used to promote `TinyNumber` and `HugeNumber` to the same type # but it cannot be instantiated, this might be useful in situations like `clamp(value, tiny, huge)` # in this case Julia attempts first to promote `tiny` and `huge` to the same type and then # uses the result to promote `value` to the resulting type. However, there is no "common" type for # both `tiny` and `huge` (except for the `Union` but we can't use it either since it introduces ambiguities) # so we introduce a special structure that will accomodate that # see also: https://github.com/ReactiveBayes/TinyHugeNumbers.jl/issues/3 # note: as a result, we cannot store `tiny` and `huge` in the same container (e.g. `Array`), # but `[ 1.0, tiny, huge ]` will work just fine struct PromoteTinyOrHuge PromoteTinyOrHuge() = error("Cannot instantiate an internal structure for promotion.") end Base.promote_rule(::Type{T}, ::Type{PromoteTinyOrHuge}) where {T<:Real} = T Base.promote_rule(::Type{PromoteTinyOrHuge}, ::Type{PromoteTinyOrHuge}) = PromoteTinyOrHuge Base.promote_rule(::Type{TinyNumber}, ::Type{HugeNumber}) = PromoteTinyOrHuge Base.convert(::Type{PromoteTinyOrHuge}, ::TinyNumber) = error("Cannot convert `tiny` to `huge`. Are you trying to put `tiny` and `huge` in the same container (e.g. `Array`)?") Base.convert(::Type{PromoteTinyOrHuge}, ::HugeNumber) = error("Cannot convert `huge` to `tiny`. Are you trying to put `tiny` and `huge` in the same container (e.g. `Array`)?") end
TinyHugeNumbers
https://github.com/ReactiveBayes/TinyHugeNumbers.jl.git
[ "MIT" ]
1.0.2
c8760444248aef64bc728b340ebc50df13148c93
code
5922
using TinyHugeNumbers, Aqua, Test Aqua.test_all(TinyHugeNumbers, deps_compat=(; check_extras=false, check_weakdeps=true)) import TinyHugeNumbers: TinyNumber, HugeNumber struct ArbitraryFloatType <: AbstractFloat end @testset "TinyHugeNumbers.jl" begin Base.eps(::Type{ArbitraryFloatType}) = 0.1 Base.convert(::Type{ArbitraryFloatType}, ::Integer) = ArbitraryFloatType() # for testing @test repr(tiny) == "tiny" @test repr(huge) == "huge" @test typeof(tiny) === TinyNumber @test typeof(huge) === HugeNumber @test convert(Float32, tiny) === 1.0f-6 @test convert(Float64, tiny) === 1e-12 @test convert(BigFloat, tiny) == big"1e-24" @test convert(ArbitraryFloatType, tiny) === 10 * eps(ArbitraryFloatType) @test tiny(Float32) === 1.0f-6 @test tiny(Float64) === 1e-12 @test tiny(BigFloat) == big"1e-24" @test tiny(ArbitraryFloatType) === 10 * eps(ArbitraryFloatType) # `convert(T, 1)` here returns an instance of type `T` @test tiny(convert(Float32, 1)) === 1.0f-6 @test tiny(convert(Float64, 1)) === 1e-12 @test tiny(convert(BigFloat, 1)) == big"1e-24" @test tiny(convert(ArbitraryFloatType, 1)) === 10 * eps(ArbitraryFloatType) @test Float32(tiny) === 1.0f-6 @test Float64(tiny) === 1e-12 @test BigFloat(tiny) == big"1e-24" @test ArbitraryFloatType(tiny) === 10 * eps(ArbitraryFloatType) @test convert(Float32, huge) === 1.0f+6 @test convert(Float64, huge) === 1e+12 @test convert(BigFloat, huge) == big"1e+24" @test convert(ArbitraryFloatType, huge) === inv(10 * eps(ArbitraryFloatType)) @test huge(Float32) === 1.0f+6 @test huge(Float64) === 1e+12 @test huge(BigFloat) == big"1e+24" @test huge(ArbitraryFloatType) === inv(10 * eps(ArbitraryFloatType)) # `convert(T, 1)` here returns an instance of type `T` @test huge(convert(Float32, 1)) === 1.0f+6 @test huge(convert(Float64, 1)) === 1e+12 @test huge(convert(BigFloat, 1)) == big"1e+24" @test huge(convert(ArbitraryFloatType, 1)) === inv(10 * eps(ArbitraryFloatType)) @test Float32(huge) === 1.0f+6 @test Float64(huge) === 1e+12 @test BigFloat(huge) == big"1e+24" @test ArbitraryFloatType(huge) === inv(10 * eps(ArbitraryFloatType)) @test @inferred clamp(1.0f0, tiny, huge) == 1.0f0 @test @inferred clamp(0.0f0, tiny, huge) == 1.0f-6 @test @inferred clamp(1.0f13, tiny, huge) == 1.0f+6 @test @inferred clamp(1.0, tiny, huge) == 1.0 @test @inferred clamp(0.0, tiny, huge) == 1e-12 @test @inferred clamp(1e13, tiny, huge) == 1e12 @test @inferred clamp(big"1.0", tiny, huge) == big"1.0" @test @inferred clamp(big"0.0", tiny, huge) == big"1e-24" @test @inferred clamp(big"1e25", tiny, huge) == big"1e+24" for T in (Float64, Float32, BigFloat, ArbitraryFloatType) @test @inferred(promote_type(T, TinyNumber, HugeNumber)) == T @test @inferred(promote_type(T, HugeNumber, TinyNumber)) == T end for a in (1, 1.0, 0, 0.0, 1.0f0, 0.0f0, Int32(0), Int32(1), big"1", big"1.0", big"0", big"0.0") T = typeof(a) for v in Real[tiny, huge] V = typeof(v) for op in [+, -, *, /, >, >=, <, <=] @test @inferred op(a, v) == op(a, convert(promote_type(T, V), v)) @test @inferred op(v, a) == op(convert(promote_type(T, V), v), a) @test @inferred op(a, v) == op(a, v) @test @inferred op(v, a) == op(v, a) end @test v <= (@inferred clamp(a, v, Inf)) <= Inf @test zero(a) <= (@inferred clamp(a, zero(a), v)) <= v for size in [3, 5] for array in [fill(a, (size,)), fill(a, (size, size))] for op in [+, -, *, /, >, >=, <, <=] @test @inferred op.(array, v) == op.(array, convert(promote_type(T, V), v)) @test @inferred op.(v, array) == op.(convert(promote_type(T, V), v), array) @test @inferred op.(array, v) == op.(array, v) @test @inferred op.(v, array) == op.(v, array) end @test @inferred clamp.(array, v, Inf) == clamp.(array, v, Inf) @test @inferred clamp.(array, zero(array), v) == clamp.(array, zero(array), v) end end end end end @testset "ForwardDiff.jl compatibility" begin import ForwardDiff f(x) = clamp(x, tiny, huge) @test @inferred(ForwardDiff.derivative(f, 1.0)) === 1.0 @test @inferred(ForwardDiff.derivative(f, 2.0)) === 1.0 @test @inferred(ForwardDiff.derivative(f, 0.0)) === 0.0 @test @inferred(ForwardDiff.derivative(f, huge + 1.0)) === 0.0 @test @inferred(ForwardDiff.derivative(f, tiny - 1.0)) === 0.0 g(x) = clamp(x^2, tiny, huge) @test @inferred(ForwardDiff.derivative(g, 1.0)) === 2.0 @test @inferred(ForwardDiff.derivative(g, 2.0)) === 4.0 @test @inferred(ForwardDiff.derivative(g, 0.0)) === 0.0 @test @inferred(ForwardDiff.derivative(g, huge + 1.0)) === 0.0 @test @inferred(ForwardDiff.derivative(g, tiny - 1.0)) === 2(tiny - 1.0) end @testset "Storing `tiny` and `huge` in arrays" begin @static if VERSION >= v"1.10" @test_throws "Cannot convert `tiny` to `huge`" [tiny, huge] @test_throws "Cannot convert `huge` to `tiny`" [huge, tiny] else @test_throws ErrorException [tiny, huge] @test_throws ErrorException [huge, tiny] end for a in (1.0, 0.0, 1.0f0, 0.0f0, big"1.0", big"0.0") @test [a, tiny, huge] == [a, tiny(a), huge(a)] @test [tiny, a, huge] == [tiny(a), a, huge(a)] @test [tiny, huge, a] == [tiny(a), huge(a), a] @test [a, huge, tiny] == [a, huge(a), tiny(a)] @test [huge, a, tiny] == [huge(a), a, tiny(a)] @test [huge, tiny, a] == [huge(a), tiny(a), a] end end
TinyHugeNumbers
https://github.com/ReactiveBayes/TinyHugeNumbers.jl.git
[ "MIT" ]
1.0.2
c8760444248aef64bc728b340ebc50df13148c93
docs
2130
# TinyHugeNumbers [![Stable](https://img.shields.io/badge/docs-stable-blue.svg)](https://reactivebayes.github.io/TinyHugeNumbers.jl/stable/) [![Dev](https://img.shields.io/badge/docs-dev-blue.svg)](https://reactivebayes.github.io/TinyHugeNumbers.jl/dev/) [![Build Status](https://github.com/reactivebayes/TinyHugeNumbers.jl/actions/workflows/CI.yml/badge.svg?branch=main)](https://github.com/reactivebayes/TinyHugeNumbers.jl/actions/workflows/CI.yml?query=branch%3Amain) [![Coverage](https://codecov.io/gh/reactivebayes/TinyHugeNumbers.jl/branch/main/graph/badge.svg)](https://codecov.io/gh/reactivebayes/TinyHugeNumbers.jl) [![PkgEval](https://JuliaCI.github.io/NanosoldierReports/pkgeval_badges/T/TinyHugeNumbers.svg)](https://JuliaCI.github.io/NanosoldierReports/pkgeval_badges/report.html) The `TinyHugeNumbers` package exports `tiny` and `huge` objects to represent tiny and huge numbers. These objects aren't really numbers and behave differently depending on the context. They do support any operation that is defined for Real numbers. For more info see Julia's documentation about promotion. `tiny` represents a (wow!) tiny number that can be used in a various computations without unnecessary type promotions. `tiny` is defined as: - `1.0f-6` for `Float32` - `1e-12` for `Float64` - `big"1e-24"` for `BigFloat` - `10 * eps(F)` for an arbitrary type `F <: AbstractFloat` ```julia julia> tiny tiny julia> 1 + tiny 1.000000000001 julia> tiny + 1 1.000000000001 julia> 1f0 + tiny 1.000001f0 julia> big"1.0" + tiny 1.000000000000000000000001 julia> big"1" + tiny 1.000000000000000000000001 ``` `huge` represents a (wow!) huge number that can be used in a various computations without unnecessary type promotions. `huge` is defined as: - `1.0f+6` for `Float32` - `1e+12` for `Float64` - `big"1e+24"` for `BigFloat` - `inv(tiny(F))` for an arbitrary type `F <: AbstractFloat` ```julia julia> huge huge julia> 1 + huge 1.000000000001e12 julia> huge + 1 1.000000000001e12 julia> 1f0 + huge 1.000001f6 julia> big"1.0" + huge 1.000000000000000000000001e+24 julia> big"1" + huge 1.000000000000000000000001e+24 ```
TinyHugeNumbers
https://github.com/ReactiveBayes/TinyHugeNumbers.jl.git
[ "MIT" ]
1.0.2
c8760444248aef64bc728b340ebc50df13148c93
docs
396
```@meta CurrentModule = TinyHugeNumbers ``` # TinyHugeNumbers The `TinyHugeNumbers` package exports `tiny` and `huge` objects to represent tiny and huge numbers. These objects aren't really numbers and behave differently depending on the context. They do support any operation that is defined for Real numbers. For more info see Julia's documentation about promotion. ```@docs tiny huge ```
TinyHugeNumbers
https://github.com/ReactiveBayes/TinyHugeNumbers.jl.git
[ "MIT" ]
0.2.0
8a73fe1574e159927031bb2b9cc6ea142f075407
code
1076
push!(LOAD_PATH, "../src/") push!(LOAD_PATH, @__DIR__) using Documenter, DocumenterTools, DocumenterCitations, DocumenterInterLinks using PermutationTests makedocs( remotes = nothing, # ELIMINATE for deploying sitename = "PermutationTests", format = Documenter.HTML((prettyurls = false)), # ELIMINATE pretty URL for deploying authors="Marco Congedo, CNRS, Grenoble, France; Livio Finos, Uni. Padova, Italia", modules = [PermutationTests], pages = [ "index.md", "Main Module" => "PermutationTests.md", "Univariate tests" => "univariate tests.md", "Multiple comparisons tests" => "multiple comparisons tests.md", "Statistics" => "statistics.md", "Test statistics" => "test statistics.md", "Tools" => "tools.md", "Create your own test" => "create your own test.md", "Chose a Test" => "chose a test.md" ] ) # Documenter can also automatically deploy documentation to gh-pages. # See "Hosting Documentation" and deploydocs() in the Documenter manual # for more information.
PermutationTests
https://github.com/Marco-Congedo/PermutationTests.jl.git
[ "MIT" ]
0.2.0
8a73fe1574e159927031bb2b9cc6ea142f075407
code
1577
push!(LOAD_PATH, "../src/") push!(LOAD_PATH, @__DIR__) using Documenter, DocumenterTools, DocumenterCitations, DocumenterInterLinks using PermutationTests makedocs( #remotes = nothing, # ELIMINATE for deploying sitename = "PermutationTests", #format = Documenter.HTML((prettyurls = false)), # ELIMINATE pretty URL for deploying format = Documenter.HTML(), authors="Marco Congedo, CNRS, Grenoble, France; Livio Finos, Uni. Padova, Italia", modules = [PermutationTests], pages = [ "index.md", "About" => "about.md", "Main Module" => "PermutationTests.md", "Univariate tests" => "univariate tests.md", "Multiple comparisons tests" => "multiple comparisons tests.md", "Package tests" => "package tests.md", "Tools" => "tools.md", "Extras" => Any[ "Statistics" => "statistics.md", "Test statistics" => "test statistics.md", "Create your own test" => "create your own test.md", "Chose a Test" => "chose a test.md" ] ] ) # Documenter can also automatically deploy documentation to gh-pages. # See "Hosting Documentation" and deploydocs() in the Documenter manual # for more information. deploydocs( # root, # target = "build", # add this folder to .gitignore! repo = "github.com/Marco-Congedo/PermutationTests.jl.git", branch = "gh-pages", # osname = "linux", # deps = Deps.pip("pygments", "mkdocs"), devbranch = "dev", devurl = "dev", # versions = ["stable" => "v^", "v#.#", devurl => devurl] )
PermutationTests
https://github.com/Marco-Congedo/PermutationTests.jl.git
[ "MIT" ]
0.2.0
8a73fe1574e159927031bb2b9cc6ea142f075407
code
10616
#= Main Module of the PermutationTests.jl Package v0.1.0 MIT License Copyright (c) 2024, Marco Congedo, CNRS, Grenoble, France: https://sites.google.com/site/marcocongedo/home =# module PermutationTests using Base.Threads using Statistics: mean, var using Random: rand, shuffle, shuffle!, MersenneTwister using Combinatorics: permutations, multiset_permutations, multinomial using Folds: Folds, Folds.maximum # import export # from this module Statistic, BivStatistic, PearsonR, CrossProd, Covariance, IndSampStatistic, AnovaF_IS, SumGroupTotalsSq_IS, SumGroupTotalsSqN_IS, StudentT_IS, Group1Total_IS, RepMeasStatistic, AnovaF_RM, SumTreatTotalsSq_RM, StudentT_RM, OneSampStatistic, StudentT_1S, Sum, TestDirection, Right, Left, Both, Assignment, Balanced, Unbalanced, TestResult, UniTest, MultcompTest, # from stats.jl ∑, ∑of², ∑∑of², μ, dispersion, σ², σ, ∑, Π, ∑ofΠ, statistic, μ0, σ1, μ0σ1, _∑Y²kn_∑y²_∑S²k, _∑y², # from tools.jl flip, assignment, eqStat, allPerms, nrPerms, membership, genPerms, table2vec, # from uniTests.jl testStatistic, _permTest!, # from uniTests_API.jl correlationTest!, rTest!, correlationTest, rTest, trendTest!, trendTest, pointBiSerialTest, anovaTestIS, fTestIS, studentTestIS, tTestIS, chiSquaredTest, Χ²Test, fisherExactTest, anovaTestRM, fTestRM, cochranqTest, qTest, mcNemarTest, studentTestRM, tTestRM, studentTestRM!, tTestRM!, studentTest1S!, tTest1S!, studentTest1S, tTest1S, signTest!, signTest, # from multcompTests.jl _permMcTest!, # from multcompTests_API.jl correlationMcTest!, rMcTest!, correlationMcTest, rMcTest, trendMcTest!, trendMcTest, pointBiSerialMcTest, anovaMcTestIS, fMcTestIS, studentMcTestIS, tMcTestIS, chiSquaredMcTest, Χ²McTest, fisherExactMcTest, anovaMcTestRM, fMcTestRM, cochranqMcTest, qMcTest, mcNemarMcTest, studentMcTestRM, tMcTestRM, studentMcTestRM!, tMcTestRM!, studentMcTest1S!, tMcTest1S!, studentMcTest1S, tMcTest1S, signMcTest!, signMcTest # Consts const titleFont = "\x1b[38;5;208m" # orange const diceFont = "\x1b[38;5;210m" # orange const separatorFont = "\x1b[38;5;220m" # orange clair const defaultFont = "\x1b[0m" const greyFont = "\x1b[90m" const 📌 = titleFont*"PermutationTests.jl "*defaultFont const dice = ("⚀", "⚁", "⚂", "⚃", "⚄", "⚅") # Types # Types for input data: All Real, Integers and Boolean (Bits) UniData = Union{AbstractVector{R}, AbstractVector{I}, AbstractVector{Bool}} where {R<:Real, I<:Int} UniDataVec = Union{AbstractVector{Vector{R}}, AbstractVector{Vector{I}}, AbstractVector{Vector{Bool}}} where {R<:Real, I<:Int} UniDataVec² = Union{AbstractVector{Vector{Vector{R}}}, AbstractVector{Vector{Vector{I}}}, AbstractVector{Vector{Vector{Bool}}}} where {R<:Real, I<:Int} DataType = Union{UniData, UniDataVec, UniDataVec²} # Useful types IntVec = AbstractVector{I} where I<: Int Into = Union{I, Nothing} where I <: Int Realo = Union{R, Nothing} where R <: Real nsType=Union{Int, Vector{Int}, @NamedTuple{n::Int, k::Int}} # Abstract Type which children are all statistics abstract type Statistic end # singletons (statistics) and Unions of singletons (statistics and their equivalent statistics) using the same permutation scheme : # _________________________________________________________________________________________________________________________________ struct PearsonR <: Statistic end # PRINCIPAL: Pearson product moment correlation coefficient (H0: R≠0) struct CrossProd <: Statistic end # EQUIVALENT to PearsonR for the case of directional test struct Covariance <: Statistic end # EQUIVALENT to PearsonR for the case of bi-directional test BivStatistic = Union{Covariance, PearsonR, CrossProd} ### Group of Bivariate Statistics # __________________________________________ struct AnovaF_IS <: Statistic end # PRINCIPAL: 1-way ANOVA for independent samples (H0: µ1 = µ2 = µ3 = … = µk) # With dichotomous data yields 1-saided and bi-directional Χ² test and Fisher Exact Tests for >2 groups struct SumGroupTotalsSq_IS <: Statistic end # EQUIVALENT to AnovaF_IS for balanced designs (groups of equal numerosity) struct SumGroupTotalsSqN_IS <: Statistic end # EQUIVALENT to AnovaF_IS in general and to StudentT_IS in the case of bi-directional tests struct StudentT_IS <: Statistic end # PRINCIPAL: Student T for independent samples (H0: μ1≠μ2) # With dichotomous data yields 1-saided and bi-directional Χ² test and Fisher Exact Tests for 2 groups # For ranked data gives the same p-value as the Mann-Whitney U test struct Group1Total_IS <: Statistic end # EQUIVALENT to StudentT_IS for the case of directional tests μ(G1) > μ(G2) IndSampStatistic = Union{AnovaF_IS, SumGroupTotalsSq_IS, SumGroupTotalsSqN_IS, StudentT_IS, Group1Total_IS} ### Group of Ind Samp Statistics # __________________________________________ struct AnovaF_RM <: Statistic end # PRINCIPAL: 1-way repeated-measure ANOVA (H0: µ1 = µ2 = µ3 = … = µk) # With dichotomous data yields 1-saided and bi-directional Cochran Q test (K>2) and to the McNemar and sign test (K=2) # For ranked data gives the same p-value as the Friedman test struct SumTreatTotalsSq_RM <: Statistic end # EQUIVALENT to AnovaF_RM in all cases struct StudentT_RM <: Statistic end # PRINCIPAL: Student T for paired samples (repeated-measure) (H0: μ1≠μ2) # EQUIVALENT data gives the same p-value as the Wilcoxon signed rank test RepMeasStatistic = Union{AnovaF_RM, SumTreatTotalsSq_RM, StudentT_RM} ### Group of Repeated-Measure Statistics # __________________________________________ struct StudentT_1S <: Statistic end # PRINCIPAL: Student T for one sample (H0: μ≠0) struct Sum <: Statistic end # EQUIVALENT to Student T for one sample (H0: μ≠0) OneSampStatistic = Union{StudentT_1S, Sum} ### Group of One-sample statistics # _________________________________________________________________________________________________________________________________ AllStatistics=Union{BivStatistic, IndSampStatistic, RepMeasStatistic, OneSampStatistic} # Parameter-free statistics, those that do not need precomputed data to be computed faster ParFreeStatistics=Union{BivStatistic, IndSampStatistic, SumTreatTotalsSq_RM, StudentT_RM, Sum} abstract type TestDirection end # Right-, Left-Directional or Bi-Directional # singletons : struct Right <: TestDirection end # struct Left <: TestDirection end # struct Both <: TestDirection end # abstract type Assignment end # Balanced or Unbalanced struct Balanced <: Assignment end # struct Unbalanced <: Assignment end # abstract type TestResult end struct UniTest <: TestResult p::Float64 stat::statistic where statistic <: Statistic obsstat::Float64 minp::Float64 nperm::Int64 testtype::Symbol direction::testDirection where testDirection <: TestDirection design::assignment where assignment <: Assignment end struct MultcompTest <: TestResult p::Vector{Float64} # different from UniTest stat::statistic where statistic <: Statistic obsstat::Vector{Float64} # different from UniTest minp::Float64 nperm::Int64 testtype::Symbol direction::testDirection where testDirection <: TestDirection design::assignment where assignment <: Assignment nulldistr::Vector{Float64} # in addition to UniTest rejections::Vector{Vector{Int64}} # in addition to UniTest stepdown::Bool # in addition to UniTest fwe::Float64 # in addition to UniTest end include("stats.jl") include("tools.jl") include("uniTests.jl") include("uniTests_API.jl") include("multcompTests.jl") include("multcompTests_API.jl") # Override Base.Show for UniTest and MultcompTest function Base.show(io::IO, ::MIME{Symbol("text/plain")}, t::Union{UniTest, MultcompTest}) println(io, titleFont, t isa UniTest ? ("\n"*rand(dice)*" Univariate Permutation test") : ("\n"*reduce(*, [rand(dice)*" " for i=1:3])*"... Multiple Comparison Permutation test")) if t isa UniTest println(io, defaultFont, "p-value = ", t.p < 0.0001 ? "<0.001" : round(t.p; digits=3)) else steps=max(1, length(t.rejections)) # number of steps stepsstr=steps==1 ? " step" : " steps" nrej=length(vcat(t.rejections...)) # number of rejections nhyp=length(t.p) # number of hypotheses proprej=round((nrej/nhyp)*100, digits=2) # proportion of rejections println(io, defaultFont, "Rejected ", nrej, " out of ", nhyp, " hypotheses ", "(", proprej, " %) in ", steps, stepsstr, " with FWE=", round(t.fwe, digits=8)) end print(io, greyFont, " ") println(io, reduce(*, [rand(dice)*" " for i=1:10])) print(io, separatorFont,".p ", greyFont, t isa UniTest ? "(p-value) " : "(p-values)") print(" ") print(io, separatorFont,".stat ", greyFont, "(test statistic)") print(" ") println(io, separatorFont,".obsstat ", greyFont, t isa UniTest ? " (observed statistic)" : " (observed statistics)") print(io, separatorFont,".minp ", greyFont, " (minimum attainable p-value)") print(" ") println(io, separatorFont,".nperm ", greyFont, "(number of permutations)") print(io, separatorFont,".testtype ", greyFont, " (exact or approximated)") print(" ") println(io, separatorFont,".direction ", greyFont, "(Both, Left or Right)") println(io, separatorFont,".design ", greyFont, " (Balanced or Unbalanced)") if t isa MultcompTest print(io, separatorFont,".nulldistr ", greyFont, " (null distribution)") print(" ") println(io, separatorFont,".rejections ", greyFont, "(for each step down)") print(io, separatorFont,".stepdown ", greyFont, " (true if stepdown)") print(" ") println(io, separatorFont,".fwe ", greyFont, "(family-wise err. stepdown)") end end # show println("\n⭐ "," Welcome to the ", 📌, "package", " ⭐\n") @info " " println(" Your Machine `", separatorFont, gethostname(), defaultFont, "` (",Sys.MACHINE, ")") println(" runs on kernel ",Sys.KERNEL, " with word size ", Sys.WORD_SIZE,".") println(" CPU Threads: ", separatorFont, Sys.CPU_THREADS, defaultFont) println(" Base.Threads: ", separatorFont, Threads.nthreads(), defaultFont) end # module
PermutationTests
https://github.com/Marco-Congedo/PermutationTests.jl.git
[ "MIT" ]
0.2.0
8a73fe1574e159927031bb2b9cc6ea142f075407
code
17851
#= multcompTests.jl Unit of the PermutationTests.jl Package MIT License Copyright (c) 2024, Marco Congedo, CNRS, Grenoble, France: https://sites.google.com/site/marcocongedo/home ########################################## # Multiple Comparisons Permutation tests # ########################################## Run `test_multcompTests()` in unit _test.jl to test this unit ============================= EXPORTED: _permMcTest! - ultimate function to perform all multiple comparison tests testStatistic - compute the ith observed and permuted statistic for multiple comparison tests UTILITIES: _preComputedData - pre-computed data for rep meas ANOVA and one-sample t-test for multiple comparison tests _randperm_multComp! - generate a random permutation for multiple comparison tests ============================= =# ###################################################################################################################################### # ----- # # Pre-compute data that is invariant to permutations for repeated measure ANOVA _preComputedData(𝐘::UniDataVec, ns, stat::AnovaF_RM) = [_∑Y²kn_∑y²_∑S²k(𝐲, ns) for 𝐲 ∈ 𝐘] _preComputedData(𝐘::UniDataVec, ns, stat::StudentT_1S) = [∑of²(𝐲) for 𝐲 ∈ 𝐘] _preComputedData(𝐘::UniDataVec, ns, stat::ParFreeStatistics) = nothing _preComputedData(𝐘, ns, stat) = nothing # allow calling with custom data types and or custum statistic # ----- # # ----- # # Generate a random permutation overwriting either vector 𝐱 or all vectors in 𝐘, depending on stat. Does not return anything. # For both BivStatistic and IndSampStatistic this is a suffling of the elements of 𝐱 and ns is ignored # For RepMeasStatistic statistics this is a suffling of all elements of 𝐱 taken k at a time. ns is needed # For OneSampStatistic statistics, the sign of the elements in the 𝐲 vectors of 𝐘 is flipped with probability 0.5. ns is ignored # Only for this latter case this procedure is algorithmically different as compared to the univariate tests, but here never return anything. # Note that instead for exact test only the 𝐱 vector is changed _randperm_multComp!(𝐱::UniData, 𝐘, stat::Union{BivStatistic, IndSampStatistic}, rng::MersenneTwister; ns::nsType = 0, ft = nothing) = shuffle!(rng, 𝐱) function _randperm_multComp!(𝐱::UniData, 𝐘, stat::RepMeasStatistic, rng::MersenneTwister; ns = @NamedTuple{n::Int, k::Int}, ft = nothing) @simd for i=0:ns.n-1 @inbounds shuffle!(rng, view(𝐱, (i*ns.k)+1:(i*ns.k)+ns.k)) # shuffling in-place of 𝐱 end end function _randperm_multComp!(𝐱::UniData, 𝐘, stat::OneSampStatistic, rng::MersenneTwister; ns::nsType = 0, ft::Tuple=(-1.0, 1.0)) signs = [rand(rng, ft) for i = 1:length(𝐘[1])] # vector of random signa with probability 0.5 (rand pick a number at random from `ft`) @simd for i ∈ eachindex(𝐘) @inbounds 𝐘[i] .*= signs # the vector of signs is the same for all variables end end # ----- # # ----- # """ ```julia # METHOD 1 function testStatistic(x, y, stat::mystat, fstat::Function; cpcd=nothing, kwargs...) # METHOD 2 function testStatistic(x, Y, i::Int, stat::mystat, fstat::Function; cpcd=nothing, kwargs...) where mystat<:Statistic ``` Compute the observed and permuted test statistic for univariate tests (Method 1) or the ``i^{th}`` observed and permuted test statistic for the ``i^{th}`` hypothesis, with ``i=1...M``, for multiple comparisons permutation tests (Method 2). If you [create your own test](@ref "Create your own test") you will write new methods for these functions taking as `stat` a test statistic of type [Statistic](@ref) you have declared. If not, you never need these functions. `Y` is a vector of elements (typically, vectors themelves) and the test-statistic is to be computed on `Y[i]`, using the permutation vector `x`. For the `fstat` and `cpcd` argument, see how to [create your own test](@ref "Create your own test"). """ testStatistic(𝐱, 𝐘::UniDataVec, i::Int, stat::AnovaF_RM; cpcd=nothing, kwargs...) = statistic(𝐱, 𝐘[i], stat; ∑Y²kn=cpcd[i][1], ∑y²=cpcd[i][2], ∑S²k=cpcd[i][3], kwargs...) testStatistic(𝐱, 𝐘::UniDataVec, i::Int, stat::StudentT_1S; cpcd=nothing, kwargs...) = statistic(𝐱, 𝐘[i], stat; ∑y²=cpcd[i], kwargs...) # all other tests implemented in PermutationsTests.jl testStatistic(𝐱, 𝐘::UniDataVec, i::Int, stat::ParFreeStatistics; cpcd=nothing, kwargs...) = statistic(𝐱, 𝐘[i], stat; kwargs...) # ----- # # ----- # """ ```julia function _permMcTest!(x, Y, ns::nsType, stat::Stat, asStat::AsStat; standardized::Bool=false, centered::Bool=false, stepdown::Bool = true, fwe::Float64 = 0.05, nperm::Int = 20000, fstat::Function = abs, compfunc::Function = >=, switch2rand::Int = Int(1e8), seed::Int = 1234, threaded::Bool = Threads.nthreads()>=4, verbose::Bool = true, cpcd = nothing) where {Stat<:Statistic, AsStat<:Statistic} ``` This function ultimately performs all **multiple comparisons permutation tests** implemented in *PermutationsTests.jl*, both *exact* and *approximate* (Monte Carlo). For running tests use the [multiple comparisons test functions](@ref "Multiple comparisons tests"). You need this function only for [creating your own tests](@ref "Create your own test"). The step-down version of the test is performed if `stepdown` is true (default). In this case the `fwe` (family-wise error) rate is used for rejection at each step (default=0.05). Rewrite `x` and/or `Y`, depending on the test performed. For the `ns` argument see [ns](@ref). `stat` can be a singleton of the [Statistic](@ref) type or a user-defined singleton of this type to be used as argument of two functions implemented by the user to compute the observed and permuted test statistics, see [create your own test](@ref "Create your own test"). !!! warning In contrast to univariate tests, equivalent statistics are not possible for multiple comparison tests, with the exception of `CrossProd()` if the data has been standardized and `Covariance()` if the data has been centered and those only for correlation-like tests. The test statistics that must be used as `Stat` for the other kinds of test if a singleton of the [Statistic](@ref) type is used are `AnovaF_IS()`, `StudentT_IS()`, `AnovaF_RM()`, and `StudentT_1S()`. `asStat` is a singleton of the [Statistic](@ref) type. It is used to determine the permutation scheme and for this purpose it will be passed to [`genPerms`](@ref) and [`nrPerms`](@ref). `asStat` determines also the input data format if you declare your own `stat` type. In this case the two functions you write for computing the observed and permuted statistics will take the `x` and `Y` arguments as it follows. For `Stat` belonging to [group](@ref "Statistic groups") - `BivStatistic` : `x` is a fixed vector with ``N`` elements and `Y` an an ``M``-vector of ``N``-vectors. The ``M`` bivariate statistics between `x` and the ``y_m`` vectors of `Y` are tested simultaneously. `ns` is ignored. - `IndSampStatistic` : we have ``K`` groups and ``N=N_1+...+N_K`` total observations; `Y` is an ``M``-vector, each one holding all observations for the ``m^{th}`` hypothesis in a single vector. The ``m^{th}`` vector ``y_m`` concatenates the observations for all groups such as [y[m][1];...;y[m][K]]. `x` is the [`membership(::IndSampStatistic)`](@ref) vector, common to all hypotheses. For example, for ``K=2``, ``N_1=2`` and ``N_2=3``, `x=[1, 1, 2, 2, 2] `. - `RepMeasStatistic` : we have ``K`` measures (*e.g.*, treatements) and ``N`` subjects; `Y` is an M-vector, each one holding the ``K*N`` observations for the ``m^{th}`` hypothesis in a single vector. The ``m^{th}`` vector ``y_m`` is such as `[Y[m][1];...;Y[m][N]]`, where each vector Y[1][n], for ``n=1…N``, holds the observations for the ``K`` treatments and `x=collect(1:K*N)` (see [`membership(::RepMeasStatistic)`](@ref)). - `OneSampStatistic` : We have ``N`` observations (*e.g.*, subjects); `Y` is an ``M``-vector, each one holding the ``N`` observations and `x=ones(Int, N)` (see [`membership(::OneSampStatistic)`](@ref)). !!! note "Nota Bene" In all cases `x` is treated as the permutation vector that will be permuted before calling the [`testStatistic`](@ref) function for each of the elements in `Y`. Optional keyword arguments `switch2rand`, `nperm`, `standardized`, `centered`, `seed`, `fstat`, `compfunc` and `verbose` have the same meaning as in the [`_permTest!`](@ref) function. If `threaded` is true (default) the function is multi-threaded if the product of the number of hypotheses, observations, and permutations exceed 500 millions. If you have unexpected problems with the function, try setting `threaded` to false. For the `cpcd` and `kargs...` arguments, see [create you own test](@ref "Create your own test"). Return a [MultcompTest](@ref) structure. The number of executed steps ``S`` can be retrived as the length of the `.rejections` field of the returned structure. *Examples* ```julia using PermutationTests N, M = 8, 100 # 100 hypotheses, N=8 x=randn(N) Y=[randn(N) for m=1:M] # bi-directional exact test of the correlation between x and # all the M vector in Y. T12 = _permMcTest!(x, Y, N, PearsonR(), PearsonR()) T12.p T12.stat #... # bi-directional exact test. Faster test by data standardization T12_2 = _permMcTest!(μ0σ1(x), [μ0σ1(y) for y in Y], N, CrossProd(), PearsonR(); standardized=true) # left-directional exact test. T12_3 = _permMcTest!(μ0σ1(x), [μ0σ1(y) for y in Y], N, CrossProd(), PearsonR(); standardized=true, fstat=flip) # as above, but force an approximate test T12_4 = _permMcTest!(μ0σ1(x), [μ0σ1(y) for y in Y], N, CrossProd(), PearsonR(); standardized=true, fstat=flip, switch2rand=1) # the same using 5000 random permutations T12_4 = _permMcTest!(μ0σ1(x), [μ0σ1(y) for y in Y], N, CrossProd(), PearsonR(); standardized=true, fstat=flip, switch2rand=1, nperm=5000) ``` To check more examples, see the *multcompTests_API.jl* unit located in the *src* github folder and function `test_multicompTests()` in the *runtests.jl* unit located in the *test* github folder. """ function _permMcTest!(𝐱, 𝐘, ns::nsType, stat::Stat, asStat::AsStat; standardized::Bool=false, centered::Bool=false, # means::Tuple=(), sds::Tuple=(), # optional kwa for correlation-like statistics stepdown::Bool = true, fwe::Float64 = 0.05, nperm::Int = 20000, fstat::Function = abs, compfunc::Function = >=, switch2rand::Int = Int(1e8), seed::Int = 1234, threaded::Bool = Threads.nthreads()>=4, verbose::Bool = true, cpcd = nothing, kwargs...) where {Stat<:Statistic, AsStat<:Statistic} # check that all vectors in 𝐘 have the same length. This is special for multivariate tests length(unique(length(𝐲) for 𝐲 ∈ 𝐘)) ≠ 1 && throw(ArgumentError(📌*" Function _permMcTest!: The elements (typically, vectors) in 𝐘 do not have all the same length")) # check arguments and prepare test testtype, nperm, direction, design, mykwargs, rng = _prepare_permtest!(𝐱, 𝐘[1], ns, asStat, fstat, nperm, switch2rand, seed, standardized, false)#, (), ()) # pre-computed data in case of some statistics. This is special for multivariate tests. Set to nothing for custom statistics pcd = _preComputedData(𝐘, ns, stat) # println("pcd: ", pcd) ####################### START TEST ############################## # observed statistics for all variables in 𝐘 # eps is to avoid floating point arithmetic errors when comparing the permuted stats obsStats = [fstat(testStatistic(𝐱, 𝐘, i, stat; cpcd=pcd, mykwargs..., kwargs...)) - sqrt(eps()) for i ∈ eachindex(𝐘)] verbose && println("Performing a ", threaded ? "(multi-threaded) " : "", "test using ", testtype == :exact ? "$nperm systematic permutations..." : "$nperm random permutations...") # initialization and reserve required memory upfront to boost performance accepted = trues(length(𝐘)) # BitArray, mask of accepted H0. Be careful, for multi-threading it is not thread safe. Use booleans instead rejections = Vector{Vector{Int64}}() # keep track of the rejected hypotheses at each step (a vector of indeces at each step) pvalues = Vector{Float64}(undef, length(𝐘)) # corrected p-values nullDistr = Vector{Float64}(undef, nperm) # Null distribution (only the one at last step will be returned) maxrejp = 0. # max rejected p-value at current step. step = 0 nSig = 0 hasRejected = true # set to false to exit the while loop and stop the step-down procedure # perform max-statistic or step-down max-statistic test, depending on whether `stepdown` is true. while hasRejected # get p-values ############################################################ # For each variable the p-value is otained as the number of elements in the null distribution of max statistics satisfting fenction # `compfunc` when compared to the the observed statistic for that variable (>= by default, don't touch it) divided by the # number of permutations. `fstat` is abs for two-tailes test, identity for right-tailed tests and flip for a left-tails test. # For exact tests P is a lazy itarator over all systematic permutations. # Nota bene: for exact tests the permutation corresponding to the observed data is the first in P, thus the observed max statistic # is naturally included in the null distribution. For the approximate (monte carlo) tests, the observed max statistic is added # to the null distribution. tx = threaded && count(accepted)*length(𝐘[1])*nperm>5e8 # decide if using multithreading. count(accepted) considers the remaining Hyp. maxf = tx ? Folds.maximum : Base.maximum # the only multi-threading function is the maximum of the p-value if testtype == :exact P = genPerms(asStat, 𝐱, ns, direction, design) # generate systematic permutations as a lazy iterator if asStat isa StudentT_1S # bug fix: for StudentT_1S only, the iterator yields tuples and can be enumerated for (j, p) in enumerate(P) # and this iterator works only expliciting the for loop nullDistr[j] = maxf(fstat(testStatistic(p, 𝐘, i, stat; cpcd=pcd, mykwargs..., kwargs...)) for i ∈ eachindex(𝐘, accepted) if accepted[i]) end else # on the other hand the other iterators cannot be enumerated nullDistr = [maxf(fstat(testStatistic(p, 𝐘, i, stat; cpcd=pcd, mykwargs..., kwargs...)) for i ∈ eachindex(𝐘, accepted) if accepted[i]) for p ∈ P] end else # Monte Carlo test for j ∈ 1:nperm-1 _randperm_multComp!(𝐱, 𝐘, asStat, rng; ns) # one of 𝐱, 𝐘 is modified depending on stat to generate a random data permutation nullDistr[j] = maxf(fstat(testStatistic(𝐱, 𝐘, i, stat; cpcd=pcd, mykwargs..., kwargs...)) for i ∈ eachindex(𝐘, accepted) if accepted[i]) end nullDistr[end] = _condMax(obsStats, accepted) end # find significance (p-values) and indices of rejected hypotheses, flag rejected hypotheses, update highest rejected p-value, # limit significance to the highest p-value that has been rejected at previous step sort!(nullDistr, rev=true) # descending order highestRejected = 0. rejpos=Int[] @simd for i ∈ eachindex(pvalues) @inbounds if accepted[i] # at first pass all hypothesis are accepted pos = findlast(x->compfunc(x, obsStats[i]), nullDistr) pvalues[i] = pos===nothing ? 1/nperm : pos/nperm # find significance if pvalues[i] <= fwe # if there is a rejection push!(rejpos, i) # keep track of rejections for giving it as output accepted[i] = false # flag this hypotheses as rejected pvalues[i] > highestRejected && (highestRejected = pvalues[i]) # find the highest rejected p-value pvalues[i] = max(pvalues[i], maxrejp) # limit significance to the highest p-value that has been rejected at previous step nSig += 1 # number of rejected hypotheses end end end maxrejp = highestRejected # Limit significance hereafter to the highest rejected pvalue at this step ############################################################ if isempty(rejpos) # no rejeced hypothesis verbose && print("Step ", step+1, ": no rejection; step-down process stops.\n") else push!(rejections, rejpos) # keep track of the rejected hypotheses at each step length(rejpos)<30 ? verbose && println("Step ", step+1, ": rejected hypotheses ", rejpos) : verbose && println("Step ", step+1, ": ", length(rejpos), " hypotheses have been rejected") end # exit while stepdown=false or if there were no rejeced hypothesis hasRejected = !stepdown || isempty(rejpos) || nSig==length(𝐘) ? false : true step += 1 end # while ############################################################ return MultcompTest(pvalues, stat, obsStats, 1/nperm, nperm, testtype, direction, design, nullDistr, rejections, stepdown, fwe) end # ----- # # ----------------------------------------------------- #
PermutationTests
https://github.com/Marco-Congedo/PermutationTests.jl.git
[ "MIT" ]
0.2.0
8a73fe1574e159927031bb2b9cc6ea142f075407
code
53286
#= multcompTests_API.jl Unit of the PermutationTests.jl Package MIT License Copyright (c) 2024, Marco Congedo, CNRS, Grenoble, France: https://sites.google.com/site/marcocongedo/home ################################################# # API for Multiple Comparison Permutation tests # ################################################# Run `test_mult_compTests_API()` in unit _test.jl to test this unit ======================================== EXPORTED: correlationMcTest!, rMcTest!, correlationMcTest, rMcTest, trendMcTest!, trendMcTest, pointBiSerialMcTest, anovaMcTestIS, fMcTestIS, studentMcTestIS, tMcTestIS, chiSquaredMcTest, Χ²McTest, fisherExactMcTest, anovaMcTestRM, fMcTestRM, cochranqMcTest, qMcTest, mcNemarMcTest, studentMcTestRM, McTestRM, studentMcTestRM!, McTestRM!, studentMcTest1S!, tMcTest1S!, studentMcTest1S, tMcTest1S, signMcTest!, signMcTest ======================================== =# # GENERAL KEYWORD ARGUMENTS IN COMMON WITH UNIVARIATE TESTS # --------------------------------------------------------- # direction: test direction, either Right(), Left() or Both(). Default: Both() # switch2rand (Int): the # of permutations starting from which the approximate test will be carried out. Default: 1e8 # nperm (Int): the # of permutations to be used if the test will be approximate (default: 20_000) # seed (Int): random # generator seed. Set to 0 to take a random seed. Any natural number allow a reproducible test.(Default: 1234) # verbose (Bool) print some information in the REPL while running the test. Set to false for running @benchmark (Default: true). # GENERAL KEYWORD ARGUMENTS THAT ARE SPECIAL TO MULTIPLE COMPARISON TESTS (NB: no `equivalent` arg is provided for multiple comparisons) # ----------------------------------------------------------------------- # stepdown: if true the step-down procedure is applied # fwe: rejection threshold for step-down procedures # threaded: if true the function will be run in multithreading for large problems ################################################################################## ### Correlation test # Example scenario of a multiple comparison correlation test: # A neuroscientist carries out an fMRI experiment on N=16 subjects, obtaining a metabolic measure of neuronal workload # at each of M=24000 brain voxels. # The experiment involes a cognitive task allowing a measure of latency to complete the task for each subject. # The scientist wish to know if there exist one ore more brain region which metabolism correlate or anticorrelate with the latency. # Let 𝐱 be the vector of N latencies for each subject and let 𝐘=[𝐲1, ..., 𝐲M] be the vector of M vectors, holding each one # the N methabolic measures for each subject, in the same order as in 𝐱. The multiple comparion test is obtained as # rMc = rMcTest!(𝐱, 𝐘) # bi-directional by default # If only a negative correlation was expected, the test would have been # rMc = rMcTest!(𝐱, 𝐘; direction=(Left)) """ ```julia function correlationMcTest(x::UniData, Y::UniDataVec; direction::TestDir = Both(), switch2rand::Int = max(Int(1e8) ÷ length(𝐘), Int(1e4)), nperm::Int = 20_000, seed::Int = 1234, verbose::Bool = true, # standardized::Bool = false, # stepdown::Bool = true, fwe::Float64 = 0.05, threaded::Bool = Threads.nthreads()>=4) where TestDir <: TestDirection ``` Multiple comparisons [Pearson product-moment correlation test](https://en.wikipedia.org/wiki/Pearson_correlation_coefficient#Testing_using_Student's_t-distribution) by data permutation. Run ``M`` correlation tests simultaneously. The input data are a fixed vector `x` and ``M`` vectors given as `Y`, a vector of ``M`` vectors ``y_1,...,y_M``. `x` and all vectors in `Y` must have equal length. The ``M`` null hypotheses have form ``H_0(m):r_{(x, y_m)}=0, \\quad m=1...M``, where ``r_{x,y_m}`` is the Pearson correlation coefficient between vector `x` and the ``m^{th}`` vector of `Y`. For optional keyword arguments, `direction`, `switch2rand`, `nperm`, `seed`, `verbose`, `stepdown`, `fwe` and `threaded`, see [here](@ref "Common kwargs for multiple comparisons tests"). If `standardized` is true, both `x` and all vectors of `Y` are assumed standardized (zero mean and unit standard deviation). With standardized input data the test can be executed faster as in this case the cross-product is actually the correlation. If `standardized` is false, the data will be standardized to execute a faster test. *Directional tests, permutation scheme and number of permutations for exact tests:* as per *univariate version* [`correlationTest`](@ref) *Aliases:* `rMcTest`, [`trendMcTest`](@ref) Return a [MultcompTest](@ref) structure. *Examples* ```julia using PermutationTests N=10; # number of observations M=100; # number of tests x=randn(N); Y=[randn(N) for i=1:M]; t=rMcTest(x, Y) # bi-directional test ``` ```julia tR=rMcTest(x, Y; direction=Right()) # right-directional test tL=McTest(x, Y; direction=Left()) # left-directional test tMC=rMcTest(x, Y; switch2rand=1) # Force a monte carlo test # Force a monte carlo test and performs 50K permutations t5K=rMcTest(x, Y; switch2rand=1, nperm= 50_000) tnoSD=rMcTest(x, Y; stepdown=false) # don't do stepdown tnoMT=rMcTest(x, Y; threaded=false) # don't run it multithreaded t001=rMcTest(x, Y; fwe=0.01) # stepdown rejects at 0.01 level instead of 0.05 ``` **Similar tests** See [correlationTest](@ref) """ function correlationMcTest(𝐱::UniData, 𝐘::UniDataVec; direction::TestDir = Both(), switch2rand::Int = max(Int(1e8) ÷ length(𝐘), Int(1e4)), nperm::Int = 20_000, seed::Int = 1234, verbose::Bool = true, # standardized::Bool = false, # stepdown::Bool = true, fwe::Float64 = 0.05, threaded::Bool = Threads.nthreads()>=4) where TestDir <: TestDirection length(𝐘)==1 && (return correlationTest(𝐱, 𝐘[1]; direction, switch2rand, nperm, seed, standardized, verbose)) length(𝐱) == length(𝐘[1]) || throw(ArgumentError(📌*"Function correlationMcTest: the first argument (𝐱) and the vectors in the second (𝐘) must have equal length. Check the documentation")) length(unique(length.(𝐘)))==1 || throw(ArgumentError(📌*"Function correlationMcTest: the vectors in the second argument (𝐘) must have all equal length. Check the documentation")) return standardized ? _permMcTest!(copy(𝐱), 𝐘, length(𝐱), PearsonR(), PearsonR(); standardized=true, stepdown, fwe, nperm, fstat=_fstat(direction), switch2rand, seed, threaded, verbose) : _permMcTest!(μ0σ1(𝐱), [μ0σ1(𝐲) for 𝐲 in 𝐘], length(𝐱), PearsonR(), PearsonR(); standardized=true, stepdown, fwe, nperm, fstat=_fstat(direction), switch2rand, seed, threaded, verbose) end # alias. The trendTest is obtained passed the trend to be tested as vector `𝐱`. For example [1, 2,...] for an ascending linear trend rMcTest = correlationMcTest # same as correlationMcTest! but in no case vector 𝐱 will be overwritten. """ ```julia function correlationMcTest!(<same args and kwargs as `correlationMcTest`>) ``` As [`correlationMcTest`](@ref), but `x` is overwritten if `standardized` is true. *Aliases:* `rMcTest!`, [`trendMcTest!`](@ref) *Univariate version:* [`correlationTest!`](@ref) """ function correlationMcTest!(𝐱::UniData, 𝐘::UniDataVec; direction::TestDir = Both(), switch2rand::Int = max(Int(1e8) ÷ length(𝐘), Int(1e4)), nperm::Int = 20_000, seed::Int = 1234, verbose::Bool = true, # standardized::Bool = false, # stepdown::Bool = true, fwe::Float64 = 0.05, threaded::Bool = Threads.nthreads()>=4) where TestDir <: TestDirection length(𝐘)==1 && (return correlationTest!(𝐱, 𝐘[1]; direction, switch2rand, nperm, seed, standardized, verbose)) length(𝐱) == length(𝐘[1]) || throw(ArgumentError(📌*"Function correlationMcTest!: the first argument (𝐱) and the vectors in the second (𝐘) must have equal length. Check the documentation")) length(unique(length.(𝐘)))==1 || throw(ArgumentError(📌*"Function correlationMcTest!: the vectors in the second argument (𝐘) must have all equal length. Check the documentation")) return standardized ? _permMcTest!(𝐱, 𝐘, length(𝐱), PearsonR(), PearsonR(); standardized=true, stepdown, fwe, nperm, fstat=_fstat(direction), switch2rand, seed, threaded, verbose) : _permMcTest!(μ0σ1(𝐱), [μ0σ1(𝐲) for 𝐲 in 𝐘], length(𝐱), PearsonR(), PearsonR(); standardized=true, stepdown, fwe, nperm, fstat=_fstat(direction), switch2rand, seed, threaded, verbose) end # alias rMcTest! = correlationMcTest! """ ```julia function trendMcTest(<same args and kwargs as correlationMcTest>) ``` """ trendMcTest = correlationMcTest """ ```julia function trendMcTest!(<same args and kwargs as correlationMcTest!>) ``` Actually aliases of [`correlationMcTest`](@ref) and [`correlationMcTest!`](@ref), respectively. `x` is any specified trend (linear, polynomial, exponential, logarithmic, trigonometric, ...) and `Y` holds the observed data. A multiple comparison Pearson product-moment correlation test between `x` and all ``M`` vectors in `Y` is then carried out. Directional tests, permutation scheme and number of permutations for exact tests: as per *univariate versions* [`trendTest`](@ref) or [`trendTest!`](@ref) Both methods return a [MultcompTest](@ref) structure. *Examples* ```julia using PermutationTests # We are goint to test an upward linear trend N=10 M=100 x=Float64.(collect(Base.OneTo(N))) # [1, 2,..., N] # out of the M vectors created here below, only one has a significant correlation Y=[[1., 2., 4., 3., 5., 6., 7., 8., 10., 9.], ([randn(N) for m=1:M-1]...)]; # Since we expect an upward linear trend, the correlation is expected to be positive, # hence we use a right-directional test to increase the power of the test. t = trendMcTest(x, Y; direction=Right()) ``` """ trendMcTest! = correlationMcTest! # alias ### ANOVA for independent samples """ ```julia # METHOD (1) function anovaMcTestIS(Y::UniDataVec, ns::IntVec; direction::TestDir = Both(), switch2rand::Int = max(Int(1e8) ÷ length(𝐘), Int(1e4)), nperm::Int = 20_000, seed::Int = 1234, verbose::Bool = true, # stepdown::Bool = true, fwe::Float64 = 0.05, threaded::Bool = Threads.nthreads()>=4) where TestDir <: TestDirection ``` """ function anovaMcTestIS(𝐘::UniDataVec, ns::IntVec; direction::TestDir = Both(), switch2rand::Int = max(Int(1e8) ÷ length(𝐘), Int(1e4)), nperm::Int = 20_000, seed::Int = 1234, verbose::Bool = true, # stepdown::Bool = true, fwe::Float64 = 0.05, threaded::Bool = Threads.nthreads()>=4) where TestDir <: TestDirection length(𝐘)==1 && (return anovaMcTestIS(𝐘[1], ns; direction, switch2rand, nperm, seed, verbose)) length(unique(length.(𝐘)))==1 || throw(ArgumentError(📌*"Function anovaMcTestIS: the vectors in the first argument (𝐘) must have all equal length. Check the documentation")) !(direction isa Both) && throw(ArgumentError(📌*"Function anovaMcTestIS: The ANOVA test can only be bi-directional. Correct the `direction` keyword argument. Check the documentation")) length(ns) < 2 && throw(ArgumentError(📌*"Function anovaMcTestIS: the second argument (ns) must be a vector of two or more integers. Check the documentation")) sum(ns) ≠ length(𝐘[1]) && throw(ArgumentError(📌*"Function anovaMcTestIS: the sum of the integers in second argument (ns) must be equal to the length of the vectprs in first argument. Check the documentation")) 𝐱 = membership(AnovaF_IS(), ns) return length(ns)>2 ? _permMcTest!(𝐱, 𝐘, ns, AnovaF_IS(), AnovaF_IS(); stepdown, fwe, nperm, switch2rand, seed, threaded, verbose) : _permMcTest!(𝐱, 𝐘, ns, StudentT_IS(), StudentT_IS(); stepdown, fwe, nperm, switch2rand, seed, threaded, verbose) end # method 2: Input data is given as a multiple comparison vector of K vectors of observations for group 1...group K. Each vector has arbitrary length. """ ```julia # METHOD (2) function anovaMcTestIS(𝐘vec::UniDataVec²; <same kwargs>) ``` **METHOD (1)** Multiple comparisons [1-way analysis of variance (ANOVA) for independent samples](https://en.wikipedia.org/wiki/One-way_analysis_of_variance) by data permutation. Run ``M`` ANOVAs simultaneously. The Input data is given as a vector `Y` holding ``M`` vectors ``𝐲1,...,𝐲M`` concatenating all observations, that is, holding each ``N=N_1+...+N_K`` observations for ``K>2`` independent samples (groups). The observations are ordered with group 1 first, then group 2,..., finally group K. Note that the group numerosity ``N_1,...,N_K`` must be the same for all ``M`` hypotheses. The only check performed is that the first vector in `Y` contains `sum(ns)` elements. The ``M`` null hypotheses have form ``H_0(m): μ_{m1}= \\ldots =μ_{mK}, \\quad m=1...M``, where ``μ_{mk}`` is the mean of the ``k^{th}`` group for the ``m^{th}`` hypothesis. `ns` is a vector of integers holding the group numerosity ``N_1,...,N_K`` (see examples below). For optional keyword arguments, `direction`, `switch2rand`, `nperm`, `seed`, `verbose`, `stepdown`, `fwe` and `threaded` see [here](@ref "Common kwargs for multiple comparisons tests"). Directional tests, permutation scheme and number of permutations for exact tests: as per *univariate version* [`anovaTestIS`](@ref) *Alias:* `fMcTestIS` Return a [MultcompTest](@ref) structure. **METHOD (2)** As method (1), but input data `Yvec` is a vector holding ``M`` vectors of K vectors of observations for group 1,..., group K. *Examples* ```julia # method (1) using PermutationTests ns=[3, 4, 5] # number of observations in group 1, 2 and 3 M=10 # number of hypotheses Yvec = [[randn(n) for n in ns] for m=1:M]; # some random Gaussian data for example t = fMcTestIS([vcat(y...) for y in Yvec], ns) # ANOVA tests are always bi-directional # Force an approximate test with 5000 random permutations tapprox = fMcTestIS([vcat(y...) for y in Yvec], ns; switch2rand=1, nperm=5000) # in method (2) only the way the input data is formatted is different t2 = fMcTestIS(Yvec) # of course, method (1) and (2) give the same p-values println(sum(abs.(t.p-t2.p))≈0. ? "OK" : "error") ``` **Similar tests** See [`anovaTestIS`](@ref) """ function anovaMcTestIS(𝐘vec::UniDataVec²; direction::TestDir = Both(), switch2rand::Int = max(Int(1e8) ÷ length(𝐘vec), Int(1e4)), nperm::Int = 20_000, seed::Int = 1234, verbose::Bool = true, # stepdown::Bool = true, fwe::Float64 = 0.05, threaded::Bool = Threads.nthreads()>=4) where TestDir <: TestDirection length(𝐘vec)==1 && (return anovaMcTestIS(𝐘vec[1]; direction, switch2rand, nperm, seed, verbose)) !(direction isa Both) && throw(ArgumentError(📌*"Function anovaMcTestIS: The ANOVA test can only be bi-directional. Correct the `direction` keyword argument. Check the documentation")) K = length(𝐘vec[1]) K < 2 && throw(ArgumentError(📌*"Function anovaMcTestIS: the vectors in first argument (𝐘vec) must hold two or more vectors. Check the documentation")) ns=[length(𝐲) for 𝐲 in 𝐘vec[1]] unique(length(y) for y in 𝐘vec)[1]==length(ns) || throw(ArgumentError(📌*"Function anovaMcTestIS: All vectors in first arguments (𝐘vec) must contain the same number of vectors. Check the documentation")) unique(length.(y) for y in 𝐘vec)[1]==ns || throw(ArgumentError(📌*"Function anovaMcTestIS: All vectors in first arguments (𝐘vec) must contain vectors of equal length in the same order. Check the documentation")) 𝐱 = membership(AnovaF_IS(), ns) return K>2 ? _permMcTest!(𝐱, [vcat(𝐲vec...) for 𝐲vec ∈ 𝐘vec], ns, AnovaF_IS(), AnovaF_IS(); stepdown, fwe, nperm, switch2rand, seed, threaded, verbose) : _permMcTest!(𝐱, [vcat(𝐲vec...) for 𝐲vec ∈ 𝐘vec], ns, StudentT_IS(), StudentT_IS(); stepdown, fwe, nperm, switch2rand, seed, threaded, verbose) end # alias fMcTestIS = anovaMcTestIS ### t-test for independent samples """ ```julia # METHOD (1) function studentMcTestIS(Y::UniDataVec, ns::IntVec; direction::TestDir = Both(), switch2rand::Int = max(Int(1e8) ÷ length(𝐘), Int(1e4)), nperm::Int = 20_000, seed::Int = 1234, verbose::Bool = true, # stepdown::Bool = true, fwe::Float64 = 0.05, threaded::Bool = Threads.nthreads()>=4, asPearson::Bool = true) where TestDir <: TestDirection ``` """ function studentMcTestIS(𝐘::UniDataVec, ns::IntVec; direction::TestDir = Both(), switch2rand::Int = max(Int(1e8) ÷ length(𝐘), Int(1e4)), nperm::Int = 20_000, seed::Int = 1234, verbose::Bool = true, # stepdown::Bool = true, fwe::Float64 = 0.05, threaded::Bool = Threads.nthreads()>=4, asPearson::Bool = true) where TestDir <: TestDirection length(𝐘)==1 && (return studentTestIS(𝐘[1], ns; direction, equivalent=true, switch2rand, nperm, seed, verbose, asPearson)) length(unique(length.(𝐘)))==1 || throw(ArgumentError(📌*"Function studentMcTestIS: the vectors in the first argument (𝐘) must have all equal length. Check the documentation")) length(ns) ≠ 2 && throw(ArgumentError(📌*"Function studentMcTestIS: the second argument (ns) must be a vector of two integer")) sum(ns) ≠ length(𝐘[1]) && throw(ArgumentError(📌*"Function studentMcTestIS: the sum of the two integers in second argument (ns) must be equal to the length of the vectors in first argument (𝐘).")) if asPearson # run t-test as a correlation test with reversed membership vector 𝐱 = membership(StudentT_IS(), ns; rev=reverse) return _permMcTest!(μ0σ1(𝐱), [μ0σ1(𝐲) for 𝐲 in 𝐘], length(𝐱), CrossProd(), PearsonR(); standardized=true, stepdown, fwe, nperm, fstat=_fstat(direction), switch2rand, seed, threaded, verbose) else 𝐱 = membership(StudentT_IS(), ns) return _permMcTest!(𝐱, 𝐘, ns, StudentT_IS(), StudentT_IS(); stepdown, fwe, fstat=_fstat(direction), nperm, switch2rand, seed, threaded, verbose) end end # method 2: input data is given as a multiple comparison-vector of two vectors of arbitrary length, holding each the data of group 1 and group 2, # respectively. """ ```julia # METHOD (2) function studentMcTestIS(Yvec::UniDataVec²; <same kwargs>) ``` """ function studentMcTestIS(𝐘vec::UniDataVec²; direction::TestDir = Both(), switch2rand::Int = max(Int(1e8) ÷ length(𝐘vec), Int(1e4)), nperm::Int = 20_000, seed::Int = 1234, verbose::Bool = true, # stepdown::Bool = true, fwe::Float64 = 0.05, threaded::Bool = Threads.nthreads()>=4, asPearson::Bool = true) where TestDir <: TestDirection length(𝐘vec)==1 && (return studentTestIS(𝐘vec[1]; direction, equivalent=true, switch2rand, nperm, seed, verbose, asPearson)) K = length(𝐘vec[1]) K ≠ 2 && throw(ArgumentError(📌*"Function studentMcTestIS: the vectors in first argument must hold two vectors")) ns=[length(𝐲) for 𝐲 in 𝐘vec[1]] unique(length(y) for y in 𝐘vec)[1]==length(ns) || throw(ArgumentError(📌*"Function studentMcTestIS: All vectors in first arguments (𝐘vec) must contain the same number of vectors. Check the documentation")) unique(length.(y) for y in 𝐘vec)[1]==ns || throw(ArgumentError(📌*"Function studentMcTestIS: All vectors in first arguments (𝐘vec) must contain vectors of equal length in the same order. Check the documentation")) if asPearson # run t-test as a correlation test with reversed membership vector 𝐱 = membership(StudentT_IS(), ns; rev=reverse) return _permMcTest!(μ0σ1(𝐱), [μ0σ1(vcat(𝐲vec...)) for 𝐲vec ∈ 𝐘vec], length(𝐱), CrossProd(), PearsonR(); standardized=true, stepdown, fwe, nperm, fstat=_fstat(direction), switch2rand, seed, threaded, verbose) else 𝐱 = membership(StudentT_IS(), ns) return _permMcTest!(𝐱, [vcat(𝐲vec...) for 𝐲vec ∈ 𝐘vec], ns, StudentT_IS(), StudentT_IS(); stepdown, fwe, fstat=_fstat(direction), nperm, switch2rand, seed, threaded, verbose) end end # method 3: Input data is given as two multiple comparison-vectors of vectors of observations, 𝐗 for group 1 and 𝐘 for group 2. # The M vectors in 𝐗 have all the same length, so do the M vectors in 𝐘, but the vectors in 𝐗 and in 𝐘 don't have to be of the same length. """ ```julia # METHOD (3) function studentMcTestIS(X::UniDataVec, Y::UniDataVec; <same kwargs>) ``` **METHOD (1)** Multiple comparisons [Student's t-test for independent samples](https://en.wikipedia.org/wiki/Student's_t-test#Independent_(unpaired)_samples) by data permutation. Run ``M`` t-tests simultaneously. Given ``M`` hypotheses with ``N=N_1+N_2`` observations for two groups each, the ``M`` null hypotheses have form ``H_0(m): μ_{m1}=μ_{m2}, \\quad m=1...M``, where ``μ_{m1}`` and ``μ_{m2}`` are the mean of group 1 and group 2, respectively, for the ``m^{th}``hypothesis. For a bi-directional test, this t-test is equivalent to the 1-way ANOVA for two independent samples. However, in contrast to the ANOVA, it can be directional. `ns` is a vector of integers holding the group numerosity ``N_1, N_2`` (see examples below). For optional keyword arguments, `direction`, `switch2rand`, `nperm`, `seed`, `verbose`, `stepdown`, `fwe` and `threaded` see [here](@ref "Common kwargs for multiple comparisons tests"). If `asPearson` is true(default), the test is run as an equivalent version of a Pearson correlation test. This is in general advantageous for multiple comparison tests, especially if approximate (see the [benchmarks](@ref "Benchmarks")). If you seek best performance for exact tests, benchmark the speed of the test with `asPearson` set to true and to false to see what version is faster for your data. !!! note "nota" If `asPearson` is true, the `.stat` field of the test result will actually be `CrossProd()`, as the data will be standardized before running the test. See [`correlationTest`](@ref). *Directional tests, permutation scheme and number of permutations for exact tests:* as per *univariate version* [`studentTestIS`](@ref) *Aliases:* `tTestMcIS`, [`pointBiSerialMcTest`](@ref) Return a [MultcompTest](@ref) structure. **METHOD (2)** As method (1), but input data `Yvec` is a vector containing ``M`` pairs of vector of arbitrary length, holding in the natural order the data corresponding to the ``m^{th}`` hypothesis for group 1 and group 2, respectively. **METHOD (3)** As method (1), but input data `X` and `Y` holds ``M`` vectors of observations each, `X` corresponding to data for group 1 and `Y` corresponding to data for group 2. The ``M`` vectors in `X` must have all the same length (``N_1``), so must the ``M`` vectors in `Y` (``N_2``). *Examples* ```julia # (1) using PermutationTests M=100 # number of hypotheses ns=[4, 5] # number of observations in group 1 and group 2 (N1 and N2) N=sum(ns) # total number of observations Yvec = [[randn(n) for n in ns] for m=1:M]; # some random Gaussian data for example Y=[vcat(yvec...) for yvec in Yvec]; t = tMcTestIS(Y, ns) # by default the test is bi-directional # Force an approximate test with 10000 random permutations tapprox = tMcTestIS(Y, ns; switch2rand=1, nperm=10000) tR=tMcTestIS(Y, ns; direction=Right()) # right-directional test tL=tMcTestIS(Y, ns; direction=Left()) # left-directional test # with a bi-directional test, t is equivalent to a 1-way ANOVA for independent samples tanova= fMcTestIS(Y, ns) println(sum(abs.(t.p - tanova.p)) ≈ 0. ? "OK" : "error") # do not run it using the CrossProd test statistic tcor = tMcTestIS(Y, ns; asPearson=false) # in method (2) only the way the input data is formatted is different t2 = tMcTestIS(Yvec) println(sum(abs.(t.p - t2.p)) ≈ 0. ? "OK" : "error") # in method (3) also, only the way the input data is formatted is different t3 = tMcTestIS([Yvec[m][1] for m=1:M], [Yvec[m][2] for m=1:M]) println(sum(abs.(t.p - t3.p)) ≈ 0. ? "OK" : "error") ``` **Similar tests** See [`studentTest1S`](@ref) """ function studentMcTestIS(𝐗::UniDataVec, 𝐘::UniDataVec; direction::TestDir = Both(), switch2rand::Int = max(Int(1e8) ÷ length(𝐘), Int(1e4)), nperm::Int = 20_000, seed::Int = 1234, verbose::Bool = true, # stepdown::Bool = true, fwe::Float64 = 0.05, threaded::Bool = Threads.nthreads()>=4, asPearson::Bool = true) where TestDir <: TestDirection length(𝐗)==1 && length(𝐘)==1 && (return studentTestIS(𝐗[1], 𝐘[1]; direction, equivalent=true, switch2rand, nperm, seed, verbose, asPearson)) length(𝐗)==length(𝐘) || throw(ArgumentError(📌*"Function studentMcTestIS: the first two arguments must contain the same number of vectors")) length(unique(length.(𝐗)))==1 || throw(ArgumentError(📌*"Function studentMcTestIS: the vectors in the first argument (𝐗) must have all equal length. Check the documentation")) length(unique(length.(𝐘)))==1 || throw(ArgumentError(📌*"Function studentMcTestIS: the vectors in the second argument (𝐘) must have all equal length. Check the documentation")) ns=[length(𝐗[1]), length(𝐘[1])] if asPearson # run t-test as a correlation test with reversed membership vector 𝐱 = membership(StudentT_IS(), ns; rev=reverse) return _permMcTest!(μ0σ1(𝐱), [μ0σ1([𝐱; 𝐲]) for (𝐱, 𝐲) ∈ zip(𝐗, 𝐘)], length(𝐱), CrossProd(), PearsonR(); standardized=true, stepdown, fwe, nperm, fstat=_fstat(direction), switch2rand, seed, threaded, verbose) else 𝐱 = membership(StudentT_IS(), ns) return _permMcTest!(𝐱, [[𝐱; 𝐲] for (𝐱, 𝐲) ∈ zip(𝐗, 𝐘)], ns, StudentT_IS(), StudentT_IS(); stepdown, fwe, nperm, fstat=_fstat(direction), switch2rand, seed, threaded, verbose) end end # alias tMcTestIS = studentMcTestIS """ ```julia function pointBiSerialMcTest(<same args and kwargs as `studentMcTestIS`>) ``` Actually an alias for [`studentMcTestIS`](@ref). Run ``M`` [point bi-serial correlation tests](https://en.wikipedia.org/wiki/Point-biserial_correlation_coefficient) simultaneously. The correlations are between the ``M`` input data vectors ``y_1,...,y_M`` given as argument `Y`, all holding ``N=N_1+N_2`` elements, and a vector ``x``, internally created, with the first ``N_1`` elements equal to `1` and the remaining ``N_2`` elements equal to `2`. If you need to use other values for the dicothomous variable ``x`` or a different order for its elements, use [`correlationMcTest`](@ref) instead. The ``M`` null hypotheses have form ``H_0(m): b_{(x,y_m)}=0, \\quad m=1...M``, where ``b_{(x,y_m)}`` is the point bi-serial correlation between ``y_m`` (the ``m^{th}`` input data vectors in `Y`) and the internally created vector ``x``. *Directional tests, permutation scheme and number of permutations for exact tests:* as per *univariate version* [`pointBiSerialTest`](@ref) Return a [MultcompTest](@ref) structure. *Examples* ```julia using PermutationTests ns=[4, 6]; # N1=4, N2=6 N=sum(ns); # number of observations Y = [rand(N) for m=1:M]; # some Gaussian data as example # implicitly, the point bi serial correlation is between # y1,...,yM and x=[1, 1, 1, 1, 2, 2, 2, 2, 2, 2] t=pointBiSerialMCTest(Y, ns) # by default the test is bi-directional ``` ```julia tR=pointBiSerialMCTest(Y, ns; direction=Right()) # right-directional test tL=pointBiSerialMCTest(Y, ns; direction=Left()) # left-directional test ``` """ pointBiSerialMcTest = studentMcTestIS ### Chi-Square and Fisher Exact Test """ ```julia function chiSquaredMcTest(tables::AbstractVector{Matrix{I}}; direction::TestDir = Both(), switch2rand::Int = max(Int(1e8) ÷ length(𝐘), Int(1e4)), nperm::Int = 20_000, seed::Int = 1234, verbose::Bool = true, # stepdown::Bool = true, fwe::Float64 = 0.05, threaded::Bool = Threads.nthreads()>=4, asPearson::Bool = true) where {I <: Int, TestDir <: TestDirection} ``` Multiple comparisons [chi-squared](https://en.wikipedia.org/wiki/Chi-squared_test) (``\\chi^2``) permutation test for ``2 \\cdot K`` contingency tables, where ``K`` is ≥2. It tests simultaneously ``M`` contingency tables, which must all have same dimension and same column sums. The ``M`` null hypotheses have form ``H_0(m): O_m=E_m``, \\quad m=1...M``, where ``O_m`` and ``E_m`` are the observed and expected frequencies of the ``m^{th}``contingency table. `tables` is a vector of ``M`` contingency tables. See [`chiSquaredTest`](@ref) for more explanations. For optional keyword arguments, `direction`, `switch2rand`, `nperm`, `seed`, `verbose`, `stepdown`, `fwe` and `threaded` see [here](@ref "Common kwargs for multiple comparisons tests"). For ``K=2`` this function calls [`studentMcTestIS`](@ref) and pass to it also argument `asPearson`, otherwise calls [`anovaMcTestIS`](@ref) and argument `asPearson` is ignored. *Directional tests, permutation scheme and number of permutations for exact tests:* as per *univariate version* [`chiSquaredTest`](@ref) *Aliases:* `Χ²McTest`, [`fisherExactMcTest`](@ref) Return a [MultcompTest] structure. !!! warning For ``K>2``, permutations of dicothomous tables may yield a null "sum of squares within", thus an infinite *F* statistic for the ANOVA. In this case the `.nulldistr` field of the returned structure will contain some julia `Inf` elements. This does not apply for the univariate version of the test ([`chiSquaredTest`](@ref)), as in this case an equivalent statistic for the ANOVA is used (see [Statistic](@ref)) and those statistics can never go to infinity. *Examples* ```julia using PermutationTests tables=[[3 3 2; 0 0 1], [1 2 2; 2 1 1], [3 1 2; 0 2 1]]; t=Χ²McTest(tables) # the test is bi-directional tables=[[6 1; 2 5], [4 1; 4 5], [5 2; 3 4]] tR=fisherExactMcTest(tables; direction=Right()) # or tR=Χ²Test(tables; direction=Right()) # do not use PearsonR statistic tR_=fisherExactMcTest(tables; direction=Right(), asPearson=false) ``` """ function chiSquaredMcTest(tables::AbstractVector{Matrix{I}}; direction::TestDir = Both(), switch2rand::Int = max(Int(1e8) ÷ length(tables), Int(1e4)), nperm::Int = 20_000, seed::Int = 1234, verbose::Bool = true, # stepdown::Bool = true, fwe::Float64 = 0.05, threaded::Bool = Threads.nthreads()>=4, asPearson::Bool = true) where {I <: Int, TestDir <: TestDirection} length(tables)==1 && (return chiSquaredTest(tables[1]; direction, equivalent=true, switch2rand, nperm, seed, verbose)) !(direction isa Both) && (size(tables[1], 2) > 2) && throw(ArgumentError(📌*"Function chiSquaredMcTest or fisherExactMcTest: For input data matrices with more than 2 columns the test can only be bi-directional. Correct or eliminate the `direction` keyword argument")) 𝐘, ns = table2vec(tables, AnovaF_IS()) # anovaTestIS will switch to t-test if there are only two groups length(ns) < 2 && throw(ArgumentError(📌*"Function chiSquaredMcTest or fisherExactMcTest: the second argument must be a vector of two or more integers")) return length(ns)>2 ? anovaMcTestIS(𝐘, ns; direction, switch2rand, nperm, seed, verbose, stepdown, fwe, threaded) : studentMcTestIS(𝐘, ns; direction, switch2rand, nperm, seed, verbose, stepdown, fwe, threaded, asPearson) end # alias Χ²McTest = chiSquaredMcTest """ ```julia function fisherExactMcTest(<same args and kwargs as `chiSquaredMcTest`>) ``` Actually an alias for [`chiSquaredMcTest`](@ref). It can be used for 2x2 contingency tables. See [`chiSquaredTest`](@ref) for more explanations. *Univariate version:* [`fisherExactTest`](@ref) Return a [MultcompTest](@ref) structure. *Examples* ```julia using PermutationTests tables=[[6 1; 2 5], [4 1; 4 5], [5 2; 3 4]]; tR=fisherExactMcTest(tables; direction=Right()) # or tR=Χ²Test(tables; direction=Right()) ``` """ fisherExactMcTest = chiSquaredMcTest # alias ### ANOVA for Repeated Measures """ ```julia # METHOD (1) function anovaMcTestRM(Y::UniDataVec, ns::@NamedTuple{n::Int, k::Int}; direction::TestDir = Both(), switch2rand::Int = max(Int(1e8) ÷ length(𝐘), Int(1e4)), nperm::Int = 20_000, seed::Int = 1234, verbose::Bool = true, # stepdown::Bool = true, fwe::Float64 = 0.05, threaded::Bool = Threads.nthreads()>=4) where TestDir <: TestDirection ``` """ function anovaMcTestRM(𝐘::UniDataVec, ns::@NamedTuple{n::Int, k::Int}; direction::TestDir = Both(), switch2rand::Int = max(Int(1e8) ÷ length(𝐘), Int(1e4)), nperm::Int = 20_000, seed::Int = 1234, verbose::Bool = true, # stepdown::Bool = true, fwe::Float64 = 0.05, threaded::Bool = Threads.nthreads()>=4) where TestDir <: TestDirection length(𝐘) == 1 && (return anovaTestRM(𝐘[1], ns; direction, equivalent=true, switch2rand, nperm, seed, verbose)) length(unique(length.(𝐘)))==1 || throw(ArgumentError(📌*"Function anovaMcTestRM: the vectors in the first argument (𝐘) must have all equal length. Check the documentation")) ns.k < 2 && throw(ArgumentError(📌*"Function anovaMcTestRM: the `k` element of second argument (a named tuple) must be 2 or more")) ns.n < ns.k && throw(ArgumentError(📌*"Function anovaMcTestRM: the `n` element of second argument (a named tuple) must be greater than the `k` element")) #ns.n % ns.k ≠ 0 && throw(ArgumentError("Function anovaMcTestRM: impossible configuration for the `n` and `k` elements of second argument (a named tuple). The former is the number of subjects, the latter the treatments.")) ns.n*ns.k ≠ length(𝐘[1]) && throw(ArgumentError("📌*Function anovaMcTestRM: the `n` and `k` elements of second argument (a named tuple) must be such that their product is equal to the length of the first argument (𝐲)")) if ns.k == 2 # do t-test if there are only two groups. Actually do one-sample test on the difference 𝐱 = membership(StudentT_1S(), ns.n) return _permMcTest!(𝐱, [𝐲[1:2:ns.n*2-1].-𝐲[2:2:ns.n*2] for 𝐲 ∈ 𝐘], ns.n, StudentT_1S(), StudentT_1S(); stepdown, fwe, nperm, fstat=_fstat(direction), switch2rand, seed, threaded, verbose) else 𝐱 = membership(AnovaF_RM(), ns) !(direction isa Both) && throw(ArgumentError("📌*Function anovaMcTestRM: The ANOVA test can only be bi-directional. Correct the `direction` keyword argument")) return _permMcTest!(𝐱, 𝐘, ns, AnovaF_RM(), AnovaF_RM(); stepdown, fwe, nperm, fstat=_fstat(direction), switch2rand, seed, threaded, verbose) end end """ ```julia # METHOD (2) function anovaMcTestRM(Yvec::UniDataVec²; <same kwargs>) ``` **METHOD (1)** Multiple comparison [1-way analysis of variance (ANOVA) for repeated measures](https://en.wikipedia.org/wiki/Repeated_measures_design#Repeated_measures_ANOVA) by data permutation. Given ``M`` hypotheses, each with ``K`` repeated measures (e.g., treatments, time, etc.) for each of ``N`` observation units (e.g., subjects, blocks, etc.), the null hypotheses have form ``H_0(m): μ_{m1}= \\ldots =μ_{mk}, \\quad m=1...M``, where ``μ_{mk}`` is the mean of the ``k^{th}`` treatment for the ``m^{th}`` hypothesis. `Y` is a vector hoding ``M`` vectors, each one concatenaning the ``K`` treatments (treatment 1,..., treatment ``K``) for each observation for the ``m^{th}`` hypothesis in this order: the ``K`` treatments for observation 1, the ``K`` treatments for observation 2, ..., the ``K`` treatments for observation ``N``. Thus, `Y` holds ``M`` vectors of ``N \\cdot K`` elements. `ns` is a julia [named tuple](https://docs.julialang.org/en/v1/manual/types/#Named-Tuple-Types) with form `(n=N, k=K)` (see examples below). For optional keyword arguments, `direction`, `switch2rand`, `nperm`, `seed`, `verbose`, `stepdown`, `fwe` and `threaded` see [here](@ref "Common kwargs for multiple comparisons tests"). *Directional tests, permutation scheme and number of permutations for exact tests:* as per *univariate version* [`anovaTestRM`](@ref) *Alias:* `fTestMcRM` Return a [MultcompTest](@ref) structure. **METHOD (2)** As (1), but `Yvec` is a vector of ``M`` vectors, each one holding ``N`` vectors holding each the ``K`` treatments for the ``n^{th}`` subject (see examples below). *Examples* ```julia # method (1) using PermutationTests N=6 # number of observation units per treatment K=3 # number of treatments M=10 # number of hypotheses Yvec = [[randn(K) for n=1:N] for m=1:M]; # some random Gaussian data for example t = fMcTestRM([vcat(yvec...) for yvec in Yvec], (n=N, k=K)) # ANOVA tests are always bi-directional ``` ```julia # Force an approximate test with 5000 random permutations tapprox = fMcTestRM([vcat(yvec...) for yvec in Yvec], (n=N, k=K); switch2rand=1, nperm=5000) # in method (2) only the way the input data is formatted is different t2 = fMcTestRM(Yvec) println(sum(abs.(t.p - t2.p)) ≈ 0. ? "OK" : "error") println(sum(abs.(t.obsstat - t2.obsstat)) ≈ 0. ? "OK" : "error") ``` **Similar tests** See [`anovaTestRM`](@ref) """ function anovaMcTestRM(𝐘vec::UniDataVec²; direction::TestDir = Both(), switch2rand::Int = max(Int(1e8) ÷ length(𝐘vec), Int(1e4)), nperm::Int = 20_000, seed::Int = 1234, verbose::Bool = true, # stepdown::Bool = true, fwe::Float64 = 0.05, threaded::Bool = Threads.nthreads()>=4) where TestDir <: TestDirection N = length(𝐘vec[1]) K = length(𝐘vec[1][1]) K < 2 && throw(ArgumentError(📌*"Function anovaMcTestRM: the first (𝐘vec) argument must be a vector of vector of two or more vectors")) N < K && throw(ArgumentError(📌*"Function anovaMcTestRM: the length of the vectors in first argument must be greater than their number")) ns=(n=N, k=K) length(𝐘vec) == 1 && (return anovaTestRM(𝐘vec[1], ns; direction, equivalent=true, switch2rand, nperm, seed, verbose)) unique(length(y) for y in 𝐘vec)[1]==N || throw(ArgumentError(📌*"Function anovaMcTestRM: All vectors in first arguments (𝐘vec) must contain the same number of vectors (N). Check the documentation")) unique(length.(y) for y in 𝐘vec)[1]==repeat([K], N) || throw(ArgumentError(📌*"Function anovaMcTestIS: All vectors in first arguments (𝐘vec) must contain vectors of equal length (K). Check the documentation")) if K == 2 # do t-test if there are only two groups. Actually do one-sample test on the difference 𝐱 = membership(StudentT_1S(), ns.n) return _permMcTest!(𝐱, [[𝐲vec[n][1] for n=1:N]-[𝐲vec[n][2] for n=1:N] for 𝐲vec ∈ 𝐘vec], ns.n, StudentT_1S(), StudentT_1S(); stepdown, fwe, nperm, fstat=_fstat(direction), switch2rand, seed, threaded, verbose) else #[𝐲[1].-𝐲[2] for 𝐲 ∈ 𝐘vec] !(direction isa Both) && throw(ArgumentError(📌*"Function anovaMcTestRM: The ANOVA test can only be bi-directional. Correct the `direction keyword argument`")) 𝐱 = membership(AnovaF_RM(), ns) return _permMcTest!(𝐱, [vcat(𝐲...) for 𝐲 ∈ 𝐘vec], ns, AnovaF_RM(), AnovaF_RM(); stepdown, fwe, nperm, fstat=_fstat(direction), switch2rand, seed, threaded, verbose) end end # alias fMcTestRM = anovaMcTestRM ### Cocharn Q test # NB: not particular efficient. For an efficient alternative see https://dl.acm.org/doi/10.1145/3095076 """ ```julia function cochranqMcTest(tables::AbstractVector{Matrix{I}}; direction::TestDir = Both(), switch2rand::Int = max(Int(1e8) ÷ length(𝐘), Int(1e4)), nperm::Int = 20_000, seed::Int = 1234, verbose::Bool = true, # stepdown::Bool = true, fwe::Float64 = 0.05, threaded::Bool = Threads.nthreads()>=4) where {I <: Int, TestDir <: TestDirection} ``` Multiple comparisons [Cochran Q](https://en.wikipedia.org/wiki/Cochran's_Q_test) by data permutation. The Cochran Q test is analogous to the 1-way ANOVA for repeated measures, but takes as input dicothomous data (zeros and ones). Given ``M`` hypotheses, consisting each in ``N`` observation units (e.g., *subjects*, *blocks*, etc.) and ``K`` repeated measures (e.g., *treatments*, *time*, etc.), the null hypotheses have form ``H_0(m): μ_{m1}= \\ldots =μ_{mk}, \\quad m=1...M``, where ``μ_{mk}`` is the mean of the ``k^{th}`` treatment. Input `tables` is a vector of ``M`` tables of zeros and ones with size ``NxK``, where ``N`` is the number of observations and ``K`` the repeated measures. See [`cochranqTest`](@ref) for more explanations. For optional keyword arguments, `direction`, `switch2rand`, `nperm`, `seed`, `verbose`, `stepdown`, `fwe` and `threaded` see [here](@ref "Common kwargs for multiple comparisons tests"). *Directional tests, Permutation scheme and number of permutations for exact tests:* as per *univariate version* [`cochranqTest`](@ref) *Aliases:* `qMcTest`, [`mcNemarMcTest`](@ref) Return a [MultcompTest](@ref) structure. *Examples* ```julia using PermutationTests tables=[ [1 1 0; 1 0 0; 1 1 1; 1 1 0; 1 0 1; 1 1 0], [1 0 0; 1 1 0; 1 1 0; 1 1 1; 1 0 0; 1 0 0], [1 0 0; 0 0 1; 1 0 1; 1 1 0; 1 0 1; 1 0 0]]; t=qMcTest(tables) # the test with K>2 can only be bi-directional ``` """ function cochranqMcTest(tables::AbstractVector{Matrix{I}}; direction::TestDir = Both(), switch2rand::Int = max(Int(1e8) ÷ length(tables), Int(1e4)), nperm::Int = 20_000, seed::Int = 1234, verbose::Bool = true, # stepdown::Bool = true, fwe::Float64 = 0.05, threaded::Bool = Threads.nthreads()>=4) where {I <: Int, TestDir <: TestDirection} length(tables)==1 && (return cochranqTest(tables[1]; direction, equivalent=true, switch2rand, nperm, seed, verbose)) 𝐘, ns = table2vec(tables, AnovaF_RM()) # anovaTestRM will switch to t-test if there are only two groups return anovaMcTestRM(𝐘, ns; direction, switch2rand, nperm, seed, verbose, stepdown, fwe, threaded) end # alias qMcTest = cochranqMcTest ### McNemar test """ ```julia function mcNemarMcTest(same args and kwargs as `cochranqMcTest`>) ``` Actually an alias for [cochranqMcTest)(@ref). Run ``M`` McNemar test simultaneously. Input `tables` is a vector of ``M`` tables of zeros and ones with size ``Nx2``, where ``N`` is the number of observations and ``2`` the number of repeated measures. See [`cochranqTest`](@ref) for more explanations. *Univariate version:* [`mcNemarTest`](@ref) Return a [MultcompTest](@ref) structure. *Examples* ```julia using PermutationTests tables=[[1 1; 1 0; 1 0; 0 0; 1 0; 1 0], [1 0; 1 1; 1 0; 0 1; 0 0; 1 0], [0 1; 0 0; 1 0; 1 0; 1 0; 1 1]]; t=mcNemarMcTest(tables) # by default the test is bi-directional tR=mcNemarMcTest(tables; direction=Right()) # right-directional test ``` """ mcNemarMcTest = cochranqMcTest # alias ### One-Sample t-test """ ```julia function studentMcTest1S(Y::UniDataVec; refmean::Realo = nothing, direction::TestDir = Both(), switch2rand::Int = max(Int(1e8) ÷ length(𝐘), Int(1e4)), nperm::Int = 20_000, seed::Int = 1234, verbose::Bool = true, # stepdown::Bool = true, fwe::Float64 = 0.05, threaded::Bool = Threads.nthreads()>=4) where TestDir <: TestDirection ``` Multiple comparison [one-sample t-test](https://en.wikipedia.org/wiki/Student's_t-test#One-sample_t-test) by data permutation. Run ``M`` one-sample t-tests simultaneously. The null hypotheses have form ``H_0(m): μ_m=μ_0, \\quad m=1...M``, where ``μ_m`` is the mean of the observations for the ``m^{th}`` hypothesis and ``μ_{0}`` is a reference population mean. `refmean` is the reference mean (``μ_0``) above. The default is `0.0`, which is the value needed in most situations. `Y` is a vector of ``M`` vectors holding each the ``N`` observations which mean is to be compared to ``μ_0``. For optional keyword arguments, `direction`, `switch2rand`, `nperm`, `seed`, `verbose`, `stepdown`, `fwe` and `threaded` see [here](@ref "Common kwargs for multiple comparisons tests"). *Directional tests, permutation scheme and number of permutations for exact tests:* as per *univariate version* [`studentTest1S`](@ref) *Alias:* `tTest1S` Return a [MultcompTest](@ref) structure. *Examples* ```julia using PermutationTests N=20 # number of observations M=100 # number of hypotheses y = [randn(N) for m=1:M]; # some random Gaussian data for example t = tMcTest1S(Y) # By deafult the test is bi-directional tR = tMcTest1S(Y; direction=Right()) # right-directional test tL = tMcTest1S(Y; direction=Left()) # Left-directional test # Force an approximate test with 5000 random permutations tapprox = tMcTest1S(Y; switch2rand=1, nperm=5000) # test H0m: μ(ym)=1.5: all will be rejected as the expected mean is 0.0 t1 = tMcTest1S(Y; refmean=1.5) ``` **Similar tests** See [`studentTest1S`](@ref) """ function studentMcTest1S(𝐘::UniDataVec; refmean::Realo = nothing, direction::TestDir = Both(), switch2rand::Int = max(Int(1e8) ÷ length(𝐘), Int(1e4)), nperm::Int = 20_000, seed::Int = 1234, verbose::Bool = true, # stepdown::Bool = true, fwe::Float64 = 0.05, threaded::Bool = Threads.nthreads()>=4) where TestDir <: TestDirection length(𝐘)==1 && (return stedentTest1S(𝐘[1]; refmean, direction, equivalent=true, switch2rand, nperm, seed, verbose)) length(unique(length.(𝐘)))==1 || throw(ArgumentError(📌*"Function studentMcTest1S: the vectors in the first argument (𝐘) must have all equal length. Check the documentation")) _permMcTest!(membership(StudentT_1S(), length(𝐘[1])), refmean===nothing ? copy(𝐘) : [𝐲.-refmean for 𝐲 in 𝐘], length(𝐘[1]), StudentT_1S(), StudentT_1S(); stepdown, fwe, nperm, fstat=_fstat(direction), switch2rand, seed, threaded, verbose) end tMcTest1S = studentMcTest1S # aliases # method (2) as studentMcTest1S!, but copy the 𝐘 vectors, so it does not overwrite them. # This method directly subtracts the reference mean """ ```julia function studentMcTest1S!(<same args and kwargs as `studentMcTest1S`>) ``` As [`studentMcTest1S`](@ref), but `Y` is overwritten in the case of approximate (random permutations) tests. *Alias:* `tTest1S!` Univariate version: [`studentTest1S!`](@ref) """ function studentMcTest1S!(𝐘::UniDataVec; refmean::Realo = nothing, direction::TestDir = Both(), switch2rand::Int = max(Int(1e8) ÷ length(𝐘), Int(1e4)), nperm::Int = 20_000, seed::Int = 1234, verbose::Bool = true, # stepdown::Bool = true, fwe::Float64 = 0.05, threaded::Bool = Threads.nthreads()>=4) where TestDir <: TestDirection length(𝐘)==1 && (return stedentTest1S!(𝐘[1]; refmean, direction, equivalent=true, switch2rand, nperm, seed, verbose)) length(unique(length.(𝐘)))==1 || throw(ArgumentError(📌*"Function studentMcTest1S!: the vectors in the first argument (𝐘) must have all equal length. Check the documentation")) _permMcTest!(membership(StudentT_1S(), length(𝐘[1])), refmean===nothing ? 𝐘 : [𝐲.-refmean for 𝐲 in 𝐘], length(𝐘[1]), StudentT_1S(), StudentT_1S(); stepdown, fwe, nperm, fstat=_fstat(direction), switch2rand, seed, threaded, verbose) end tMcTest1S! = studentMcTest1S! ### Sign Test # Takes as input K vectors of vectors of N booleans, where N is the number of subjects. """ ```julia function signMcTest(Y::Union{AbstractVector{BitVector}, AbstractVector{Vector{Bool}}}; direction::TestDir = Both(), switch2rand::Int= max(Int(1e8) ÷ length(𝐘), Int(1e4)), nperm::Int = 20_000, seed::Int = 1234, verbose::Bool = true, # stepdown::Bool = true, fwe::Float64 = 0.05, threaded::Bool = Threads.nthreads()>=4) where TestDir <: TestDirection ``` Multiple comparisons [sign test](https://en.wikipedia.org/wiki/Sign_test) by data permutation. Run ``M`` sign tests simultaneously.The null hypotheses have form ``H_0(m): E_m(true)=E_m(false), \\quad m=1...M``, where ``E_m(true)`` and ``E_m(false)`` are the expected number of true and false occurrences, respectively, in the ``m^{th}`` hypothesis. `Y` ia a vector of ``M`` vectors holding each ``N`` booleans. For optional keyword arguments, `direction`, `switch2rand`, `nperm`, `seed`, `verbose`, `stepdown`, `fwe` and `threaded` see [here](@ref "Common kwargs for multiple comparisons tests"). *Directional tests, permutation scheme and number of permutations for exact tests:* as per *univariate version* [`signTest`](@ref) Return a [MultcompTest](@ref) structure. *Examples* ```julia using PermutationTests N=20; # number of observations M=100; # number of hypotheses Y = [rand(Bool, N) for m=1:M]; # some random Gaussian data for example t = signMcTest(Y) # By deafult the test is bi-directional tR = signMcTest(Y; direction=Right()) # right-directional test tL = signMcTest(Y; direction=Left()) # Left-directional test # Force an approximate test with 5000 random permutations tapprox = signMcTest(Y; switch2rand=1, nperm=5000) ``` """ function signMcTest(𝐘::Union{AbstractVector{BitVector}, AbstractVector{Vector{Bool}}}; direction::TestDir = Both(), switch2rand::Int= max(Int(1e8) ÷ length(𝐘), Int(1e4)), nperm::Int = 20_000, seed::Int = 1234, verbose::Bool = true, # stepdown::Bool = true, fwe::Float64 = 0.05, threaded::Bool = Threads.nthreads()>=4) where TestDir <: TestDirection length(𝐘)==1 && (return signTest(𝐘[1]; direction, equivalent=true, switch2rand, nperm, seed, verbose)) length(unique(length.(𝐘)))==1 || throw(ArgumentError(📌*"Function signMcTest: the vectors in the first argument (𝐘) must have all equal length. Check the documentation")) studentMcTest1S!([Float64.(𝐲).-0.5 for 𝐲 ∈ 𝐘]; refmean=0., direction, switch2rand, nperm, seed, verbose, stepdown, fwe, threaded) end """ ```julia function studentMcTestRM(<same args and kwargs as `studentMcTest1S`>) ``` Actually an alias for [`studentMcTest1S`](@ref) In order to run a multiple comparisons t-test for repeated measure, use as data input the vector of ``M`` vectors of differences across the two measurements (or treatments, time, etc.). Do not change the `refmean` default value. See [`studentMcTest1S`](@ref) for more details. *Directional tests, permutation scheme and number of permutations for exact tests:* as per [`studentTest1S`](@ref) *Univariate version:* [`studentTestRM`](@ref) *Alias:* `tMcTestRM` Return a [MultcompTest](@ref) structure. *Examples* ```julia using PermutationTests N=10 # number of observation per treatment M=100 # number of hypotheses # suppose you have data as Y1=[randn(N) for m=1:M]; # measurement 1 Y2=[randn(N) for m=1:M]; # measurement 2 # Let us compute the differences as Y=[y1-y2 for (y1, y2) in zip(Y1, Y2)]; t=tMcTestRM(Y) # by default the test is bi-directional tR=tMcTestRM(Y; direction=Both()) # right-directional test # if test tR is significant for some hypotheses, # for these hypotheses the mean of measurement 1 # exceeds the mean of measurement 2. ``` """ studentMcTestRM = studentMcTest1S tMcTestRM = studentMcTest1S """ (2) function studentMcTestRM!(<same args and kwargs as `studentMcTest1S!`>) Actually an alias for [`studentMcTest1S!`](@ref). `Y` is overwritten in the case of approximate (random permutations) tests. *Alias:* `tMcTestRM!` """ studentMcTestRM! = studentMcTest1S! tMcTestRM! = studentMcTest1S! # ----------------------------------------------------- #
PermutationTests
https://github.com/Marco-Congedo/PermutationTests.jl.git
[ "MIT" ]
0.2.0
8a73fe1574e159927031bb2b9cc6ea142f075407
code
27606
#= Stats.jl Unit of the PermutationTests.jl Package MIT License Copyright (c) 2024, Marco Congedo, CNRS, Grenoble, France: https://sites.google.com/site/marcocongedo/home ############################# # Low-Level Test Statistics # ############################# Run `test_stats()` in unit _test.jl to test this unit ======================================== EXPORTED: SCALARS functions of vectors --------------------------------------------------------------- ∑(𝐱) sum (sum_i (x_i)) ∑of²(𝐱) sum of squares (sum_i(x_i²)) ∑∑of²(𝐱) sum and sum of squares in one pass μ(𝐱) arithmetic average (1/N ∑(𝐱)) dispersion(𝐱) sum of squares of deviations from the mean σ²(𝐱) variance (1/N sum_i(x_i-μ(𝐱))²) σ(𝐱) standard deviation sqrt (1/N sum_i(x_i-μ(𝐱))²) ∑(𝐱, 𝐲) sum of 𝐱 + 𝐲 (sum_i (x_i y_i)) Π(𝐱) product (product_i(x_i)) ∑ofΠ(𝐱, 𝐲) sum of products (sum_i (x_i*y_i)) statistic(𝐱, 𝐲, [statistic]; standardized=false, centered=true, means=(), sds=(), k, ns, ∑Y²kn, ∑y², ∑S²k) compute a statistic of independent variable 𝐱 and dependent variable 𝐲. [statistic] can be any statistic: CrossProd, Covariance, PearsonR, ..... Depending on the statistic, some kwargs may be passed to speed up computations VECTOR functions of vectors --------------------------------------------------------------- μ0(𝐱) recenter (zero mean: 𝐱-μ(𝐱)𝟏) σ1(𝐱) equalize (unit standard deviation: 𝐱/σ(𝐱)) μ0σ1(𝐱) standardize (zero mean and unit standard deviation: (𝐱-μ(𝐱)𝟏)/σ(𝐱)) _∑y²(𝐲) _∑Y²kn_∑y²_∑S²k OTHERS --------------------------------------------------------------- _∑Y²kn _∑S²k NON-EXPORTED UTILITIES: _getmeans _anova_IS_fixed_params _getsds _cond∑_IS _cond∑_RM _anova_IS_fixed_params ============================= =# ############################################ # Low-level statistical computations ############################################ # sum """ ```julia function (x::UniData) ``` Alias for julia `sum(x)`. Sum of the elements in `x`. """ ∑(𝐱::UniData) = sum(𝐱) # sum of squares """ ```julia function ∑of²(x::UniData) ``` Sum of squares of the elements in `x` """ ∑of²(𝐱::UniData) = sum(abs2, 𝐱) # sum and sum of squares in one pass """ ```julia function ∑∑of²(x::UniData) ``` Compute the sum and sum of squares of the elements in `x` in one pass and return them as a 2-tuple. *Examples* ```julia using PermutationTests x=randn(10) s, s² = ∑∑of²(x) ``` """ function ∑∑of²(𝐱::UniData) s, s² = 0., 0. @simd for x ∈ 𝐱 @inbounds s += x @inbounds s² += abs2(x) end s, s² end # mean """ ```julia function μ(x::UniData) ``` Alias for julia `mean(x)`. Arithmetic mean of the elements in `x`. """ μ(𝐱::UniData) = mean(𝐱) # create a centered copy of 𝐱, giving or not the mean to go faster """ ```julia function μ0(x::UniData; mean::Realo=nothing) ``` Return `x` centered (zero mean). Center around `mean` if it is provided. `mean` must be a real number. """ μ0(𝐱::UniData; mean::Realo=nothing) = mean === nothing ? 𝐱.-μ(𝐱) : 𝐱.-mean # sum of squares of deviations from the mean, with the mean given """ ```julia function dispersion(x::UniData, mean::Real) ``` Sum of squared deviations of the elements in `x` around `mean`. `mean` must be provided and must be a real number. *Examples* ```julia using PermutationTests x=randn(10) d=dispersion(x, μ(x)) ``` """ function dispersion(𝐱::UniData, mean::Real) d=0. @simd for x in 𝐱 @inbounds d += abs2(x-mean) end d end """ ```julia function dispersion(x::UniData; centered::Bool=false, mean::Realo=nothing) ``` If `centered` is true, return the sum of the squares of the elements in `x`, otherwise, if `mean` is provided return the sum of squared deviations of the elements in `x` from `mean`, otherwise, return the sum of squared deviations of the elements in `x` from their mean. *Examples* ```julia using PermutationTests x=randn(10) x0=μ0(x) μx=μ(x) m=μ(x) # in decreasing order of efficiency d1=dispersion(x0) d2=dispersion(x, mean=μx) d3=dispersion(x) d1==d2==d3 # -> true ``` """ dispersion(𝐱::UniData; centered::Bool=false, mean::Realo=nothing) = centered ? ∑of²(𝐱) : (mean===nothing ? dispersion(𝐱, μ(𝐱)) : dispersion(𝐱, mean)) """ ```julia function σ²(x::UniData; corrected::Bool=false, centered::Bool=false, mean::Realo=nothing) ``` Population variance of the ``N`` elements in x (default), or its unbiased sample estimator if `corrected` is true. If `centered` is true return the sum of the squared elements in `x` divided by ``N``, or ``N-1`` if `corrected` is true, otherwise, call julia standard function `var` with arguments `corrected` and `mean`. """ σ²(𝐱::UniData; corrected::Bool=false, centered::Bool=false, mean::Realo=nothing) = centered ? ∑of²(𝐱)/(corrected ? (length(𝐱)-1) : length(𝐱)) : var(𝐱; corrected, mean) """ ```julia function σ(x::UniData; corrected::Bool=false, centered::Bool=false, mean::Realo=nothing) ``` Population standard deviation of the elements in `x` or its unbiased sample estimator. Call [`σ²`](@ref) with the same arguments and return its square root. """ σ(𝐱::UniData; corrected::Bool=false, centered::Bool=false, mean::Realo=nothing) = sqrt(σ²(𝐱; corrected, centered, mean)) """ ```julia σ1(x::UniData; corrected::Bool=false, centered::Bool=false, mean::Realo=nothing, sd::Realo=nothing) ``` Return `x` equalized (unit standard deviation). If `sd` is provided, return `x` equalized with respect to it, otherwise call [`σ`](@ref) with optional arguments `corrected`, `centered` and `mean` and equalize `x`. *Examples* ```julia using PermutationTests x=randn(3) μx=μ(x) # mean σx=σ(x) # sd xμ0=μ0(x) # centered data # in decreasing order of efficiency e1=σ1(xμ0; sd=σx, centered=true) e2=σ1(xμ0; centered=true) e3=σ1(x; mean=μx, sd=σx) e4=σ1(x; mean=μx) println(σ(e4)≈1.0 ? "OK" : "Error") # -> "OK" ``` """ σ1(𝐱::UniData; corrected::Bool=false, centered::Bool=false, mean::Realo=nothing, sd::Realo=nothing) = 𝐱./(sd===nothing ? σ(𝐱; corrected, centered, mean) : sd) """ ```julia μ0σ1(x::UniData; corrected::Bool=false, centered::Bool=false, mean::Realo=nothing, sd::Realo=nothing) ``` Return `x` standardized (zero mean and unit standard deviation). If `centered` is true, equalize `x` by calling [`σ1`](@ref) with optional arguents `corrected`, `centered` and `sd`, otherwise standardize `x` after computing the mean, if it is not provided as `mean`, and the standard deviation, if it is not provided, calling `σ`[@ref] with optional arguments `corrected` and `centered`. *Examples* ```julia using PermutationTests x=randn(3) μx=μ(x) # mean σx=σ(x) # sd xμ0=μ0(x) # centered data # in decreasing order of efficiency z1=μ0σ1(xμ0; sd=σx, centered=true) z2=μ0σ1(xμ0; centered=true) z3=μ0σ1(x; mean=μx, sd=σx) z4=μ0σ1(x; mean=μx) z5=μ0σ1(x; sd=σx) z6=μ0σ1(x) println(μ(z6)≈0. ? "OK" : "Error") # -> "Ok" println(σ(z6)≈1. ? "OK" : "Error") # -> 'OK" ``` """ μ0σ1(𝐱::UniData; corrected::Bool=false, centered::Bool=false, mean::Realo=nothing, sd::Realo=nothing) = if centered return σ1(𝐱; corrected, centered=true, sd=(sd===nothing ? σ(𝐱; corrected, centered=true) : sd)) else m = mean === nothing ? μ(𝐱) : mean s = sd === nothing ? σ(𝐱; corrected, centered=false, mean=m) : sd return [(x-m)/s for x in 𝐱] # can use Folds.map for this end """ ```julia function Π(x::UniData) ``` Product of the elements in `x`. Alias of julia function `prod`. """ Π(𝐱::UniData) = prod(𝐱) """ ```julia function ∑ofΠ(x::Union{UniData, Tuple}, y::UniData) ``` Inner product of `x` and `y`. """ function ∑ofΠ(𝐱::Union{UniData, Tuple}, 𝐲::UniData) p = 0. @simd for i in eachindex(𝐲) # here eachindex(𝐱, 𝐲) gives an error @inbounds p += 𝐱[i]*𝐲[i] end p end ############################################ # Test Statistics ############################################ # -------------------------------------------------------------------- # Pearson Product Moment R and equivalent Cross-Product and Covariance # -------------------------------------------------------------------- _getmeans(𝐱::UniData, 𝐲::UniData; means::Tuple=()) = isempty(means) ? (μ(𝐱), μ(𝐲)) : (means[1], means[2]) _getsds(𝐱::UniData, 𝐲::UniData; centered::Bool=false, means::Tuple=(), sds::Tuple=()) = if isempty(sds) # standard deviations if centered return σ(𝐱, centered=true), σ(𝐲, centered=true) else return isempty(means) ? (σ(𝐱), σ(𝐲)) : (σ(𝐱, mean=means[1]), σ(𝐲, mean=means[2])) end else return sds[1], sds[2] end """ ```julia function statistic(x::UniData, y::UniData, stat::PearsonR; standardized::Bool=false, centered::Bool=false, means::Tuple=(), sds::Tuple=(), kwargs...) ``` Pearson product-moment correlation *r* statistic of input data vector `x` and `y`. If the means and/or standard deviations of `x` and `y` are passed as tuple `means` and `sds`, respectively, they are not computed. If `centered` is true, the two vectors are assumed to have zero mean. If `standardized` is true both x and y are assumed standardized, thus only the cross-product needs to be computed. This is by far the most efficient way if this function is to be called repeatedly on the same data input vectors and for computing p-values by data permutations as the cross-product is en equivalent test statistic for the Pearson correlation if the data is standardized. *Examples* ```julia using PermutationTests x, y = randn(10), randn(10); c1 = statistic(x, y, PearsonR()) zx=μ0σ1(x); zy=μ0σ1(y); c2 = statistic(zx, zy, PearsonR(); standardized=true) ``` see [`μ0σ1`](@ref) """ statistic(𝐱::UniData, 𝐲::UniData, stat::PearsonR; standardized::Bool=false, centered::Bool=false, means::Tuple=(), sds::Tuple=(), kwargs...) = standardized ? ∑ofΠ(𝐱, 𝐲) / length(𝐱) : statistic(𝐱, 𝐲, Covariance(); centered, means, kwargs...) / prod(_getsds(𝐱, 𝐲; centered, means, sds)) """ ```julia function statistic(x::UniData, y::UniData, stat::Covariance; centered::Bool=false, means::Tuple=(), kwargs...) ``` Covariance of data input vectors x and y. Equivalent to the Pearson correlation *r* test statistic for bi-directional correlation tests, see [Statistic](@ref). For the optional keyword arguments, see the method [`statistic(x, y, stat::PearsonR)`](@ref). *Examples* ```julia using PermutationTests x, y = randn(10), randn(10) c1 = statistic(x, y, Covariance()) c2 = statistic(μ0(x), μ0(y), Covariance(); centered=true) μx=μ(x) μy=μ(y) c3 = statistic(x, y, Covariance(); means=(μx, μy)) ``` see [`μ0`](@ref), [`μ`](@ref) """ statistic(𝐱::UniData, 𝐲::UniData, stat::Covariance; centered::Bool=false, means::Tuple=(), kwargs...) = centered ? ∑ofΠ(𝐱, 𝐲)/length(𝐱) : (∑ofΠ(𝐱, 𝐲)/length(𝐱))-prod(_getmeans(𝐱, 𝐲; means)) """ ```julia function statistic(x::UniData, y::UniData, stat::CrossProd; kwargs...) ``` Cross-product (inner product) of data input vectors x and y. Equivalent to the Pearson correlation *r* test statistic for directional correlation tests and always if the data is standardized, see [Statistic](@ref). *Examples* ```julia using PermutationTests x, y = randn(10), randn(10) c = statistic(x, y, CrossProd()) ``` """ statistic(𝐱::UniData, 𝐲::UniData, stat::CrossProd; kwargs...) = ∑ofΠ(𝐱, 𝐲) # -------------------------------------------------------------------- # ANOVA for Independent Samples F and equivalent sum of group totals, # sum of square group total and mean, Student T (all used also for Chi², # Fisher Exact Test statistic and point bi-serial correlation tests) # -------------------------------------------------------------------- # Return 2 tuple (k, ns), where k is the number of groups and ns is the numerosity vector # If askwargs=true is passed, return instead the named tuple (k=k, ns=ns) function _anova_IS_fixed_params(𝐱::IntVec; askwargs=false) k=length(unique(𝐱)) ns=[count(x->x==i, 𝐱) for i=1:k] return askwargs ? (k=k, ns=ns) : (k, ns) end """ ```julia function statistic(x::IntVec, y::UniData, stat::AnovaF_IS; k::Into=nothing, ns::Union{Vector{Int}, Nothing}=nothing, kwargs...) ``` *F* statistic of the 1-way ANOVA for independent samples, see [Edgington (1995)](@ref "References"), p. 60. The data is given as an unique vector `y`, holding the observations for each group in the natural order, thus for ``K`` groups `y` holds ``N=N_1+ \\ldots +N_K`` elements, where ``N_k`` is the number of observations for the ``k^{th}`` group. `x` is the [`membership(::IndSampStatistic)`](@ref) vector. `k` is the number of groups (independent samples). If omitted it will be computed. `ns` is the group numerosity vector with form `ns=[N1,..., NK]`. If omitted it will be computed. *Examples* ```julia using PermutationTests g1=[1.0, 2.0, 3.0, 4.0] # observations for group 1 g2=[1.1, 2.8, 3.2, 4.4, 5.3] # observations for group 2 ns=[length(g1), length(g2)] # N1, N2 y=vcat(g1, g2) x=membership(AnovaF_IS(), ns) F=statistic(x, y, AnovaF_IS()) # or, to avoid finding k and ns from y F2=statistic(x, y, AnovaF_IS(); k=2, ns=ns) # The square of the t test statistic for independent samples for a bi-directional test # is equal to the above F test statistics t=statistic(x, y, StudentT_IS(); ns=ns) println(t^2≈F ? "OK" : "error") ``` """ function statistic(𝐱::IntVec, 𝐲::UniData, stat::AnovaF_IS; k::Into=nothing, ns::Union{Vector{Int}, Nothing}=nothing, kwargs...) k===nothing && (k=length(unique(𝐱))) ns===nothing && (ns=[count(x->x==i, 𝐱) for i=1:k]) n=length(𝐱) ∑𝐲s = Vector{Float64}(undef, k) SSTv = 0. @inbounds for i=1:k e=𝐲[𝐱.==i] # it is better to allocate e here and perform sum and sum of squares sequentially on e s, s² = ∑∑of²(e) ∑𝐲s[i] = s SSTv += s² end ms = sum(∑𝐲s)^2/n SSB = sum(∑𝐲s[i]^2/ns[i] for i=1:k) - ms # sum of squares between groups Edgington, page 60 SST = SSTv - ms # Total sum of squares SSW = SST - SSB # sum of squares within groups if SSW ≈ 0. return Inf #throw(ErrorException(📌*"Function statistic(x, y, AnovaF_IS()): The sum of squares within is equal to zero")) else return (SSB*(n-k))/(SSW/(k-1)) # F statistic : (SSB / (k-1)) / (SSW / (n-k)) end # NB some dicothomous tables yield a sum of squares within SSW = 0, thus F=Inf end # Sum the elements of 𝐲 if the corresponding elements of 𝐱 are equal to k # For Ind Samp ANOVA-like statistics the data is arranged as s1g1, s2g1,..., sn1g1, s2g1, s2g2,...,sn2g2,... ... snNgK. # This function then return the total for a group indexed by k. # 𝐱 must be of the form [repeat(1, N1); repeat(2, N2),..., repeat(2, NK)] or any valid permutation, for example # for N1=3, N2=2 and K=2 the observed statistic is given by 𝐱=[1 1 1 2 2] and a valid permutation is [2 1 2 1 1] # NOT SAFE function _cond∑_IS(𝐱::IntVec, 𝐲::UniData, k::Int) s=0. @simd for i ∈ eachindex(𝐱) # before it was i=1:length(𝐱) @inbounds 𝐱[i]==k && (s += 𝐲[i]) end s end """ ```julia function statistic(x::IntVec, y::UniData, stat::SumGroupTotalsSq_IS; k::Into=nothing, kwargs...) ``` Sum of squared group totals. Equivalent to the 1-way ANOVA for independent samples *F* test statistic in balanced designs, see [Statistic](@ref). For optional keyword argument `k`, see the [`statistic`](@ref) method for `AnovaF_IS` here above. """ function statistic(𝐱::IntVec, 𝐲::UniData, stat::SumGroupTotalsSq_IS; k::Into=nothing, kwargs...) k===nothing && (k=length(unique(𝐱))) sum(abs2, (_cond∑_IS(𝐱, 𝐲, i) for i=1:k)) end #= Robust version of SumGroupTotalsAbs_IS. It does not yield the same p-value as the F statistic function statistic(𝐱::IntVec, 𝐲::UniData, stat::SumGroupTotalsAbs_IS; k::Into=nothing, kwargs...) k===nothing && (k=length(unique(𝐱))) sum(abs, (_cond∑_IS(𝐱, 𝐲, i) for i=1:k)) end =# # Equivalent to StudentT_IS for bi-diretional tests. """ ```julia function statistic(x::IntVec, y::UniData, stat::SumGroupTotalsSqN_IS; k::Into=nothing, ns::Union{Vector{Int}, Nothing}=nothing, kwargs...) ``` Sum of squared group totals divided each by the group numerosity. Equivalent to the 1-way ANOVA for independent samples *F* test statistic in general, see [Statistic](@ref). For optional keyword arguments `k` and `ns` and for examples, see the [`statistic`](@ref) method for `AnovaF_IS` here above. """ function statistic(𝐱::IntVec, 𝐲::UniData, stat::SumGroupTotalsSqN_IS; k::Into=nothing, ns::Union{Vector{Int}, Nothing}=nothing, kwargs...) k===nothing && (k=length(unique(𝐱))) ns===nothing && (ns=[count(x->x==i, 𝐱) for i=1:k]) sum(((_cond∑_IS(𝐱, 𝐲, i) for i=1:k) .|> abs2)./ns) end """ ```julia function statistic(x::IntVec, y::UniData, stat::StudentT_IS; k::Into=nothing, ns::Union{Vector{Int}, Nothing}=nothing, kwargs...) ``` Student's *t* statistic for independent samples, see [Edgington (1995)](@ref "References"), p. 3. For all arguments except `stat` and examples see the [`statistic`](@ref) method for `AnovaF_IS` here above. """ function statistic(𝐱::IntVec, 𝐲::UniData, stat::StudentT_IS; k::Into=nothing, ns::Union{Vector{Int}, Nothing}=nothing, kwargs...) k===nothing && (k=length(unique(𝐱))) ns===nothing && (ns=[count(x->x==i, 𝐱) for i=1:k]) length(ns)≠2 && throw(ArgumentError(📌*"Function statistic (StudentT_IS): `ns` must contain 2 integer")) 𝐠1, 𝐠2 = 𝐲[𝐱.==1], 𝐲[𝐱.==2] # data for the two groups μ1, μ2 = μ(𝐠1), μ(𝐠2) # mean for the two groups pσ² = (dispersion(𝐠1, μ1) + dispersion(𝐠2, μ2)) / (ns[1] + ns[2] - 2) # pooled variance return (μ1 - μ2) / sqrt(pσ²/ns[1] +pσ²/ns[2]) end """ ```julia function statistic(x::IntVec, y::UniData, stat::Group1Total_IS; kwargs...) ``` Sum of observations for group 1. Equivalent to the Students's *t* test statistic for independent samples for diretional tests, see [Statistic](@ref). For arguments `x` and `y` and for examples, see the [`statistic`](@ref) method for `AnovaF_IS` here above. """ statistic(𝐱::IntVec, 𝐲::UniData, stat::Group1Total_IS; kwargs...) = _cond∑_IS(𝐱, 𝐲, 1) # -------------------------------------------------------------------- # Repeated Measures Statistics # -------------------------------------------------------------------- # Sum the elements of 𝐲 if mod1(x, k)==k, where x are the elements of 𝐱 corresponding to the elements of 𝐲. # For Rep Meas ANOVA-like statistics the data is arranged as s1t1, s1t2, ..., s1tk, s2t1, s2t2,...,s2tk,... ... sntk, # where s is subjects and t is treatment. # This function then return the total for each treatement k. # 𝐱 must be of the form [1,..., nk]o r any valid permutation, for example for n=2, k=3 # the observed statistic is given by 𝐱=[1 2 3 4 5 6] and a valid permutation is [2 1 3 6 5 4]. # Note that the permutations are restricted within successive k elements, i.e., inside the bars: | 2 1 3 | 6 5 4 | ... |. function _cond∑_RM(𝐱::IntVec, 𝐲::UniData, k::Int, ns::@NamedTuple{n::Int, k::Int}) s=0. @simd for i ∈ k:ns.k:ns.n*ns.k @inbounds s += 𝐲[𝐱[i]] end s end # ∑ of al observations, squared and dividen by k*n. For computing 1-way Rep Meas ANOVA F statistic _∑Y²kn(𝐲, ns) = abs2(sum(𝐲))/(ns.k*ns.n) # Pre-compute some data for the [`statistic`](@ref) methods computing the `StudentT_1S` test-statistic # and the `AnovaF_RM` test-statistic. # Return the sum of all squared observations in `y`. _∑y²(𝐲) = ∑of²(𝐲) # sum of subject totals; squared and divided by n. For computing 1-way Rep Meas ANOVA F statistic _∑S²k(𝐲, ns) = sum(abs2(sum(view(𝐲[i:i+ns.k-1], :)))/ns.k for i=1:ns.k:ns.n*ns.k) # The three above in one pass as a vector # Pre-compute some data for the [`statistic`](@ref) computing the `AnovaF_RM` test-statistic. # Return a vector of three elements [_∑Y²kn, `_∑y²`, `_∑S²k`]. _∑Y²kn_∑y²_∑S²k(𝐲, ns) = [abs2(sum(𝐲))/(ns.k*ns.n), ∑of²(𝐲), sum(abs2(sum(view(𝐲[i:i+ns.k-1], :)))/ns.k for i=1:ns.k:ns.n*ns.k)] """ ```julia function statistic(x::IntVec, y::UniData, stat::AnovaF_RM; ns::@NamedTuple{n::Int, k::Int}, ∑Y²kn::Realo=nothing, ∑y²::Realo=nothing, ∑S²k::Realo=nothing, kwargs...) ``` *F* statistic of 1-way ANOVA for repeated measures, see [Edgington (1995)](@ref "References"), p. 102. The data is given as an unique vector `y` concatenaning the ``N`` observations for the ``K`` measures (treatments, time, ...) in the natural order, that is, the ``K`` treatments for observation 1, ..., the ``K`` tratments for observation ``N``. Thus, `y` holds ``N \\cdot K`` elements. `x` is the [`membership(::RepMeasStatistic)`](@ref) vector. `ns` is a julia [named tuple](https://docs.julialang.org/en/v1/manual/types/#Named-Tuple-Types) with form `(n=N, k=K)` (see examples below). `∑Y²kn`, `∑y²` and `∑S²k` can be optionally provided to speed up computations since these quantities are invariant by data permutations. The exported function `_∑Y²kn_∑y²_∑S²k` can be used for this purpose, see the examples below. *Examples* ```julia using PermutationTests # K=2 (measurements), N=4 (observations) o1=[1.0, 2.0]; # first observation o2=[2.0, 2.8]; # second observation o3=[3.0, 2.6]; # third observation o4=[4.0, 4.1]; # fourth observation ns=(n=4, k=2); # four obs. and two measurements y=vcat(o1, o2, o3, o4); x=membership(AnovaF_RM(), ns); F=statistic(x, y, AnovaF_RM(); ns=ns) # pre-compute some data pcd=_∑Y²kn_∑y²_∑S²k(y, ns); F2=statistic(x, y, AnovaF_RM(); ns=ns, ∑Y²kn=pcd[1], ∑y²=pcd[2], ∑S²k=pcd[3]) # The t test statistic for repeated measures is the same as the one-sample # t test statistic on the difference of the two measurements. # The square of those statistics for a bi-directional test are equal to # the above F test statistics. x=membership(StudentT_1S(), ns.n) t=statistic(x, y[1:2:ns.n*2-1].-y[2:2:ns.n*2], StudentT_1S()) println(t^2≈F ? "OK" : "error") ``` """ function statistic(𝐱::IntVec, 𝐲::UniData, stat::AnovaF_RM; ns::@NamedTuple{n::Int, k::Int}, ∑Y²kn::Realo=nothing, ∑y²::Realo=nothing, ∑S²k::Realo=nothing, kwargs...) # quantities that are invariant by permutation ∑Y²kn === nothing && (∑Y²kn = _∑Y²kn(𝐲, ns)) ∑y² === nothing && (∑y² = _∑y²(𝐲)) ∑S²k === nothing && (∑S²k = _∑S²k(𝐲, ns)) ∑T²n = sum(abs2(_cond∑_RM(𝐱, 𝐲, i, ns))/ns.n for i=1:ns.k) SSB = ∑T²n-∑Y²kn SSe = ∑y²-∑T²n-∑S²k+∑Y²kn return (SSB/SSe)*(ns.n-1) # F statistic : (SSB / (k-1)) / (SSE / (n-1)(k-1)) end """ ```julia function statistic(x::IntVec, y::UniData, stat::SumTreatTotalsSq_RM; ns::@NamedTuple{n::Int, k::Int}, kwargs...) ``` Sum of squared treatment totals. Equivalent to the 1-way ANOVA for repeated measures *F* test statistic in general, see [Statistic](@ref). For optional keyword argument `ns` see the [`statistic`](@ref) method for `AnovaF_RM` here above. """ function statistic(𝐱::IntVec, 𝐲::UniData, stat::SumTreatTotalsSq_RM; ns::@NamedTuple{n::Int, k::Int}, kwargs...) sum(abs2, (_cond∑_RM(𝐱, 𝐲, i, ns) for i=1:ns.k)) end # -------------------------------------------------------------------- # One-sample Statistics # -------------------------------------------------------------------- # NB: these statistics behave differently for exact and approximate tests. # For exact tests 𝐱 is a tuple. For approximate tests it is the useual UniData type, but it is ignored # 1 sample t-test. See https://en.wikipedia.org/wiki/Student's_t-test # StudentT_1S; H0: μ=0. Optionally provide ∑y² to go faster. function _studentT_1S(𝐲::UniData; ∑y²::Realo=nothing) n = length(𝐲) m = μ(𝐲) if ∑y² === nothing s = σ(𝐲; mean=m, corrected=true) return (m * sqrt(n))/s else ∑y²n = ∑y²/n m² = abs2(m) diff = ∑y²n - m² if abs(diff) < 1e-1 # try to avoid catastrophic cancellation s = σ(𝐲; mean=m, corrected=true) return (m * sqrt(n))/s else s = sqrt(diff*(n/(n-1))) # ∑y² is invariant by permutations return (m * sqrt(n))/s end end end # this version taking a tuple as argument is needed for systematic permutations # as the iterator for permutations yields tuples """ ```julia function statistic(x::Tuple, y::UniData, stat::StudentT_1S; ∑y²::Realo=nothing, kwargs...) ``` Student's one-sample *t* statistic. `y` is the input data. `x` is a tuple holding as many 1.0 as elements in `y`. `∑y²` can be optionally provided to speed up computations, since this quantity is invariant by data permutations. The exported function `_∑y²` can be used for this purpose, see the examples below. *Examples* ```julia using PermutationsTest y=randn(6); x=(1., 1., 1., 1., 1., 1.); t=statistic(x, y, StudentT_1S()) pcd=_∑y²(y) t2=statistic(x, y, StudentT_1S(); ∑y²=pcd) println(t≈t2 ? "OK" : "Error") ``` """ statistic(𝐱::Tuple, 𝐲::UniData, stat::StudentT_1S; ∑y²::Realo=nothing, kwargs...) = _studentT_1S(𝐱 .* 𝐲; ∑y²) """ ```julia function statistic(x::UniData, y::UniData, stat::StudentT_1S; ∑y²::Realo=nothing, kwargs...) ``` Student's one-sample *t* statistic. `y` is the input data. `x` is the [`membership(::OneSampStatistic)`](@ref) vector. `∑y²` can be optionally provided to speed up computations since this quantity is invariant by data permutations. The exported function `_∑y²` can be used for this purpose, see the examples below. *Examples* ```julia using PermutationsTest y=randn(6); x=membership(StudentT_1S(), length(y)); t=statistic(x, y, StudentT_1S()) pcd=_∑y²(y) t2=statistic(x, y, StudentT_1S(); ∑y²=pcd) println(t≈t2 ? "OK" : "Error") ``` """ statistic(𝐱::UniData, 𝐲::UniData, stat::StudentT_1S; ∑y²::Realo=nothing, kwargs...) = _studentT_1S(𝐲; ∑y²) # Sum (used for exact tests) """ ```julia function statistic(x::Tuple, y::UniData, stat::Sum; kwargs...) ``` """ statistic(𝐱::Tuple, 𝐲::UniData, stat::Sum; kwargs...) = ∑ofΠ(𝐱, 𝐲) # safer to use (𝐱 ⋅ 𝐲) # Sum (used for approximate tests) """ ```julia function statistic(x::UniData, y::UniData, stat::Sum; kwargs...) ``` Sum of the elements in input data vector `y`. Equivalent to the one-sample *t* test statistic in general, see [Statistic](@ref). `x` is the [`membership(::OneSampStatistic)`](@ref) vector. """ statistic(𝐱::UniData, 𝐲::UniData, stat::Sum; kwargs...) = sum(𝐲) # maximum of `obsStats` considering only those elements which corrisponding element in `accepted` is true. # used by _permTest! in unit multcompTest.jl function _condMax(obsStats::UniData, accepted::BitArray) m = 0 @simd for i ∈ eachindex(obsStats, accepted) @inbounds accepted[i] && obsStats[i]>m && (m = obsStats[i]) end return m end ####################################################################################
PermutationTests
https://github.com/Marco-Congedo/PermutationTests.jl.git
[ "MIT" ]
0.2.0
8a73fe1574e159927031bb2b9cc6ea142f075407
code
28823
#= tools.jl Unit of the PermutationTests.jl Package MIT License Copyright (c) 2024, Marco Congedo, CNRS, Grenoble, France: https://sites.google.com/site/marcocongedo/home ####################################### # General Tools for Permutation tests # ###################################### ======================================== EXPORTED: assignment Return Balanced() or Unbalanced() for a given test test eqStat equivalent statistics allPerms number of permutations for a given test nrPerms number of non-redundant permutations for a given test membership create the membership vector for Independent Samples ANOVA tests and equivalent genPerms generate systematic permutations table2vec Convert a table to vectors to be used as input to test functions. flip flip the sign for a Number and negate for a Bool testStatistic UTILITIES _fstat _direction _check_ns - used by _permTest! _test_params - used by _permTest! _prepare_permtest! - used by _permTest! ============================= =# # ----- # """ ```julia flip(x::Bool) flip(x::Union{R, I}) where {R<:Real, I<:Int} ``` Invert the sign of a real number or integer and negate a boolean. This function may be needed for argument `fstat` to call [`_permTest!`](@ref) or [`_permMcTest!`](@ref) if you [create your own test](@ref "Create your own test") - see the example on how to create a test for the [Chatterjee correlation](@ref "Example 5: univariate Chatterjee correlation"). It can also be useful when you create a new test in the code you deveolop for computing your own test statistics. """ flip(x::Bool) = !x flip(x::Union{R, I}) where {R<:Real, I<:Int} = -x # ----- # # ----- # # Function to be applied to the permutation statistic before comparing it to the observed one so as to obtain # a test with direction Left, Right or Both. See [TestDirection](@ref) and _permTest!. _fstat(direction::Left) = flip _fstat(direction::Right) = identity _fstat(direction::Both) = abs # ----- # # inverse function of _fstat # ----- # function _direction(fstat::Function) if fstat === abs return Both() elseif fstat === identity return Right() elseif fstat === flip return Left() else throw(ArgumentError(📌*" Function _direction: invalid input")) end end # ----- # # ----- # """ ```julia function assignment(stat::Union{BivStatistic, OneSampStatistic}, ns::Int) function assignment(stat::IndSampStatistic, ns::Vector{Int}) function assignment(stat::RepMeasStatistic, ns::@NamedTuple{n::Int, k::Int}) ``` Analyse the [ns](@ref) argument for test statistic given as singleton `stat` and return a singleton of type [Assignment](@ref), `Balanced()` if the design is balanced (equal subjects in all groups/measurements), `Unbalanced()` otherwise. Only for test-statistics of the `IndSampStatistic` [group](@ref "Statistic groups") the result may be `Unbalanced()`; for all the others the result is always `Balanced()`. The complete list of test statistics is [here](@ref "Statistics"). *Examples* ```julia using PermutationTests assignment(PearsonR(), 12) # -> Balanced() assignment(AnovaF_IS(), [5, 5, 6]) # -> Unbalanced() assignment(AnovaF_IS(), [6, 6, 6]) # -> Balanced() assignment(StudentT_IS(), [5, 6]) # -> Unbalanced() assignment(StudentT_IS(), [5, 5]) # -> Balanced() assignment(AnovaF_RM(), (n=10, k=3)) # -> Balanced() assignment(StudentT_1S(), 8) # -> Balanced() ``` """ assignment(stat::Union{BivStatistic, OneSampStatistic}, ns::Int) = Balanced() assignment(stat::IndSampStatistic, ns::Vector{Int}) = length(unique(ns))==1 ? Balanced() : Unbalanced() assignment(stat::RepMeasStatistic, ns::@NamedTuple{n::Int, k::Int}) = Balanced() # ----- # # ----- # """ ```julia function eqStat(stat, direction::TestDir, design::Assign) where {TestDir<: TestDirection, Assign <: Assignment} ``` Return the most efficient statistic equivalent to `stat`, for the given singleton `direction` of type [TestDirection](@ref) and singleton `design` of type [Assignment](@ref). `stat` is a singleton of one of the five typical test statistics, that is, `PearsonR()`, `AnovaF_IS()`, `StudentT_IS`, `AnovaF_RM()` or `StudentT_1S()`, see [Statistic](@ref). To avoid errors, use the result of [`assignment`](@ref) as argument `design`. Do not use `StudentT_RM()` as `stat`; *PermutationTests.jl* never use this test statistic. instead, t-tests for repeated measures are carried out as one-sample t-tests on the difference of the two measurements. *Examples* ```julia using PermutationTests a=assignment ns=12 eqStat(PearsonR(), Both(), a(PearsonR(), ns)) # -> Covariance() eqStat(PearsonR(), Right(), a(PearsonR(), ns)) # -> CrossProd() ns=[6, 6, 6] eqStat(AnovaF_IS(), Both(), a(AnovaF_IS(), ns)) # -> SumGroupTotalsSq_IS() ns=[6, 7, 6] eqStat(AnovaF_IS(), Both(), a(AnovaF_IS(), ns)) # -> SumGroupTotalsSqN_IS() ns=[6, 7] eqStat(StudentT_IS(), Both(), a(StudentT_IS(), ns)) # -> SumGroupTotalsSqN_IS() eqStat(StudentT_IS(), Left(), a(StudentT_IS(), ns)) # -> Group1Total_IS() ns=(n=10, k=3) eqStat(AnovaF_RM(), Both(), a(AnovaF_RM(), ns)) # -> SumTreatTotalsSq_RM() eqStat(AnovaF_RM(), Right(), a(AnovaF_RM(), ns)) # -> SumTreatTotalsSq_RM() ns=7 eqStat(StudentT_1S(), Both(), a(StudentT_1S(), ns)) # -> Sum() eqStat(StudentT_1S(), Left(), a(StudentT_1S(), ns)) # -> Sum() ``` """ eqStat(stat::PearsonR, direction::TestDir, design::Assign) where {TestDir<: TestDirection, Assign <: Assignment} = direction isa Both ? Covariance() : CrossProd() eqStat(stat::AnovaF_IS, direction::TestDir, design::Assign) where {TestDir<: TestDirection, Assign <: Assignment} = design isa Balanced ? SumGroupTotalsSq_IS() : SumGroupTotalsSqN_IS() eqStat(stat::StudentT_IS, direction::TestDir, design::Assign) where {TestDir<: TestDirection, Assign <: Assignment} = direction isa Both ? SumGroupTotalsSqN_IS() : Group1Total_IS() eqStat(stat::AnovaF_RM, direction::TestDir, design::Assign) where {TestDir<: TestDirection, Assign <: Assignment} = SumTreatTotalsSq_RM() eqStat(stat::StudentT_RM, direction::TestDir, design::Assign) where {TestDir<: TestDirection, Assign <: Assignment} = StudentT_RM() # No eq stat is developed in this case as the test should be done as a one-sample test on the difference eqStat(stat::StudentT_1S, direction::TestDir, design::Assign) where {TestDir<: TestDirection, Assign <: Assignment} = Sum() # ----- # # ----- # """ ```julia function allPerms(stat::BivStatistic, ns::Int) function allPerms(stat::IndSampStatistic, ns::Vector{Int}) function allPerms(stat::RepMeasStatistic, ns::@NamedTuple{n::Int, k::Int}) function allPerms(stat::OneSampStatistic, ns::Int) ``` Total number of systemetic permutations (exact test) for a test statistic given as singleton `stat` of a given [group](@ref "Statistic groups"). For the `ns` argument see [ns](@ref). For an exact tests with ``N`` observations and ``K`` groups/measuremets, the total number of systematic permutations is - for `stat` a `BivStatistic` :``\\quad N!`` - for `stat` a `IndSampStatistic` : ``\\quad \\frac{N!}{N_1! \\cdot \\ldots \\cdot N_K!}`` - for `stat` a `RepMeasStatistic` : ``\\quad K!^N`` - for `stat` a `OneSampStatistic` : ``\\quad 2^N`` For the number of non-redundant permutations, which is the actual number of permutations that are listed for exact tests, see [`nrPerms`](@ref). *Examples* ```julia # Total number of possible permutations for a 1-way ANOVA for indepedent samples # test with a total of 18 observations in three balanced groups. allPerms(AnovaF_IS(), [6, 6, 6]) # -> 17153136 # Total number of possible permutations for a correlation test with 12 observations. allPerms(PearsonR(), 12) # -> 479001600 ``` """ allPerms(stat::BivStatistic, ns::Int) = factorial(big(ns)) allPerms(stat::IndSampStatistic, ns::Vector{Int}) = multinomial(ns...) allPerms(stat::RepMeasStatistic, ns::@NamedTuple{n::Int, k::Int}) = factorial(big(ns.k))^ns.n allPerms(stat::OneSampStatistic, ns::Int) = exp2(BigInt(ns)) # ----- # # ----- # """ ```julia function nrPerms(stat::Union{BivStatistic, OneSampStatistic}, ns::Int, total, direction::TestDir, design::Assign=Balanced()) function nrPerms(stat::IndSampStatistic, ns::Vector{Int}, total, direction::TestDir, design::Assign) function nrPerms(stat::RepMeasStatistic, ns::@NamedTuple{n::Int, k::Int}, total, direction::TestDir, design::Assign=Balanced()) where {TestDir<: TestDirection, Assign <: Assignment} ``` Number of non-redundant systemetic permutations. This is the actual number of permutations that are listed for an exact test. Depending on the test direction and design, there may exists redundant permutations, *i.e.*, permutations that yields the same test statistic. These permutations are therefore eliminated, yielding a faster test. `stat` is the test statistic used by the test given as a singleton. It belongs to one [group](@ref "Statistic groups") of test statistics. For the `ns` argument see [ns](@ref). `total` is the total number of systematic permutations. In order to avoid errors, it should be given as the resut of the [`allPerms`](@ref) function. `direction` is a singleton of type [TestDirection](@ref). `design` is a singleton of type [Assignment](@ref). In order to avoid errors, use the result of [`assignment`](@ref) as argument `design`. With `stat` a `IndSampStatistic` and a balanced design, the non-redundant permutations are ``\\frac{total}{K!}``, with ``K`` the number of groups. With `stat` a `RepMeasStatistic` and a bi-directional tests, the non-redundant permutations are ``\\frac{total}{K!}``, with ``K`` the number of measures. For `stat` a `BivStatistic` or a `OneSampStatistic` return `total`, that is, there is no possible redundancy. Note that the elimination of redundant permutations is rarely implemented in software packages for permutation tests. *Examples* ```julia using PermutationTests # Number of possible permutations for a 1-way ANOVA for indepedent samples # test with a total of 18 observations in three balanced groups. ns=[6, 6, 6] total=allPerms(AnovaF_IS(), ns) # -> 17153136 # Number of non-redundant permutations that will be actually listed # to perform the test. design=assignment(AnovaF_IS(), ns) nrPerms(AnovaF_IS(), ns, total, Both(), design) # -> 2858856 ``` """ nrPerms(stat::Union{BivStatistic, OneSampStatistic}, ns::Int, total, direction::TestDir, design::Assign=Balanced()) where {TestDir<: TestDirection, Assign <: Assignment} = total nrPerms(stat::IndSampStatistic, ns::Vector{Int}, total, direction::TestDir, design::Assign) where {TestDir<: TestDirection, Assign <: Assignment} = direction isa Both && design isa Balanced ? total ÷ (factorial(big(length(ns)))) : total nrPerms(stat::RepMeasStatistic, ns::@NamedTuple{n::Int, k::Int}, total, direction::TestDir, design::Assign=Balanced()) where {TestDir<: TestDirection, Assign <: Assignment} = direction isa Both ? total ÷ (factorial(big(ns.k))) : total # ----- # # ----- # """ ```julia function membership(stat::IndSampStatistic, ns::Vector{Int}) ``` Create the appropriate argument `x` to be used by functions [`_permTest!`](@ref) and [`_permMcTest!`](@ref) when you [create your own test](@ref "Create your own test") using the permutation scheme of test statistics belonging to the `IndSampStatistic` [group](@ref "Statistic groups"). For `stat` a `IndSampStatistic`, `ns` is a group numerosity vector, *i.e.*, a vector of positive integers `[N1,...,NK]`, where ``K`` is the number of groups and ``N_k`` is the number of observations for the ``k^{th}`` group (see [ns](@ref)). Return the group membership vector `[repeat (1, N1);...; repeat(K, Nk)]` If `rev=reverse` is passed as keyword argument, return instead group membership vector `[repeat (K, N1);...; repeat(1, Nk)]`. This is used to run t-tests for independent samples using the `PearsonR()` [Statistic](@ref), see for example [`studentTestIS`](@ref). *Examples* ```julia using PermutationsTests membership(AnovaF_IS(), [3, 4]) # return the vector [1, 1, 1, 2, 2, 2, 2] ``` """ membership(stat::IndSampStatistic, ns::Vector{Int}; rev=identity) = vcat([ones(Int, rev(ns)[i])*i for i ∈ rev(eachindex(ns))]...) # it was for i=1:length(ns) """ ```julia function membership(stat::RepMeasStatistic, ns::@NamedTuple{n::Int, k::Int}) ``` Create the appropriate argument `x` to be used by functions [`_permTest!`](@ref) and [`_permMcTest!`](@ref) when you [create your own test](@ref "Create your own test") using the permutation scheme of test statistics belonging to the `RepMeasStatistic` [group](@ref "Statistic groups"). For `stat` a `RepMeasStatistic`, `ns` is a named tuple, such as `(n=N, k=K)`, where ``N`` is the number of observations (e.g., *subjects*) and ``K`` the number of measurements (or *treatments*, *times*, ect.), see [ns](@ref). Return `collect(1:N*K)`. *Examples* ```julia using PermutationsTests membership(AnovaF_RM(), (n=2, k=4)) # return the vector [1, 2, 3, 4, 5, 6, 7, 8] ``` """ membership(stat::RepMeasStatistic, ns::@NamedTuple{n::Int, k::Int}) = collect(1:ns.n*ns.k) #repeat(1:ns.k, ns.n) """ ```julia function membership(stat::OneSampStatistic, ns::Int) ``` Create the appropriate argument `x` to be used by functions [`_permTest!`](@ref) and [`_permMcTest!`](@ref) when you [create your own test](@ref "Create your own test") using the permutation scheme of test statistics belonging to the `OneSampStatistic` [group](@ref "Statistic groups"). For `stat` a `OneSampStatistic`, `ns` is the number of observations (e.,g., *subjects*) given as an integer, see [ns](@ref). Return `ones(Int, ns)`. *Examples* ```julia using PermutationsTests membership(Sum(), 5) # return the vector [1, 1, 1, 1, 1] ``` """ membership(stat::OneSampStatistic, ns::Int) = ones(Int, ns) # ----- # # ----- # """ ```julia function genPerms(stat::BivStatistic, x::UniData, ns::Int, direction::TestDir, design::Assign) function genPerms(stat::IndSampStatistic, x::UniData, ns::Vector{Int}, direction::TestDir, design::Assign) function genPerms(stat::RepMeasStatistic, x::UniData, ns::@NamedTuple{n::Int, k::Int}, direction::TestDir, design::Assign) function genPerms(stat::OneSampStatistic, x::UniData, ns::Int, direction::TestDir, design::Assign) where {TestDir<: TestDirection, Assign <: Assignment} ``` Generate a *lazy* iterator over all possible (systematic) permutations according to the permutation scheme to be used for test statistic `stat`, which is given as a singleton of type [Statistic](@ref). Note that data permutation in *PermutationsTests.jl* are always obtained by lazy iterators, that is, permutations are never listed physically. This is one of the main reasons why the package is fast and allocates little memory. You do not need these functions for general usage of the package, however you need to know them if you wish to [create your own test](@ref "Create your own test"). There exists a permutation scheme for each [group](@ref "Statistic groups") the test statistics `stat` belong to. `x` is the [`membership`](@ref) vector. For the `ns` argument see [ns](@ref). `direction` is a singleton of type [TestDirection](@ref). `design` is a singleton of type [Assignment](@ref). In order to avoid errors, use the result of [`assignment`](@ref) as argument `design`. With `stat` a `BivStatistic` (*e.g.*, `PearsonR()`), the iterations unfold the ``N!`` possible reorderings of the ``N`` elements in vector `x` and argument `ns` is ignored. In this case `x` is either a trend (e.g., [1,...,N] for a linear trend) or a variable to be permuted for correlation/trend tests. With `stat` a `IndSampStatistic` (*e.g.*, `AnovaF_IS()`), the iterations unfold the ``\\frac{N!}{N_1 \\cdot \\ldots \\cdot N_K}`` possible arrangements of ``N`` elements in ``K`` groups. In this case `x` is ignored and `ns` is a vector holding the K group numerosities (i.e., [N1,...,Nk]). For this scheme, if the design is balanced, *i.e.*, all elements of ns are equal, some permutations are redundant, see [`nrPerms`](@ref). With `stat` a `RepMeasStatistic` (*e.g.*, `AnovaF_RM()`), the iterations unfold the ``(K!)^N`` reordering of ``K`` measures (e.g., treatments) in all ``N`` observation (e.g., subjects). In this case `x` is ignored and `ns` is a [named tuple](https://docs.julialang.org/en/v1/manual/types/#Named-Tuple-Types) with form `(n=N, k=K)`. For this scheme, if the test is bi-directional some permutations are redundant, see [`nrPerms`](@ref). With `stat` a `OneSampStatistic` (*e.g.*, `StudentT_1S()`), the iteartions unfold the ``2^N`` flip-sign patterns. In this case `x` is ignored and `ns=N`, where ``N`` is the number of observations. !!! note "nota bene" Only for `stat` belonging to the `OneSampStatistic` group, the iterator generates tuples and not arrays (see examples below). !!! tip "keep in mind" Regardless the permutation scheme, the first generated iteration always correspons to the "permutation" of the data as it has been observed (that is, the only permutation that actually does not permute the data). *Examples* ```julia using PermutationsTests x=membership(PearsonR(), 3) # -> [1, 2, 3] # The observations are always listed in the natural order 1, 2,... Pr = genPerms(PearsonR(), x, 0, Both(), Balanced()) collect(Pr) # physically list the iterations # yields the 6 = 3! elements [1, 2, 3]...[3, 2, 1] # Here the integers represent the permuted position of the obervations in x PfIS = genPerms(AnovaF_IS(), Int[], [2, 3], Both(), Unbalanced()) collect(PfIS) # yields the 10 = 5!/2!3! elements [1, 1, 2, 2, 2]...[2, 2, 2, 1, 1] # Here the integers represent the permuted group to which the corresponding # obervations in the data vector `y` belongs. see `_permTest!`. # If the design is balanced and the test is bi-directional, # only 1/k! of the permutations are retained, thus PfIS_ = genPerms(AnovaF_IS(), Int[], [2, 2], Both(), Balanced()) collect(PfIS_) # yields the 3 = (4!/2!2!)/2! elements [1, 1, 2, 2], [1, 2, 2, 1] and [2, 1, 2, 1] PfRM = genPerms(AnovaF_RM(), Int[], (n=2, k=3), Right(), Balanced()) collect(PfRM) # yields the 36 = (k!)^n elements [1, 2, 3, 4, 5, 6], [1, 3, 2, 4, 5, 6], # ..., [3, 2, 1, 6, 5, 4] # Here the integers represent the treatement for each subject to which the # corresponding obervation in the data vector `y` belongs. see `_permTest!`. # If the test is bi-directional, # only 1/k! of the permutations are retained, thus PfRM_ = genPerms(AnovaF_RM(), Int[], (n=2, k=3), Both(), Balanced()) collect(PfRM_) # yields instead the 6 = (k!)^n / elements [1, 2, 3, 4, 5, 6], [1, 3, 2, 4, 5, 6], # ..., [3, 2, 1, 4, 5, 6] Pt1S = genPerms(StudentT_1S(), Int[], 3, Both(), Balanced()) collect(Pt1S) # yields the 8=2^3 elements (1, 1, 1), (-1, 1, 1), (1, -1, 1), (-1, -1, 1), #..., (-1, -1, -1) # Here the integers represent the sign to be applied to each observation # at each data permutation. # Note that only for OneSampStatistic, the iterator generates tuples and not arrays. ``` """ genPerms(stat::BivStatistic, 𝐱::UniData, ns::Int, direction::TestDir, design::Assign) where {TestDir<: TestDirection, Assign <: Assignment} = permutations(𝐱) function genPerms(stat::IndSampStatistic, 𝐱::UniData, ns::Vector{Int}, direction::TestDir, design::Assign) where {TestDir<: TestDirection, Assign <: Assignment} n, k, msp = sum(ns), length(ns), multiset_permutations # for balanced design in IS ANOVA-like tests, only the permutations respecting condition i % factorial(k) == 1 are needed memb = vcat([ones(Int, ns[i])*i for i ∈ eachindex(ns)]...) return design isa Balanced && direction isa Both ? (p for (i, p) in enumerate(msp(memb, n)) if i % factorial(k) == 1) : msp(memb, n) end # the concatenation of iterators' product of (permutations(1:k), permutations(1k+1:1k+k), ..., permutations((n-1)k+1:(n-1)*k+k)) function genPerms(stat::RepMeasStatistic, 𝐱::UniData, ns::@NamedTuple{n::Int, k::Int}, direction::TestDir, design::Assign) where {TestDir<: TestDirection, Assign <: Assignment} # for bi-directional tests RM ANOVA-like tests, only the first non_redundant = all ÷ factorial(k) permutations are needed if !(direction isa Both) return (vcat(p...) for p in Iterators.product((permutations((i*ns.k)+1:(i*ns.k)+ns.k ) for i in 0:ns.n-1)...)) # yields : [1, 2, 3, 4, 5, 6], [2, 1, 3, 4, 5, 6],... else needed = allPerms(stat, ns) ÷ factorial(ns.k) # take only the first `needed` permutations : return Iterators.take((vcat(p...) for p in Iterators.product((permutations((i*ns.k)+1:(i*ns.k)+ns.k ) for i in 0:ns.n-1)...)), needed) end end genPerms(stat::OneSampStatistic, 𝐱::UniData, ns::Int, direction::TestDir, design::Assign) where {TestDir<: TestDirection, Assign <: Assignment} = Iterators.product(((1., -1.) for i=1:ns)...) # Iterators.map(SVector, Iterators.product(((1., -1.) for i=1:ns)...)) !!!!!! xxx Arrays # ----- # # ----- # # check the `ns` argument, which is given as input for several test functions # second check only for internal test to allow new test creations that have a fifferent 𝐲 function _check_ns(𝐲, ns, stat::Union{BivStatistic, OneSampStatistic}) ns isa Int || throw(ArgumentError(📌*" Function _check_ns: for bivariate and OneSampStatistic statistics `ns` must be an integer")) 𝐲 isa DataType && ns≠length(𝐲) && throw(ArgumentError(📌*" Function _check_ns: for bivariate and OneSampStatistic statistics `ns` must be an integer equal to the length of 𝐲")) end function _check_ns(𝐲, ns, stat::IndSampStatistic) ns isa IntVec || throw(ArgumentError(📌*" Function _check_ns: for Independent Samples statistics `ns` must be a vector of integer")) 𝐲 isa DataType && sum(ns)≠length(𝐲) && throw(ArgumentError(📌*" Function _check_ns: for Independent Samples statistics the elements in `ns` must sum up to the length of vector argument 𝐲")) end function _check_ns(𝐲, ns, stat::RepMeasStatistic) ns isa NamedTuple || throw(ArgumentError(📌*" Function _check_ns: for Repeated Measure statistics `ns` must be a NamedTuple")) 𝐲 isa DataType && ns.n*ns.k≠length(𝐲) && throw(ArgumentError(📌*" Function _check_ns: for Repeated Measure statistics the `k`(# of treatments) and `n`(# of subjects) fields in `ns` must sum up to the length of vector argument 𝐲")) end # ----- # # ----- # # Return the test type (:exact or :approximate) and the number of permutations, given the number of observations, # the group numerosity vector n, the test statistic `stat`, the default number of permutations # for an approximate test `nperm` and the upper limit for the number of permutations to allow an exact test. # If observations > 30 or the number of systematic permutations exceeds `switch2rand` the the approximate # test with nperm permutations is chosen, otherwise the exact test is chosen. function _test_params(stat::Stat, ns, fstat::Function, observations, nperm, switch2rand) where Stat<:Statistic design = assignment(stat, ns) # Balanced() or Unbalanced() direction = _direction(fstat) if observations > 26 # avoid to compute large factorials testtype = :approximate nonRed = nperm else totalperm = allPerms(stat, ns) # Total systematic permutations. nonRed = BigInt(nrPerms(stat, ns, totalperm, direction, design)) # non-redundant systematic permutations if nonRed>switch2rand testtype = :approximate nonRed = nperm else nperm=Int(nonRed) # (totalperm) # Typecast to Int as allPerms uses BigInt. NB thi change argument nperm testtype = :exact end end return testtype, nperm, direction, design end # ----- # # ----- # # make checks and prepare the ensuing _perm_test! function function _prepare_permtest!(𝐱, 𝐲, ns, stat, fstat, nperm, switch2rand, seed, standardized, centered)#, means, sds) # check ns argument _check_ns(𝐲, ns, stat) # determine whether the permutations are to be systematic or random (testtype), their number (npern) , # the test direction (direction) and whether the design is balanced or unbalanced (design) testtype, nperm, direction, design = _test_params(stat, ns, fstat, length(𝐲), nperm, switch2rand) # for OneSampStatistic and approximate tests 𝐱 is not used. For all other cases 𝐱 and 𝐲 must have equal length) # 𝐲 isa DataType in order to allow to create tests with different data types 𝐲 isa DataType && !((stat isa OneSampStatistic) & (testtype == :approximate)) && length(𝐱) ≠ length(𝐲) && throw(ArgumentError(📌*"Function _prepare_permtest!: the length of vector argument 𝐱 and 𝐲 is not equal")) rng = nothing testtype == :approximate && (rng = MersenneTwister(seed==0 ? rand(UInt32) : seed)) # use Random.seed!(1234) to reset the seed of the random number generator; getkwargs(𝐱, 𝐲, ns, stat::CrossProd) = (k=0, ns=0) getkwargs(𝐱, 𝐲, ns, stat::Covariance) = (k=0, ns=0, centered=centered) getkwargs(𝐱, 𝐲, ns, stat::PearsonR) = (k=0, ns=0, standardized=standardized, centered=centered)#, means=means, sds=sds) getkwargs(𝐱, 𝐲, ns, stat::IndSampStatistic) = (_anova_IS_fixed_params(𝐱; askwargs=true)..., ft=0) # ft is dummy, but otherwise does not compile getkwargs(𝐱, 𝐲, ns, stat::Union{RepMeasStatistic, OneSampStatistic}) = (k=0, ns=ns) mykwargs = getkwargs(𝐱, 𝐲, ns, stat) return testtype, nperm, direction, design, mykwargs, rng end # ----- # """ ```julia function table2vec(table::Matrix{I}, stat::IndSampStatistic) function table2vec(tables::AbstractVector{Matrix{I}}, stat::IndSampStatistic) function table2vec(table::Matrix{I}, stat::RepMeasStatistic) function table2vec(tables::AbstractVector{Matrix{I}}, stat::RepMeasStatistic) where I<:Int ``` Format tables of dicothomous data so as to create data input for test functions. Return the 2-tuple holding the formatted table as a vector (for univariate test) or a vector of vectors (for multiple comparisons tests) and the appropriate argument [ns](@ref). You do not need to use these functions in general, as they are called internally by the test functions. However they may be useful if you [create your own test](@ref "Create your own test") for dicothomous data. `stat` is a singleton of the [Statistic](@ref) type, that is, a test-statistic belonging to one of the [group of test statistics](@ref "Statistic groups"). For the usage of these functions, see the documentation of the test functions using them: **Univariate test functions** - [`chiSquaredTest`](@ref) - [`fisherExactTest`](@ref) - [`cochranqTest`](@ref) - [`mcNemarTest`](@ref) **Multiple comparisons test functions** - [`chiSquaredMcTest`](@ref) - [`fisherExactMcTest`](@ref) - [`cochranqMcTest`](@ref) - [`mcNemarMcTest`](@ref) """ function table2vec(table::Matrix{I}, stat::IndSampStatistic) where I<:Int size(table, 1) > 2 && throw(ArgumentError(📌*" Function table2vec: the contingency table may have at most two rows (but any K≥2 columns)")) return Float64.(vcat([fill(1-(r-1), table[r, c]) for c in axes(table, 2) for r in axes(table, 1)]...)), vec(sum(table, dims=1)) end function table2vec(tables::AbstractVector{Matrix{I}}, stat::IndSampStatistic) where I<:Int size(tables[1], 1) > 2 && throw(ArgumentError(📌*" Function table2vec: the contingency tables may have at most two rows (but any K≥2 columns)")) return [Float64.(vcat([fill(1-(r-1), t[r, c]) for c in axes(t, 2) for r in axes(t, 1)]...)) for t ∈ tables], vec(sum(tables[1], dims=1)) end function table2vec(table::Matrix{I}, stat::RepMeasStatistic) where I<:Int N, K = size(table) K < 2 && throw(ArgumentError(📌*" Function table2vec: the table must have at least two columns (treatements)")) N < K && throw(ArgumentError(📌*" Function table2vec: the number of rows of the table (subjects) must be graeter than the number of columns (treatments)")) return Float64.(vcat(table'...)), (n=N, k=K) end function table2vec(tables::AbstractVector{Matrix{I}}, stat::RepMeasStatistic) where I<:Int N, K = size(tables[1]) K < 2 && throw(ArgumentError(📌*" Function table2vec: the tables must have at least two columns (treatements)")) N < K && throw(ArgumentError(📌*" Function table2vec: the number of rows of the tables (subjects) must be graeter than the number of columns (treatments)")) return [Float64.(vcat(t'...)) for t ∈ tables], (n=N, k=K) end # ----- #
PermutationTests
https://github.com/Marco-Congedo/PermutationTests.jl.git
[ "MIT" ]
0.2.0
8a73fe1574e159927031bb2b9cc6ea142f075407
code
11131
#= uniTests.jl Unit of the PermutationTests.jl Package MIT License Copyright (c) 2024, Marco Congedo, CNRS, Grenoble, France: https://sites.google.com/site/marcocongedo/home ################################ # Univariate Permutation tests # ################################ ============================= EXPORTED: - _permTest! - ultimate function to perform all univariate tests - testStatistic - compute observed and permuted test statistic for univariate tests UTILITIES: - _randperm_uni! - generate a random permutattion overwriting either the 𝐱 or 𝐲 vector - _additional_kwargs_uni! - additional keyword arguments for _permTest! depending on the statistic =# # ----- # # Generate a random permutation overwriting either vector 𝐱 or vector 𝐲, depending on stat and return them as a tuple. # For both BivStatistic and IndSampStatistic this is a suffling of the elements of 𝐱 and ns is ignored # For RepMeasStatistic statistics this is a suffling of all elements of 𝐱 taken k at a time. ns is needed # For OneSampStatistic statistics, the sign of the elements in 𝐲 is flipped with probability 0.5. ns is ignored # Note that instead for exact test only the 𝐱 vector is changed _randperm_uni!(𝐱::UniData, 𝐲, stat::Union{BivStatistic, IndSampStatistic}, rng::MersenneTwister; ns::nsType = 0, ft = nothing) = return (shuffle!(rng, 𝐱), 𝐲) function _randperm_uni!(𝐱::UniData, 𝐲, stat::RepMeasStatistic, rng::MersenneTwister; ns = @NamedTuple{n::Int, k::Int}, ft = nothing) @simd for i=0:ns.n-1 @inbounds shuffle!(rng, view(𝐱, (i*ns.k)+1:(i*ns.k)+ns.k)) # shuffling in-place of 𝐱 end return (𝐱, 𝐲) end function _randperm_uni!(𝐱::UniData, 𝐲, stat::OneSampStatistic, rng::MersenneTwister; ns::nsType = 0, ft::Tuple=(-1.0, 1.0)) @simd for i ∈ eachindex(𝐲) @inbounds 𝐲[i] *= rand(rng, ft) # flip the sign of the elements of 𝐲 with probability 0.5 (rand pick a number at random from `ft`) end return (𝐱, 𝐲) end # ----- # # Add some keyword arguments to kwargs for some statistics. # ----- # function _additional_kwargs_uni!(kwargs, 𝐲, ns, stat, cpcd) stat isa AnovaF_RM && (kwargs = (kwargs..., ∑Y²kn=_∑Y²kn(𝐲, ns), ∑y²=_∑y²(𝐲), ∑S²k=_∑S²k(𝐲, ns))) stat isa StudentT_1S && (kwargs = (kwargs..., ∑y²=∑of²(𝐲))) cpcd === nothing || (kwargs = (kwargs..., cpcd=cpcd)) return kwargs end # ----- # # Compute observed and permuted statistics. Use an alias of `statistic` to allow a consistent # sintax when creating custom univariate and multiple comparison tests # ----- # testStatistic(𝐱, 𝐲::UniData, stat::AllStatistics; kwargs...) = statistic(𝐱, 𝐲, stat; kwargs...) # ----- # # ----- # """ ```julia function _permTest!(x, y, ns::nsType, stat::Stat, asStat::AsStat; standardized::Bool=false, centered::Bool=false, nperm::Int = 20000, fstat::Function = abs, compfunc::Function = >=, switch2rand::Int = Int(1e8), seed::Int = 1234, verbose::Bool = true, cpcd = nothing, kwargs...) where {Stat<:Statistic, AsStat<:Statistic} ``` This function ultimately performs all **univariate permutation tests** implemented in *PermutationsTests.jl*, both *exact* and *approximate* (Monte Carlo). For running tests use the [univariate test functions](@ref "Univariate tests"). You need this function only for [creating your own tests](@ref "Create your own test"). Rewrite `x` and/or `y`, depending on the test performed. For the `ns` argument see [ns](@ref). `stat` can be a singleton of the [Statistic](@ref) type or a user-defined singleton of this type to be used as argument of a function implemented by the user to compute both the observed and permuted test statistics, see [create your own test](@ref "Create your own test"). `asStat` is a singleton of the [Statistic](@ref) type. It is used to determine the permutation scheme and for this purpose it will be internally passed to [`genPerms`](@ref) and [`nrPerms`](@ref). `asStat` determines also the input data format if you declare your own `stat` type. In this case the function you write for computing the observed and permuted test statistic will take the `x` and `y` arguments as it follows: For `Stat` belonging to [group](@ref "Statistic groups") - `BivStatistic` : `x`, `y` are the two vectors of ``N`` elements each for which the bivariate statistic is to be tested. `ns` is ignored. - `IndSampStatistic` : we have ``K`` groups and ``N=N_1+...+N_K`` total observations; `y` holds all observations in a single vector such as `[y1;...;yK]` and `x` is the [`membership(::IndSampStatistic)`](@ref) vector. For example, for ``K=2``, ``N_1=2`` and ``N_2=3``, `x=[1, 1, 2, 2, 2]`. - `RepMeasStatistic` : we have ``K`` measures (*e.g.*, treatements) and ``N`` subjects; `y` holds the ``K*N`` observations in a single vector such as `[y1;...;yN]`, where each vector ``y_i``, for ``i=1...N``, holds the observation at the ``K`` treatments and `x=collect(1:K*N)` (see [`membership(::RepMeasStatistic)`](@ref)). - `OneSampStatistic` : We have ``N`` observations (*e.g.*, subjects); `y` holds the ``N`` observations and `x=ones(Int, N)` (see [`membership(::OneSampStatistic)`](@ref)). !!! note "Nota Bene" In all cases `x` is treated as the permutation vector that will be permuted before calling the [`testStatistic`](@ref) function. For `length(x)>30` the approximate test is performed in all cases, otherwise, if the number of systematic permutations exceeds `switch2rand` the approximate test is performed using `nperm` random permutations (default 20000), otherwise, the exact test is performed. `switch2rand` defaults to 1e8. To perform approximate tests in all cases, set `switch2rand`, for example, to 1. If `stat` is a `BivStatistic`, it optionally uses kwargs `standardized` or `centered` to compute them faster, see for example [`correlationTest`](@ref). `seed` is the initial seed for generating random permutations (not used for exact tests). To use a random seed, pass `seed=0`. For `seed` any natural number, the test will be reproducible. `fstat` is a function applied to the test statistic. By default this is the julia `abs` function, which takes the absolute value, hence yieds a bi-directional test for a test statistic distributed symmetrically around zero. For a right-directional test using such test statistics pass here `identity`. For a left-directional using such test statistics pass here [`flip`](@ref). `compfunc` is the function to compare the observed statistics to the permuted statistics. The default function is `>=`. Don't change it unless you have studied the code of the function. If `verbose` is true, print some information in the REPL while running the test. Set to false if you run benchmarks. The default is true. For the `cpcd` and `kwargs...` argument, see [create you own test](@ref "Create your own test"). Return a [UniTest](@ref) structure. *Examples* ```julia using PermutationTests x=randn(6) y=randn(6) # bi-directional exact test of the correlation between x and y t8 = _permTest!(μ0(x), μ0(y), length(x), Covariance(), Covariance(); centered=true) t8.p t8.stat #... # make a left-directional test and standardize the data t8_2 = _permTest!(μ0σ1(x), μ0σ1(y), length(x), Covariance(), Covariance(); standardized=true, fstat=flip) # the same but force an approximate test t8_3 = _permTest!(μ0σ1(x), μ0σ1(y), length(x), Covariance(), Covariance(); standardized=true, fstat=flip, switch2rand=1) # the same using 5000 random permutations t8_4 = _permTest!(μ0σ1(x), μ0σ1(y), length(x), Covariance(), Covariance(); standardized=true, fstat=flip, switch2rand=1, nperm=5000) ``` To check more examples, see the *uniTests_API.jl* unit located in the *src* github folder and function `test_unitests()` in the *runtests.jl* unit located in the *test* github folder. """ function _permTest!(𝐱, 𝐲, ns::nsType, stat::Stat, asStat::AsStat; standardized::Bool=false, centered::Bool=false, # means::Tuple=(), sds::Tuple=(), # optional kwa for correlation-like statistics nperm::Int = 20000, fstat::Function = abs, compfunc::Function = >=, switch2rand::Int = Int(1e8), seed::Int = 1234, verbose::Bool = true, cpcd = nothing, kwargs...) where {Stat<:Statistic, AsStat<:Statistic} # check arguments and prepare test testtype, nperm, direction, design, mykwargs, rng = _prepare_permtest!(𝐱, 𝐲, ns, asStat, fstat, nperm, switch2rand, seed, standardized, centered)#, means, sds) c, f, s, r! = compfunc, fstat, testStatistic, _randperm_uni! # aliases ####################### START TEST ############################## verbose && println("Performing a test using ", testtype == :exact ? "$nperm systematic permutations..." : "$nperm random permutations...") # observed statistic. eps is to avoid floating point arithmetic errors when comparing the permuted stats mykwargs = _additional_kwargs_uni!(mykwargs, 𝐲, ns, stat, cpcd) # more kwargs for some test statistics obsStat = f(testStatistic(𝐱, 𝐲, stat; mykwargs..., kwargs...)) - sqrt(eps()) # get p-value ############# # The p-value is otained summing the number of time the function `fstat` applied to the permutated statistics satisfyies fucntionc `c` # (default: the permutation statistic is greater then or equal to the observed one) and dividing by the number of permutation. # `fstat` is abs for two-tailes test, identity for right-tailed tests and flip for a left-tails test. # For exact tests P is an itarator over all systematic permutations. # Nota bene: for exact tests the permutation corresponding to the observed data is the first in P, # hence the sum across all permutations is considered. For approximate (monte carlo) tests 1 is added to the sum to occount # for the permutation corresponding to the observed data. if testtype == :exact P = genPerms(asStat, 𝐱, ns, direction, design) # generate systematic permutations # check to be removed later on #nperm ≠ length(P) && throw(ArgumentError("nperm is not equal to the length of P, $nperm, $(length(P))")) pvalue = sum(c(f(s(p, 𝐲, stat; mykwargs..., kwargs...)), obsStat) for p ∈ P) / nperm else # Monte Carlo test # N.B. r! return 𝐱_, 𝐲_, one of which is modified depending on stat to generate a random data permutation pvalue = (1+sum(c(f(s(r!(𝐱, 𝐲, asStat, rng; ns)..., stat; mykwargs..., kwargs...)), obsStat) for i ∈ 1:nperm-1)) / nperm end ############# return UniTest(pvalue, stat, obsStat, 1/nperm, nperm, testtype, direction, design) #return pvalue, stat, obsStat, 1/nperm, nperm, testtype, direction, design end # ----- # # Note: for Onesampstat for exact tests x is changed, for approximate tests y is changed
PermutationTests
https://github.com/Marco-Congedo/PermutationTests.jl.git
[ "MIT" ]
0.2.0
8a73fe1574e159927031bb2b9cc6ea142f075407
code
52608
#= uniTests_API.jl Unit of the PermutationTests.jl Package MIT License Copyright (c) 2024, Marco Congedo, CNRS, Grenoble, France: https://sites.google.com/site/marcocongedo/home ######################################## # API for Univariate Permutation tests # ######################################## Run `test_uniTests_API()` in unit _test.jl to test this unit ======================================== EXPORTED: correlationTest!, rTest!, correlationTest, rTest, trendTest!, trendTest, pointBiSerialTest, anovaTestIS, fTestIS, studentTestIS, tTestIS, chiSquaredTest, Χ²Test, fisherExactTest, anovaTestRM, fTestRM, cochranqTest, qTest, mcNemarTest, studentTestRM, tTestRM, studentTestRM!, tTestRM!, studentTest1S!, tTest1S!, studentTest1S, tTest1S, signTest!, signTest, UTILITIES: - _permutationTest - _permutationTest! ======================================== =# # GENERAL KEYWORD ARGUMENTS # direction: test direction, either Right(), Left() or Both(). Default: Both() # equivalent (Bool): if true, the fastest equivalent statistic will be used. Default: true # switch2rand (Int): the # of permutations starting from which the approximate test will be carried out. Default: 1e8 # nperm (Int): the # of permutations to be used if the test will be approximate (default: 20_000) # seed (Int): random # generator seed. Set to 0 to take a random seed. Any natural number allow a reproducible test.(Default: 1234) # verbose (Bool) print some information in the REPL while running the test. Set to false for running @benchmark (Default: true). ##### ## This function ultimately run all tests. No check on data input is performed # This method run all tests BUT the correlation and trend tests and the 1 sample tests - 9 arguments function _permutationTest(𝐲::UniData, ns::Union{Vector{Int}, @NamedTuple{n::Int, k::Int}}, stat, direction, equivalent, switch2rand, nperm, seed, verbose) 𝐱 = membership(stat, ns) design = assignment(stat, ns) eqstat = equivalent ? eqStat(stat, direction, design) : stat return _permTest!(𝐱, 𝐲, ns, eqstat, eqstat; fstat=_fstat(direction), switch2rand, nperm, seed, verbose) end # This run only correlation and trend tests. Don't use for other tests! - 10 arguments function _permutationTest!(𝐱::UniData, 𝐲::UniData, standardized, centered, direction, equivalent, switch2rand, nperm, seed, verbose) centered && direction==Both() && (equivalent=true) if standardized eqstat = CrossProd() else eqstat = equivalent ? eqStat(PearsonR(), direction, Balanced()) : PearsonR() end return _permTest!(𝐱, 𝐲, length(𝐱), eqstat, eqstat; standardized, centered, fstat=_fstat(direction), switch2rand, nperm, seed, verbose) end # This run only one-sample t-tests, hence repeated-measures t-tests. Don't use for other tests! # NB: for exact tests 𝐱 is rewritten, but for monte carlo tests input data vector 𝐲 is rewritten - 8 arguments function _permutationTest!(𝐲::UniData, ns::Int, direction, equivalent, switch2rand, nperm, seed, verbose) 𝐱 = membership(StudentT_1S(), ns) eqstat = equivalent ? eqStat(StudentT_1S(), direction, Balanced()) : StudentT_1S() return _permTest!(𝐱, 𝐲, ns, eqstat, eqstat; fstat=_fstat(direction), switch2rand, nperm, seed, verbose) end ### Correlation test """ ```julia function correlationTest(x::UniData, y::UniData; direction::TestDir = Both(), equivalent::Bool = true, switch2rand::Int = Int(1e8), nperm::Int = 20_000, seed::Int = 1234, standardized::Bool = false, centerd::Bool = false, verbose::Bool = true) where TestDir <: TestDirection ``` Univariate [Pearson product-moment correlation test](https://en.wikipedia.org/wiki/Pearson_correlation_coefficient#Testing_using_Student's_t-distribution) by data permutation. The null hypothesis has form ``H_0: r_{(x,y)}=0``, where ``r_{(x,y)}`` is the correlation between the two input data vectors, `x` and `y`, typically real, both holding ``N`` observations. For optional keyword arguments, `direction`, `equivalent`, `switch2rand`, `nperm`, `seed` and `verbose`, see [here](@ref "Common kwargs for univariate tests"). If `standardized` is true, both `x` and `y` are assumed standardized (zero mean and unit standard deviation). Provided that the input data is standardized, the test provides the same p-value, however it can be executed faster as in this case the cross-product is equivalent to the Pearon *r* statistic (see [Statistic](@ref)). If `centered` is true, both `x` and `y` are assumed centered (zero mean). The test provides the same p-value, however it can be executed faster if the test is bi-directional as in this case the equivalent statistic, the covariance, reduces to the cross-product divided by N. If neither `standardized` nor `centered` is true, the data will be standardized to execute a faster test using the cross-product as test-statistic. *Directional tests* - For a right-directional test, the correlation is expected to be positive. A negative correlation will result in a p-value higehr then 0.5. - For a left-directional test, the correlation is expected to be negative. A positive correlation will result in a p-value higehr then 0.5. *Permutation scheme:* under the null hypothesis, the position of the observations in the data input vectors bears no meaning. The exchangeability scheme consists then in shuffling the observations of vector `x` or vector `y`. *PermutationTests.jl* shuffles the observations in `x`. *Number of permutations for exact tests:* there are ``N!`` possible ways of reordering the ``N`` observations in `x`. *Aliases:* `rTest!`, [`trendTest!`](@ref) *Multiple comparisons version:* [correlationMcTest!](@ref) Return a [UniTest](@ref) structure. *Examples* ```julia using PermutationTests N=10 # number of observations x, y = randn(N), randn(N) # some random Gaussian data for example t = rTest(x, y) # by deafult the test is bi-directional ``` ```@julia tR = rTest(x, y; direction=Right()) # right-directional test tL = rTest(x, y; direction=Left()) # Left-directional test # Force an approximate test with 5000 random permutations tapprox = rTest(x, y; switch2rand=1, nperm=5000) ``` **Similar tests** Typically, the input data is real, but can also be of type integer or boolean. If either `x` or `y` is a vector of booleans or a vector of dicothomous data (only 0 and 1), this function will actually perform a permutation-based version of the [point bi-serial correlation test](https://en.wikipedia.org/wiki/Point-biserial_correlation_coefficient). However, as shown in the preceeding link, the point bi-serial correlation test is equivalent to the t-test for independent sample, thus it can be tested using the t-test for independent samples, which will need many less permutations as compared to a correlation test for an exact test (see examples below). A dedicated function in available with name [`pointBiSerialTest`](@ref), which is an alias for [`studentTestIS`](@ref) and allowa the choice to run the test using a correlation- or t-test statistic. If `x` or `y` represent a *trend*, for example a linear trend given by `[1, 2,...N]`, we otain the permutation-based trend correlation test, which can be used to test the fit of any type of regression of `y` on `x` - see [trendTest](@ref). if `y` is a shifted version of `x` with a lag ``l``, this function will test the significance of the *autocorrelation at lag ``l``, see the page [Create your own test](@ref). *Examples* ```julia # Point bi-serial correlation test using PermutationTests N=10 # number of observations x=[0, 0, 0, 0, 1, 1, 1, 1, 1, 1] y = rand(N) t = rTest(x, y) # Exactly the same test can be obtained as a t-test for independent sample, # but much faster as for an exact test the latter needs only 210 permutations # while the former needs 3628800 permutations. # This is available with a dedicated function t2=pointBiSerialTest(y, [4, 6]) println(t.p ≈ t2.p ? "OK" : "error") ``` """ correlationTest(𝐱::UniData, 𝐲::UniData; direction::TestDir = Both(), equivalent::Bool = true, switch2rand::Int = Int(1e8), nperm::Int = 20_000, seed::Int = 1234, standardized::Bool = false, centered::Bool = false, verbose::Bool = true) where TestDir <: TestDirection = correlationTest!((standardized || centered) ? copy(𝐱) : 𝐱, 𝐲; direction, equivalent, switch2rand, nperm, seed, standardized, centered, verbose) # alias. The trendTest is obtained passed the trend to be tested as vector `𝐱`. For example [1, 2,...] for an ascending linear trend rTest = correlationTest """ ```julia function correlationTest!(<same args and kwargs as `correlationTest`>) ``` As [`correlationTest`](@ref), but `x` is overwritten if neither `standardized` nor `centered` is true. *Aliases:* `rTest!`, [`trendTest!`](@ref) *Multiple comparisons version:* [correlationMcTest!](@ref) """ function correlationTest!(𝐱::UniData, 𝐲::UniData; direction::TestDir = Both(), equivalent::Bool = true, switch2rand::Int = Int(1e8), nperm::Int = 20_000, seed::Int = 1234, standardized::Bool = false, centered::Bool = false, verbose::Bool = true) where TestDir <: TestDirection length(𝐱) == length(𝐲) || throw(ArgumentError(📌*"Function correlationTest!: the first two arguments are the vectors of the two variables and must have equal length.")) if standardized return _permutationTest!(𝐱, 𝐲, true, centered, direction, equivalent, switch2rand, nperm, seed, verbose) elseif centered return _permutationTest!(𝐱, 𝐲, false, true, direction, equivalent, switch2rand, nperm, seed, verbose) else _permutationTest!(μ0σ1(𝐱), μ0σ1(𝐲), true, false, direction, equivalent, switch2rand, nperm, seed, verbose) end end # alias rTest! = correlationTest! # same as correlationTest! but copy vector 𝐱, thus this will not be overwritten. """ ```julia function trendTest(<same args and kwargs as `correlationTest`>) ``` """ trendTest = correlationTest """ ```julia function trendTest!(<same args and kwargs as `correlationTest!`>) ``` Actually aliases for [`correlationTest`](@ref) and [`correlationTest!`](@ref), respectively. The two vectors `x` and `y` of ``N`` elements each are provided as data input. `x` is a specified trend and `y` holds the observed data. A Pearson product-moment correlation test between `x` and `y` is then carried out. `x` can hold any trend, such as linear, polynomial, exponential, logarithmic, power, trigonometric... *Directional tests, permutation scheme and number of permutations for exact tests:* as per [`correlationTest`](@ref) Multiple comparisons versions: [`trendMcTest`](@ref) and [`trendMcTest!`](@ref) Both methods return a [UniTest](@ref) structure. *Examples* ```julia using PermutationTests # We are goint to test an upward linear trend N=10 x=Float64.(collect(Base.OneTo(N))) # [1, 2, ..., N] y=[1., 2., 4., 3., 5., 6., 7., 8., 10., 9.] # Supposing we expect an upward linear trend, # hence the correlation is expected to be positive, # we can use a right-directional test to increase the power of the test. t = trendTest(x, y; direction=Right()) ``` """ trendTest! = correlationTest! ### ANOVA for independent samples """ ```julia # METHOD (1) function anovaTestIS(y::UniData, ns::IntVec; direction::TestDir = Both(), equivalent::Bool = true, switch2rand::Int = Int(1e8), nperm::Int = 20_000, seed::Int = 1234, verbose::Bool = true) where TestDir <: TestDirection ``` """ function anovaTestIS(𝐲::UniData, ns::IntVec; direction::TestDir = Both(), equivalent::Bool = true, switch2rand::Int = Int(1e8), nperm::Int = 20_000, seed::Int = 1234, verbose::Bool = true) where TestDir <: TestDirection length(ns) < 2 && throw(ArgumentError(📌*"Function anovaTestIS: the second argument (ns) must be a vector of two or more integers")) sum(ns) ≠ length(𝐲) && throw(ArgumentError(📌*"Function anovaTestIS: the sum of the integers in second argument (ns) must be equal to the length of the first argument (𝐲)")) stat = length(ns) == 2 ? StudentT_IS() : AnovaF_IS() # do t-test if there are only two groups stat isa AnovaF_IS && !(direction isa Both) && throw(ArgumentError(📌*"Function anovaTestIS: The ANOVA test can only be bi-directional. Correct the `direction` keyword argument")) return _permutationTest(𝐲, ns, stat, direction, equivalent, switch2rand, nperm, seed, verbose) end """ ```julia # METHOD (2) function anovaTestIS(yvec::UniDataVec; <same kwargs>) ``` **METHOD (1)** Univariate [1-way analysis of variance (ANOVA) for independent samples](https://en.wikipedia.org/wiki/One-way_analysis_of_variance) by data permutation. Given ``N=N1+...+N_K`` observations in ``K`` groups, the null hypothesis has form ``H_0: μ_1= \\ldots =μ_K``, where ``μ_k`` is the mean of the ``k^{th}`` group. `y` is a vector concatenaning the vector of observations in each group, in the natural order. Thus, it holds ``N`` elements. `ns` is a vector of integers holding the group numerosity (see examples below). For optional keyword arguments, `direction`, `equivalent`, `switch2rand`, `nperm`, `seed` and `verbose`, see [here](@ref "Common kwargs for univariate tests"). *Directional tests* Possible only for ``𝐾=2``, in which case the test reduces to a Student' t-test for independent samples and the test directionality is given by keyword arguement `direction`. See function [`studentTestIS`](@ref) and its multiple comparisons version [`studentMcTestIS`](@ref). *Permutation scheme:* under the null hypothesis, the group membership of the observations bears no meaning. The exchangeability scheme consists then in reassigning the ``N`` observations in the ``K`` groups respecting the original group numerosity. *Number of permutations for exact tests:* there are ``\\frac{N!}{N_1 \\cdot \\ldots \\cdot N_K}`` possible ways of reassigning the ``N`` observations in the ``K`` groups. **Alias:** `fTestIS` *Multiple comparisons version:* [anovaMcTestIS](@ref) Both methods return a [UniTest](@ref) structure. **METHOD (2)** As (1), but `yvec` is a vector of K vectors of observations, of for each group. *Examples* ```julia # (1) using PermutationTests ns=[4, 5, 6] # number of observations in group 1, 2 and 3 yvec = [randn(n) for n in ns] # some random Gaussian data for example t = fTestIS(vcat(yvec...), ns) # ANOVA tests are always bi-directional ``` ```julia # Force an approximate test with 5000 random permutations tapprox = fTestIS(vcat(yvec...), ns; switch2rand=1, nperm=5000) ``` ```julia # in method (2) only the way the input data is formatted is different t2 = fTestIS(yvec) println(t.p ≈ t2.p ? "OK" : "error") ``` **Similar tests** Typically, for ANOVA the input data is real, but can also be of type integer or boolean. For dicothomous data, with this function one can obtain a permutation-based version of the [Χ² test](https://en.wikipedia.org/wiki/Chi-squared_test) for ``K \\cdot 2`` contingency tables, which has the ability to give exact p-values. For ``2 \\cdot 2`` contingency tables it yields exactly the same p-value of the [Fisher exact test](https://en.wikipedia.org/wiki/Fisher's_exact_test), which is also exact, as the name suggests. In these cases it is more convenient to use the [chiSquaredTest](@ref) and [fisherExactTest](@ref) functions though, which accept contingency tables as data input. """ function anovaTestIS(𝐲vec::UniDataVec; direction::TestDir = Both(), equivalent::Bool = true, switch2rand::Int = Int(1e8), nperm::Int = 20_000, seed::Int = 1234, verbose::Bool = true) where TestDir <: TestDirection K = length(𝐲vec) K < 2 && throw(ArgumentError(📌*"Function anovaTestIS: the first argument (𝐲vec) must be a vector of two or more vectors")) #N = sum(length(𝐲) for 𝐲 ∈ 𝐲vec) stat = K == 2 ? StudentT_IS() : AnovaF_IS() # do t-test if there are only two groups stat isa AnovaF_IS && !(direction isa Both) && throw(ArgumentError(📌*"Function anovaTestIS: The ANOVA test can only be bi-directional. Correct the `direction keyword argument`")) ns=[length(𝐲) for 𝐲 in 𝐲vec] return _permutationTest(vcat(𝐲vec...), ns, stat, direction, equivalent, switch2rand, nperm, seed, verbose) end # alias fTestIS = anovaTestIS ### t-test for independent samples """ ```julia # METHOD (1) function studentTestIS(y::UniData, ns::IntVec; direction::TestDir = Both(), equivalent::Bool = true, switch2rand::Int = Int(1e8), nperm::Int = 20_000, seed::Int = 1234, verbose::Bool = true, asPearson::Bool = true) where TestDir <: TestDirection ``` """ function studentTestIS(𝐲::UniData, ns::IntVec; direction::TestDir = Both(), equivalent::Bool = true, switch2rand::Int = Int(1e8), nperm::Int = 20_000, seed::Int = 1234, verbose::Bool = true, asPearson::Bool = true) where TestDir <: TestDirection length(ns) ≠ 2 && throw(ArgumentError(📌*"Function studentTestIS: the second argument (ns) must be a vector of two integer")) sum(ns) ≠ length(𝐲) && throw(ArgumentError(📌*"Function studentTestIS: the sum of the two integers in second argument (ns) must be equal to the length of the first argument (𝐲)")) if asPearson # run t-test as a correlation test with reversed membership vector 𝐱 = membership(StudentT_IS(), ns; rev=reverse) return correlationTest(𝐱, 𝐲; direction, equivalent, switch2rand, nperm, seed, standardized=false, centered=false, verbose) else return _permutationTest(𝐲, ns, StudentT_IS(), direction, equivalent, switch2rand, nperm, seed, verbose) end end """ ```julia # METHOD (2) function studentTestIS(yvec::UniDataVec; <same kwargs>) ``` """ function studentTestIS(𝐲vec::UniDataVec; direction::TestDir = Both(), equivalent::Bool = true, switch2rand::Int = Int(1e8), nperm::Int = 20_000, seed::Int = 1234, verbose::Bool = true, asPearson::Bool = true) where TestDir <: TestDirection K = length(𝐲vec) K ≠ 2 && throw(ArgumentError(📌*"Function studentTestIS: the first argument (𝐲vec) must be a vector of two vectors")) ns=[length(𝐲) for 𝐲 in 𝐲vec] if asPearson # run t-test as a correlation test with reversed membership vector 𝐱 = membership(StudentT_IS(), ns; rev=reverse) return correlationTest(𝐱, vcat(𝐲vec...); direction, equivalent, switch2rand, nperm, seed, standardized=false, centered=false, verbose) else return _permutationTest(vcat(𝐲vec...), ns, StudentT_IS(), direction, equivalent, switch2rand, nperm, seed, verbose) end end """ ```julia # METHOD (3) function studentTestIS(y1::UniData, y2::UniData; <same kwargs>) ``` **METHOD (1)** Univariate [Student's t-test for independent samples](https://en.wikipedia.org/wiki/Student's_t-test#Independent_(unpaired)_samples) by data permutation. Given ``N=N1+N_2`` observations in two groups, the null hypothesis has form ``H_0: μ_1=μ_2``, where ``μ_1`` and ``μ_1`` are the mean for group 1 and group 2, respectively. For a bi-directional test, this t-test is equivalent to a 1-way ANOVA for two independent samples. However, in contrast to the ANOVA, it can be directional. `y` is a vector concatenaning the vector of observations in the two groups. Thus, it holds ``N`` elements. `ns` is a vector of integers holding the group numerosity (see examples below). For optional keyword arguments, `direction`, `equivalent`, `switch2rand`, `nperm`, `seed` and `verbose`, see [here](@ref "Common kwargs for univariate tests"). If `asPearson` is true (default), the test is run as an equivalent version of a Pearson correlation test. This is not faster in general for exact univariate tests, since the t-test needs less permutations, but is in general advantageous for approximate tests (see the [benchmarks](@ref "Benchmarks")). If your need to perform exact tests, you may want to set `asPearson` to false. !!! note "nota" If `asPearson` is true, the `.stat` field of the test result will actually be `CrossProd()`, as the data will be standardized before running the test. See [`correlationTest`](@ref). *Directional tests* - For a right-directional test, ``μ_1`` is expected to exceed ``μ_2``. If the opposite is true, the test will result in a p-value higehr then 0.5. - For a left-directional test, ``μ_2`` is expected to exceed ``μ_1``. If the opposite is true, the test will result a p-value higehr then 0.5. *Permutation scheme:* under the null hypothesis, the group membership of the observations bears no meaning. The exchangeability scheme consists then in reassigning the ``N`` observations in the two groups respecting the original group numerosity. *Number of permutations for exact tests:* there are ``\\frac{N!}{N_1 \\cdot N_2}`` possible reassigments of the ``N`` observations in the two groups. *Aliases:* `tTestIS`, [`pointBiSerialTest`](@ref) *Multiple comparisons version:* [`studentMcTestIS`](@ref) Return a [UniTest](@ref) structure. **METHOD (2)** As (1), but `yvec` is a vector of 2-vectors of observations for group 1 and group 2 (see examples below). **METHOD (3)** As (1), but the observations are given separatedly for the two groups as two vectors `y1` and `y2` (see examples below). *Examples* ```julia # (1) using PermutationTests ns=[4, 5]; # number of observations in group 1 and group 2 (N1 and N2) y=[randn(n) for n∈ns]; # some Gaussian data as example t = tTestIS(vcat(y...), ns) # by default the test is bi-directional # with a bi-directional test, t is equivalent to a 1-way ANOVA for independent samples tanova= fTestIS(vcat(y...), ns) println(t.p ≈ tanova.p ? "OK" : "error") # do not run it using the CrossProd test statistic tcor = tTestIS(vcat(y...), ns; asPearson=false) # Force an approximate test with 10000 random permutations tapprox = fTestIS(vcat(y...), ns; switch2rand=1, nperm=10000) tR=tTestIS(vcat(y...), ns; direction=Right()) # right-directional test tL=tTestIS(vcat(y...), ns; direction=Left()) # left-directional test # in method (2) only the way the input data is formatted is different t2 = tTestIS(y) println(t.p ≈ t2.p ? "OK" : "error") # in method (3) also, only the way the input data is formatted is different t3 = tTestIS(y[1], y[2]) println(t.p ≈ t3.p ? "OK" : "error") ``` **Similar tests** Typically, the input data is real, but can also be of type integer or boolean. For dicothomous data, with this function one can obtain the same p-value as the one given by the Fisher exact test, however in this case it is more convenient to use the [`fisherExactTest`](@ref) function, since it accepts contingency tables as input. This function can also be used to perform a permutation-based point-biserial correlation test. See the dedicated function [`pointBiSerialTest`](@ref). """ function studentTestIS(𝐱::UniData, 𝐲::UniData; direction::TestDir = Both(), equivalent::Bool = true, switch2rand::Int = Int(1e8), nperm::Int = 20_000, seed::Int = 1234, verbose::Bool = true, asPearson::Bool = true) where TestDir <: TestDirection # no check is needed when data is input this way ns=[length(𝐱), length(𝐲)] if asPearson # run t-test as a correlation test with reversed membership vector 𝐱_ = membership(StudentT_IS(), ns; rev=reverse) return correlationTest(𝐱_, [𝐱; 𝐲]; direction, equivalent, switch2rand, nperm, seed, standardized=false, centered=false, verbose) else return _permutationTest([𝐱; 𝐲], ns, StudentT_IS(), direction, equivalent, switch2rand, nperm, seed, verbose) end end # alias tTestIS = studentTestIS """ ```julia function pointBiSerialTest(<same args and kwargs as `studentTestIS`>) ``` Actually an alias for [`studentTestIS`](@ref). Univariate [point bi-serial correlation test](https://en.wikipedia.org/wiki/Point-biserial_correlation_coefficient) by data permutation. The correlation is between an input vector `y` of ``N=N_1+N_2`` elements and a vector ``x``, internally created, with the first ``N_1`` elements equal to `1` and the remaining ``N_2`` elements equal to `2`. If you need to use other values for the dicothomous variable ``x`` or a different order for its elements, use [`correlationTest`](@ref) instead. The null hypothesis has form ``H_0: b_{(x,y)}=0``, where ``b_{(x,y)}`` is the point bi-serial correlation between input data vectors `y` and the internally created vector ``x``. Directional tests, permutation scheme and number of permutations for exact tests: as per [`studentTestIS`](@ref) *Multiple comparisons version:* [`pointBiSerialMcTest`](@ref) Return a [UniTest](@ref) structure. *Examples* ```julia using PermutationTests ns=[4, 6] # number of observations in group 1 and group 2 (N1 and N2) N=sum(ns) # total number of observations y = rand(N) # some Gaussian data as example # implicitly, the point bi serial correlation is # between y and x=[1, 1, 1, 1, 2, 2, 2, 2, 2, 2] t=pointBiSerialTest(y, ns) # by default the test is bi-directional tR=pointBiSerialTest(y, ns; direction=Right()) # right-directional test tL=pointBiSerialTest(y, ns; direction=Left()) # left-directional test ``` """ pointBiSerialTest = studentTestIS # alias ### Chi-Squared and Fisher Exact Test # See `table2vec` for explanation of the table format. """ ```julia function chiSquaredTest(table::Matrix{I}; direction::TestDir = Both(), equivalent::Bool = true, switch2rand::Int = Int(1e8), nperm::Int = 20_000, seed::Int = 1234, verbose::Bool = true, asPearson::Bool = true) where {I <: Int, TestDir <: TestDirection} ``` Univariate [chi-squared](https://en.wikipedia.org/wiki/Chi-squared_test) (``\\chi^2``) permutation test for ``2 \\cdot K`` contingency tables, where ``K`` is ≥2. The null hypothesis has form ``H_0: O=E``, where ``O`` and ``E`` are the observed and expected frequencies of the contingency table. `table` is a contingency table given in the form of a matrix of integers. For example, the contingency table | 0 | 2 | 3 | Failures | 3 | 1 | 0 | Successes will be given as ```julia table=[0 2 3; 3 1 0] ``` For optional keyword arguments, `direction`, `equivalent`, `switch2rand`, `nperm`, `seed` and `verbose`, see [here](@ref "Common kwargs for univariate tests"). For ``K=2`` this function calls [`studentTestIS`](@ref) and pass to it also argument `asPearson`, otherwise calls [`anovaTestIS`](@ref) and argument `asPearson` is ignored. In contrast to Pearson's asymptotic ``\\chi^2``, with permutation tests the sample size does not have to be large. Actually, for large sample sizes Pearson's test is more efficient. For small sample sizes the p-value can be obtained using all possible permutations, thus being exact and will be the same as the p-value obtained using the [Fisher exact test](https://en.wikipedia.org/wiki/Fisher%27s_exact_test). This permutation test is therefore not particularly useful when compared to the standard ``\\chi^2`` and Fisher exact test, however, its multiple comparison version allows the control of the family-wise error rate through data permutation. *Directional tests* Possible only for ``𝐾=2``, in which case the test reduces to a Fisher exact test and the test directionality is given by keyword arguement `direction`. See function [`fisherExactTest`](@ref) and its multiple comparisons version [`fisherExactMcTest`](@ref). *Permutation scheme:* the contingency table is converted to ``K`` vectors holding each as many observations as the corresponding column sum. The conversion is operated internally by function [`table2vec`](@ref). The elements of the vectors are as many zeros and ones as the counts of the two cells of the correspondind column. The F-statistic of the 1-way ANOVA for indepedent samples is then an equivalent test-statistic for the ``\\chi^2`` and the permutation scheme of that ANOVA applies (see [`anovaTestIS`](@ref)). *Number of permutations for exact tests:* there are ``\\frac{N!}{N_1 \\cdot\\ldots\\cdot N_K}`` possible permutations, where ``K`` is the number of columns in the contingency table and ``N_k`` is the ``k^{th}`` column sum. *Aliases:* `Χ²Test`, [`fisherExactTest`](@ref) *Multiple comparisons version:* [chiSquaredMcTest](@ref) Return a [UniTest](@ref) structure. *Examples* ```julia using PermutationTests table=[0 2 2; 3 1 0] t=Χ²Test(table) # the test is bi-directional ``` ```julia table=[6 1; 2 5] tR=fisherExactTest(table; direction=Right()) # or tR=Χ²Test(table; direction=Right()) ``` """ function chiSquaredTest(table::Matrix{I}; direction::TestDir = Both(), equivalent::Bool = true, switch2rand::Int = Int(1e8), nperm::Int = 20_000, seed::Int = 1234, verbose::Bool = true, asPearson::Bool = true) where {I <: Int, TestDir <: TestDirection} 𝐲, ns = table2vec(table, AnovaF_IS()) # anovaTestIS will switch to t-test if there are only two groups k = length(ns) k < 2 && throw(ArgumentError(📌*"Function chiSquaredTest or fisherExactTest: error reading first argument (table)")) !(direction isa Both) && (k > 2) && throw(ArgumentError(📌*"Function chiSquaredTest or fisherExactTest: For input data matrices with more than 2 columns the test can only be bi-directional. Correct or eliminate the `direction` keyword argument")) k==2 ? tTestIS(𝐲, ns; direction, equivalent, switch2rand, nperm, seed, verbose, asPearson) : fTestIS(𝐲, ns; direction, equivalent, switch2rand, nperm, seed, verbose) end # alias Χ²Test = chiSquaredTest """ ```julia function fisherExactTest(<same args and kwargs as `chiSquaredTest`>) ``` Perform an univariate [Fisher exact test](https://en.wikipedia.org/wiki/Fisher's_exact_test) by data permutation. Alias for [chiSquaredTest](@ref). It can be used for ``2 \\cdot 2`` contingency tables. The contingency table in this case has form: | a | b | | c | d | - For a right-directional test, ``a/c`` is expected to exceed ``b/d``. If the opposite is true, the test will result in a p-value higehr then 0.5. - For a left-directional test, ``b/d`` is expected to exceed ``a/c``. If the opposite is true, the test will result in a p-value higehr then 0.5. !!! tip "Nota Bene" For ``K=2``, any input data matrix gives the same p-value as its transpose. *Multiple comparisons version:* [fisherExactMcTest](@ref) Return a [UniTest](@ref) structure. *Examples* ```julia using PermutationTests table=[6 1; 2 5] t=fisherExactTestTest(table) # or t=Χ²Test(table) # bi-directional test ``` ```julia tR=fisherExactTest(table; direction=Right()) # right-directional test ``` """ fisherExactTest = chiSquaredTest # alias ### ANOVA for Repeated Measures """ ```julia # METHOD (1) function anovaTestRM(y::UniData, ns::@NamedTuple{n::Int, k::Int}; direction::TestDir = Both(), equivalent::Bool = true, switch2rand::Int = Int(1e8), nperm::Int = 20_000, seed::Int = 1234, verbose::Bool = true) where TestDir <: TestDirection ``` """ function anovaTestRM(𝐲::UniData, ns::@NamedTuple{n::Int, k::Int}; direction::TestDir = Both(), equivalent::Bool = true, switch2rand::Int = Int(1e8), nperm::Int = 20_000, seed::Int = 1234, verbose::Bool = true) where TestDir <: TestDirection ns.k < 2 && throw(ArgumentError(📌*"Function anovaTestRM: the `k` element of second argument (a named tuple) must be 2 or more")) ns.n < ns.k && throw(ArgumentError(📌*"Function anovaTestRM: the `n` element of second argument (a named tuple) must be greater than the `k` element")) ns.n*ns.k ≠ length(𝐲) && throw(ArgumentError(📌*"Function anovaTestRM: the `n` and `k` elements of second argument (a named tuple) must be such that their product is equal to the length of the first argument (𝐲)")) if ns.k == 2 stat = StudentT_1S() # do t-test if there are only two groups. Actually do one-sample test on the difference return _permutationTest!(𝐲[1:2:ns.n*2-1].-𝐲[2:2:ns.n*2], ns.n, direction, equivalent, switch2rand, nperm, seed, verbose) else stat = AnovaF_RM() !(direction isa Both) && throw(ArgumentError(📌*"Function anovaTestRM: The ANOVA test can only be di-directional. Correct the `direction` keyword argument")) return _permutationTest(𝐲, ns, stat, direction, equivalent, switch2rand, nperm, seed, verbose) end end """ ```julia # METHOD (2) function anovaTestRM(yvec::UniDataVec; <same kwargs>) ``` METHOD (1) Univariate [1-way analysis of variance (ANOVA) for repeated measures](https://en.wikipedia.org/wiki/Repeated_measures_design#Repeated_measures_ANOVA) by data permutation. Given ``K`` repeated measures (e.g., treatments, time, etc.) for each of ``N`` observation units (e.g., subjects, blocks, etc.), the null hypothesis has form ``H_0: μ_1= \\ldots =μ_K``, where ``μ_k`` is the mean of the ``k^{th}`` treatment. `y` is a vector concatenaning the ``K`` treatments (treatment 1,..., treatment ``K``) for each observation in this order: the ``K`` treatments for observation 1, the ``K`` treatments for observation 2, ..., the ``K`` treatments for observation ``N``. Thus, `y` holds ``N \\cdot K`` elements. `ns` is a julia [named tuple](https://docs.julialang.org/en/v1/manual/types/#Named-Tuple-Types) with form `(n=N, k=K)` (see examples below). For optional keyword arguments, `direction`, `equivalent`, `switch2rand`, `nperm`, `seed` and `verbose`, see [here](@ref "Common kwargs for univariate tests"). *Directional tests* Possible only for ``𝐾=2``, in which case the test reduces to a one-sample Student' t-test on the differences of the two treatments and the test directionality is given by keyword arguement `direction`. See function [`studentTest1S`](@ref) and its multiple comparisons version [`studentMcTest1S`](@ref). *Permutation scheme:* under the null hypothesis, the order of the ``K`` measurements bears no meaning. The exchangeability scheme consists then in reordering the ``K`` measurements within the ``N`` observation units. *Number of permutations for exact tests:* there are ``K!^N`` possible ways of reordering the ``K`` measurements in all ``N`` observation units. **Alias:** `fTestRM` *Multiple comparisons version:* [anovaMcTestRM](@ref) Both methods return a [UniTest](@ref) structure. METHOD (2) As (1), but `yvec` is a vector of ``N`` vectors holding each the ``K`` treatments for the ``n^{th}`` subject (see examples below). *Examples* ```julia # (1) using PermutationTests N=6; # number of observation units K=3; # number of measurements y = [randn(K) for n=1:N] # some random Gaussian data for example t = fTestRM(vcat(y...), (n=N, k=K)) # ANOVA tests are always bi-directional ``` ```julia # Force an approximate test with 5000 random permutations tapprox = fTestRM(vcat(y...), (n=N, k=K); switch2rand=1, nperm=5000) ``` ```julia # in method (2) only the way the input data is formatted is different t2 = fTestRM(y) println(t.p ≈ t2.p ? "OK" : "error") ``` **Similar tests** Typically, the input data is real, but can also be of type integer or boolean. For dicothomous data, with this function one can obtain the permutation-based Cochran Q test for ``K>2`` and the permutation-based McNemar test for ``K=2``, but with the ability to give exact p-values. For these two tests the dedicated functions [`cochranqTest`](@ref) and [`mcNemarTest`](@ref) is available. """ function anovaTestRM(𝐲vec::UniDataVec; direction::TestDir = Both(), equivalent::Bool = true, switch2rand::Int = Int(1e8), nperm::Int = 20_000, seed::Int = 1234, verbose::Bool = true) where TestDir <: TestDirection N = length(𝐲vec) K = length(𝐲vec[1]) K < 2 && throw(ArgumentError(📌*"Function anovaTestRM: the first argument (𝐲vec) must be a vector of two or more vectors")) kk = length(unique(length(𝐲vec))) kk ≠ 1 && throw(ArgumentError(📌*"Function anovaTestRM: For a repeated-measure ANOVA all vectors in argument `𝐲vec` must be of the same length")) N < K && throw(ArgumentError(📌*"Function anovaTestRM: the length of the vectors in first argument (𝐲vec) must be greater than their number")) if K == 2 stat = StudentT_1S() # do t-test if there are only two groups. Actually do one-sample test on the difference return _permutationTest!([𝐲vec[n][1] for n=1:N]-[𝐲vec[n][2] for n=1:N], N, direction, equivalent, switch2rand, nperm, seed, verbose) else stat = AnovaF_RM() !(direction isa Both) && throw(ArgumentError(📌*"Function anovaTestRM: The ANOVA test can only be bi-directional. Correct the `direction keyword argument`")) ns=(n=N, k=K) #ns=(n=K, k=N) return _permutationTest(vcat(𝐲vec...), ns, stat, direction, equivalent, switch2rand, nperm, seed, verbose) end end fTestRM = anovaTestRM # alias ### Cocharn Q test # NB: not particular efficient. For an efficient alternative see https://dl.acm.org/doi/10.1145/3095076 """ ```julia function cochranqTest(table::Matrix{I}; direction::TestDir = Both(), equivalent::Bool = true, switch2rand::Int = Int(1e8), nperm::Int = 20_000, seed::Int = 1234, verbose::Bool = true) where {I <: Int, TestDir <: TestDirection} ``` Univariate [Cochran Q](https://en.wikipedia.org/wiki/Cochran's_Q_test) test by data permutation. The Cochran Q test is analogous to the 1-way ANOVA for repeated measures, but takes as input dicothomous data (zeros and ones). Given ``N`` observation units (e.g., subjects, blocks, etc.) and ``K`` repeated measures (e.g., treatments, time, etc.), the null hypothesis has form ``H_0: μ_1= \\ldots =μ_K``, where ``μ_k`` is the mean of the ``k^{th}`` measure. When ``K=2`` the test reduces to the [McNemar test](https://en.wikipedia.org/wiki/McNemar's_test), which is the analogous to the Student's t-test for repeated measures taking as input dicothomous data (zeros and ones). Input `table` is a ``N \\cdot K`` table of zeros and ones, where ``N`` is the number of observations and ``K`` the repeated measures. Transposed, one such data would look like | 1 | 1 | 1 | 1 | 1 | 1 | Measure 1 | 1 | 0 | 1 | 1 | 0 | 1 | Measure 2 | 0 | 0 | 1 | 0 | 1 | 0 | Measure 3 This table shall be given as input such as ```table=[1 1 0; 1 0 0; 1 1 1; 1 1 0; 1 0 1; 1 1 0]``` and internally it will be converted to the appropriate format by function [`table2vec`](@ref). !!! note "Redundant permutations" Adding any number of vectors `[0 0 0]` or `[1 1 1]` in any combination to the table here above, yields exactly the same p-value using systematic permutations, but increase the number of permutations to be listed. If such vector exist in your data, you can delete them to obatin a faster test. For optional keyword arguments, `direction`, `equivalent`, `switch2rand`, `nperm`, `seed` and `verbose`, see [here](@ref "Common kwargs for univariate tests"). In contrast to the [Cochran Q](https://en.wikipedia.org/wiki/Cochran's_Q_test) and [McNemar](https://en.wikipedia.org/wiki/McNemar's_test) asymptotic tests, with permutation tests the sample size does not have to be large. Actually, for large sample sizes the Cochran Q and McNemar tests are more efficient, although they do not provide an exact p-value (an exact test for the case ``K=2`` can be derived though). Overall, this permutation test is not very useful when compared to the standard Cochran Q and McNemar tests, however, its multiple comparison version allows the control of the family-wise error rate by means of data permutation. *Directional tests* Possible only for ``𝐾=2``, in which case the test reduces to a MnNemar test and the test directionality is given by keyword arguement `direction`. See function [`mcNemarTest`](@ref) and its multiple comparisons version [`mcNemarMcTest`](@ref). *Permutation scheme:* the F-statistic of the 1-way ANOVA for repeated measure is an equivalent test-statistic for the Cochran Q test and the permutation scheme of that ANOVA applies (see [`anovaTestRM`](@ref)). The permutation scheme is the same for tha case of ``K=2`` (McNemar test). *Number of permutations for exact tests:* there are ``K!^N`` possible ways of reordering the ``K`` measurements in all the ``N`` observation units. *Aliases:* `qTest`, `mcNemarTest` *Multiple comparisons versions:* [`cochranqMcTest`](@ref), [`mcNemarMcTest`](@ref) Return a [UniTest](@ref) structure. *Examples* ```julia using PermutationTests table=[1 1 0; 1 0 0; 1 1 1; 1 1 0; 1 0 1; 1 1 0] t=qTest(table) # the test is bi-directional ``` """ function cochranqTest(table::Matrix{I}; direction::TestDir = Both(), equivalent::Bool = true, switch2rand::Int = Int(1e8), nperm::Int = 20_000, seed::Int = 1234, verbose::Bool = true) where {I <: Int, TestDir <: TestDirection} 𝐲, ns = table2vec(table, AnovaF_RM()) # anovaTestRM will switch to t-test if there are only two groups ns.k == 2 ? studentTest1S!(𝐲[1:2:(ns.n)*2-1].-𝐲[2:2:(ns.n)*2]; refmean = nothing, direction, equivalent, switch2rand, nperm, seed, verbose) : anovaTestRM(𝐲, ns; direction, equivalent, switch2rand, nperm, seed, verbose) end qTest = cochranqTest # alias """ ```julia function mcNemarTest(same args and kwargs as `cochranqTest`>) ``` Univariate [McNemar test](https://en.wikipedia.org/wiki/McNemar's_test) by data permutation. Alias for [`cochranqTest`](@ref). It can be used for ``2 \\cdot 2`` contingency tables. Notice that [`cochranqTest`](@ref) does not accept data input in the form of a contingency table. If your data is in the form of a contingency table, here is how you can convert it: given the contingency table | a | b | | c | d | you will create a vector holding: - as many vectors `[0, 1]` as the ``b`` frequency. - as many vectors `[1, 0]` as the ``c`` frequency. For example, the contingency table | 1 | 2 | | 3 | 4 | will be given as input such as as ```julia table=[0 1; 0 1; 1 0; 1 0; 1 0] ``` !!! note "Redundant permutations" Adding any number of vectors `[0 0]` or `[1 1]` in any combination to the table here above, yields exactly the same p-value using systematic permutations. Like in the asymptotic McNemar test, these vector correspond to elements `a` and `d` of the contingency table and have no effect. *Directional tests* - For a right-directional test, ``c`` is expected to exceed ``b``. If the opposite is true, the test will result in a p-value higher then 0.5. - For a left-directional test, ``b`` is expected to exceed ``c``. If the opposite is true, the test will result in a p-value higher then 0.5. *Multiple comparisons version:* [`mcNemarMcTest`](@ref) Return a [UniTest](@ref) structure. *Examples* ```julia using PermutationTests table=[1 0; 1 0; 1 0; 1 0; 0 1] t=mcNemarTest(table) # by default the test is bi-directional tR=mcNemarTest(table; direction=Right()) # right-directional test ``` """ mcNemarTest = cochranqTest # alias # https://en.wikipedia.org/wiki/McNemar%27s_test ### One-Sample t-test """ ```julia function studentTest1S(𝐲::UniData; refmean::Realo = nothing, direction::TestDir = Both(), equivalent::Bool = true, switch2rand::Int = Int(1e8), nperm::Int = 20_000, seed::Int = 1234, verbose::Bool = true) where TestDir <: TestDirection = ``` Univariate [one-sample t-test](https://en.wikipedia.org/wiki/Student's_t-test#One-sample_t-test) by data permutation. The null hypothesis has form ``H_0: μ=μ_0``, where ``μ`` is the mean of the observations and ``μ_0`` is a reference population mean. `refmean` is the reference mean (``μ_0``) above. The default is ``0``, which is the value used for most tests. For optional keyword arguments, `direction`, `equivalent`, `switch2rand`, `nperm`, `seed` and `verbose`, see [here](@ref "Common kwargs for univariate tests"). *Directional tests* - For a right-directional test, ``μ`` is expected to exceeds ``μ_0``. If the opposite is true the test will result in a p-value higehr then 0.5. - For a left-directional test, ``μ_0`` is expected to exceeds ``μ``. If the opposite is true the test will result in a p-value higehr then 0.5. *Permutation scheme:* the one-sample t-test test is equivalent to a t-test for two repeated measures, the mean of the difference of which is tested by the one-sample t-test. Under the null hypothesis, the order of the two measurements bears no meaning. The exchangeability scheme consists then in reordering the two measurements in the ``N`` observation units. For a one-sample t-test, this amounts to considering the observations with the observed and switched sign. *Number of permutations for exact tests:* there are ``2^N`` possible ways of reordering the two measurements in the ``N`` observations of `y`. For the one-sample t-test, this is the number of possible configurations of the signs of the observations. **Alias:** `tTest1S` Multiple comparisons version: [`studentMcTest1S`](@ref) Return a [UniTest](@ref) structure. *Examples* ```julia using PermutationTests N=20 # number of observations y = randn(N) # some random Gaussian data for example t = tTest1S(y) # test H0: μ(y)=0. By deafult the test is bi-directional t = tTest1S(y; refmean=1.) # test H0: μ(y)=1 tR = tTest1S(y; direction=Right()) # right-directional test tL = tTest1S(y; direction=Left()) # Left-directional test # Force an approximate test with 5000 random permutations tapprox = tTest1S(y; switch2rand=1, nperm=5000) ``` **Similar tests** Typically, the input data is real, but can also be of type integer or boolean. If either `y` is a vector of booleans or a vector of dicothomous data (only 0 and 1), this function will actually perform a permutation-based version of the [sign test](https://en.wikipedia.org/wiki/Sign_test). With boolean input, use the [signTest](@ref) function. Passing as data input the vector of differences of two repeated measurements, this function carries out the Student's t-test for repeated measurements. If you need such a test you may want to use the [`studentTestRM`](@ref) alias. """ studentTest1S(𝐲::UniData; refmean::Realo = nothing, direction::TestDir = Both(), equivalent::Bool = true, switch2rand::Int = Int(1e8), nperm::Int = 20_000, seed::Int = 1234, verbose::Bool = true) where TestDir <: TestDirection = _permutationTest!(refmean===nothing ? copy(𝐲) : 𝐲.-refmean, length(𝐲), direction, equivalent, switch2rand, nperm, seed, verbose) tTest1S = studentTest1S # aliases """ ```julia function studentTest1S!(y::UniData; <same args and kwargs as `studentTest1S`>) ``` As [`studentTest1S`](@ref), but `y` is overwritten in the case of approximate (random permutations) tests. **Alias:** `tTest1S!` **Multiple Comparison version:** [`studentMcTest1S!`](@ref) """ studentTest1S!(𝐲::UniData; refmean::Realo = nothing, direction::TestDir = Both(), equivalent::Bool = true, switch2rand::Int = Int(1e8), nperm::Int = 20_000, seed::Int = 1234, verbose::Bool = true) where TestDir <: TestDirection = _permutationTest!(refmean===nothing ? 𝐲 : 𝐲.-refmean, length(𝐲), direction, equivalent, switch2rand, nperm, seed, verbose) # alias tTest1S! = studentTest1S! # as studentTest1S!, but copy 𝐲, so it does not overwrite it. This method directly subtracts the reference mean ### Sign Test """ ```julia signTest(𝐲::Union{BitVector, Vector{Bool}}; direction::TestDir = Both(), equivalent::Bool = true, switch2rand::Int = Int(1e8), nperm::Int = 20_000, seed::Int = 1234, verbose::Bool = true) where TestDir <: TestDirection = ``` Univariate [sign test](https://en.wikipedia.org/wiki/Sign_test) by data permutation. The null hypothesis has form ``H_0: E(true)=E(false)``, where ``E(true)`` and ``E(false)`` are the expected number of true and false occurrences, respectively. `y` ia a vector of ``N`` booleans. For optional keyword arguments, `direction`, `equivalent`, `switch2rand`, `nperm`, `seed` and `verbose`, see [here](@ref "Common kwargs for univariate tests"). *Directional tests* - For a right-directional test, ``E(true)`` is expected to exceeds ``E(false)``. If the opposite is true the test will result in a p-value higehr then 0.5. - For a left-directional test, ``E(false)`` is expected to exceeds ``E(true)``. If the opposite is true the test will result in a p-value higehr then 0.5. Permutation scheme and number of permutations for exact tests: as per [`studentTest1S`](@ref). The significance of the univariate sign test can be obtained much more efficiently using the binomial distribution. This permutation test is therefore not useful at all in the univariate case, however, its multiple comparison version allows the control of the family-wise error rate by data permutations. **Multiple comparisons version** [`signMcTest`](@ref) Return a [UniTest](@ref) structure. *Examples* ```julia using PermutationTests N=20; # number of observations y = rand(Bool, N); # some random Gaussian data for example t = signTest(y) # By deafult the test is bi-directional tR = signTest(y; direction=Right()) # right-directional test tL = signTest(y; direction=Left()) # Left-directional test # Force an approximate test with 5000 random permutations tapprox = signTest(y; switch2rand=1, nperm=5000) ``` """ signTest(𝐲::Union{BitVector, Vector{Bool}}; direction::TestDir = Both(), equivalent::Bool = true, switch2rand::Int = Int(1e8), nperm::Int = 20_000, seed::Int = 1234, verbose::Bool = true) where TestDir <: TestDirection = studentTest1S!((Float64.(𝐲)).-0.5; refmean=nothing, direction, equivalent, switch2rand, nperm, seed, verbose) """ ```julia function studentTestRM(<same args and kwargs as `studentTest1S`>) ``` Univariate [t-test for repeated measures](https://en.wikipedia.org/wiki/Paired_difference_test) by data permutation. Actually an alias for [`studentTest1S`](@ref). In order to run a t-test for repeated measure, use as data input the vector of differences across measurements. Do not change the `refmean` default value. See [`studentTest1S`](@ref) for more details. **Alias:** `tTestRM` *Multiple comparisons version:* [`studentMcTestRM`](@ref) Return a [UniTest](@ref) structure. *Examples* ```julia using PermutationTests y1=randn(10) # measurement 1 y2=randn(10) # measurement 2 t=tTestRM(y1.-y2) # # by default the test is bi-directional tR=tTestRM(y1.-y2; direction=Both()) # right-directional test # if test tR is significant, the mean of measurement 1 exceeds the mean of measurement 2. ``` """ studentTestRM = studentTest1S tTestRM = studentTest1S """ ```julia function studentTestRM!(<same args and kwargs as `studentTestRM`>) ``` Actually an alias for [`studentTest1S!`](@ref). See [`studentTestRM`](@ref) for the usage of this function. **Alias:** `tTestRM!` *Multiple comparisons version:* [`studentMcTestRM!`](@ref) """ studentTestRM! = studentTest1S! tTestRM! = studentTest1S! # ----------------------------------------------------- #
PermutationTests
https://github.com/Marco-Congedo/PermutationTests.jl.git
[ "MIT" ]
0.2.0
8a73fe1574e159927031bb2b9cc6ea142f075407
code
1416
# This script is not part of the PermutatioTests.jl package. # It allows to build that package and its documentation locally from the source code, # without actually installing the package. # It is useful for developing purposes using the Julia # `Revise` package (that you need to have installed on your PC, # together with the `Documenter` package for building the documentation). # You won't need this script for using the package. # # MIT License # Copyright (c) 2024, Marco Congedo, CNRS, Grenobe, France: # https://sites.google.com/site/marcocongedo/home # # DIRECTIONS: # 1) If you have installed the PermutationTests.jl from github or Julia registry, uninstall it. # 2) Change the `juliaCodeDir` path here below to the path # where the PermutationTests.jl folder is located on your computer. # 3) Run this sript (With VS code, click anywhere here and hit ALT+Enter) # begin juliaCodeDir = joinpath(homedir(),"Documents", "Documenti", "Code", "julia") scrDir = joinpath(juliaCodeDir, "PermutationTests", "src") docsDir = joinpath(juliaCodeDir, "PermutationTests", "docs") push!(LOAD_PATH, scrDir) using Documenter, Revise, PermutationTests cd(docsDir) clipboard("""makedocs(sitename="PermutationTests", modules=[PermutationTests], remotes = nothing)""") @info("\nRight-click and press ENTER on the REPL for building the documentation."); end
PermutationTests
https://github.com/Marco-Congedo/PermutationTests.jl.git
[ "MIT" ]
0.2.0
8a73fe1574e159927031bb2b9cc6ea142f075407
code
14104
# Unit "benchmarks.jl", additional resource to the PemutationTests.jl package for the julia language # # MIT License # Copyright (c) 2024, # Marco Congedo, CNRS, Grenoble, France: # https://sites.google.com/site/marcocongedo/home # CONTENTS : # This unit benchmark the speed of execution of the univarate and multiple comparison tests # implemented in PermutationTests.jl. It creates tables and plots of the minimum execution time in milliseconds, # memory usage in Megabytes and memory allocation count. # NB: for univariate tests we use @threads for speeding up the monte carlo simulations, whereas for # multiple comparisons tests we don't as the main testing function is multi-threaded, thus we leave the logic # processing unit free to be used by the main testing function. # REQUIRED PACKAGES : PermutationsTests, BenchmarkTools, PrettyTables, Distributions, Plots # NB: if with Plots.jl you use the plotly() back-end, as in the code, # you may need to install packages 'PlotlyBase' and 'PlotlyKaleido' using Random:MersenneTwister # julia built-in using PrettyTables, Plots, Plots.Measures using BenchmarkTools, Base.Threads using Distributions:Binomial using PermutationTests plotly() # select Plots.jl backend # time will be given in milliseconds function addResults!(np, m, T, G, M, A, i, j; timeInSec=false) T[i, j] = timeInSec ? m.time/(1e9) : m.time/(1e6) # milliseconds, seconds if timeInSec=true G[i, j] = m.gctime/1e6 #milliseconds M[i, j] = round(Int, m.memory/1e3) # Megabyte A[i, j] = m.allocs end rng = MersenneTwister(1234) # Create a table function gettable(n, k, rng) table=zeros(Int64, 2, k) nk=n÷k for i=1:size(table, 2) table[1, i]=rand(rng, Binomial((n/2)÷k, 0.5)) table[2, i]=table[1, i]<nk ? (nk-table[1, i]) : 0 end # correct the table is the sum of the columns sum > N for i=1:size(table, 2) cs=sum(table[:, i]) while cs>nk if table[1, i]>0 table[1, i]-=1 end cs=sum(table[:, i]) if cs>nk if table[2, i]>0 table[2, i]-=1 end end end end # correct the table if k is even and n is odd s=sum(table) while s<n table[1, 1]+=1 s=sum(table) end return table end ## UNIVARIATE TESTS #################################################################### N=[9, 90, 900, 9000, 90000] # All tests are run with `numPerm` random permutations numPerm=10000 nTests=11 nn=length(N) T=Matrix{Float64}(undef, nn, nTests) # time G=Matrix{Float64}(undef, nn, nTests) # garbage collector time M=Matrix{Int64}(undef, nn, nTests) # Memory A=Matrix{Int64}(undef, nn, nTests) # Allocations # Correlation test @threads for i = 1:length(N) n = N[i] x = randn(n) y = randn(n) t = @benchmark rTest($x, $y; switch2rand=1, nperm=numPerm, verbose=false) addResults!(numPerm, minimum(t), T, G, M, A, i, 1) println("Correlation Test. Done for N = ", N[i], ", Minimum Time(ms): ", minimum(t).time/1e6) end # 1-way ANOVA for indepedent samples @threads for i = 1:length(N) n = N[i] x = randn(n) ns = [n÷3, n÷3, n-((n÷3)*2)] t = @benchmark fTestIS($x, $ns; switch2rand=1, nperm=numPerm, verbose=false) addResults!(numPerm, minimum(t), T, G, M, A, i, 2) println("1-way ANOVA IS Test. Done for N = ", N[i], ", Minimum Time(ms): ", minimum(t).time/1e6) end # t-test for indepedent samples @threads for i = 1:length(N) n = N[i] x = randn(n) ns = [n÷2, n-(n÷2)] t = @benchmark tTestIS($x, $ns; switch2rand=1, nperm=numPerm, verbose=false, asPearson=false) addResults!(numPerm, minimum(t), T, G, M, A, i, 3) println("Student t IS Test. Done for N = ", N[i], ", Minimum Time(ms): ", minimum(t).time/1e6) end # t-test for indepedent samples by Pearson Correlation @threads for i = 1:length(N) n = N[i] x = randn(n) ns = [n÷2, n-(n÷2)] t = @benchmark tTestIS($x, $ns; switch2rand=1, nperm=numPerm, verbose=false, asPearson=true) addResults!(numPerm, minimum(t), T, G, M, A, i, 4) println("Student t IS Test. Done for N = ", N[i], ", Minimum Time(ms): ", minimum(t).time/1e6) end # Chi-Square @threads for i = 1:length(N) n = N[i] k = 3 x = gettable(n, k, rng) t = @benchmark Χ²Test($x; switch2rand=1, nperm=numPerm, verbose=false) addResults!(numPerm, minimum(t), T, G, M, A, i, 5) println("Chi-Square Test. Done for N = ", N[i], ", Minimum Time(ms): ", minimum(t).time/1e6) end # Fisher Exact Test @threads for i = 1:length(N) n = N[i] k = 2 x = gettable(n, k, rng) t = @benchmark fisherExactTest($x; switch2rand=1, nperm=numPerm, verbose=false) addResults!(numPerm, minimum(t), T, G, M, A, i, 6) println("Fisher exact Test. Done for N = ", N[i], ", Minimum Time(ms): ", minimum(t).time/1e6) end # 1-way ANOVA for repeated samples @threads for i = 1:length(N) n = N[i] k = 3 x = randn(n*k) ns = (n=n, k=k) t = @benchmark fTestRM($x, $ns; switch2rand=1, nperm=numPerm, verbose=false) addResults!(numPerm, minimum(t), T, G, M, A, i, 7) println("1-way ANOVA RM Test. Done for N = ", N[i], ", Minimum Time(ms): ", minimum(t).time/1e6) end # Cochran Q test @threads for i = 1:length(N) n = N[i] k = 3 x = Int.(rand(Bool, n, k)) t = @benchmark qTest($x; switch2rand=1, nperm=numPerm, verbose=false) addResults!(numPerm, minimum(t), T, G, M, A, i, 8) println("Cochran Q Test. Done for N = ", N[i], ", Minimum Time(ms): ", minimum(t).time/1e6) end # McNemar test @threads for i = 1:length(N) n = N[i] k = 2 x = Int.(rand(Bool, n, k)) t = @benchmark mcNemarTest($x; switch2rand=1, nperm=numPerm, verbose=false) addResults!(numPerm, minimum(t), T, G, M, A, i, 9) println("McNemar Test. Done for N = ", N[i], ", Minimum Time(ms): ", minimum(t).time/1e6) end # one sample t-test @threads for i = 1:length(N) n = N[i] x = randn(n) t = @benchmark tTest1S($x; switch2rand=1, nperm=numPerm, verbose=false) addResults!(numPerm, minimum(t), T, G, M, A, i, 10) println("One-Sample Student-t Test. Done for N = ", N[i], ", Minimum Time(ms): ", minimum(t).time/1e6) end # Sign Test @threads for i = 1:length(N) n = N[i] x = rand(Bool, n) t = @benchmark signTest($x; switch2rand=1, nperm=numPerm, verbose=false) addResults!(numPerm, minimum(t), T, G, M, A, i, 11) println("Sign Test. Done for N = ", N[i], ", Minimum Time(ms): ", minimum(t).time/1e6) end # Tables labels=["Pearson r" "ANOVA F IS" "St. t IS" "St. t IS(r)" "χ²" "Fisher Exact" "ANOVA F RM" "Cochran Q" "McNemar" "St. t 1S" "Sign"] print(" Minumum Execution Time (ms), ", numPerm," Random Permutations") pretty_table(hcat(Int.(N), T); formatters = ft_printf("%5.2f", 2:4), header = ( hcat("N", labels),), header_crayon = crayon"yellow bold") print(" Memory Allocations (MB), ", numPerm," Random Permutations") pretty_table(hcat(Int.(N), M); formatters = ft_printf("%5.2f", 2:4), header = ( hcat("N", labels),), header_crayon = crayon"yellow bold") print(" Memory Allocation count, ", numPerm," Random Permutations") pretty_table(hcat(Int.(N), A); formatters = ft_printf("%5.2f", 2:4), header = ( hcat("N", labels),), header_crayon = crayon"yellow bold") # Plots labels=["Pearson r" "ANOVA F IS" "Student t IS" "Student t IS as r" "χ²" "Fisher Exact" "ANOVA F RM" "Cochran Q" "McNemar" "One-sample Student t" "Sign"] kwargs=(yscale=:log10, minorgrid=true, label=labels, xlabel="Number of observations", leg=:topleft, left_margin = 25mm, bottom_margin = 5mm, right_margin = 5mm, lw=2, xticks = ([1:1length(N);], string.(N)), size=(900, 600), tickfontsize=11, labelfontsize=14, legendfontsize=10,) # temp: remove once the tests are done also for the Chi-Square test plot(T; ylabel="Minimum execution time (ms)", title="$numPerm permutations", ylims=(1, 1e5), kwargs...) plot(M; ylabel="Memory allocation (MB)", title="$numPerm permutations", ylims=(1e2, 1e5), kwargs...) plot(M; ylabel="allocation count", title="$numPerm permutations", ylims=(1e5, 1e7*3), kwargs...) ## Multiple Comparison TESTS #################################################################### M_=[10, 100, 1000, 10000] N=12 numPerm=10000 nTests=11 nm=length(M_) T=Matrix{Float64}(undef, nm, nTests) # time G=Matrix{Float64}(undef, nm, nTests) # garbage collector time M=Matrix{Int64}(undef, nm, nTests) # Memory A=Matrix{Int64}(undef, nm, nTests) # Allocations # Correlation test x = randn(N) for i=1:length(M_) y = [randn(N) for j=1:M_[i]] t = @benchmark rMcTest($x, $y; switch2rand=1, nperm=numPerm, verbose=false) addResults!(numPerm, minimum(t), T, G, M, A, i, 1; timeInSec=true) println("Correlation Test. Done for M = ", M_[i], ", Minimum Time(s): ", minimum(t).time/1e9) end # 1-way ANOVA for indepedent samples for i=1:length(M_) x = [randn(N) for j=1:M_[i]] ns=[N÷3, N÷3, N-((N÷3)*2)] t = @benchmark fMcTestIS($x, $ns; switch2rand=1, nperm=numPerm, verbose=false) addResults!(numPerm, minimum(t), T, G, M, A, i, 2; timeInSec=true) println("1-way ANOVA IS Test. Done for M = ", M_[i], ", Minimum Time(s): ", minimum(t).time/1e9) end # t-test for indepedent samples for i=1:length(M_) x = [randn(N) for j=1:M_[i]] ns=[N÷2, N-(N÷2)] t = @benchmark tMcTestIS($x, $ns; switch2rand=1, nperm=numPerm, verbose=false, asPearson=false) addResults!(numPerm, minimum(t), T, G, M, A, i, 3; timeInSec=true) println("Student t IS Test. Done for M = ", M_[i], ", Minimum Time(s): ", minimum(t).time/1e9) end # t-test for indepedent samples as PearsonR for i=1:length(M_) x = [randn(N) for j=1:M_[i]] ns=[N÷2, N-(N÷2)] t = @benchmark tMcTestIS($x, $ns; switch2rand=1, nperm=numPerm, verbose=false, asPearson=true) addResults!(numPerm, minimum(t), T, G, M, A, i, 4; timeInSec=true) println("Student t IS Test as Pearson. Done for M = ", M_[i], ", Minimum Time(s): ", minimum(t).time/1e9) end # Chi-Square Test for i=1:length(M_) k = 3 x = [gettable(N, k, rng) for j=1:M_[i]] t = @benchmark Χ²McTest($x; switch2rand=1, nperm=numPerm, verbose=false) addResults!(numPerm, minimum(t), T, G, M, A, i, 5; timeInSec=true) println("Χ² Test. Done for M = ", M_[i], ", Minimum Time(s): ", minimum(t).time/1e9) end # Fisher Exact Test for i=1:length(M_) k = 2 x = [gettable(N, k, rng) for j=1:M_[i]] t = @benchmark fisherExactMcTest($x; switch2rand=1, nperm=numPerm, verbose=false) addResults!(numPerm, minimum(t), T, G, M, A, i, 6; timeInSec=true) println("Fisher Exact Test. Done for M = ", M_[i], ", Minimum Time(s): ", minimum(t).time/1e9) end # 1-way ANOVA for repeated measures for i=1:length(M_) x = [randn(N) for j=1:M_[i]] ns=(n=N÷3, k=3) t = @benchmark fMcTestRM($x, $ns; switch2rand=1, nperm=numPerm, verbose=false) addResults!(numPerm, minimum(t), T, G, M, A, i, 7; timeInSec=true) println("1-way ANOVA RM Test. Done for M = ", M_[i], ", Minimum Time(s): ", minimum(t).time/1e9) end # Cochran Q Test for i=1:length(M_) k = 3 x = [Int.(rand(Bool, N÷k, k)) for j=1:M_[i]] t = @benchmark qMcTest($x; switch2rand=1, nperm=numPerm, verbose=false) addResults!(numPerm, minimum(t), T, G, M, A, i, 8; timeInSec=true) println("Cochran Q Test. Done for M = ", M_[i], ", Minimum Time(s): ", minimum(t).time/1e9) end # McNemar Test for i=1:length(M_) k = 3 x = [Int.(rand(Bool, N÷k, k)) for j=1:M_[i]] t = @benchmark qMcTest($x; switch2rand=1, nperm=numPerm, verbose=false) addResults!(numPerm, minimum(t), T, G, M, A, i, 9; timeInSec=true) println("McNemar Test. Done for M = ", M_[i], ", Minimum Time(s): ", minimum(t).time/1e9) end # One-sample t-test for i=1:length(M_) x = [randn(N) for j=1:M_[i]] t = @benchmark tMcTest1S($x; switch2rand=1, nperm=numPerm, verbose=false) addResults!(numPerm, minimum(t), T, G, M, A, i, 10; timeInSec=true) println("One-Sample Student-t Test. Done for M = ", M_[i], ", Minimum Time(s): ", minimum(t).time/1e9) end # Sign Test for i=1:length(M_) x = [rand(Bool, N) for j=1:M_[i]] t = @benchmark signMcTest($x; switch2rand=1, nperm=numPerm, verbose=false) addResults!(numPerm, minimum(t), T, G, M, A, i, 11; timeInSec=true) println("Sign Test. Done for M = ", M_[i], ", Minimum Time(s): ", minimum(t).time/1e9) end # Tables labels=["Pearson r" "ANOVA F IS" "St. t IS" "St. t IS(r)" "χ²" "Fisher Exact" "ANOVA F RM" "Cochran Q" "McNemar" "St. t 1S" "Sign"] print(" Minumum Execution Time (s), ", numPerm," Random Permutations, N=", N) pretty_table(hcat(Int.(M_), T); formatters = ft_printf("%5.2f", 2:4), header = ( hcat("M", labels),), header_crayon = crayon"yellow bold") print(" Memory Allocations (MB), ", numPerm," Random Permutations, N=", N) pretty_table(hcat(Int.(M_), M); formatters = ft_printf("%5.2f", 2:4), header = ( hcat("M", labels),), header_crayon = crayon"yellow bold") print(" Memory Allocation count, ", numPerm," Random Permutations, N=", N) pretty_table(hcat(Int.(M_), A); formatters = ft_printf("%5.2f", 2:4), header = ( hcat("M", labels),), header_crayon = crayon"yellow bold") # Plots labels=["Pearson r" "ANOVA F IS" "Student t IS" "Student t IS as r" "χ²" "Fisher Exact" "ANOVA F RM" "Cochran Q" "McNemar" "One-sample Student t" "Sign"] kwargs=(yscale=:log10, minorgrid=true, label=labels, xlabel="Number of hypotheses", leg=:topleft, left_margin = 35mm, bottom_margin = 5mm, right_margin = 5mm, lw=2, xticks = ([1:1length(M_);], string.(M_)), size=(900, 600), tickfontsize=11, labelfontsize=14, legendfontsize=10,) # temp: remove once the tests are done also for the Chi-Square test plot(T; ylabel="Minimum Execution time (s)", title="$numPerm permutations", ylims=(0.1, 1e2), kwargs...) plot(M; ylabel="Memory allocation (MB)", title="$numPerm permutations", ylims=(1e4*3, 1e8*2), kwargs...) plot(M; ylabel="allocation count", title="$numPerm permutations", ylims=(1e4*3, 1e9), kwargs...)
PermutationTests
https://github.com/Marco-Congedo/PermutationTests.jl.git
[ "MIT" ]
0.2.0
8a73fe1574e159927031bb2b9cc6ea142f075407
code
10325
# Unit "_test.jl", additional resource to the PemutationTests.jl package for the julia language # # MIT License # Copyright (c) 2024, # Marco Congedo, CNRS, Grenoble, France: # https://sites.google.com/site/marcocongedo/home # ? CONTENTS : # This unit tests the validity of all univariate and multiple comaprison tests implemented # in the PermutationsTests.jl package. # The general methodology is to create data under H0 and perform the test. # The procedure is repeated many times in order to estimate the rejection threshold # at many type I error rates (univariate tests) and the average proportion of rejections # for a given family-wise error rate (multiple comparison tests). # REQUIRED PACKAGES : PermutationsTests, Plots, Distributions using Dates:now, toms, Minute # julia built-in using Random:MersenneTwister # julia built-in using Plots, Plots.Measures using Distributions: Binomial using PermutationTests plotly() # Grid of histograms function Hplot(P, N, time, filename; noplot=false, layout=(2, 3)) plots=(Plots.stephist(P[:, i], xlims=(0, 1), label=false, xlabel="p-values", ylabel="Frequency", title="N=$(N[i])" , titlefont=10, bin=40, bottom_margin = 10mm, left_margin = 10mm) for i=1:size(P, 2)) p=Plots.plot(plots..., size=(1000, 600), layout = layout) #png(filename) noplot || return p end # Grid of p-p plots function ppplot(x, P, N, time, filename; noplot=false, layout=(2, 2)) plots=(Plots.plot([x, sort(P[:, i])], x, xlims=(0, 1), ylims=(0, 1), label=false, #label=["Expected" "Observed"], xlabel="Expected p-value", ylabel="Observed p-value", title="N=$(N[i])" , titlefont=10, bottom_margin = 10mm, left_margin = 10mm) for i=1:size(P, 2)) p=Plots.plot(plots..., size=(1000, 600), layout = layout) #png(filename) noplot || return p end ## UNIVARIATE TESTS # set the monte carlo simulations Nrep=1000 x=[i/Nrep for i=1:Nrep] # x-data for p-p plots s2r=Int(1e5) # switch 2 random if more than 1e5 permutations # Correlation test N=[6, 12, 24, 48] # number of observations begin ⌚ = now() P = [rTest(randn(n), randn(n); switch2rand=s2r, verbose=false).p for r=1:Nrep, n ∈ N] time = now()-⌚ end times=string(round(toms(time) / toms(Minute(1)); digits=2)) Hplot(P, N, time, joinpath(@__DIR__, "uni r test_H"); layout=(2, 2)) ppplot(x, P, N, time, joinpath(@__DIR__, "uni r test_L"); layout=(2, 2)) # 1-way ANOVA for indepedent samples N=[9, 18, 36, 72] # number of observations begin ⌚ = now() P = [fTestIS(randn(n), [n÷3, n÷3, n-((n÷3)*2)]; switch2rand=s2r, verbose=false).p for r=1:Nrep, n ∈ N] time = now()-⌚ end times=string(round(toms(time) / toms(Minute(1)); digits=2)) Hplot(P, N, time, joinpath(@__DIR__, "uni fIS test_H"); layout=(2, 2)) ppplot(x, P, N, time, joinpath(@__DIR__, "uni fIS test_L"); layout=(2, 2)) # t-test for indepedent samples N=[9, 18, 36, 72] # number of observations begin ⌚ = now() P = [tTestIS(randn(n), [n÷2, n-(n÷2)]; switch2rand=s2r, verbose=false, asPearson=false).p for r=1:Nrep, n ∈ N] time = now()-⌚ end times=string(round(toms(time) / toms(Minute(1)); digits=2)) Hplot(P, N, time, joinpath(@__DIR__, "uni tIS test_H"); layout=(2, 2)) ppplot(x, P, N, time, joinpath(@__DIR__, "uni tIS test_L"); layout=(2, 2)) # Chi-Square test K=[2, 2, 4, 4] # number of columns in table N=[10, 20, 10, 20] rng = MersenneTwister(1234) begin ⌚ = now() P = [Χ²Test(rand(rng, Binomial(n, 0.5), 2, k), switch2rand=Int(1E6), verbose=false).p for r=1:Nrep, (n, k) ∈ zip(N, K)] time = now()-⌚ end times=string(round(toms(time) / toms(Minute(1)); digits=2)) Hplot(P, N, time, joinpath(@__DIR__, "uni Chi test_H"); layout=(2, 2)) ppplot(x, P, N, time, joinpath(@__DIR__, "uni Chi test_L"); layout=(2, 2)) # 1-way ANOVA for repeated measures N=[9, 18, 36, 72] # number of observations begin ⌚ = now() P = [fTestRM(randn(n), (n=n÷3, k=3); switch2rand=s2r, verbose=false).p for r=1:Nrep, n ∈ N] time = now()-⌚ end times=string(round(toms(time) / toms(Minute(1)); digits=2)) Hplot(P, N, time, joinpath(@__DIR__, "uni fRM test_H"); layout=(2, 2)) ppplot(x, P, N, time, joinpath(@__DIR__, "uni fRM test_L"); layout=(2, 2)) # Cochran Q test N=[9, 18, 36, 72] # number of observations k=3 begin ⌚ = now() P = [qTest(Int.(rand(Bool, n÷k, k)); switch2rand=s2r, verbose=false).p for r=1:Nrep, n ∈ N] time = now()-⌚ end times=string(round(toms(time) / toms(Minute(1)); digits=2)) Hplot(P, N, time, joinpath(@__DIR__, "uni q test_H"); layout=(2, 2)) ppplot(x, P, N, time, joinpath(@__DIR__, "uni q test_L"); layout=(2, 2)) # one sample t-test N=[9, 18, 36, 72] # number of observations begin ⌚ = now() P = [tTest1S(randn(n); switch2rand=s2r, verbose=false).p for r=1:Nrep, n ∈ N] time = now()-⌚ end times=string(round(toms(time) / toms(Minute(1)); digits=2)) Hplot(P, N, time, joinpath(@__DIR__, "uni t1S test_H"); layout=(2, 2)) ppplot(x, P, N, time, joinpath(@__DIR__, "uni t1S test_L"); layout=(2, 2)) # Sign Test N=[9, 18, 36, 72] # number of observations begin ⌚ = now() P = [signTest(rand(Bool, n); switch2rand=s2r, verbose=false).p for r=1:Nrep, n ∈ N] time = now()-⌚ end times=string(round(toms(time) / toms(Minute(1)); digits=2)) Hplot(P, N, time, joinpath(@__DIR__, "uni sign test_H"); layout=(2, 2)) ppplot(x, P, N, time, joinpath(@__DIR__, "uni sign test_L"); layout=(2, 2)) # one-sided tests ... ############################################################################################""""" ## MULTPLE COMPARISON TESTS # set up monte carlo simutaions FWE=0.05 # Family-wise error Nrep=100 # number of repetitions s2r=Int(1e5) # switch 2 random if more than 1e5 permutations M=[2, 5, 10, 100] # number of hypoteses R=Matrix{Float64}(undef, length(M), 6) # Correlation test n=6 nrPerms(PearsonR(), n, allPerms(PearsonR(), n), Both()) for i=1:length(M) rejected = sum(count(≤(FWE), rMcTest(randn(n), [randn(n) for j=1:M[i]]; switch2rand=s2r, verbose=false, threaded=true, fwe=FWE, stepdown=true).p) for r=1:Nrep) println("done for m=", M[i]) R[i, 1] = (rejected/(Nrep*M[i])) # proportion of rejected hypotheses end sum(R[:, 1].>FWE)>0 ? (@warn "the r test does not control the FWE" R[:, 1]) : (@info "the r test controls the FWE" R[:, 1]) # result: R = [ 0.03, 0.008, 0.002, 0.0007] # ANOVA for independent samples n=8 ns=[n÷3, n÷3, n-((n÷3)*2)] nrPerms(AnovaF_IS(), ns, allPerms(AnovaF_IS(), ns), Both(), Unbalanced()) for i=1:length(M) rejected = sum(count(≤(FWE), fMcTestIS([randn(n) for j=1:M[i]], ns; switch2rand=s2r, verbose=false, threaded=true, fwe=FWE, stepdown=true).p) for r=1:Nrep) println("done for m=", M[i]) R[i, 2] = (rejected/(Nrep*M[i])) # proportion of rejected hypotheses end sum(R[:, 2].>FWE)>0 ? (@warn "the ANOVA IS test does not control the FWE" R[:, 2]) : (@info "the ANOVA IS test controls the FWE" R[:, 2]) # result: R = [ 0.025, 0.008, 0.008, 0.0005] # t-test for independent samples n=12 ns=[n÷2, n-(n÷2)] nrPerms(StudentT_IS(), ns, allPerms(StudentT_IS(), ns), Both(), Balanced()) for i=1:length(M) rejected = sum(count(≤(FWE), tMcTestIS([randn(n) for j=1:M[i]], ns; switch2rand=s2r, verbose=false, threaded=true, fwe=FWE, stepdown=true).p) for r=1:Nrep) println("done for m=", M[i]) R[i, 3] = (rejected/(Nrep*M[i])) # proportion of rejected hypotheses end sum(R[:, 3].>FWE)>0 ? (@warn "the t-test IS does not control the FWE" R[:, 3]) : (@info "the t-test IS controls the FWE" R[:, 3]) # result: R = [ 0.03, 0.014, 0.003, 0.0001] # Chi-Square n=3 # expected frequency in each cell k=3 # number of columns in tables rng = MersenneTwister(1234) # generate tables with fixed column sum equal to twice the expected frequency `n` # the first element of each column is generate randomly and the second is such that the col sum is 2n function gettable(n, k, rng) table=zeros(Int64, 2, k) for i=1:size(table, 2) table[1, i]=rand(rng, Binomial(n, 0.5)) table[2, i]=(2*n)-table[1, i] end return table end for i=1:length(M) rejected = sum(count(≤(FWE), Χ²McTest([gettable(n, k, rng) for j=1:M[i]]; switch2rand=s2r, verbose=false, threaded=true, fwe=FWE, stepdown=true).p) for r=1:Nrep) println("done for m=", M[i]) R[i, 4] = (rejected/(Nrep*M[i])) # proportion of rejected hypotheses end sum(R[:, 4].>FWE)>0 ? (@warn "the Chi-Suqared test does not control the FWE" R[:, 4]) : (@info "the Chi-Suqared test controls the FWE" R[:, 4]) # ANOVA for repeated measures n=12 ns=(n=4, k=3) nrPerms(AnovaF_RM(), ns, allPerms(AnovaF_RM(), ns), Both()) for i=1:length(M) rejected = sum(count(≤(FWE), fMcTestRM([randn(n) for j=1:M[i]], ns; switch2rand=s2r, verbose=false, threaded=true, fwe=FWE, stepdown=true).p) for r=1:Nrep) println("done for m=", M[i]) R[i, 5] = (rejected/(Nrep*M[i])) # proportion of rejected hypotheses end sum(R[:, 5].>FWE)>0 ? (@warn "the ANOVA RM test does not control the FWE" R[:, 5]) : (@info "the ANOVA RM test controls the FWE" R[:, 5]) # result: R = [ 0.005, 0.01, 0.008, 0.0003] # one-sample t-test n=9 nrPerms(StudentT_1S(), n, allPerms(StudentT_1S(), n), Both()) for i=1:length(M) rejected = sum(count(≤(FWE), tMcTest1S([randn(n) for j=1:M[i]]; switch2rand=s2r, verbose=false, threaded=true, fwe=FWE, stepdown=true).p) for r=1:Nrep) println("done for m=", M[i]) R[i, 6] = (rejected/(Nrep*M[i])) # proportion of rejected hypotheses end sum(R[:, 6].>FWE)>0 ? (@warn "the ANOVA RM test does not control the FWE" R[:, 6]) : (@info "the ANOVA RM test controls the FWE" R[:, 6]) # result: R = [ 0.015, 0.008, 0.008, 0.0007] kwargs=(minorgrid=true, label=["r" "F(is)" "t(is)" "Χ²" "F(rm)" "t"], xlabel="Number of hypotheses", leg=:topright, lw=2, xticks = ([1:1length(M);], string.(M)), tickfontsize=11, labelfontsize=14, legendfontsize=10, right_margin = 10mm, size=(900, 600)) plot(R; ylabel="Average proportion of rejections", title="FWE control for α=0.05", ylims=(0, 0.05), kwargs...) plot(R; ylabel="average proportion of rejections")
PermutationTests
https://github.com/Marco-Congedo/PermutationTests.jl.git
[ "MIT" ]
0.2.0
8a73fe1574e159927031bb2b9cc6ea142f075407
code
18939
# Unit "_power.jl", additional resource to the PemutationTests.jl package for the julia language # # MIT License # Copyright (c) 2024, # Marco Congedo, CNRS, Grenoble, France: # https://sites.google.com/site/marcocongedo/home # ? CONTENTS : # This unit compares the power of all univariate and multiple comparison tests implemented # in the PermutationsTests.jl package to parametric equivalent tests. # The general methodology is to create data under under H1 with some affect size (under H0 and H1 for multiple # comparison tests) and perform the tests. # The procedure is repeated many times in order to estimate the probability to reject the # hypothesis for the univariate tests and the proportion of rejected hypotheses among the false hypotheses # for multiple comparison tests. It also includes some more in depth analysis of the behavior of the tests. # REQUIRED PACKAGES : PermutationsTests, Plots, StatsPlots, LaTeXStrings, Distributions, LinearAlgebra, PrettyTables using Plots, Plots.Measures, StatsPlots, LaTeXStrings using Distributions using LinearAlgebra: I, Hermitian using PrettyTables using PermutationTests plotly() # select Plots.jl backend ##** UTILITIES FOR Correlation # Create M multivariate Normal Standard variables of N elements with unit variance and correlation matrix such that # 1) if M=2, the first variable has correlation ρ with the second # 2) if M>2, the first variable is given correlation ρ with all the others # and variables 2 to M are given correlation ρ2 in between each other. # The data is returned to be compatible as input of rTest and rMcTest, # that is, as two vectors 𝐱, 𝐲 if M==2 and first vector x, vectors 2 to M as a vector of vector 𝐘 if M>2. # Example: x, y = gen_correlated_data(10, 2, sigr(10, 0.05), 0) # M=2 # Example: x, y = gen_correlated_data(10, 20, sigr(10, 0.05), sigr(10, 0.1)) # M>2 function gen_correlated_data(N, M, ρ, ρ2) R=Matrix(1.0I, M, M) # deired correlation matrix for i=2:size(R, 2) # correlation between the first and all other variables. it suffice to write the upper off diagonal elements R[1, i]=ρ end if M>2 for j=2:size(R, 1), i=j+1:size(R, 2) # correlation among variables 2:M. it suffice to write the upper off diagonal elements R[j, i]=ρ2 end end D=MvNormal(fill(0.0, M), Matrix(Hermitian(R))) Y=Matrix(rand(D, N)) # generate random sample if M == 2 return Y[1, :], Y[2, :] else return Y[1, :], [Y[i, :] for i=2:M] end end # Return the correlation of two variables of N elements must have so as to be significantly correlated # at the α level using the unidirectional t-test for the correlation coefficient: t = (r*(sqrt(n-2)))/sqrt(1-r²) # Solving the above equation for r given t, yields r=sqrt(x/(x+1)), where x=t²/(n-2) function sigr(N, α) x=abs2(cquantile(TDist(N-2), α))/(N-2) return sqrt(x/(x+1)) end # use to check the above equation : r2t(sigr(N, α), N) must give the t(N-2 df)-value yielding α under the curve on its right r2t(r, N)=(r*(sqrt(N-2)))/sqrt(1-abs2(r)) # Fisher z-transformation r -> Normal(0, 1) #Fisherz(r, N) = atanh(r)/sqrt((1/N)+6/(2*N^2)) # asymptotyc correlation test based on t-test with N-2 df rTestAsy(𝐱, 𝐲, N) = ccdf(TDist(N-2), r2t(cor(𝐱, 𝐲), N)) # asymptotyc correlation test based on the Fisher transformation of correlation coefficient #rTestAsy(𝐱, 𝐲, N) = ccdf(Normal(), Fisherz(cor(𝐱, 𝐲), N)) ##** ##-- UTILITIES FOR T-TESTS INDEPENDENT Samples # return M pairs of independent samples with N÷2 elements each. # 1) if M=1 the mean of the second sample is shifted bu μ, i.e., if μ1 is the mean of the distribution, the second sample has mean μ1+μ. # 2) if M>1 the mean of the second sample of the first nH1 pairs only shifted bu μ. By defalt nH1=M, i.e., all samples are shifted. # Furthermore, if M>1, the expected correlation between the M variables within the first and second group is ρ. # The data is returned to be compatible as input of tTestIS and tMcTestIS, # that is, as a vector 𝐲 if M==1 and a vector of M vectors 𝐲 if M>1, where 𝐲 concatenates the two samples. # Example: Y = gen_shifted_data(10, 1, sigt(10, 0, 0.05), 0) # M=1 # Example: Y = gen_shifted_data(10, 3, sigt(10, 0, 0.05), sigr(10, 0.1)) # M>1, all under H1 # Example: Y = gen_shifted_data(10, 20, sigt(10, 0, 0.05), sigr(10, 0.1); nH1=5) # M>1, 5 under H1 and 15 under H0 function gen_shifted_data(N::Int, M::Int, μ::Float64, ρ; nH1=:all) Nd2=N÷2 if M==1 D=Normal() return vcat(rand(D, Nd2), rand(D, Nd2).+μ) else R=Matrix(1.0I, M, M) # desired correlation matrix for ALL variables for j=1:size(R, 1), i=j+1:size(R, 2) # correlation among all variables 2:M. it suffice to write the upper off diagonal elements R[j, i]=ρ end D=MvNormal(fill(0.0, M), Matrix(Hermitian(R))) μ1 = nH1===:all ? repeat([μ], M) : [repeat([μ], nH1); zeros(Float64, M-nH1)] X=rand(D, Nd2) Y=rand(D, Nd2) return [vcat(X[i, :], Y[i, :].+μ1[i]) for i=1:M] end end # Return the mean a sample of N÷2 elements must have so as to be significantly smaller at the α level # as compared to μ1, the mean of a sample of N÷2 elements to be compared to using the # unidirectional t-test for independent samples. # The UNBIASED variance of the two samples is assumed equal to 1. # According to a t-test with pooled unbiased standard deviation = 1, sigt(N, μ1, α)/sqrt(2/N) = t, # where t is the value of the student t-statistic yielding a p-value equal to α. # NB: Generating random samples of the second group with this mean the expected power of a most uniformly powerful # test is 0.5 using the Normal distribution for generating the data. This is so because because the expected proportion # of samples with mean more extreme or equal to this mean is 0.5. sigt(N, μ1, α) = μ1 - sqrt(2/N) * cquantile(TDist(N-2), α) # parametric right-directional t-test for uncorrelated samples tTestISAsy(𝐱, 𝐲, N, ns) = ccdf(TDist(N-2), statistic(𝐱, 𝐲, StudentT_IS(); k=2, ns=ns)) ##-- ### UNIVARIATE TESTS ############################################################ # set the monte carlo simulations Nrep=1000 #x=[i/Nrep for i=1:Nrep] # x-data for p-p plots s2r=Int(1e5) # switch 2 random if more than 1e5 permutations ## Correlation test N=[6, 9, 36, 100] # sample size A=Matrix{Float64}(undef, Nrep, length(N)) # p-values of asymptotic test P=Matrix{Float64}(undef, Nrep, length(N)) # p-values of permutation test α=0.01 # expected correlation p-value T1E=0.05 # type 1 error for n=1:length(N), r=1:Nrep 𝐱, 𝐲 = gen_correlated_data(N[n], 2, sigr(N[n], α), 0) # setting 0 instead of sigr(N[n], α) the hyp is under H0 P[r, n] = rTest(𝐱, 𝐲; switch2rand=s2r, direction=Right(), verbose=false).p A[r, n] = rTestAsy(𝐱, 𝐲, N[n]) end # proportion of rejected hypotheses propRejP=[count(≤(T1E), P[:, n])/Nrep for n=1:length(N)] propRejA=[count(≤(T1E), A[:, n])/Nrep for n=1:length(N)] nam = repeat("N=" .* string.(N), outer = 2) gbkwargs=(tickfontsize=11, labelfontsize=14, legendfontsize=10, leg=:bottom, title="r-test, α=$α", label=["Param" "Perm"]) if Plots.backend()==Plots.PlotlyBackend() groupedbar(nam, hcat(propRejA, propRejP), ylabel="Power "*"(1-β)", leg=:bottom, tickfontsize=11, title="Pearson correlation test, α=$(T1E), 𝔼p=$α", label=["Parametric" "Permutation"], legendfontsize=12, size=(800, 500)) # hline!([0.5], label="𝔼(1-β)", lw=2, c=:grey) # the expected power when α = T1E is 0.5 else groupedbar(nam, hcat(propRejA, propRejP), label=["Param" "Perm"], ylabel="Power "*L"(1-β)", title="r-test, α=$(T1E), , 𝔼p=$α") # hline!([0.5], label=L"E(1-β)", lw=2, c=:grey) # the expected power when α = T1E is 0.5 end hkwargs=(xlim=(0, 0.4), bins=100, alpha=0.7, color=[:cyan :yellow], label=["Param" "Perm"]) lkwargs=(lw=4, c=:grey, label="nominal "*L"α") histogram(hcat(A[:, 1], P[:, 1]); title="Histogram of p-values (N=$(N[1]))", hkwargs...) # N=6 vline!([T1E]; lkwargs...) histogram(hcat(A[:, 2], P[:, 2]); title="Histogram of p-values (N=$(N[2]))", hkwargs...) # N=9 vline!([T1E]; lkwargs...) histogram(hcat(A[:, 3], P[:, 3]); title="Histogram of p-values (N=$(N[3]))", hkwargs...) # N=36 vline!([T1E]; lkwargs...) histogram(hcat(A[:, 4], P[:, 4]); title="Histogram of p-values (N=$(N[3]))", hkwargs...) # N=100 vline!([T1E]; lkwargs...) #################################################################### # Analysis of the behavior of the t-test correlation parametric test. # This block of code is sot essential N=[6, 9, 36, 100] # sample size A=Matrix{Float64}(undef, Nrep, length(N)) # p-values of asymptotic test P=Matrix{Float64}(undef, Nrep, length(N)) # p-values of permutation test pTheo=[0.9998*(1-rand())+0.0001 for r=1:Nrep] # theoretical p-values ∈ (0.0001, 0.9999] for n=1:length(N), r=1:Nrep 𝐱, 𝐲 = gen_correlated_data(N[n], 2, sigr(N[n], pTheo[r]), 0) P[r, n] = rTest(𝐱, 𝐲; switch2rand=s2r, direction=Right(), verbose=false).p A[r, n] = rTestAsy(𝐱, 𝐲, N[n]) end # p observed - p theoretical scatter(pTheo, A.-pTheo; label="N=".*string.(N'), xlims=(0, 1), xlabel="theoretical p", ylabel="p observed - p theoretical", ms=2, ma=0.61, smooth=true, lw=3) scatter(pTheo, P.-pTheo; label="N=".*string.(N'), xlims=(0, 1), xlabel="theoretical p", ylabel="p observed - p theoretical", ms=2, ma=0.61, smooth=true, lw=3) # the two below are equivalent: p obs Asy - p the - p obs Perm - p the = p obs Asy - p obs Perm D=A-P scatter(pTheo, (A.-pTheo)-(P.-pTheo); label="N=".*string.(N'), xlims=(0, 1), xlabel="theoretical p", ylabel="p-value difference (Param-Perm)", ms=2, ma=0.61, lw=3) scatter(pTheo, D; label="N=".*string.(N'), xlims=(0, 1), xlabel="theoretical p", ylabel="p-value difference (Param-Perm)", ms=2, ma=0.61, lw=3) # smooth=true # mean of the differences A-B for each value of N meandiff=[mean(D[:, n]) for n=1:length(N)] # one-sample t-test on D to test H0: A-B = 0 for each value of N pdiff = [tTest1S(D[:, n]).p for n=1:length(N)] # Another way to do it: difference of z-tranformed p-values obtained by the asymptotic and permutation test Dz=[cquantile(Normal(), A[r, n])-cquantile(Normal(), P[r, n]) for r=1:Nrep, n=1:length(N)] scatter(pTheo, Dz; label="N=".*string.(N'), xlims=(0, 1), xlabel="theoretical p", ylabel="z(p-value) difference (Param-Perm)", ms=2, ma=0.61, smooth=true, lw=3) # mean of the differences z(A)-z(B) for each value of N meandiff=[mean(Dz[:, n]) for n=1:length(N)] # one-sample t-test on Dz to test H0: z(A)-z(B) = 0 for each value of N pdiff = [tTest1S(Dz[:, n]).p for n=1:length(N)] #################################################################### ## t-test for indepedent samples N=[12, 24, 48, 200] # total sample size, must be even A=Matrix{Float64}(undef, Nrep, length(N)) # p-values of parametric test P=Matrix{Float64}(undef, Nrep, length(N)) # p-values of permutation test α=0.01 # expected t-test p-value T1E=0.05 # type 1 error for n=1:length(N) ns=[N[n]÷2, N[n]÷2] 𝐱=membership(StudentT_IS(), ns) for r=1:Nrep 𝐲 = gen_shifted_data(N[n], 1, sigt(N[n], 0., α), 0) P[r, n] = tTestIS(𝐲, [N[n]÷2, N[n]÷2]; switch2rand=s2r, direction=Right(), verbose=false, asPearson=false).p A[r, n] = tTestISAsy(𝐱, 𝐲, N[n], ns) end end # proportion of rejected hypotheses propRejP=[count(≤(T1E), P[:, n])/Nrep for n=1:length(N)] propRejA=[count(≤(T1E), A[:, n])/Nrep for n=1:length(N)] nam = repeat("N=" .* string.(N), outer = 2) gbkwargs=(tickfontsize=11, labelfontsize=14, legendfontsize=12, leg=:bottom, title="r-test, α=$(T1E), 𝔼p=$α", label=["Param" "Perm"]) if Plots.backend()==Plots.PlotlyBackend() groupedbar(nam, hcat(propRejA, propRejP), ylabel="Power "*"(1-β)", leg=:bottom, tickfontsize=11, title="Student's t test Independent Samples, , α=$(T1E), 𝔼p=$α", label=["Parametric" "Permutation"], legendfontsize=12, size=(800, 500)) # hline!([0.5], label="𝔼(1-β)", lw=2, c=:grey) # the expected power when α = T1E is 0.5 else groupedbar(nam, hcat(propRejA, propRejP), label=["Param" "Perm"], ylabel="Power "*L"(1-β)", title="r-test, , α=$(T1E), 𝔼p=$α") # hline!([0.5], label=L"E(1-β)", lw=2, c=:grey) # the expected power when α = T1E is 0.5 end hkwargs=(xlim=(0, 0.4), bins=100, alpha=0.7, color=[:cyan :yellow], label=["Param" "Perm"]) lkwargs=(lw=4, c=:grey, label="nominal "*L"α") histogram(hcat(A[:, 1], P[:, 1]); title="Histogram of p-values (N=$(N[1]))", hkwargs...) # N=12 vline!([T1E]; lkwargs...) histogram(hcat(A[:, 2], P[:, 2]); title="Histogram of p-values (N=$(N[2]))", hkwargs...) # N=24 vline!([T1E]; lkwargs...) histogram(hcat(A[:, 3], P[:, 3]); title="Histogram of p-values (N=$(N[3]))", hkwargs...) # N=48 vline!([T1E]; lkwargs...) histogram(hcat(A[:, 4], P[:, 4]); title="Histogram of p-values (N=$(N[3]))", hkwargs...) # N=100 vline!([T1E]; lkwargs...) ############################################################################################### # Analysis of the behavior of the t-test. # This block of code is sot essential N=[12, 24, 48, 200] # total sample size, must be even A=Matrix{Float64}(undef, Nrep, length(N)) # p-values of parametric test P=Matrix{Float64}(undef, Nrep, length(N)) # p-values of permutation test pTheo=[0.9998*(1-rand())+0.0001 for r=1:Nrep] # theoretical p-values ∈ (0.0001, 0.9999] for n=1:length(N) ns=[N[n]÷2, N[n]÷2] 𝐱=membership(StudentT_IS(), ns) for r=1:Nrep 𝐲 = gen_shifted_data(N[n], 1, sigt(N[n], 0., pTheo[r]), 0.) P[r, n] = tTestIS(𝐲, [N[n]÷2, N[n]÷2]; switch2rand=s2r, direction=Right(), verbose=false).p A[r, n] = tTestISAsy(𝐱, 𝐲, N[n], ns) end end # p observed - p theoretical scatter(pTheo, A.-pTheo; label="N=".*string.(N'), xlims=(0, 1), xlabel="theoretical p", ylabel="p obseved-theoretical", ms=2, ma=0.61, smooth=true, lw=3) scatter(pTheo, P.-pTheo; label="N=".*string.(N'), xlims=(0, 1), xlabel="theoretical p", ylabel="p observed-theoretical", ms=2, ma=0.61, smooth=true, lw=3) # the two below are equivalent: ((p obs Para) - (p the)) - ((p obs Perm) - (p the)) = (p obs Para) - (p obs Perm) D=A-P scatter(pTheo, (A.-pTheo)-(P.-pTheo); label="N=".*string.(N'), xlims=(0, 1), xlabel="theoretical p", ylabel="p-value difference (Para-Perm)", ms=2, ma=0.61, lw=3) scatter(pTheo, D; label="N=".*string.(N'), xlims=(0, 1), xlabel="theoretical p", ylabel="p-value difference (Para-Perm)", ms=2, ma=0.61, lw=3) #smooth=true # mean of the differences A-B for each value of N meandiff=[mean(D[:, n]) for n=1:length(N)] # one-sample t-test on D to test H0: A-B = 0 for each value of N pdiff = [tTest1S(D[:, n]).p for n=1:length(N)] # Another way to do it: difference of z-tranformed p-values obtained by the parametric and permutation test Dz=[cquantile(Normal(), A[r, n])-cquantile(Normal(), P[r, n]) for r=1:Nrep, n=1:length(N)] scatter(pTheo, Dz; label="N=".*string.(N'), xlims=(0, 1), xlabel="theoretical p", ylabel="z(p-value) difference (Para-Perm)", ms=2, ma=0.61, smooth=true, lw=3) # mean of the differences z(A)-z(B) for each value of N meandiff=[mean(Dz[:, n]) for n=1:length(N)] # one-sample t-test on Dz to test H0: z(A)-z(B) = 0 for each value of N pdiff = [tTest1S(Dz[:, n]).p for n=1:length(N)] ############################################################################################### ############################################################ ## MULTIPLE COMPARISONS TESTS ############################################################ # set up monte carlo simutaions Nrep=100 # number of repetitions s2r=Int(1e5) # switch 2 random if more than 1e5 permutations ## Correlation test n=24 α=0.01 # expected p-value of the correlation between x and all y variables αρ=0.1 # # expected p-value of the correlation between all y variables FWE=0.05 # Family-wise error M=[5, 20, 100] # number of hypotheses P=Matrix{Float64}(undef, Nrep, length(M)) A=Matrix{Float64}(undef, Nrep, length(M)) nrPerms(PearsonR(), n, allPerms(PearsonR(), n), Right()) for i=1:length(M) for r=1:Nrep 𝐱, 𝐲 = gen_correlated_data(n, M[i], sigr(n, α), αρ≈1 ? 0.0 : sigr(n, αρ)) P[r, i] = count(≤(FWE), rMcTest(𝐱, 𝐲; switch2rand=s2r, verbose=false, threaded=true, fwe=FWE, direction=Right(), stepdown=true).p) A[r, i] = count(≤(FWE/M[i]), [rTestAsy(𝐱, y, n) for y ∈ 𝐲]) # bonferroni corrected end println("done for m=", M[i]) end # average number of rejections / number of hypotheses under H1 (power) P_=(sum(P, dims=1)./Nrep)./M' A_=(sum(A, dims=1)./Nrep)./M' # make a table labels=["Permutation" "Parametric"] println(" Average rejections / hypotheses under H1 (Power)") print(" correlation test, ", n," observations") pretty_table(hcat(Int.(M), P_', A_'); formatters = ft_printf("%5.2f", 2:3), header = ( hcat("M", labels),), header_crayon = crayon"yellow bold") # difference between the rejection of the parametric - permutation test D=P-A scatter(Base.OneTo(Nrep), D, label="M=".*string.(M'), xlabel="Simulations", ylabel="rejections Perm - rejections Param", ms=3, ma=0.61, tickfontsize=11, labelfontsize=13, legendfontsize=11) ## t-test for independent samples M=[5, 20, 100] # number of hypotheses ns=[8, 8] # must be balanced, see gen_shifted_data n=sum(ns) # n1+n2 𝐱=membership(StudentT_IS(), ns) α=0.01 # expected p-value of the correlation between x and all y variables αρ=0.1 # # expected p-value of the correlation between all y variables nH1=[M[i]÷2 for i=1:length(M)] FWE=0.05 # Family-wise error P=Matrix{Float64}(undef, Nrep, length(M)) A=Matrix{Float64}(undef, Nrep, length(M)) nrPerms(StudentT_IS(), ns, allPerms(StudentT_IS(), ns), Right(), Balanced()) for i=1:length(M) for r=1:Nrep 𝐲 = gen_shifted_data(n, M[i], sigt(n, 0., α), αρ≈1 ? 0.0 : sigr(n, αρ); nH1=nH1[i]) P[r, i] = count(≤(FWE), tMcTestIS(𝐲, ns; switch2rand=s2r, verbose=false, threaded=true, fwe=FWE, direction=Right(), stepdown=true, asPearson=false).p) A[r, i] = count(≤(FWE/M[i]), [tTestISAsy(𝐱, y, n, ns) for y ∈ 𝐲]) # bonferroni corrected end println("done for m=", M[i]) end # average rejections / number of hypotheses under H1 (power) - make a table P_=(sum(P, dims=1)./Nrep)./nH1' A_=(sum(A, dims=1)./Nrep)./nH1' # make a table labels=["Permutation" "Parametric"] println(" Average rejections / hypotheses under H1 (Power)") print(" Student's t test for Ind. Samples, ", ns," subjects per group") pretty_table(hcat(Int.(M), P_', A_'); formatters = ft_printf("%5.2f", 2:3), header = ( hcat("M", labels),), header_crayon = crayon"yellow bold") # difference between the rejection of the parametric - permutation test D=P-A scatter(Base.OneTo(Nrep), D, label="M=".*string.(M'), xlabel="Simulations", ylabel="rejections Perm - rejections Param", ms=3, ma=0.61, tickfontsize=11, labelfontsize=13, legendfontsize=11) ###
PermutationTests
https://github.com/Marco-Congedo/PermutationTests.jl.git
[ "MIT" ]
0.2.0
8a73fe1574e159927031bb2b9cc6ea142f075407
code
26433
# Unit "runtests.jl" of the PemutationTests.jl package # # MIT License # Copyright (c) 2024, # Marco Congedo, CNRS, Grenoble, France: # https://sites.google.com/site/marcocongedo/home # ? CONTENT: # test_stats() # test_unitests() # test_unitests_API() # test_multicompTests() # test_multicompTests_API() # The test of all the above is at the end of the script # REQUIRED PACKAGES : PermutationsTests, Test, Statistics using Random: randn, seed! # julia built-in using Test: @test, @testset using Statistics: mean, var, std, cov, cor using PermutationTests seed!(12345); # test all functions in stats.jl function test_stats(; tol=0) println("============ Basic Statistics functions =================") println() n=10 𝐱=abs.(randn(n)) 𝐲=abs.(randn(n)) m=mean(𝐱) v=var(𝐱; corrected=false) sd=std(𝐱; corrected=false) 𝐱c=𝐱.-m println("∑(𝐱), ∑of²(𝐱), ∑∑of²(𝐱), Π(𝐱), ∑ofΠ(𝐱, 𝐲), μ(𝐱)") @testset "\nSums and Products " begin @test ∑(𝐱) ≈ sum(𝐱); @test ∑of²(𝐱) ≈ sum(𝐱.^2); @test sum(∑∑of²(𝐱)) ≈ sum(𝐱) + sum(𝐱.^2); @test Π(𝐱) ≈ prod(𝐱); @test ∑ofΠ(𝐱, 𝐲) ≈ sum(𝐱.*𝐲); @test μ(𝐱) ≈ mean(𝐱); end println("dispersion(𝐱), σ²(𝐱), σ(𝐱)") @testset "\nMeasures of dispersion " begin @test isapprox(dispersion(𝐱; mean=m), v*n, atol=tol); @test isapprox(dispersion(𝐱c; centered=true), var(𝐱c; corrected=false)*n, atol=tol); @test isapprox(dispersion(𝐱), v*n, atol=tol); @test isapprox(σ(𝐱), sd; atol=tol); @test isapprox(σ(𝐱; mean=m), sd, atol=tol); @test isapprox(σ(𝐱c; centered=true), std(𝐱c; corrected=false), atol=tol); end println("μ0(𝐱), σ1(𝐱), μ0σ1(𝐱)") @testset "\nData Transformations " begin @test isapprox(mean(μ0(𝐱)), 0, atol=1e-1); @test isapprox(mean(μ0(𝐱; mean=m)), 0, atol=1e-1); @test isapprox(σ(σ1(𝐱)), 1, atol=tol); @test isapprox(σ(σ1(𝐱; mean=m, sd=sd)), 1, atol=tol); a=μ0(𝐱) @test isapprox(σ(σ1(a; centered=true, sd=sd)), 1, atol=tol); @test isapprox(σ(σ1(a; centered=true)), 1, atol=tol); @test isapprox(σ(σ1(𝐱; mean=m)), 1, atol=tol); @test isapprox(σ(σ1(𝐱; sd=sd)), 1, atol=tol); a=μ0σ1(𝐱) @test (isapprox(μ(a), 0, atol=1e-1) && isapprox(σ(a), 1, atol=1e-1)); a=μ0σ1(𝐱; sd=sd) @test (isapprox(μ(a), 0, atol=1e-1) && isapprox(σ(a), 1, atol=1e-1)); a=μ0σ1(𝐱; mean=m) @test (isapprox(μ(a), 0, atol=1e-1) && isapprox(σ(a), 1, atol=1e-1)); a=μ0σ1(𝐱; mean=m, sd=sd) @test (isapprox(μ(a), 0, atol=1e-1) && isapprox(σ(a), 1, atol=1e-1)); b=μ0(𝐱) a=μ0σ1(b; centered=true) @test (isapprox(μ(a), 0, atol=1e-1) && isapprox(σ(a), 1, atol=1e-1)); a=μ0σ1(b; centered=true, sd=σ(b; centered=true)) @test (isapprox(μ(a), 0, atol=1e-1) && isapprox(σ(a), 1, atol=1e-1)); end c=cov(𝐱, 𝐲; corrected=false) 𝐱0μ=μ0(𝐱) 𝐲0μ=μ0(𝐲) c0=cov(𝐱0μ, 𝐲0μ; corrected=false) println("CrossProd(), Covariance(), PearsonR()") @testset "\nBivariate Statistics " begin @test statistic(𝐱, 𝐲, CrossProd()) ≈ ∑ofΠ(𝐱, 𝐲); @test statistic(𝐱0μ, 𝐲0μ, Covariance(); centered=true, means=()) ≈ c0 ; @test statistic(𝐱, 𝐲, Covariance(); means=(mean(𝐱), mean(𝐲))) ≈ c; @test statistic(𝐱, 𝐲, Covariance()) ≈ c; r=cor(𝐱, 𝐲) @test statistic(𝐱, 𝐲, PearsonR()) ≈ r ; @test statistic(𝐱, 𝐲, PearsonR(); means=(μ(𝐱), μ(𝐲))) ≈ r ; @test statistic(𝐱, 𝐲, PearsonR(); means=(μ(𝐱), μ(𝐲)), sds=(σ(𝐱), σ(𝐲))) ≈ r ; 𝐱_=μ0σ1(𝐱) 𝐲_=μ0σ1(𝐲) @test statistic(𝐱_, 𝐲_, PearsonR(); standardized=true) ≈ r ; end println("AnovaF_IS(), SumGroupTotalsSq_IS(), Group1Total_IS(), StudentT_IS()") @testset "\nIndependent Sample Statistics " begin 𝐱 = [1, 1, 1, 2, 2, 2] 𝐲 = [1.3, 2.5, 0.5, 2.5, 6.3, 1.4] k=length(unique(𝐱)) ns=[count(x->x==i, 𝐱) for i=1:k] @test isapprox(statistic(𝐱, 𝐲, AnovaF_IS(); k=k, ns=ns), 1.52214, atol=1e-1); @test isapprox(statistic(𝐱, 𝐲, AnovaF_IS()), 1.52214, atol=1e-1); 𝐱 = [1, 1, 2, 2] 𝐲 = [1, 2, 3, 4] @test isapprox(statistic(𝐱, 𝐲, SumGroupTotalsSq_IS(); k=2), (1+2)^2+(3+4)^2, atol=tol); @test isapprox(statistic(𝐱, 𝐲, SumGroupTotalsSqN_IS(); k=2, ns=[2, 2]), ((1+2)^2)/2+((3+4)^2)/2, atol=tol); 𝐱=[1, 1, 1, 2, 2, 2] 𝐲=[1., 2., 3., 1.5, 2.5, 2.9] @test isapprox(statistic(𝐱, 𝐲, Group1Total_IS()), 6.0, atol=tol); ns=[3, 3] @test isapprox(statistic(𝐱, 𝐲, StudentT_IS(); k=2, ns=ns), -0.42146361521, atol=tol); end println("\nAnovaF_RM(), SumTreatTotalsSq_RM()") @testset "Repeated-Measures Statistics " begin # (Edgington, page 103-104) n, k = 3, 3 𝐱=collect(1:n*k) 𝐲 = [10., 11., 13., 13., 14., 17., 6., 8., 9.] ns=(n=n, k=k) @test isapprox(statistic(𝐱, 𝐲, SumTreatTotalsSq_RM(); ns), 3451, atol=tol); # https://statistics.laerd.com/statistical-guides/repeated-measures-anova-statistical-guide-2.php n, k = 6, 3 𝐱=collect(1:n*k) 𝐲=[45., 50., 55., 42., 42., 45., 36., 41., 43., 39., 35., 40., 51., 55., 59., 44., 49., 56.] ns=(n=n, k=k) @test isapprox(statistic(𝐱, 𝐲, AnovaF_RM(); ns=ns), 12.53, atol=1e-1); end println("\nStudentT_1S(), Sum()") @testset "One-Sample Statistics " begin # https://www.machinelearningplus.com/statistics/one-sample-t-test/ 𝐲=[21.5, 24.5, 18.5, 17.2, 14.5, 23.2, 22.1, 20.5, 19.4, 18.1, 24.1, 18.5].-20 𝐱=[1.] @test isapprox(statistic(𝐱, 𝐲, StudentT_1S()), 0.2006, atol=1e-1); sumy²=sum(abs2, 𝐲) @test isapprox(statistic(𝐱, 𝐲, StudentT_1S(), ∑y²=sumy²), 0.2006, atol=1e-1); @test isapprox(statistic(𝐱, 𝐲, Sum(); testtype = :approximate), sum(𝐲), atol=1e-1); end println() return true end ##################################################################################### # Test all functions in uniTests.jl function test_unitests(; tol=1e-1) println("============ Univariate test functions =================") println() # Product-moment Correlation (E.S. Edington, page 208) println("Product-moment Correlation tests : "); 𝐱=[2.0, 4.0, 6.0, 8.0, 10.0] 𝐲=[1.0, 3.0, 5.0, 8.0, 7.0] #_permTest!(𝐱, 𝐲, length(𝐱), CrossProd(); fstat=identity) @test _permTest!(copy(𝐱), 𝐲, length(𝐱), CrossProd(), CrossProd(); fstat=identity, verbose=false).p ≈ (2/120) ; print("right-directional ✔, ") @test _permTest!(copy(𝐱), 𝐲, length(𝐱), CrossProd(), CrossProd(); fstat=flip, verbose=false).p ≈ (119/120) ; print("left-directional ✔, ") @test _permTest!(copy(𝐱), 𝐲, length(𝐱), Covariance(), Covariance(), verbose=false).p ≈ (4/120) ; println("bi-directional ✔ ") println("") println("Correlation - trend tests : "); 𝐱=[2.0, 4.0, 6.0, 8.0, 10.0] 𝐲=[1.0, 3.0, 5.0, 8.0, 7.0] n=length(𝐲) 𝐱=collect(Base.OneTo(n)) #_permTest!(𝐱, 𝐲, length(𝐱), CrossProd(); fstat=identity) @test _permTest!(copy(𝐱), 𝐲, length(𝐱), CrossProd(), CrossProd(); fstat=identity, verbose=false).p ≈ (2/120) ; print("right-directional ✔, ") @test _permTest!(copy(𝐱), 𝐲, length(𝐱), CrossProd(), CrossProd(); fstat=flip, verbose=false).p ≈ (119/120) ; print("left-directional ✔, ") @test _permTest!(copy(𝐱), 𝐲, length(𝐱), Covariance(), Covariance(), verbose=false).p ≈ (4/120) ; println("bi-directional ✔ ") _permTest!(copy(𝐱), 𝐲, length(𝐱), CrossProd(), CrossProd(); fstat=identity, switch2rand=1, nperm=5000, seed=0, verbose=false) # run approximate test println("") # 1-Way ANOVA for independent samples (E.S. Edington, page 62) 𝐲=[1, 2, 3, 4, 5, 7, 8, 9, 10] # NB: input data can be also integer ns=[2, 3, 4] 𝐱=membership(AnovaF_IS(), ns) println("1-way independent samples ANOVA test : "); @test _permTest!(copy(𝐱), 𝐲, ns, AnovaF_IS(), AnovaF_IS(), verbose=false).p ≈ (2/1260) ; print("F statistic ✔, ") print("Equivalence of ES SumGroupTotalsSqN_IS() : "); @test _permTest!(copy(𝐱), 𝐲, ns, AnovaF_IS(), AnovaF_IS(), verbose=false).p ≈ _permTest!(copy(𝐱), 𝐲, ns, SumGroupTotalsSqN_IS(), SumGroupTotalsSqN_IS(), verbose=false).p ; println(" ✔ ") println("Second test:") # 1-Way ANOVA for independent samples (E.S. Edgington, page 70) 𝐲=[1, 2, 3, 4, 5, 6, 7, 8, 9] # NB: input data can be also integer ns=[2, 3, 4] 𝐱=membership(AnovaF_IS(), ns) @test _permTest!(copy(𝐱), 𝐲, ns, AnovaF_IS(), AnovaF_IS(), verbose=false).p ≈ (6/1260) ; print("F statistic ✔, ") @test _permTest!(copy(𝐱), 𝐲, ns, SumGroupTotalsSqN_IS(), SumGroupTotalsSqN_IS(), verbose=false).p ≈ (6/1260) ; println("SumGroupTotalsSqN_IS statistic ✔ ") println("") println("test the number of non-redundant permutations ") ns=[3, 3, 3] stat=AnovaF_IS() @test allPerms(stat, ns) / nrPerms(stat, ns, allPerms(stat, ns), Both(), Balanced()) ≈ factorial(length(ns)); print("✔, ") _permTest!(copy(𝐱), 𝐲, ns, SumGroupTotalsSqN_IS(), SumGroupTotalsSqN_IS(), verbose=false, switch2rand=1, nperm=5000) # run approximate test # T-tests (independent samples) 𝐲=[4., 5., 6., 7., 1., 2., 3] ns=[4, 3] 𝐱=membership(StudentT_IS(), ns) println("t-test independent samples (bi-directional): "); _permTest!(copy(𝐱), 𝐲, ns, StudentT_IS(), StudentT_IS(); switch2rand=1, seed=0, verbose=false) @test _permTest!(copy(𝐱), 𝐲, ns, StudentT_IS(), StudentT_IS(), verbose=false).p ≈ (2/35) ; print("StudentT_IS statistic ✔, ") @test _permTest!(copy(𝐱), 𝐲, ns, SumGroupTotalsSqN_IS(), SumGroupTotalsSqN_IS(), verbose=false).p ≈ (2/35) ; println("SumGroupTotalsSqN_IS statistic ✔, ") @test _permTest!(copy(𝐱), 𝐲, ns, StudentT_IS(), StudentT_IS(), fstat=identity, verbose=false).p ≈ (1/35) ; print("StudentT_IS statistic rigth-directional ✔ ") @test _permTest!(copy(𝐱), 𝐲, ns, Group1Total_IS(), Group1Total_IS(), fstat=identity, verbose=false).p ≈ (1/35) ; println("SumGroupTotalsSqN_IS statistic rigth-directional ✔ ") _permTest!(copy(𝐱), 𝐲, ns, Group1Total_IS(), Group1Total_IS(), fstat=identity, verbose=false, switch2rand=1, nperm=5000) # run approximate test println("") # 1-Way repeated-measures ANOVA (E.S. Edgington, page 103-104) n, k = 3, 3 𝐲 = [10., 11., 13., 13., 14., 17., 6., 8., 9.] ns=(n=n, k=k) 𝐱=membership(AnovaF_RM(), ns) println("1-Way Repeated Measure ANOVA :"); @test _permTest!(copy(𝐱), 𝐲, ns, AnovaF_RM(), AnovaF_RM(); verbose=false).p ≈ (1/36); print("AnovaF_RM statistic ✔, ") print("Equivalence of SumTreatTotalsSq_RM statistic: "); @test _permTest!(copy(𝐱), 𝐲, ns, SumTreatTotalsSq_RM(), SumTreatTotalsSq_RM(), verbose=false).p ≈ _permTest!(copy(𝐱), 𝐲, ns, SumTreatTotalsSq_RM(), SumTreatTotalsSq_RM(), verbose=false).p ; println(" ✔ ") _permTest!(copy(𝐱), 𝐲, ns, AnovaF_RM(), AnovaF_RM(); switch2rand=1, nperm=5000, seed=0, verbose=false) # run approximate test println("test the number of non-redundant permutations ") ns=(n=6, k=3) stat=AnovaF_RM() @test allPerms(stat, ns) / nrPerms(stat, ns, allPerms(stat, ns), Both(), Balanced()) ≈ factorial(ns.k); print("✔, ") # One-sample t-test ns = 6 𝐲 = randn(ns).+0.7 𝐱=membership(StudentT_1S(), ns) println("One-sample t-test :"); @test _permTest!(copy(𝐱), copy(𝐲), ns, StudentT_1S(), StudentT_1S(), verbose=false).p ≈ _permTest!(copy(𝐱), copy(𝐲), ns, Sum(), Sum(), verbose=false).p ; println(" Equivalence of Sum ✔ ") # just run the approximate test ns = 18 𝐱=Int[] 𝐲 = randn(ns)#.+0.7 _permTest!(copy(𝐱), copy(𝐲), ns, StudentT_1S(), StudentT_1S(); switch2rand=1, nperm=5000, seed=0, verbose=false) # run approximate test println() return true end #####################################################################################################"" # Test all functions in uniTests_API.jl function test_uniTests_API(; tol=1e-1) println("============ API for univariate test functions =================") println() println("Correlation tests : "); 𝐱=[2.0, 4.0, 6.0, 8.0, 10.0] 𝐲=[1.0, 3.0, 5.0, 8.0, 7.0] @test rTest(𝐱, 𝐲; direction = Right(), verbose=false).p ≈ (2/120) ; print("right-dir (r) ✔, ") @test rTest(𝐱, 𝐲; direction = Left(), verbose=false).p ≈ (119/120) ; print("left-dir (r) ✔, ") @test rTest(𝐱, 𝐲; direction = Both(), verbose=false).p ≈ (4/120) ; println("bi-dir (r) ✔, ") correlationTest(𝐱, 𝐲; direction = Both(), switch2rand=1, verbose=false) println("") println("1-way ANOVA for independent samples (method 1): "); 𝐲=[1., 2., 3., 4., 5., 7., 8., 9., 10.] ns=[2, 3, 4] 𝐱=membership(AnovaF_IS(), ns) @test fTestIS(𝐲, ns; direction = Both(), verbose=false).p ≈ (2/1260) ; print("bi-dir (F) ✔, ") 𝐲=[[1., 2.], [3., 4., 5.],[7., 8., 9., 10.]] print(" method 2 ") @test fTestIS(𝐲, direction = Both(), verbose=false).p ≈ (2/1260) ; print("bi-dir (F) ✔, ") 𝐲=[[1., 2., 3], [3.1, 4., 5.],[7., 8., 9.]] ns=[3, 3, 3] np=nrPerms(AnovaF_IS(), ns, allPerms(AnovaF_IS(), ns), Both(), Balanced()) @test fTestIS(𝐲; direction = Both(), verbose=false).nperm ≈ np ; println("non-redundant permutations ✔, ") println("") println("t-test independent samples (method 1): "); 𝐲=[4., 5., 6., 7., 1., 2., 3] ns=[4, 3] @test tTestIS(𝐲, ns; direction = Both(), verbose=false).p ≈ (2/35) ; print("bi-dir (T) ✔, ") @test tTestIS(𝐲, ns; direction = Right(), verbose=false).p ≈ (1/35) ; println("right-dir (T) ✔, ") print("method 2 ") 𝐲=[[4., 5., 6., 7.] , [1., 2., 3]] @test tTestIS(𝐲; direction = Both(), verbose=false).p ≈ (2/35) ; print("bi-dir (T) ✔, ") @test tTestIS(𝐲; direction = Right(), verbose=false).p ≈ (1/35) ; println("right-dir (T) ✔, ") print("method 3 ") 𝐱=[4., 5., 6., 7.] 𝐲=[1., 2., 3] @test tTestIS(𝐱, 𝐲; direction = Both(), verbose=false).p ≈ (2/35) ; print("bi-dir (T) ✔, ") @test tTestIS(𝐱, 𝐲; direction = Right(), verbose=false).p ≈ (1/35) ; print("right-dir (T) ✔, ") # 𝐲=[4., 5., 6., 7., 0., 1., 2., 3] ns=[4, 4] np=nrPerms(StudentT_IS(), ns, allPerms(StudentT_IS(), ns), Both(), Balanced()) @test tTestIS(𝐲, ns; direction = Both(), verbose=false, asPearson=false).nperm ≈ np ; println("non-redundant permutationns ✔, ") println("") println("Chi-Square and Fisher Exact Test : "); table=[0 2 2; 3 1 0] @test Χ²Test(table; direction = Both(), verbose=false).p ≈ 0.22857142857142856 ; print("bi-dir (Χ²) ✔, ") table=[1 7; 6 2] # asymptotic Χ²-test: Χ²=6.3492, p=0.011743 https://stats.libretexts.org/Learning_Objects/02%3A_Interactive_Statistics/37%3A__Chi-Square_Test_For_Independence_Calculator @test Χ²Test(table; direction = Both(), verbose=false, asPearson=false).p ≈ 0.04055944055944056 ; print("bi-dir (Χ²) ✔, ") @test Χ²Test(table; direction = Right(), verbose=false, asPearson=false).p ≈ 0.9993006993006993 ; print("right-dir (Χ²) ✔, ") @test Χ²Test(table; direction = Left(), verbose=false, asPearson=false).p ≈ 0.02027972027972028 ; println("left-dir (Χ²) ✔, ") table=[11 3; 1 9] # https://en.wikipedia.org/wiki/Fisher%27s_exact_test @test Χ²Test(table; direction = Right(), verbose=false, asPearson=false).p ≈ 0.0013797280926100418 ; print("right-dir (Χ²) ✔, ") @test Χ²Test(table; direction = Both(), verbose=false, asPearson=false).p ≈ 0.0027594561852200836 ; println("bi-dir (Χ²) ✔, ") println("") println("1-way ANOVA for Repeated Measures : "); 𝐲 = [10., 11., 13., 13., 14., 17., 6., 8., 9.] n, k = 3, 3 ns=(n=n, k=k) 𝐱=membership(AnovaF_RM(), ns) @test fTestRM(𝐲, ns; direction = Both(), verbose=false).p ≈ (1/36); print("bi-dir (F) ✔, ") print(" method 2 ") 𝐲 = [[10., 11., 13.] , [13., 14., 17.], [6., 8., 9.]] @test fTestRM(𝐲; direction = Both(), verbose=false).p ≈ (1/36); println("bi-dir (F) ✔, ") println("") println("One-sample t-test "); 𝐲=[21.5, 24.5, 18.5, 17.2, 14.5, 23.2, 22.1, 20.5, 19.4, 18.1, 24.1, 18.5] @test studentTest1S!(𝐲; refmean = 20, direction = Both(), verbose=false).p ≈ 0.84765625 ; print("bi-dir (t) ✔, ") 𝐲=[21.5, 24.5, 18.5, 17.2, 14.5, 23.2, 22.1, 20.5, 19.4, 18.1, 24.1, 18.5] @test studentTest1S!(𝐲; refmean = 20, direction = Right(), verbose=false).p ≈ 0.423828125 ; print("right-dir (t) ✔, ") 𝐲=[21.5, 24.5, 18.5, 17.2, 14.5, 23.2, 22.1, 20.5, 19.4, 18.1, 24.1, 18.5] @test studentTest1S!(𝐲; refmean = 20, direction = Left(), verbose=false).p ≈ 0.581787109375 ; println("left-dir (t) ✔, ") 𝐲=[21.5, 24.5, 18.5, 17.2, 14.5, 23.2, 22.1, 20.5, 19.4, 18.1, 24.1, 18.5] @test studentTest1S(𝐲; refmean = 20, direction = Both(), verbose=false).p ≈ 0.84765625 ; print("bi-dir (t) ✔, ") @test studentTest1S(𝐲; refmean = 20, direction = Right(), verbose=false).p ≈ 0.423828125 ; print("right-dir (t) ✔, ") @test studentTest1S(𝐲; refmean = 20, direction = Left(), verbose=false).p ≈ 0.581787109375 ; println("left-dir (t) ✔, ") println("") println("Cochran Test : "); table=[1 1 0; 1 0 0; 1 1 1; 1 1 0; 1 0 1; 1 1 0] @test cochranqTest(table; direction = Both(), verbose=false).p ≈ 0.12345679012345678 ; print("bi-dir (Q) ✔, ") table=[1 1; 1 0; 1 1; 1 0; 1 0; 1 1; 1 0] 𝐲, ns = table2vec(table, AnovaF_RM()) @test cochranqTest(table; direction = Both(), verbose=false).p ≈ 0.125 ; println("bi-dir (Q) ✔, ") println("") println("Sign test :"); 𝐲 = Bool.([1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 1, 0]) @test signTest(𝐲; direction=Both(), verbose=false).p ≈ 0.454498291015625 ; print("bi-dir (t) ✔, ") @test signTest(𝐲; direction=Right(), verbose=false).p ≈ 0.8949432373046875; print("right-dir (t) ✔ ") @test signTest(𝐲; direction=Left(), verbose=false).p ≈ 0.2272491455078125; println("left-dir (t) ✔ ") println("") return true end ######################################################################################" # test all functions in multicompTests.jl function test_multicompTests(; tol=1e-1) println("============ Multiple comparison test functions =================") # Product-moment Correlation println("") println("Product-moment Correlation tests : "); 𝐱=[2.0, 4.0, 6.0, 8.0, 10.0] 𝐘=[[1.0, 3.0, 5.0, 8.0, 7.0], [7.0, 8.0, 5.0, 3.0, 1.0]] # first hyp is positively and second negatively correlated to 𝐱 #_permTest!(𝐱, 𝐲, length(𝐱), CrossProd(); fstat=identity) @test sum(_permMcTest!(copy(𝐱), 𝐘, length(𝐱), PearsonR(), PearsonR(); verbose=false).p)<=(0.05*length(𝐘)) ;print("bi-directional ✔, ") # both are significant for a two-tailed test @test findall(p->p<=0.05, _permMcTest!(copy(𝐱), 𝐘, length(𝐱), PearsonR(), PearsonR(); fstat=identity, verbose=false).p)==[1] ; print("right-directional ✔, ") # first only significant for a right-tailed test @test findall(p->p<=0.05, _permMcTest!(copy(𝐱), 𝐘, length(𝐱), PearsonR(), PearsonR(); fstat=flip, verbose=false).p)==[2] ; println("left-directional ✔, ") # second only significant for a left-tailed test _permMcTest!(copy(𝐱), 𝐘, length(𝐱), PearsonR(), PearsonR(); fstat=identity, switch2rand=1, nperm=5000, verbose=false); # run the approximate test println("") # Use this as an example: the univariate two-dir test gives p-value 0.033 for both hypothesis, hence using Bonferroni none is rejected. # Instead the r-max test rejectes them both at the 0.05 level at the first step. # 1-Way ANOVA for independent samples ns=[6, 8, 6] # use even numbers here n=sum(ns) isodd(n) && throw(ArgumentError("test_multicompTests(): 1-way independent samples ANOVA test, n must be even")) 𝐘=[collect(Base.OneTo(n)).*1.0, [100. for i=1:n].+randn(n), [100. for i=1:n].+randn(n)] # only first hypothesis is to be rejected 𝐱=membership(AnovaF_IS(), ns) print("1-way independent samples ANOVA test : "); @test findall(p->p<=0.05, _permMcTest!(copy(𝐱), 𝐘, ns, AnovaF_IS(), AnovaF_IS(); verbose=false).p)==[1] ; println(" ✔, ") _permMcTest!(copy(𝐱), 𝐘, ns, AnovaF_IS(), AnovaF_IS(); switch2rand=1, nperm=5000, seed=0, verbose=false); # run approximate test # T-tests (independent samples) ns=[8, 8] # use even numbers n=sum(ns) isodd(n) && throw(ArgumentError("test_multicompTests(): 1-way independent samples ANOVA test, n must be even")) 𝐘=[collect(Base.OneTo(n)).*1.0, [100. for i=1:n].+randn(n), [100. for i=1:n].+randn(n)] # only first hypothesis is to be rejected 𝐱=membership(StudentT_IS(), ns) println("t-test independent samples test : "); @test findall(p->p<=0.05, _permMcTest!(copy(𝐱), 𝐘, ns, StudentT_IS(), StudentT_IS(); verbose=false).p)==[1] ; print(" bi-directional ✔, ") @test isempty(findall(p->p<=0.05, _permMcTest!(copy(𝐱), 𝐘, ns, StudentT_IS(), StudentT_IS(); fstat=identity, verbose=false).p)) ; print(" right-directional ✔, ") @test findall(p->p<=0.05, _permMcTest!(copy(𝐱), 𝐘, ns, StudentT_IS(), StudentT_IS(); fstat=flip, verbose=false).p)==[1] ; println(" left-directional ✔, ") _permMcTest!(copy(𝐱), 𝐘, ns, StudentT_IS(), StudentT_IS(); verbose=false, switch2rand=1, nperm=5000); #run approximate test println("") # 1-Way repeated-measures ANOVA n, k = 4, 3 # if change this, change also H0 and H1 H1=[10., 11., 13., 12., 14., 17., 6., 8., 9., 7., 8., 9.] H0=[10., 11., 13., 17., 14., 12., 6., 8., 9., 9., 8., 7.] 𝐘 = [H1, H0, H0] # only the first hypothesis is to be rejected ns=(n=n, k=k) 𝐱=membership(AnovaF_RM(), ns) print("1-Way Repeated Measure ANOVA (method 1):"); @test findall(p->p<=0.05, _permMcTest!(copy(𝐱), 𝐘, ns, AnovaF_RM(), AnovaF_RM(); verbose=false).p)==[1] ; println(" ✔, ") _permMcTest!(copy(𝐱), 𝐘, ns, AnovaF_RM(), AnovaF_RM(); verbose=false, switch2rand=1, nperm=5000); # run approximate test println("") # One-sample t-test ns = 10 H1=[1.0, 2.0, -0.2, 3.0, 1.5, 0.1, 0.2, 0.3, 0.4, 0.23] H0=[-0.1, 0.11, -0.2, 0.18, -0.4, 0.38, -0.16, 0.18, -0.4, 0.41] 𝐘 = [H0, H1, H0] # only the second hypothesis is to be rejected 𝐱=membership(StudentT_1S(), ns) print("One-sample t-test :"); @test findall(p->p<=0.05, _permMcTest!(copy(𝐱), copy(𝐘), ns, StudentT_1S(), StudentT_1S(); verbose=false).p)==[2]; println(" ✔ ") _permMcTest!(copy(𝐱), copy(𝐘), ns, StudentT_1S(), StudentT_1S(); verbose=false, switch2rand=1, nperm=5000); # just run the approximate test return true end function test_multcompTests_API(; tol=1e-1) println("============ API for multiple comparison test functions =================") println() # Product-moment Correlation println("") println("Product-moment Correlation tests : "); 𝐱=[2.0, 4.0, 6.0, 8.0, 10.0] 𝐘=[[1.0, 3.0, 5.0, 8.0, 7.0], [7.0, 8.0, 5.0, 3.0, 1.0]] # first hyp is positively and second negatively correlated to 𝐱 #_permTest!(𝐱, 𝐲, length(𝐱), CrossProd(); fstat=identity) @test sum(rMcTest(𝐱, 𝐘; verbose=false).p)<=(0.05*length(𝐘)) ;print("bi-directional ✔, ") # both are significant for a two-tailed test @test findall(p->p<=0.05, rMcTest(𝐱, 𝐘; direction=Right(), verbose=false).p)==[1] ; print("right-directional ✔, ") # first only significant for a right-tailed test @test findall(p->p<=0.05, rMcTest(𝐱, 𝐘; direction=Left(), verbose=false).p)==[2] ; println("left-directional ✔, ") # second only significant for a left-tailed test println("") # Use this as an example: the univariate two-dir test gives p-value 0.033 for both hypothesis, hence using Bonferroni none is rejected. # Instead the r-max test rejectes them both at the 0.05 level at the first step. # 1-Way ANOVA for independent samples ns=[6, 6, 8] # use even numbers here n=sum(ns) isodd(n) && throw(ArgumentError("test_multicompTests(): 1-way independent samples ANOVA test, n must be even")) 𝐘=[collect(Base.OneTo(n)).*1.0, [100. for i=1:n].+randn(n), [100. for i=1:n].+randn(n)] # only first hypothesis is to be rejected print("1-way independent samples ANOVA test : "); @test findall(p->p<=0.05, fMcTestIS(𝐘, ns; verbose=false).p)==[1] ; println(" ✔, ") # T-tests (independent samples) ns=[8, 8] # use even numbers n=sum(ns) isodd(n) && throw(ArgumentError("test_multicompTests(): 1-way independent samples ANOVA test, n must be even")) 𝐘=[collect(Base.OneTo(n)).*1.0, [100. for i=1:n].+randn(n), [100. for i=1:n].+randn(n)] # only first hypothesis is to be rejected println("t-test independent samples test : "); @test findall(p->p<=0.05, tMcTestIS(𝐘, ns; verbose=false).p)==[1] ; print("bi-directional ✔, ") @test isempty(findall(p->p<=0.05, tMcTestIS(𝐘, ns; direction=Right(), verbose=false).p)) ; print(" right-directional ✔, ") @test findall(p->p<=0.05, tMcTestIS(𝐘, ns; direction=Left(), verbose=false).p)==[1] ; println(" left-directional ✔, ") println("") # 1-Way repeated-measures ANOVA n, k = 4, 3 # if change this, change also H0 and H1 H1=[10., 11., 13., 12., 14., 17., 6., 8., 9., 7., 8., 9.] H0=[10., 11., 13., 17., 14., 12., 6., 8., 9., 9., 8., 7.] 𝐘 = [H1, H0, H0] # only the first hypothesis is to be rejected ns=(n=n, k=k) print("1-Way Repeated Measure ANOVA (method 1):"); @test findall(p->p<=0.05, fMcTestRM(𝐘, ns; verbose=false).p)==[1] ; println(" ✔, ") println("") # One-sample t-test ns = 10 H1=[1.0, 2.0, -0.2, 3.0, 1.5, 0.1, 0.2, 0.3, 0.4, 0.23] H0=[-0.1, 0.11, -0.2, 0.18, -0.4, 0.38, -0.16, 0.18, -0.4, 0.41] 𝐘 = [H0, H1, H0] # only the second hypothesis is to be rejected 𝐱=membership(StudentT_1S(), ns) print("One-sample t-test :"); @test findall(p->p<=0.05, tMcTest1S(𝐘; verbose=false).p)==[2]; println(" ✔ ") return true end # test all units of package PermutationTests @testset "\nAll tests... " begin @test test_stats()==true @test test_unitests()==true @test test_uniTests_API()==true @test test_multicompTests()==true @test test_multcompTests_API()==true end println("\n All tests done.")
PermutationTests
https://github.com/Marco-Congedo/PermutationTests.jl.git
[ "MIT" ]
0.2.0
8a73fe1574e159927031bb2b9cc6ea142f075407
docs
2616
## PermutationTests.jl | <img src="docs/src/assets/logo.png" height="90"> | [![](https://img.shields.io/badge/docs-stable-blue.svg)](https://Marco-Congedo.github.io/PermutationTests.jl/stable) | |:---------------------------------------:|:--:| A fast pure-[**julia**](https://julialang.org/) package for *univariate* and *multiple comparisons* statistical *hypothesis testing* based on *permutation theory*. Besides featuring an API with many tests, this package allows you to create your own permutation tests. --- ## Installation Execute the following command in julia's REPL: ]add PermutationTests --- ## Available tests All tests have a *univariate* and *multiple comparisons* version: - Pearson product-moment correlation - Trend correlation (fit of any kind of regression) - Point bi-serial correlation* - Student's t for independent samples - 1-way ANOVA for independent samples - Χ² for 2xK contingency tables* - Fisher exact test* (2x2 contingency tables) - Student's t for repeated-measures - 1-way ANOVA for repeated-measures - Cochran Q* - McNemar* - One-sample Student's t - Sign* (* for dicothomous data) --- ## Quick start As an example, let's run a Pearson correlation univariate test: ``` using PermutationTests # number of observations N=10 # some random Gaussian data x, y = randn(N), randn(N) t = rTest(x, y) ``` The test result `t` is a structure and its fields are printed in yellow, looking like this: <img src="docs/src/assets/Result_example.png" width="380"> Thus, for exmple, the p-value and the number of permutations used by the test are retrived such as ``` t.p t.nperm ``` --- ## About the authors [Marco Congedo](https://sites.google.com/site/marcocongedo), corresponding author and developer of the package, is a Research Director of [CNRS](http://www.cnrs.fr/en) (Centre National de la Recherche Scientifique), working at [UGA](https://www.univ-grenoble-alpes.fr/english/) (University of Grenoble Alpes, France). **Contact**: first name dot last name at gmail dot com [Livio Finos](https://pnc.unipd.it/finos-livio/), is Full professor at the [Department of Statistical Sciences](https://www.unipd.it/en/stat) of [Univerità di Padova, Italy](https://pnc.unipd.it/). **Contact**: first name dot last name at unipd dot it --- ## Disclaimer This version has been roughly tested. Independent reviewers for both the code and the documentation are welcome. --- | **Documentation** | |:---------------------------------------:| | [![](https://img.shields.io/badge/docs-stable-blue.svg)](https://Marco-Congedo.github.io/PermutationTests.jl/stable) |
PermutationTests
https://github.com/Marco-Congedo/PermutationTests.jl.git
[ "MIT" ]
0.2.0
8a73fe1574e159927031bb2b9cc6ea142f075407
docs
8850
# Main module Here below are the types declared in the package that you may need to use. --- #### TestDirection ```julia abstract type TestDirection end ``` This is the abstract type for the three possible *test directionalities*. Instances of this type are julia [singletons](https://docs.julialang.org/en/v1/manual/types/#man-singleton-types) and are used as arguments of test functions. | Type | Test Directionality | |:----------|:----------| | `Both` | bi-directional test (default for all tests) | | `Right` | right-tailed test | | `Left` | left-tailed test | --- #### Assignment ```julia abstract type Assignment end ``` This is the abstract type for the two possible *test designs*. Instances of this type are julia [singletons](https://docs.julialang.org/en/v1/manual/types/#man-singleton-types). The test design is determined automatically by the test functions and is one of the field of the structure returned by the test functions. | Type | Test Design | |:----------|:----------| | `Balanced` | equal number of subjects in all groups/tratments/blocks... | | `Unbalanced` | unequal number of subjects in the groups/tratments/blocks... | --- #### TestResult ```julia abstract type TestResult end ``` This is the abstract type for the structures returned by all test functions. --- #### UniTest All functions carrying out [univariate tests](@ref "Univariate tests") return the following structure of type [TestResult](@ref): ```julia struct UniTest <: TestResult p::Float64 stat::statistic where statistic <: Statistic obsstat::Float64 minp::Float64 nperm::Int64 testtype::Symbol direction::testDirection where testDirection <: TestDirection design::assignment where assignment <: Assignment end ``` **Fields**: - `.p`: the p-value of the test. - `.stat`: the actual test-statistic that has been used as a singleton, see [Statistic](@ref). - `.obsstat`: observed statistic, the value of the test-statistic `.stat` for the input data. - `.nperm`: the number of permutations used to obtain the p-value. - `.minp`: the minimum attainable p-value, given by 1 / `nperm`. - `.testtype`: either `:exact` or `:approximate`, depending on whether all possible or a random number of permutations, respectively, have been used. - `.direction`: the test-directionality set by the user as a singleton, see [TestDirection](@ref). - `.design`: the test design, as established by the test function as a singleton, see [Assignment](@ref). --- #### MultcompTest All functions carrying out [multiple comparisons tests](@ref "Multiple comparisons tests") return the following structure of type [TestResult](@ref): ```julia struct MultcompTest <: TestResult p::Vector{Float64} stat::statistic where statistic <: Statistic obsstat::Vector{Float64} minp::Float64 nperm::Int64 testtype::Symbol direction::testDirection where testDirection <: TestDirection design::assignment where assignment <: Assignment nulldistr::Vector{Float64} rejections::Vector{Vector{Int64}} stepdown::Bool fwe::Float64 end ``` **Fields**: The fields `.stat`, `.minp`, `.nperm`,`.testtype`, `.direction` and `.design` are the same as per the [UniTest](@ref) test result structure. For the others, special to multiple comparisons tests, say the test concerned ``M`` multiple-comparisons hypotheses, used ``P`` permutations and the step down procedure performed ``S`` steps. ``S`` will be equal to one if the step down procedure is not used or if it stops after the first step: - `.p`: the vectors of ``M`` p-values of the test. - `.obsstat`: observed statistics, the values of the ``M`` test-statistics `.stat` for the input data. - `.nulldistr`: if ``S`` is equal to 1 this is the vector holding the null-distribution of the test-statistic computed by data permutation, otherwise it is the vector holding the null-distribution obtained at the last step of the step down procedure. - `.rejections`: a vector holding ``S`` vectors, each one holding the indeces of the hypotheses that have been rejected at the corresponding step of the step down procedure. - `.stepdown`: `true` if the step down procedure has been used, `false` otherwise. - `.fwe`: the family-wise error rate set by the user. This is used only if `.stepdown` is `true`. By default it is fixed to `0.05` for all multiple comparisons tests. --- #### Statistic ```julia abstract type Statistic end ``` This is the abstract type for all *test statistics*. This type is useful if you want to [create your own test](@ref "Create your own test"). If you don't, you can skip the rest of this page. All test-statistic are julia [singletons](https://docs.julialang.org/en/v1/manual/types/#man-singleton-types), that is, immutable composite type (struct) with no fields. For each typical test-statistic used for paramtric tests, there exist an associated *equivalent test-statistic* that gives the same p-value with a particular univariate permutation test. This happens because the test-statistic can usually be decomposed in several terms, some of which are invariant to data permutation for a given test directionality (see [TestDirection](@ref)) and/or test design (see [Assignment](@ref)). Univariate tests in *Permutations.jl* make use of this equivalence to always yield the fastest test possible. In the following table, we list the usual test-statistic used for parametric tests in **bold** and the equivalent test-statistic used for univariate permutation tests just below, along with the test directionality and/or test design for which they apply. | Test-statistic | Type | When it applies| |:----------|:----------|:----------| | **Pearson correlation coefficient r** | `PearsonR` | always | | Cross Product | `CrossProd` | directional test* | | Covariance| `Covariance` | bi-directional test | | **1-way ANOVA for independent samples F** | `AnovaF_IS` | always | | Sum of group totals squared | `SumGroupTotalsSq_IS` | balanced design | | Sum of group totals squared/N| `SumGroupTotalsSqN_IS` | always | | **Student t for independent samples** | `StudentT_IS` | always | | Sum of group totals squared | `Group1Total_IS` | directional | | Sum of group totals squared/N| `SumGroupTotalsSqN_IS` | bi-directional test | | **1-way ANOVA for repeated measures F** | `AnovaF_RM` | always | | Sum of treatement totals squared | `SumTreatTotalsSq_RM` | always | | **One-sample Stedent t**| `StudentT_1S` | always | | Sum of observations| `Sum` | always | | | | * always if the data is standardized | The equivalent statistic that has been employed for a given univariate test is returned as one of the field of the [test result](@ref "UniTest"). To know a-priori what equivalent statistic will be used for a test, see [`eqStat`](@ref). Note that equivalent statistics are not used for multiple comparisons tests, as they are not dimensionless and their use could unduly favor some hypotheses over others. Test statistics are computed internally by the test functions of the package. If you need to compute them for other purposes, see the page on [test statistics](@ref "Test statistics"). --- #### Statistic groups All implemented test-statistics are grouped in four union types: - `BivStatistic` : all bivariate test-statistics - `IndSampStatistic` : all indepedent samples test-statistics - `RepMeasStatistic` : all repeated measures test-statistics - `OneSampStatistic` : all one-sample test-statistics, actually a special case of `RepMeasStatistic`. Regardless the actual test-statstic used in the permutation test, the union type it belongs to indicates the permutation scheme it is subjected to, which in turn determines the number of possible data permutations. The test statistics composing the four groups are listed in the table here below: | `BivStatistic`| `IndSampStatistic` | `RepMeasStatistic` | `OneSampStatistic`| |:--------------|:----------------------|:----------------------|:------------------| |`PearsonR` |`AnovaF_IS` |`AnovaF_RM` |`StudentT_1S` | |`CrossProd` |`SumGroupTotalsSq_IS` |`SumTreatTotalsSq_RM` |`Sum` | |`Covariance` |`SumGroupTotalsSqN_IS` | | | | |`StudentT_IS` | | | | |`Group1Total_IS` | | | | |`SumGroupTotalsSqN_IS` | | | ```julia # Singletons StudentT_1S() isa IndSampStatistic # false StudentT_1S() isa OneSampStatistic # true StudentT_1S() isa StudentT_1S # true # These are types instead and are never used as such StudentT_1S <: IndSampStatistic # false StudentT_1S <: OneSampStatistic # true ```
PermutationTests
https://github.com/Marco-Congedo/PermutationTests.jl.git
[ "MIT" ]
0.2.0
8a73fe1574e159927031bb2b9cc6ea142f075407
docs
3820
# About --- ## About the code **PermutationTests.jl** includes seven code units (.jl files): | Unit | Description | |:----------|:----------| | PermutationTests.jl | Main module, declaration of constants, types and structuress | | stats.jl | Low-level computations for statistics and test-statistic | | tools.jl | General tools | | uniTests.jl | Univariate tests | | uniTests_API.jl | API for univariate tests | | multcompTests.jl | Multiple comparisons tests | | multcompTests_API.jl | API for multiple comparisons tests | In addition, units for running [benchmarks](@ref "Benchmarks"), [error control](@ref "Error Control") tests and [power](@ref "Power") analysis can be found in the [src\extras](https://github.com/Marco-Congedo/PermutationTests.jl/tree/master/src/extras) folder. A unit to test the main functions is available as well in the [test](https://github.com/Marco-Congedo/PermutationTests.jl/tree/master/test) folder. --- ## About the authors [Marco Congedo](https://sites.google.com/site/marcocongedo), corresponding author and developer of the package, is a Research Director of [CNRS](http://www.cnrs.fr/en) (Centre National de la Recherche Scientifique), working at [UGA](https://www.univ-grenoble-alpes.fr/english/) (University of Grenoble Alpes, France). **Contact**: first name dot last name at gmail dot com [Livio Finos](https://pnc.unipd.it/finos-livio/), is Full professor at the [Department of Statistical Sciences](https://www.unipd.it/en/stat) of [Univerità di Padova, Italy](https://pnc.unipd.it/). **Contact**: first name dot last name at unipd dot it --- ## Disclaimer This version has been roughly tested. Independent reviewers for both the code and the documentation are welcome. --- ## TroubleShoothing | Problem | Solution | |:----------|:----------| | [Folds.jl](https://github.com/JuliaFolds/Folds.jl) does not work properly for future versions of julia | use keyword argument `threaded=false` for multiple comparison tests | --- ## Other relevant packages - [HypothesisTests.jl](https://github.com/JuliaStats/HypothesisTests.jl) - [StaticPermutations.jl](https://github.com/jipolanco/StaticPermutations.jl) - [BitPermutations.jl](https://github.com/giacomogiudice/BitPermutations.jl) --- ## References [R.A. Fisher](https://en.wikipedia.org/wiki/Ronald_Fisher) (1935) The Design of Experiments, Hafner. E.S. Edgington (1995), Randomization Tests, Marcel Dekker Inc. A.P. Holmes, R.C. Blair, J.D.G Watson, I. Ford (1996) Non-Parametric Analysis of Statistic Images From Functional Mapping Experiments. Journal of Cerebral Blood Flow and Metabolism 16:7-22. F. Pesarin (2001) Multivariate Permutation Tests with applications in Biostatistics. John Wiley & Sons. E. J. G. Pitman (1937) Significance tests which may be applied to samples from any population, Royal Statistical Society Supplement, 4: 119-130 and 225-32 (parts I and II). [E. J. G. Pitman](https://en.wikipedia.org/wiki/E._J._G._Pitman) (1938) Significance tests which may be applied to samples from any population. Part III. The analysis of variance test. Biometrika. 29 (3–4): 322–335. P.H. Westfall, S.S. Young (1993) Resampling-Based Multiple Testing: Examples and Methods for P-Value Adjustment, John Wiley & Sons. A.M. Winkler, M.A. Webster, J.C. Brooks, et al. (2016) Non-parametric combination and related permutation tests for neuroimaging. Human Brain Mapping, 37(4):1486-511. --- ## Contents ```@contents Pages = [ "index.md", "about.md", "PermutationTests.md", "univariate tests.md", "multiple comparisons tests.md", "package tests.md", "tools.md", "statistics.md", "test statistics.md", "create your own test.md", "chose a test.md" ] Depth = 2 ``` --- ## Index ```@index ```
PermutationTests
https://github.com/Marco-Congedo/PermutationTests.jl.git
[ "MIT" ]
0.2.0
8a73fe1574e159927031bb2b9cc6ea142f075407
docs
1536
# Chose a test The scheme below can help finding the appropriate hypothesis test giving the problem at hand. Navigate from "**Start**" following the appropriate *ellipses* for your problem to find the solution in the *rectangles*. The tests that are available in this package are numbered within parentheses and listed in the table below. Remark that the kind of tests referred to as *independent samples* and *repeated measures* throughout this documentation are referred to in the schame as *unpaired* and *paired*, respectively. Those terms are synonimous. ![Figure 1](assets/Discernment.png) | | Univariate tests | Multiple comparisons tests | |:----|:--------------------------|:---------------------------| | (1) | [`chiSquaredTest`](@ref) | [`chiSquaredMcTest`](@ref) | | (2) | [`cochranqTest`](@ref) | [`cochranqMcTest`](@ref) | | (3) | [`mcNemarTest`](@ref) | [`mcNemarMcTest`](@ref) | | (4) | [`mcNemarTest`](@ref) | [`mcNemarMcTest`](@ref) | | (5) | [`signTest`](@ref) | [`signMcTest`](@ref) | | (6) | [`correlationTest`](@ref) | [`correlationMcTest`](@ref)| | (7) | [`studentTestRM`](@ref) | [`studentMcTestRM`](@ref) | | (8) | [`studentTestIS`](@ref) | [`studentMcTestIS`](@ref) | | (9) | [`anovaTestRM`](@ref) | [`anovaMcTestRM`](@ref) | | (10)| [`anovaTestIS`](@ref) | [`anovaMcTestIS`](@ref) | --- For more available tests, see [univariate tests](@ref "Univariate tests") and [multiple comparisons tests](@ref "Multiple comparisons tests").
PermutationTests
https://github.com/Marco-Congedo/PermutationTests.jl.git
[ "MIT" ]
0.2.0
8a73fe1574e159927031bb2b9cc6ea142f075407
docs
33922
# Create your own test This page illustrates how you can create **univariate** and **multiple comparisons** permutation tests besides those already supported by *PermutationsTests.jl*. Good knowledge and understanding of the whole documentation is required for continuing reading this page, including the **Extras** pages. There are two ways you can extend the capability of *PermutationTests.jl*. - The first, very simple, but limited, is by using existing tests with particular data input. - The second, which needs a little development, but is much more general, allows you to create new tests defining your own test statistics. The illustration proceeds by examples of increasing complexity. ## Index of examples | Serial | Examples | |:----------:|:----------| | 1 | [Univariate autocorrelation test](@ref "Example 1: univariate autocorrelation test") | | 2 | [Post-hoc tests for 1-way repeated-measures ANOVA](@ref "Example 2: Post-hoc tests for 1-way repeated-measures ANOVA") | | 3 | [Univariate t-test for independent samples](@ref "Example 3: univariate t-test for independent samples") | | 4 | [Multiple comparison correlation test](@ref "Example 4: multiple comparisons correlation test") | | 5 | [Univariate Chatterjee correlation](@ref "Example 5: univariate Chatterjee correlation") | | 6 | [Multiple comparisons Chatterjee correlation](@ref "Example 6: multiple comparisons Chatterjee correlation") | | 7 | [Univariate distance correlation](@ref "Example 7: univariate distance correlation") | | 8 | [Multiple comparison distance correlation](@ref "Example 8: multiple comparisons distance correlation") | ## Using existing tests The approach for constructing univariate and multiple comparisons tests is illustrated by creating tests for the **autocorrelation**, which are not in the API of the package. --- ### Example 1: univariate autocorrelation test As an example, let us detect the presence of autocorrelation at lag 1, similar to what the [Durbin-Watson test](https://en.wikipedia.org/wiki/Durbin%E2%80%93Watson_statistic) does. *PermutationTests.jl* implements the Pearson product moment correlation statistic and a test for it. We can then test the null hypothesis that the autocorrelation at lag 1 is equal to zero by performing a correlation test on a data vector `x` and a lagged version of itself `y`. This is simply achieved by calling the [`_permTest!`](@ref) function, which ultimately performs all [univariate tests](@ref "Univariate tests") implemented in the package. First, let us create some data autorrelated at lag 1 to get a working example: ```julia using PermutationTests N=300 data=randn(N) for i=2:length(data) data[i-1]=data[i-1]+data[i] end # Data and lagged version of the data x=data[1:end-1] y=data[2:end] ``` Our univariate test on autocorrelation is obtained with ```julia t = _permTest!(copy(x), y, N-1, PearsonR(), PearsonR()) ``` NB: we pass a copy of `x` as this vector will be permuted. If we wish to wrap the test in a friendly function, we can write ```julia autocorTest(x; kwargs...) = _permTest!(x[1:end-1], x[2:end], length(x)-1, PearsonR(), PearsonR(); kwargs...) ``` The test will be executed then simply as ```julia t2 = autocorTest(data) ``` By default the test is bi-directional, thus the above call is a test for the autocorrelation regardless its sign. Our function `autocorTest` accepts all optional keyword arguments of the [`_permTest!`](@ref) function, thus we can easily obtain exact or approximate tests with a specified number of permutations, left- or right-directional tests, etc. !!! warning "Nota Bene" A multiple comparisons test for autocorrelation, that is, one testing for the autocorrelation at several lags simultaneously, cannot be done trivially by data permutation. See for example Romano and Tirlea (2022). For this reason such a test is not given as an example here below. **Reference**: J.P. Romano, M.A. Tirlea (2022) Permutation testing for dependence in time series. Journal of Time Series Analysis, 43(5), 781-807. --- ### Example 2: Post-hoc tests for 1-way repeated-measures ANOVA When a 1-way ANOVA for repeated measures is significant, it is most often of interest to examine the differences between the treatment all taken pair-wise to understand where the significance comes from. Formally, given ``K`` treatments the null hypothesis of the ANOVA is stated such as ``H_0: μ_1= ... =μ_K``. Post-hoc tests take the form ``H_0: μ_i=μ_j, i≠j=1,...,K`` and can be tested as a series of t-tests for repeated measures. The post-hoc tests are to be done simultaneously and a correction for multiple comparisons is to be applied. A control of the family-wise error rate in the strong sense is achieved with a multiple-comparison permutation test, as shown in the example below: ```julia using PermutationTests N=12 # Number of observation units per treatment K=3 # Number of treatments # Some random Gaussian data for example # The last (third) treatment will have mean higher than the other two yvec = [randn(K) for n=1:N]; for n=1:N yvec[n][K]+=2.0 end t = anovaTestRM(yvec) # ANOVA test # Let us create the K(K-1)/2 all-pair-wise difference vectors NK=N*K y=vcat(yvec...) d12=y[1:K:NK].-y[2:K:NK] d13=y[1:K:NK].-y[3:K:NK] d23=y[2:K:NK].-y[3:K:NK] # post-hoc tests pht = studentMcTestRM([d12, d13, d23]) ``` Verify that the second and third p-value in `pht.p` are significant. Inspecting the mean of `d12`, `d13` and `d23` will reveal the form of the effect across tratments. A general code for post-hoc test (for any `K`) is: ```julia d=[y[i:K:NK].-y[j:K:NK] for i=1:K, j=1:K if i≠j && j>i] pht2 = studentMcTestRM(d) ``` !!! warning "Nota Bene" Note that post-hoc tests cannot be trivially performed by data permutation as here above in the case of a 1-way ANOVA for independent samples. --- ## Defining new test statistics You can create your own permutation tests based on a *custom test statistic* as long as the permutation scheme for your test is supported by *PermutationTests.jl*. The ability to create **a test for virtually whatever test-statistic** is a fine characteristics of *PermutationTests.jl* and will be illustrated below with examples of ascending complexity. The procedure to follow is the same whether you want to create your own **univariate** or **multiple comparisons test**. It involves two preliminary steps: 1) define a new [`Statistic`](@ref) type to name the test statistic you want to use 2) write a method for the [`testStatistic`](@ref) function to compute the test statistic for both the observed and permuted data You then obtain the test just calling the [`_permTest!`](@ref) function for an univariate test and the [`_permMcTest!`](@ref) for a multiple comparisons test, as we will show. Two arguments of these functions are particularly important: - Argument `asStat`, which determines the permutation scheme of the test. !!! tip "keep in mind" Four permutation schemes are implemented in the package, corresponding to four implemented groups of test-statistics. The `asStat` argument can be one of the following built-in test statistics or any test statistic belonging to the same [group](@ref "Statistic groups"): - `PearsonR()` - `AnovaF_IS()` - `AnovaF_RM()` - `StudentT_1S()` Refer to the documentation of [`genPerms`](@ref) and the documentation linked therein. - Argument `fstat`, which is a function applied to all observed and permuted statistic. !!! tip "keep in mind" Argument `fstat` of `_permTest!` by default is the `abs` julia function, which yields a bi-directional test for a test-statistic that is distributed symmetrically around zero. For such test-statistics you will use `fstat=identity` for a right-directional test and `fstat=`[`flip`](@ref) for a left-directional test. Note that this may not be appropriate for your own test statistic. For example, if your test statistic is not symmetric and a right-tailed test is of interest, you must use `fstat=identity`. See below for examples. !!! warning "important" The permutation vector, which is always the first argument of the [`_permTest!`](@ref) function for an univariate test and of the [`_permMcTest!`](@ref) for a multiple comparisons test must correspond to the permutation yielding the observed statistic (*i.e.*, no data permutation). --- ### Example 3: univariate t-test for independent samples We create a new test for the difference of the mean between two independent samples. Such a test is equivalent to the *Student's t-test for independent samples*, since the mean difference is the nominator of the t statistic and the denominator is invariant with respect to data permutation. The permutations scheme is the same as the permutation scheme of the `AnovaF_IS()` (or `StudentT_IS`) test statistic, hence it is supported by *PermutationTests.jl* and we can reuse it. First, let us import `testStatistic` from *PermutationTests.jl* since we will write a new method for it: ```julia using PermutationTests import PermutationTests: testStatistic ``` (1) Define a new `Statistic` type to name the test statistic you want to use ```julia struct MeanDiff <: Statistic end ``` (2) Write a method for the `testStatistic` function to compute the mean difference, it does not matter if the data is observed or permuted. We will input the data exactly as for the `AnovaF_IS()` (or `StudentT_IS`) statistic. Our observations are divided in two groups. In this case, for this and equivalent statistics, data input is given as a single vector `y` of length ``N1+N2``, with the N1 observations followed by the N2 observations (see [`studentTestIS`](@ref)). The first argument of the `testStatistic` method is **always** the permutation vector x, holding in this case 1 for subjects of group 1 and 2 for subjects of group 2, that is, `x=[repeat ([1], N1); repeat([2], N2)]`. When given as input, `x` will reflect the positioning of the observed data and for permuted data it will be a permutation thereof. A simple implementation could be: ```julia function testStatistic(x, y, stat::MeanDiff; kwargs...) # get the number of subjects in each gruoup ns=[count(j->j==i, x) for i=1:length(unique(x))] s=[0., 0.] @simd for i ∈ eachindex(x, y) @inbounds (s[x[i]] += y[i]) end return (s[1]/ns[1]) - (s[2]/ns[2]) # mean difference end ``` That's it. Let's test our own test. First create some data ```julia y=[4., 5., 6., 7., 1., 2., 3] ns=[4, 3] # N1=4, N2=3 ``` For the permuttaion vector the dedicated function `membership` is available: ```julia x=membership(StudentT_IS(), ns) # = [repeat ([1], N1); repeat([2], N2)] ``` A two-directional exact test, as performed by PermutationTests.jl is ```julia println("t-test independent samples (bi-directional) using PermutationsTest.jl: "); t1 = studentTestIS(y, ns) ``` Let us run the test we have created. Notice that argument `stat` of `_permTest!` is `MeanDiff()`, while argument `asStat` is `AnovaF_IS()` The default `fstat` is julia abs() function, thus the test will be bi-directional as for the test `t1` here above. ```julia println("t-test independent samples (bi-directional) using our own statistic: "); t2 = _permTest!(copy(x), y, ns, MeanDiff(), AnovaF_IS()) ``` NB: we pass a copy of `x` as this vector will be permuted. --- We now illustrate with a simple example a nice opportunity we have to write efficient code to compute test statistics; the above implementation of the `testStatistic` function computes the group numerosity (`ns=[N1, N2]`) at each permutation, however `ns` is invariant to permutations. Let us rewrite the function then using the `cpcd` argument, which will be passed to the `_permTest!` functions in order to (optionally) pre-compute `ns`: ```julia function testStatistic(x, y, stat::MeanDiff; cpcd=nothing, kwargs...) if cpcd===nothing ns=[count(j->j==i, x) for i=1:length(unique(x))] else ns=cpcd end s=[0., 0.] @simd for i ∈ eachindex(x, y) @inbounds (s[x[i]] += y[i]) end return (s[1]/ns[1]) - (s[2]/ns[2]) # mean difference end ``` Running the test now can use the `cpcd` argument to avoid redundant computations: ```julia t3 = _permTest!(copy(x), y, ns, MeanDiff(), StudentT_IS(); cpcd=ns) ``` You can check that the p-values obtained by all the above tests is identical: ```julia t1.p≈t2.p≈t3.p ? (@info "It works!") : (@error "It does not work!") ``` To run a right-directional test: ```julia t4 = _permTest!(copy(x), y, ns, MeanDiff(), StudentT_IS(); fstat = identity) ``` To run a left-directional approximate test (see [`_permTest!`](@ref)): ```julia t5 = _permTest!(copy(x), y, ns, MeanDiff(), StudentT_IS(); fstat = flip, switch2rand=1) ``` Etc. As an exercise, wrap the test we have created in a friendly function. !!! tip "Nota Bene" We are not restricted to the use of a `cpcd` argument. In later examples we will show how to use an arbitrary number of specially defined keywords in order to obtain efficient tests. --- ### Example 4: multiple comparisons correlation test We create another version of the Pearson product-moment correlation test between a fixed variable given as a vector `x` and ``M`` variables given as a vector of ``M`` vectors `Y`. We want to test simultaneously all correlations between `x` and `Y[m]`, for ``m=1...M``. The procedure to follow is the same with two differences: the function [`testStatistic`](@ref) will now compute each one of the ```M`` test statistics and we will finally call the [`_permMcTest!`](@ref) function instead of the `_permMcTest!` function. The permutations scheme for the correlation test is the one of the `PearsonR()` statistic, hence it is supported by *PermutationTests.jl* and we can reuse it (using the appropriate `asStat` argument of `_permMcTest!`). First, let us import `testStatistic` from *PermutationTests.jl* and what we need for the computations: ```julia using PermutationTests import PermutationTests: testStatistic using LinearAlgebra: dot, ⋅ # we are going to use the dot product ``` (1) Define a new `Statistic` type to name the test statistic you want to use, such as ```julia struct MyPearsonR <: Statistic end ``` (2) Write a function to compute the ``i{th}`` observed and permuted test statistic. In order to obtain a faster test we will work with standardized variables, thus the Pearson correlation is given simply by the cross-product divided by N. We can write then ```julia testStatistic(x, Y, i, stat::MyPearsonR; kwargs...) = (x ⋅ Y[i])/length(x) ``` That's it. Let's test our own test. First create some data as example: ```julia N, M = 7, 100 # N=7 observations, M=100 hypotheses x=randn(N); Y=[randn(N) for m=1:M]; ``` A two-directional exact test, as performed by PermutationTests.jl is obtained by ```julia println("correlation test using PermutationsTest.jl: "); t1 = rMcTest!(x, Y) ``` Let's run our own test. Remind that our test works only for standardized variables, thus we have to input standardized variables. We can use function [`μ0σ1`](@ref): ```julia println("correlation test using our own test: "); t2 = _permMcTest!(μ0σ1(x), [μ0σ1(y) for y ∈ Y], length(x), MyPearsonR(), PearsonR()) ``` Check that the p-values obtained by the two tests is identical: ```julia abs(sum(t1.p-t2.p))<1e-8 ? (@info "my test works!") : (@error "my test does not work!") ``` Check also the observed statistics: ```julia abs(sum(t1.obsstat-t2.obsstat))<1e-8 ? (@info "my test works!") : (@error "my test does not work!") ``` To run a right-directional test: ```julia t3 = _permMcTest!(μ0σ1(x), [μ0σ1(y) for y ∈ Y], length(x), MyPearsonR(), PearsonR(); fstat = identity) ``` To run a left-directional approximate test: ```julia t4 = _permMcTest!(μ0σ1(x), [μ0σ1(y) for y ∈ Y], length(x), MyPearsonR(), PearsonR(); fstat = identity, switch2rand=1) ``` As an excercise, wrap our test in a friendly function that will standardize the input data before running the test. --- ### Example 5: univariate Chatterjee correlation Examples (4) and (5) are not very interesting per se, as they are just equivalent forms of tests already implemented in the API of *PermutationTests.jl*. Creating genuinely new tests is not necesserely more complicated thought, as it is shown in this example. The Chatterjee (2021) correlation ``ξ_{x→y}`` is an asymmetric, asymptotycally consistent estimator of how much a random variable ``y`` is a measurable function of ``x``. Thus, we can use it to test a null hypothesis of the form ``H_0: y≠f(x)``. The function ``f`` does not have to be monotonic, nor linear. In the following, ``x`` and ``y`` are assumed continuous with no ties. Let ``r`` be the ranks of variable ``y`` computed after sorting ``y`` by ascending order of ``x``. The coefficient is given by ``ξ_{x→y}= 1-\frac{3δ_{x→y}(r)}{n²-1}``, where ``δ_{x→y}(r)=\sum_{1}^{n-1}\left| r_{i+1} - r_i \right|`` ``ξ_{x→y}`` takes value in interval ``[0, 1]`` asymptotically. The limits with finite sampling are ``[-1/2+O(1/n), (n-2)/(n+1)]``. ``ξ`` has a simple asymptotic Gaussian distribution given by ``√n*ξ \sim N(0, 2/5)`` and is computed in ``O(n\textrm{log}n)``. **Reference**: S. Chatterjee (2021) a new coefficient of correlation, journal of the american statistical association 116(536), 506-15 --- Let us now construct a univariate permutation tests for ``ξ_{x→y}``. The following code block defines a function to create it: ```julia using PermutationTests using StatsBase: ordinalrank # install StatsBase.jl if you don't have it import PermutationTests: testStatistic struct Chatterjeeξ <: Statistic end testStatistic(r, y, stat::Chatterjeeξ; kwargs...) = sum(abs, diff(r)) xiCorPermTest(x, y; kwargs...) = _permTest!(ordinalrank(y[sortperm(x)]), [], length(x), Chatterjeeξ(), PearsonR(); fstat = flip, kwargs...) ``` As in [example 3](@ref "Example 3: univariate t-test for independent samples"), we import `testStatistic` and we define a type for the test statistic of interest as a [`Statistic`](@ref) type, which we have named `Chatterjeeξ`. Notice that we use ``δ_{x→y}(r)`` as an equivalent test statistic for ``ξ_{x→y}``. Notice also that while this is possible because ``δ_{x→y}(r)`` and ``ξ_{x→y}`` are a monotonic function of each other, their relationship is inverted, which will be taken care of later. Then, we declare a [`testStatistic`](@ref) method for computing the ``δ_{x→y}(r)`` quantity defined above for the observed and permuted data. Finally, we invoke the [`_permTest!`](@ref) function. The test works this way: `_permTest!` takes as input the ``n`` ranks and list all ``n!`` permutations of the rank indices for an exact test, or a random number of them for an approximate test. As the ranks are a permutation of ``(1.,...,n)`` themselves, at each permutation the `testStatistic` function is invoked and the test statistic is computed directly on the permutation vector, whcih is always passed by `_permTest!` to `testStatistic` as the first argument. Notice that the test of interest is meaningful only as a right-directional test for ``ξ_{x→y}``, but this is a left-directional test for ``δ_{x→y}(r)``, therefore we have used keyword argument `fstat = flip`. This takes care of the aforementioned inverse relationship of our equivalents statistic. Let's use the test we have created: ```julia n = 100 x = randn(n) y = randn(n) t = xiCorPermTest(x, y) # is not signifant y = x.^2+randn(length(x))/5 t1 = xiCorPermTest(x, y) # y is a function of x with little noise ``` --- ### Example 6: multiple comparisons Chatterjee correlation --- Next, let us define the multiple comparisons permutation test for ``ξ_{x→y}``. We wish to test simultaneously ``H_0(m): y_m≠f(x), m=1...M`` The code could be: ```julia using PermutationTests using StatsBase: ordinalrank # install StatsBase.jl if you don't have it import PermutationTests: testStatistic struct Chatterjeeξ <: Statistic end testStatistic(p, Y, m::Int, stat::Chatterjeeξ; kwargs...) = 1.0-((3*sum(abs, diff(Y[m][p])))/(abs2(length(x))-1)) # Take as input x and Y=y1,...,yM function xiCorPermMTest(x, Y; kwargs...) p = sortperm(x) n = length(x) x_ = collect(Base.OneTo(n)) return _permMcTest!(x_, [ordinalrank(y[p]) for y ∈ Y], n, Chatterjeeξ(), PearsonR(); fstat = identity, kwargs...) end ``` The first four lines are to be omitted if we continue writing on the same unit where we have written the univariate test. Again, we define a method for the `testStatistic` function and we invoke the the [`_permMcTest!`](@ref) function. Here we have to adopt a slightly different strategy: `testStatistic` takes as input the permutation vector and the ranks of the ``y_1,..,y_M`` vectors. It computes the ``ξ_{x→y}`` statistic (note: not an equivalent statistic) for these vectors after sorting them all by **the same** sorting key at each permutation, which is the permutation vector passed by `_permMcTest!` to `testStatistic` as the `x_` vector. Note that ``ξ_{x→y}`` can take negative values, thus we pass to `_permMcTest!` keyword argument `fstat = identity`; this will result in the correct right-directional test we sought. Let's use the test we have created: ```julia n = 100 m = 10 x = randn(n) Y = [randn(n) for i=1:m] t = xiCorPermMTest(x, Y) # is not signifant Y = [x.^2+randn(length(x))/5 for i=1:m] t1 = xiCorPermMTest(x, Y) # y1,...ym are a function of x with little noise ``` --- ### Example 7: univariate distance correlation This and next example illustrate how we can crete a test for a complex test statistic, still avoiding redundant computations, as if we wrote the code for a permutation test from scratch. The **distance correlation** (Skézely, Rizzo and Bakirov, 2007) extends the concept of correlation to distances among objects living in metric spaces, yielding a measure of dependence that is somehow sensitive to linear and non-linear dependence. We will here limit ourselves to scalars, vectors and matrices, it does not matter if real or complex. Let ``{(X_k, Y_k): k=1...K}`` be ``K`` pairs of observations (may be scalars, vectors, matrices). The elements within ``X`` and ``Y`` must have the same size, but the size of the elements in ``X`` may be different from the size of those in ``Y``. Let ``D_x`` and ``D_y`` be the distance matrices with elements ``D_x^{(ij)}=\left| X_i - X_j \right|_p : i,j={1,...,K}`` and ``D_y^{(ij)}=\left| Y_i - Y_j \right|_p : i,j={1,...,K}``, where ``\left|\cdot\right|_p`` is the p-norm, with ``p∈(0, 2]``. Let ``H=I-K^{-1}\textbf{1}\textbf{1}^T`` be the centering matrix, where ``I`` is the identity matrix and ``\textbf{1}`` is the vector of ones. Let ``A=HD_xH'`` and ``B=HD_yH'`` be the double-centered distance matrices. Then the **distance variance** is defined such as ``\nu(X)=\frac{1}{K^2}\sum_{i,j=1}^{K}a_{ij}^2`` and the **distance covariance** such as ``\nu(X, Y)=\frac{1}{K^2}\sum_{i,j=1}^{K}a_{ij}^2b_{ij}^2``. Finally, the **distance correlation** is defined such as ``\rho(X, Y)=\frac{\nu(X, Y)}{\sqrt{\nu(X)\nu(Y)}}``, where by convention it takes value zero if the denominator is zero. **Reference**: G.J. Székely, M.L. Rizzo, N.K. Bakirov (2007). Measuring and testing dependence by correlation of distances Ann. Statist. 35(6): 2769-2794. --- After giving the definition, let us see how we can create a univariate permutation tests for the distance correlation. First, let us define some functions we will need. ```julia using LinearAlgebra: I, norm, Hermitian, LinearAlgebra # Distance matrix for an array `X` of scalars, vectors, matrices, etc. # The `n` elements of `X` can be real or complex. # `pnorm` is the norm used to get distaces d_ij=norm(X[i]-X[j], pnorm), # see julia LinearAlgenbra.norm function. # Return the distance matrix filled only in the upper triangle. # Note: this is always real. function dm(x, n; pnorm=2) D = Matrix{Float64}(undef, n, n) for i=1:n-1 @simd for j=i+1:n @inbounds D[i, j] = norm(x[i]-x[j], pnorm) end end @simd for i=1:n @inbounds D[i, i] = 0. end return D end # Distance variance. Eq. (2.9) in Székemy, Rizzo and Bakirov(2007). # D is a distance matrix dVar(D) = sum(x->abs2(x), D)/size(D, 1)^2 # Distance covariance. Eq. (2.8) in Székemy, Rizzo and Bakirov(2007) # Dx and Dy are two distance matrices of equal size dCov(Dx, Dy) = sum(Dx.*Dy)/size(Dx, 1)^2 # Distance correlation. Eq. (2.10) in Székemy, Rizzo and Bakirov(2007) # Dx and Dy are two distance matrices of equal size function dCor(Dx, Dy) den = dVar(Dx) * dVar(Dy) return den > 0 ? sqrt(dCov(Dx, Dy)/sqrt(den)) : 0. end ``` --- We are now ready to create the univariate test. First, let us import `testStatistic`: ```julia using PermutationTests import PermutationTests: testStatistic ``` Given two vectors of elements `x` and `y` with distance matrices `Dx` and `Dy`, the test is obtained permuting the indices of `x`. Instead of recomputing distance matrix `Dx` at each permutation, the strategy is to permute instead the rows and columns of `Dx` by a permutation matrix `P` that is changed at each permutation according to the permutation vector `x`. Let us then write the function to do this: ```julia # Overwrite P with a permutation matrix given a vector x holding a # permutation of n indices. P must exist, be square and have same dimension as x function permMatrix!(P, x) fill!(P, 0.) @simd for i∈axes(P, 1) @inbounds P[i, x[i]] = 1. end return P end ``` As in the previous examples, we need to define a type for the distance correlation statistic: ```julia struct Dcor <: Statistic end ``` Next, as in the previous example, we need to define a method for `testStatistic`. This function takes as arguments a permutation vector `p` and `Dy`, the distance matrces of `y`, which is fixed across permutations. Furthermore, we will use four specially defined keyword arguments: - `H` : the centering matrix - `P` : the permutation matrix (to be updated at each call of the function) - `Dx`: the original distance matrix for data `x` - `dVarDy`: the distance variance of `y` At each permutation then, we will permute and double-center `Dx` in order to compute the distance correlation. The quantities that are invariant by permutation are passed to the function so that we do not need to recompute them. ```julia function testStatistic(x, HDyH, stat::Dcor; H, P, Dx, dVarHDyH, kwargs...) permMatrix!(P, x) # Hx * P * Dx * P' * Hx', Dx with rows and columns permuted HP = H*P HxPDxPHx = HP * Dx * HP' # permuted and double centered Dx den = dVar(HxPDxPHx) * dVarHDyH # dVar(Dx) * dVar(Dy), square of the denominator of dCor return den > 0 ? sqrt(dCov(HxPDxPHx, HDyH)/sqrt(den)) : 0. # dCor end ``` Finally, we write a function preparing the data and calling the [`_permTest!`](@ref) function. The preparation involves computing the distance matrices (once and for all), making some checks, creating the permutation vector `p` and the keyword arguments that will be passed internally to the function `testStatistic` we have created by `_permTest!`. Importantly, the vector `p` is created so as to correspond to the permutation yielding the observed statistic (``i.e.``, no data permutation), that is, in this case, the vector with the indices in the natural order ``1...n``. ```julia # The test takes as input two vectors of elements, which may be scalars, vectors or matrices. function dCorPermTest(x, y; pnorm=2, kwargs...) n = length(x) Dx = Hermitian(dm(x, n; pnorm)) Dy = Hermitian(dm(y, n; pnorm)) size(Dx, 1) == size(Dx, 2) || throw(ArgumentError("Function dCorPermTest: Did you want to call dCorPermMTest intead? The `Dx` and `Dy` distance matrices that have been computed are not square")) size(Dx) == size(Dy) || throw(ArgumentError("Function dCorPermTest: Did you want to call dCorPermMTest intead? The `Dx` and `Dy` distance matrices that have been computed are not square or do not have the same size")) p = collect(Base.OneTo(n)) # permutation vector # the centering matrix, the identity matrix, HDyH, dVar(HDyH) Id = Matrix{Float64}(I, n, n) H = Id - fill(1/n, n, n) # the centering matrix P = copy(Id) # the permutation matrix HDyH = H * Dy * H' dVarHDyH = dVar(HDyH) # the distance variace of HDyH (invariant to permutations) return _permTest!(p, HDyH, n, Dcor(), PearsonR(); fstat=identity, H, P, Dx, dVarHDyH, kwargs...) end ``` We are done. Let us use the function. We make an example where the elements of `x` and `y` are vectors. You can verify yourself that the test works in the same way if they are scalars or matrices. ```julia # Vectors n=10 l=20 x=[randn(l) for i=1:n] y=[randn(l) for i=1:n] perm = dCorPermTest(x, y; pnorm=2, switch2rand=1) # non-linear relationship (could be detected) y=[x_.^2+randn(length(x_))./10 for x_ in x] perm = dCorPermTest(x, y; switch2rand=1) ``` --- ### Example 8: multiple comparisons distance correlation This example reuses the code we have already written for the previous [example 7](@ref "Example 7: univariate distance correlation"). The strategy here is the same as in that example, however here we have to be more careful as there are several keyword arguments that will be updated at each permutation. The additional code we need to create a multiple comparisons permutation test is here below. As compared to the previous example, note that: - we are asking function `_permMcTest!` to pass internally to the function `testStatistic` the product `HPDxPH` as keyword argument because we do not want to compute it for every call of the `testStatistic` function, but only when it is called for the first hypothesis. - we are similarly also passing the distance variance of Dx `dVarDx` as a keyword argument for the same reason. Note also - the syntax `[:]` to update variables passed as keyword - the fact that `dVarHDxH` is passed as a vector of one element so as to be possible to update it thanks to the syntax `[:]`. ```julia function testStatistic(x, HDYH, m::Int, stat::Dcor; H=H, P=P, Dx, dVarHDYH, HxPDxPHx, dVarHDxH, kwargs...) if m==1 permMatrix!(P, x) # Hx * P * Dx * P' * Hx', Dx with rows and columns permuted HP = H * P HxPDxPHx[:] = HP * Dx * HP' # notice the [:] syntax; this kwarg is updated when m=1 dVarHDxH[:] = [dVar(HxPDxPHx)] # notice the [:] syntax; this kwarg is updated when m=1 end den = dVarHDxH[1] * dVarHDYH[m] # dVar(Dx) * dVar(Dy), square of the denominator of dCor return den > 0 ? sqrt(dCov(HxPDxPHx, HDYH[m])/sqrt(den)) : 0. # dCor end function dCorPermMTest(x, Y; pnorm=2, kwargs...) n = length(x) Dx = Hermitian(dm(x, n; pnorm)) DY = [Hermitian(dm(y, n; pnorm)) for y ∈ Y] size(Dx, 1) == size(Dx, 2) || throw(ArgumentError("Function dCorPermMTest: The `Dx` and `Dy` distance matrices that have been computed are not square")) size(Dx) == size(DY[1]) || throw(ArgumentError("Function dCorPermMTest: The `Dx` and `Dy` distance matrices that have been computed are not square or do not have the same size")) length(unique(size.(DY, 1))) == 1 || throw(ArgumentError("Function dCorPermMTest: All elements of second data input must have equal size")) n = size(Dx, 1) p = collect(Base.OneTo(n)) # permutation vector # keyword arguments that are not updated Id = Matrix{Float64}(I, n, n) H = Id - fill(1/n, n, n) P = copy(Id) HDYH = [H*Dy*H' for Dy ∈ DY] dVarHDYH = dVar.(HDYH) # Initialize keyword arguments that will be updated HxPDxPHx = Matrix{Float64}(undef, size(Dx)...) dVarHDxH = [0.0] # NB, cannot pass a scalar as kwargs if it is to be updated! return _permMcTest!(p, HDYH, n, Dcor(), PearsonR(); fstat=identity, threaded=false, H, P, Dx, dVarHDYH, HxPDxPHx, dVarHDxH, kwargs...) end ``` --- Let us use the multiple comaparions test we have just created. **Example where `x` and `y` hold vectors:** ```julia # Vectors n=10 l=20 m=30 x=[randn(l) for i=1:n] Y=[[randn(l) for i=1:n] for j=1:m] # random data. No hypothesis should be significant perm = dCorPermMTest(x, Y) # The y1...ym variables are noisy copy of x. # The p-value should be significant for about the first M/2 hypothesis out of M. # The actual number of rejected hypotheses could be slighty different then M/2. for i=1:m÷2 Y[i]=[x[j].+randn(l)./2 for j=1:n] end perm = dCorPermMTest(x, Y) ``` **Example where `x` and `y` hold matrices:** ```julia # Matrices n=10 l=20 m=30 x=[randn(l, l) for i=1:n] Y=[[randn(l, l) for i=1:n] for j=1:m] # random data. No hypothesis should be significant perm = dCorPermMTest(x, Y) # The y1...ym variables are noisy copy of x. # The p-value should be significant for about the first M/2 hypothesis out of M # The actual number of rejected hypotheses could be slighty different then M/2. for i=1:m÷2 Y[i]=[x[j].+randn(l, l)./2 for j=1:n] end perm = dCorPermMTest(x, Y) ``` --- In conclusion, in the above examples we have illustrated how to create permutation tests of increasing complexity. The last two examples concerns tests that are pretty complex and very different from any of the test implemented in *Permutationtests.jl*, where even the permutation scheme had to be defined differently. The diverse procedures exposed here above can be adapted to new problems in order to create a countless number of new permutation tests. ## Useful functions for creating your own tests --- ```@docs _permTest! _permMcTest! flip membership testStatistic ```
PermutationTests
https://github.com/Marco-Congedo/PermutationTests.jl.git
[ "MIT" ]
0.2.0
8a73fe1574e159927031bb2b9cc6ea142f075407
docs
7546
# PermutationTests.jl --- ## Installation Execute the following command in Julia's REPL: ]add PermutationTests --- #### Requirements **Julia**: version ≥ 1.10 --- #### Dependencies | standard Julia packages | external packages | |:-----------------------:|:-----------------------| | [Random](https://docs.julialang.org/en/v1/stdlib/Random/#Random.Random) | [Combinatorics](https://github.com/JuliaMath/Combinatorics.jl)| | [Statistics](https://bit.ly/2Oem3li) | [Folds](https://github.com/JuliaFolds/Folds.jl) | | [Test](https://docs.julialang.org/en/v1/stdlib/Test/#Test.@test) | | --- ## Quick start Here are some quick examples to show how *PermutationTests.jl* works: --- **Univariate test for correlation** Given two vectors of ``N`` observations, ``x`` and ``y``, test the null hypothesis ``H_0: r_{(x,y)}=0``, where ``r_{(x,y)}`` is the [Pearson product-moment correlation](https://en.wikipedia.org/wiki/Pearson_correlation_coefficient) between ``x`` and ``y``. First, we chose a [Type I error](https://en.wikipedia.org/wiki/Type_I_and_type_II_errors) ``α`` , typically fixed to Ronald Fisher's classical 0.05 level. ```@example using PermutationTests N=10 # number of observations x, y = randn(N), randn(N) # some random Gaussian data for example t = rTest(x, y) ``` We reject the null hypothesis if the p-value is less then or equal to ``α``, otherwise we suspend any judgement. The result of the test is a structure, which fields are printed in yellow. For example: ```julia t.p # p-value t.nperm # number of permutations used by the test ``` --- **Multiple comparison test for correlation** Given a vector of ``N`` observations ``x`` and ``M`` vectors of ``N`` observations ``y_m``, test simutaneously the ``M`` null hypotheses ``H_0(m):r_{(x, y_m)}=0, m=1...M``, where ``r_{(x,y_m)}`` is the Pearson product-moment correlation between ``x`` and the ``m^{th}`` vector ``y_m``. First, we fix the family-wise error [(FWE)](https://en.wikipedia.org/wiki/Family-wise_error_rate) rate we are willing to tolerate, say, at level 0.05. ```@example using PermutationTests N=10 # number of observations M=100 # number of hypotheses x, Y = randn(N), [randn(N) for m=1:M] # random Gaussian data t = rMcTest(x, Y) # by default the FWE is 0.05 ``` For each one of the ``m`` hypotheses, we reject the null hypothesis if its p-value is smaller than the nominal level (0.05), otherwise we suspend any judgement. The result of the test is a structure, which fields are printed in yellow. For example: ```julia t.p # p-values t.obsstat # observed test statistics ``` --- ## Preamble If you have no idea what a [`statistical hypothesis test`](https://en.wikipedia.org/wiki/Statistical_hypothesis_test) is, most probably you are on the wrong web page. If you do, but you have no idea what a [permutation test](https://en.wikipedia.org/wiki/Permutation_test) is, check first my [introduction to permutation tests](https://sites.google.com/site/marcocongedo/science/tutorials?authuser=0). If you need help to establish what hypothesis test is appropriate for your data, check [this page](@ref "Chose a test"). Permutation tests offer a different way to obtain the p-value usually obtained with well-known parametric tests, such as the *t-test for independent samples*, the *ANOVA for repeated mesures*, etc. In contrast to parametric tests, permutation tests may provide the *exact* p-value for the test, not an approximated value based on probability distribution theory, and make use of less stringent assumptions. Moreover, using permutation tests it is possible to use any test-statistic, not just those with known distribution under the null hypothesis, as such distribution is obtained by data permutation. Permutation tests have been introduced by none other than R.A. Fisher and E.J.G Pitman in the late '30 (see the [references](@ref "References")), but has become feasable only thanks to the advent of modern computers. When multiple hypotheses are to be tested simultaneously, the [multiple comparisons problem](https://en.wikipedia.org/wiki/Multiple_comparisons_problem) arises: statistical tests perforormed on each hypothesis separatedly cannot control anymore the probability to falsely reject the null hypothesis ([Type I error](https://en.wikipedia.org/wiki/Type_I_and_type_II_errors)). Using the *extremum-statistic* (also known as *min-p*) union-intersection test (see [Winkler et al., 2016](@ref "References")), permutation tests control the probabilty to commit one or more Type I error over the total number of hypotheses tested, regardless the configuration of true and false hypotheses, that is, they control the family-wise error [(FWE)](https://en.wikipedia.org/wiki/Family-wise_error_rate) rate in the strong sense (see [Westfall and Young, 1993](@ref "References")). While other multiple comparisons correction procedures controlling the FWE exists, such as the well-known [Bonferroni](https://en.wikipedia.org/wiki/Bonferroni_correction) or [Holm-Bonferroni](https://en.wikipedia.org/wiki/Holm%E2%80%93Bonferroni_method), they assume independence of the hypotheses. Instead, permutation tests do not. Actually, they naturally adapt to *any degree and form of correlation among the hypotheses*, thus they result more powerful when the hypotheses are not independent (see [power](@ref "Power")). Thanks to these characteristics, permutation tests conctitute the ideal framework for large-scale, possibly correlated, statistical hypothesis testing. This is the case, for instance of **genomics** (gene expression level) and **neuroimaging** (brain voxel activation), where up to hundreds of thousands of hypotheses, often largely correlated, must be tested simultaneusly. --- ## Overview *PermutationTests.jl* implements several *univariate* permutation tests and for all of them the corresponding *multiple comparisons* permutation tests based on the *min-p* union-intersection principle, with or without the *step down* procedure ([Holmes et *al.*, 1996; Westfall and Young, 1993](@ref "References")). For multiple comparisons tests, only tha case when all hypotheses are homogeneous is considered (same test statistic, same number of observations divided in the same number of groups/measurements). Here is the list of available tests: | Univariate and Multiple Comparisons Permutation Tests | |:----------| | Pearson product-moment correlation | | Trend correlation (fit of any kind of regression) | | Point bi-serial correlation* | | Student's t for independent samples | | 1-way ANOVA for independent samples | | Χ² for 2xK contingency tables* | | Fisher exact test* (2x2 contingency tables) | | Student's t for repeated-measures | | 1-way ANOVA for repeated-measures | | Cochran Q*| | McNemar*| | One-sample Student's t | | Sign*| | * for dicothomous data | You may also find useful the tests we have created as [examples](@ref "Index of examples") of how to create new tests. When the number of permutations is high, *PermutationTests.jl* computes approximate (Monte Carlo) p-values. All test functions switches automatically from systematic to Monte Carlo permutations, but the user can force them to use either one permutation listing procedure. For all kinds of implemented univariate tests, *PermutationTests.jl* always employs the most computationally effective equivalent test-statistic and only the required (non-redundant) systematic permutations, yielding very efficient permutation tests (see [Benchmarks](@ref)).
PermutationTests
https://github.com/Marco-Congedo/PermutationTests.jl.git
[ "MIT" ]
0.2.0
8a73fe1574e159927031bb2b9cc6ea142f075407
docs
4564
# Multiple comparisons tests With a multiple comparisons test ``M`` null hypotheses are tested simultaneously. By deriving the null distribution with the max-statistic approach, the following permutation tests control the family-wise error [(FWE)](https://en.wikipedia.org/wiki/Family-wise_error_rate) rate, that is, the probability to commit one or more [Type I error](https://en.wikipedia.org/wiki/Type_I_and_type_II_errors) at the nominal level: --- #### Multiple comparisons test functions | test | use function | alias | |:-----|:----------------|:---------------| | Pearson correlation | [`correlationMcTest`](@ref)| `rMcTest`| | Trend correlation | [`trendMcTest`](@ref)| | | Point bi-serial correlation | [`pointBiSerialMcTest`](@ref) | | | Student's t for independent samples | [`studentMcTestIS`](@ref) | `tMcTestIS` | | 1-way ANOVA for independent samples | [`anovaMcTestIS`](@ref) | `fMcTestIS` | | Chi-squared | [`chiSquaredMcTest`](@ref) | `Χ²McTest` | | Fisher exact| [`fisherExactMcTest`](@ref)| | | Student's t for repeated measures | [`studentMcTestRM`](@ref) | `tMcTestRM` | | 1-way ANOVA for repeated measures | [`anovaMcTestRM`](@ref) | `fMcTestRM` | | Cochran Q | [`cochranqMcTest`](@ref) | `qMcTest` | | McNemar| [`mcNemarMcTest`](@ref)| | | One-sample Student's t | [`studentMcTest1S`](@ref) | `tMcTest1S` | | Sign test | [`signMcTest`](@ref) | | You may also find useful the tests we have created as examples of how to create new tests: | Test | |:----------| | [Post-hoc tests for 1-way repeated-measures ANOVA](@ref "Example 2: Post-hoc tests for 1-way repeated-measures ANOVA") | | [Chatterjee correlation](@ref "Example 6: multiple comparisons Chatterjee correlation") | | [Distance correlation](@ref "Example 8: multiple comparisons distance correlation") | --- For creating other tests, see [Create your own test](@ref). For univariate tests, see [Univariate tests](@ref). --- #### Common kwargs for multiple comparisons tests The following optional keyword arguments are common to all multiple comparisons test functions: - `direction`: an instance of [TestDirection](@ref), either `Right()`, `Left()` or `Both()`. The default is `Both()`. - `nperm`: an integer providing the number of random permutations to be used for an approximate test. It defaults to `20000`. - `switch2rand`: an integer setting the upper limit of permutations to be listed exhaustively. It defaults to `1e8`. If the number of possible permutations exceeds `switch2rand`, the approximate test with `nperm` random permutations will be performed, otherwise an exact test with all possible permutations will be performed. In order to force an approximate test, set `switch2rand` to a small integer such as `1`. In order to know the number of possible permutations, see [`nrPerms`](@ref). - `seed`: an integer. It applies only to approximate tests. Set to `0` to use a random seed for generating random permutations. Any natural number results instead in a reproducible test. It defaults to `1234`. - `verbose`: a boolean. Print some information in the REPL while running the test. Set to false if you run benchmarks. The default is `true`. - `stepdown` : a boolean. If true (default) the step-down procedure is used. This is at least as powerfu as the standard procedure and still controls the FWE. - `fwe` : a real number in (0, 1). This is used by the step-down prcedure to control the family-wise error (FWE) rate at this level. By default it is 0.05. - `threaded` : a boolean. If true (default) some computations are multi-threaded if the product of the number of hypotheses, observations, and permutations exceed 500 millions. --- #### Multiple comparisons tests API --- ## Correlation test ```@docs correlationMcTest correlationMcTest! ``` --- ## Trend test ```@docs trendMcTest trendMcTest! ``` --- ## Point bi-serial correlation test ```@docs pointBiSerialMcTest ``` --- ## Student's t-test for independent samples ```@docs studentMcTestIS ``` --- ## 1-way ANOVA for independent samples ```@docs anovaMcTestIS ``` --- ## Chi-squared test ```@docs chiSquaredMcTest ``` --- ## Fisher exact test ```@docs fisherExactMcTest ``` --- ## Student's t-test for repeated measures ```@docs studentMcTestRM studentMcTestRM! ``` --- ## 1-way ANOVA for repeated measures ```@docs anovaMcTestRM ``` --- ## Cochran Q test ```@docs cochranqMcTest ``` --- ## McNemar test ```@docs mcNemarMcTest ``` --- ## One-sample Student's t-test ```@docs studentMcTest1S studentMcTest1S! ``` --- ## Sign test ```@docs signMcTest ```
PermutationTests
https://github.com/Marco-Congedo/PermutationTests.jl.git
[ "MIT" ]
0.2.0
8a73fe1574e159927031bb2b9cc6ea142f075407
docs
6420
# Package tests The code units pointed to in this page should be run within the general julia environment once *PermutationTests.jl* has been [installed](@ref "Installation"). --- ## Code tests For testing the main functions of the package, run the `runtests.jl` unit, located in the [test](https://github.com/Marco-Congedo/PermutationTests.jl/tree/master/test) folder. --- ## Benchmarks Multiple comparison tests are multi-threaded. In general *PermutationTests.jl* is very fast; you may expect to wait less then a second to get the result of a multiple comparison correlation test involving 20000 hypotheses with samples of 20 observations each. For running benchmarks on your computer use the `benchmarks.jl` unit located in the [src\extras\benchmarks](https://github.com/Marco-Congedo/PermutationTests.jl/tree/master/src/extras/benchmarks) folder. In that folder you will also find a pdf showing plots and tables generated by the unit, as it is currently published. --- !!! tip "Benchmarks hardware" Here below are the results obtained running the unit on a regular laptop running under Windows 10 equipped with a *Intel Core i7-8650U CPU @ 1.90GHz* and *32Go of RAM*. For **univariate tests**, the figure below reports the minimum execution time for approximate tests using 10000 random permutations for various numbers of observations (e.g., subjects): ![Figure 2](assets/benchmarks_uni.png) *Legend: IS=independent samples, RM=repeated measures, 1S=one-sample, St.=Student* We see that with 9000 observations, all tests execute within 4s, with the correlation/trend test, all types of t-tests, the McNemar test and the sign test executing within 1s. --- For **multiple comparisons tests**, the figure below reports the minimum execution time for approximate tests using 10000 random permutations for 12 observations and various numbers of hypotheses: ![Figure 3](assets/benchmarks_multComp.png) *Legend: IS=independent samples, RM=repeated measures, 1S=one-sample, St.=Student* We see that for sample size = 12 and 1000 hypotheses, the correlation and t-test for independent samples complete in about 200ms, while the other tests need about 2 to 8 seconds. --- ## Error Control All univariate statistical hypothesis tests must control the [type I error](https://en.wikipedia.org/wiki/Type_I_and_type_II_errors) under the null hypotheses. As explained in the [overview](@ref "Overview"), the multiple comparisons tests implemented in *PermutationTests.jl* control the [(FWE)](https://en.wikipedia.org/wiki/Family-wise_error_rate) rate under the global null hypothesis. The `errorControl.jl` unit located in the [src\extras\errorControl](https://github.com/Marco-Congedo/PermutationTests.jl/tree/master/src/extras/errorControl) folder runs simulations to verify these errors for all implemented tests. In that folder you will also find a pdf showing the plots of the data the unit produces as it is currently published. As an example, in the figure below the orange line is the p-p plot of the observed p-values versus the expected p-values under the null hypothesis. The plot has been obtained with 1000 simulations of a **univariate Pearson correlation test** by data permutation with four sample sizes (``N``). The blue line traces the expected p-values (control level): ![Figure 4](assets/errror_uni_corr.png) --- For **multivariate permutation tests**, the figure below show the proportion of rejected hypotheses obtained across 100 simulations for several tests and 2, 5, 10 or 100 hypotheses tested simultaneously. The FWE is controlled if the proportion is inferior to the nominal FWE level of the test, 0.05 for this simulation. ![Figure 5](assets/error_multComp.png) --- ## Power The power of a statstical hypothesis test is the probability that the test correctly rejects the null hypothesis when it is false. It depends on many factors, including the sample size, the effect size, the characteristics of the test and more. The `power.jl` unit located in the [src\extras\power](https://github.com/Marco-Congedo/PermutationTests.jl/tree/master/src/extras/power) folder contains example code to estimate the power of two univariate and multiple comparisons tests implemented in *PermutationTests.jl*. The code can be expanded for the other implemented tests as well as for running the power analysis with different parameters. In that folder you will also find a pdf showing the plots of the data the unit, as it is currently published, produces. As an example, the figure below compares the power of the **univariate Pearson correlation test** to its parametric counterpart, which is the usual test for correlation or of the slope of a regression line (see section "Slope of a regression line" [here](https://en.wikipedia.org/wiki/Student's_t-test)). The power is estimated for four sample size values (``N``) using random Gaussian data and 1000 simulations. ![Figure 6](assets/power_uni_cor.png) We see that the power of the permutation and parametric test is very close for all sample size values. --- For **multivariate permutation tests**, the figure below show the proportion of truly rejected hypotheses (number of rejected hypotheses divided by the number of false hypotheses) of the t-test for indipendent samples ( 8 subjects per group) obtained with 100 simulations when testing 5, 20 and 100 hypotheses simultaneously (``M``). In these simulations, multivariate Gaussian data is generated under ``H_0`` for half of the hypotheses and for the remaining half with an effect size allowing an expected p-value equal to 0.01 for each hypothesis tested separatedly with the parametric test. The hypotheses have geen generated uncorrelated and with three different degrees of uniform correlation such that the expected p-value of the correlation ``𝔼p(ρ)`` is equal to 1, 0.1 or 0.01. See the [preamble](@ref "Preamble") for a discussion on correlation among hypotheses. ![Figure 7](assets/power_multComp.png) We see that, on the average of all simulations, the multiple comparisons permutation max-t test implemented in this package is always more powerful than the Bonferroni correction procedure, it does not matter the number of hypotheses and whether the hypotheses are correlated or not. The advantage of the permutation approach increases as the correlation among variables (ρ) increases (hence its expected p-value decreases).
PermutationTests
https://github.com/Marco-Congedo/PermutationTests.jl.git
[ "MIT" ]
0.2.0
8a73fe1574e159927031bb2b9cc6ea142f075407
docs
1885
# Statistics Collection of low-level, pure-julia, efficient functions for computing **statistics** and **data transformations**. These functions are heavely used internally by the package. You do not need them to carry out permutation tests, however they are exported because they may turn useful. For general usage of this package you can skip this page altogheter. ## Scalars functions of vectors (statistics) | Function | descriptiion | expression | |:--------|:---------------------|:---------------------| |[`∑`](@ref)(x) |sum| ``\sum_{i=1}^{N}x_i``| |[`∑of²`](@ref)(x) |sum of squares| ``\sum_{i=1}^{N}x_i^2``| |[`∑∑of²`](@ref)(x) |sum and sum of squares| ``\sum_{i=1}^{N}x_i`` and ``\sum_{i=1}^{N}x_i^2`` in one pass | |[`μ`](@ref)(x) |mean| ``\frac{1}{N} \sum_{i=1}^{N}x_i`` | |[`dispersion`](@ref)(x) |sum of squared deviations| ``\sum_{i=1}^{N}(x_i- \mu (x))^2`` | |[`σ²`](@ref)(x) |variance| ``\frac{1}{N} \sum_{i=1}^{N}(x_i- \mu (x))^2`` | |[`σ`](@ref)(x) |standard deviation | ``\sqrt{\sigma^2(x)}`` | |[`∑`](@ref)(x, y) | sum of (x + y) | ``\sum_{i=1}^{N}(x_i+y_i)`` | |[`Π`](@ref)(c) | product |``\prod_{i=1}^{N}x_i``| |[`∑ofΠ`](@ref)(x, y) | inner product of two vectors| ``x \cdot y = \sum_{i=1}^{N}(x_i \cdot y_i)``| ## Vector functions of vectors (data transformations) | Function | descriptiion | |:--------|:---------------------| |[`μ0`](@ref)(x) | recenter (zero mean): ``x_i \gets x_i- \mu (x), \forall i=1 \dots N`` | |[`σ1`](@ref)(x) | equalize (unit standard deviation): ``x_i \gets \frac{x_i}{\sigma (x)}, \forall i=1 \dots N`` | |[`μ0σ1`](@ref)(x) | standardize (zero mean and unit standard deviation): ``x_i \gets \frac{x_i- \mu (x)}{\sigma (x)}, \forall i=1 \dots N`` | ```@docs ∑ ∑of² ∑∑of² μ dispersion σ² σ Π ∑ofΠ ``` --- ```@docs μ0 σ1 μ0σ1 ```
PermutationTests
https://github.com/Marco-Congedo/PermutationTests.jl.git
[ "MIT" ]
0.2.0
8a73fe1574e159927031bb2b9cc6ea142f075407
docs
553
# Test statistics The test statistics used by *PermutationTests.jl* are computed by the several methods of the `statistic` function listed here below. You do not need to use them to carry out permutation tests, however they are exported because they may turn useful. For general usage of this package you can skip this page. All `statistic` methods take a singleton of the [Statistic](@ref) type and other arguments to yield a specific test-statistic. All test statistics are grouped in four [Statistic groups](@ref). --- ```@docs statistic ```
PermutationTests
https://github.com/Marco-Congedo/PermutationTests.jl.git
[ "MIT" ]
0.2.0
8a73fe1574e159927031bb2b9cc6ea142f075407
docs
964
# Tools Collection of utilities. At times, you will be referred to this page by the documentation, but for general usage of this package you can skip this page. --- ## ns The argument `ns` is often employed in the functions below, but also by some functions carrying out permutation tests. This argument is special to each [group of statistics](@ref "Statistic groups"). In the table here below ``N`` denotes the number of observations and ``K`` the number of groups or measurements: | Statistics group | `ns` argument | |:------------------|:--------------| |`BivStatistic` | an integer indicating the number of bivariate observations ``N`` | |`IndSampStatistic` | a vector of integers, holding the group numerosity ``[N_1,..., N_K]`` | |`RepMeasStatistic` | a tuple with form ``ns=(n=N, k=K)`` | |`OneSampStatistic` | an integer indicating the number of observations ``N`` | --- ```@docs assignment eqStat allPerms nrPerms genPerms table2vec ```
PermutationTests
https://github.com/Marco-Congedo/PermutationTests.jl.git
[ "MIT" ]
0.2.0
8a73fe1574e159927031bb2b9cc6ea142f075407
docs
3689
# Univariate tests They are used when a single null hypothesis is to be tested. The following tests are available. --- #### Univariate test functions | Test | Function | Alias | |:-----|:----------------|:---------------| | Pearson correlation | [`correlationTest`](@ref)| `rTest`| | Trend correlation | [`trendTest`](@ref)| | | Point bi-serial correlation | [`pointBiSerialTest`](@ref) | | | Student's t for independent samples | [`studentTestIS`](@ref) | `tTestIS` | | 1-way ANOVA for independent samples | [`anovaTestIS`](@ref) | `fTestIS` | | Chi-squared | [`chiSquaredTest`](@ref) | `Χ²Test` | | Fisher exact| [`fisherExactTest`](@ref)| | | Student's t for repeated measures | [`studentTestRM`](@ref) | `tTestRM` | | 1-way ANOVA for repeated measures | [`anovaTestRM`](@ref) | `fTestRM` | | Cochran Q | [`cochranqTest`](@ref) | `qTest` | | McNemar| [`mcNemarTest`](@ref)| | | One-sample Student's t | [`studentTest1S`](@ref) | `tTest1S` | | Sign | [`signTest`](@ref) | | You may also find useful the tests we have created as examples of how to create new tests: | Test | |:----------| | [Autocorrelation](@ref "Example 1: univariate autocorrelation test") | | [Chatterjee correlation](@ref "Example 5: univariate Chatterjee correlation") | | [Distance correlation](@ref "Example 7: univariate distance correlation") | --- For creating other tests, see [Create your own test](@ref). For multiple comparisons tests, see [Multiple comparisons tests](@ref). --- #### Common kwargs for univariate tests The following optional keyword arguments are common to all univariate test functions: - `direction`: an instance of [TestDirection](@ref), either `Right()`, `Left()` or `Both()`. The default is `Both()`. - `equivalent`: a boolean. If `true` (default), the fastest equivalent statistic will be used. See [Statistic](@ref). - `nperm`: an integer providing the number of random permutations to be used for an approximate test. It defaults to `20000`. - `switch2rand`: an integer setting the upper limit of permutations to be listed exhaustively. It defaults to `1e8`. If the number of possible permutations exceeds `switch2rand`, the approximate test with `nperm` random permutations will be performed, otherwise an exact test with all possible permutations will be performed. In order to force an approximate test, set `switch2rand` to a small integer such as `1`. In order to know in advance the number of possible permutations, see [`nrPerms`](@ref). - `seed`: an integer. It applies only to approximate tests. Set to `0` to use a random seed for generating random permutations. Any natural number results instead in a reproducible test. It defaults to `1234`. - `verbose`: a boolean. Print some information in the REPL while running the test. Set to false if you run benchmarks. The default is `true`. --- #### Univariate tests API --- ## Correlation test ```@docs correlationTest correlationTest! ``` --- ## Trend test ```@docs trendTest trendTest! ``` --- ## Point bi-serial correlation test ```@docs pointBiSerialTest ``` --- ## Student's t-test for independent samples ```@docs studentTestIS ``` --- ## 1-way ANOVA for independent samples ```@docs anovaTestIS ``` --- ## Chi-squared test ```@docs chiSquaredTest ``` --- ## Fisher exact test ```@docs fisherExactTest ``` --- ## Student's t-test for repeated measures ```@docs studentTestRM studentTestRM! ``` --- ## 1-way ANOVA for repeated measures ```@docs anovaTestRM ``` --- ## Cochran Q test ```@docs cochranqTest ``` --- ## McNemar test ```@docs mcNemarTest ``` --- ## One-sample Student's t-test ```@docs studentTest1S studentTest1S! ``` --- ## Sign test ```@docs signTest ```
PermutationTests
https://github.com/Marco-Congedo/PermutationTests.jl.git
[ "MIT" ]
0.8.2
ee1b863b5c9913ba40df8cd3bd7bb58837fb24c2
code
800
using SimJulia, Distributions, BenchmarkTools function exp_source(sim::Simulation, lambd::Float64, server::Resource, mu::Float64) while true dt = rand(Exponential(1/lambd)) yield(timeout(sim, dt)) @oldprocess customer(sim, server, mu) end end function customer(sim::Simulation, server::Resource, mu::Float64) yield(request(server)) dt = rand(Exponential(1/mu)) yield(timeout(sim, dt)) yield(release(server)) end function customer2(sim::Simulation, server::Resource, mu::Float64) request(server) do req yield(req) dt = rand(Exponential(1/mu)) yield(timeout(sim, dt)) end end function test_mm1(n::Float64) sim = Simulation() server = Resource(sim) @oldprocess exp_source(sim, 1.0, server, 1.1) run(sim, n) end test_mm1(100.0) @btime test_mm1(100.0)
SimJulia
https://github.com/JuliaDynamics/ConcurrentSim.jl.git
[ "MIT" ]
0.8.2
ee1b863b5c9913ba40df8cd3bd7bb58837fb24c2
code
276
using SimJulia, BenchmarkTools function fibonnaci(sim::Simulation) a = 0.0 b = 1.0 while true yield(timeout(sim, 1)) a, b = b, a+b end end function run_test() sim = Simulation() @oldprocess fibonnaci(sim) run(sim, 10) end run_test() @btime run_test()
SimJulia
https://github.com/JuliaDynamics/ConcurrentSim.jl.git
[ "MIT" ]
0.8.2
ee1b863b5c9913ba40df8cd3bd7bb58837fb24c2
code
661
using ResumableFunctions, SimJulia, Distributions, BenchmarkTools @resumable function exp_source(sim::Simulation, lambd::Float64, server::Resource, mu::Float64) while true dt = rand(Exponential(1 / lambd)) @yield timeout(sim, dt) @process customer(sim, server, mu) end end @resumable function customer(sim::Simulation, server::Resource, mu::Float64) @yield request(server) dt = rand(Exponential(1 / mu)) @yield timeout(sim, dt) @yield release(server) end function test_mm1(n::Float64) sim = Simulation() server = Resource(sim) @process exp_source(sim, 1.0, server, 1.1) run(sim, n) end test_mm1(100.0) @btime test_mm1(100.0)
SimJulia
https://github.com/JuliaDynamics/ConcurrentSim.jl.git
[ "MIT" ]
0.8.2
ee1b863b5c9913ba40df8cd3bd7bb58837fb24c2
code
304
using ResumableFunctions, SimJulia, BenchmarkTools @resumable function fibonnaci(sim::Simulation) a = 0.0 b = 1.0 while true @yield timeout(sim, 1) a, b = b, a+b end end function run_test() sim = Simulation() @process fibonnaci(sim) run(sim, 10) end run_test() @btime run_test()
SimJulia
https://github.com/JuliaDynamics/ConcurrentSim.jl.git
[ "MIT" ]
0.8.2
ee1b863b5c9913ba40df8cd3bd7bb58837fb24c2
code
576
using Documenter using ResumableFunctions using SimJulia makedocs( sitename = "SimJulia", authors = "Ben Lauwens", pages = [ "Home" => "index.md", "Tutorial" => "tutorial.md", "Topical Guides" => ["Basics" => "guides/basics.md", "Environments" => "guides/environments.md", "Events" => "guides/events.md",], "Examples" => ["Ross" => "examples/ross.md", "Latency" => "examples/Latency.md"], "API" => "api.md" ] ) deploydocs( repo = "github.com/BenLauwens/SimJulia.jl.git" )
SimJulia
https://github.com/JuliaDynamics/ConcurrentSim.jl.git
[ "MIT" ]
0.8.2
ee1b863b5c9913ba40df8cd3bd7bb58837fb24c2
code
973
""" Main module for SimJulia.jl – a discrete event process oriented simulation framework for Julia. """ module SimJulia using DataStructures using Dates using ResumableFunctions import Base.run, Base.isless, Base.show, Base.yield, Base.get import Base.(&), Base.(|) import Dates.now export AbstractEvent, Environment, value, state, environment export Event, succeed, fail, @callback, remove_callback export timeout export Operator, (&), (|), AllOf, AnyOf export @resumable, @yield export AbstractProcess, Simulation, run, now, active_process, StopSimulation export Process, @process, interrupt export Container, Resource, Store, put, get, request, release, cancel export nowDatetime include("base.jl") include("events.jl") include("operators.jl") include("simulations.jl") include("processes.jl") include("resources/base.jl") include("resources/containers.jl") include("resources/stores.jl") include("utils/time.jl") end
SimJulia
https://github.com/JuliaDynamics/ConcurrentSim.jl.git
[ "MIT" ]
0.8.2
ee1b863b5c9913ba40df8cd3bd7bb58837fb24c2
code
2321
abstract type AbstractEvent end abstract type Environment end @enum EVENT_STATE idle=0 scheduled=1 processed=2 struct EventProcessed <: Exception ev :: AbstractEvent end struct EventNotIdle <: Exception ev :: AbstractEvent end mutable struct BaseEvent env :: Environment id :: UInt callbacks :: Vector{Function} state :: EVENT_STATE value :: Any function BaseEvent(env::Environment) new(env, env.eid+=one(UInt), Vector{Function}(), idle, nothing) end end function show(io::IO, ev::AbstractEvent) print(io, "$(typeof(ev)) $(ev.bev.id)") end function show(io::IO, env::Environment) if env.active_proc === nothing print(io, "$(typeof(env)) time: $(now(env)) active_process: nothing") else print(io, "$(typeof(env)) time: $(now(env)) active_process: $(env.active_proc)") end end function environment(ev::AbstractEvent) :: Environment ev.bev.env end function value(ev::AbstractEvent) :: Any ev.bev.value end function state(ev::AbstractEvent) :: EVENT_STATE ev.bev.state end function append_callback(func::Function, ev::AbstractEvent, args::Any...) :: Function ev.bev.state === processed && throw(EventProcessed(ev)) cb = ()->func(ev, args...) push!(ev.bev.callbacks, cb) cb end macro callback(expr::Expr) expr.head !== :call && error("Expression is not a function call!") esc(:(SimJulia.append_callback($(expr.args...)))) end function remove_callback(cb::Function, ev::AbstractEvent) i = findfirst(x -> x == cb, ev.bev.callbacks) i != 0 && deleteat!(ev.bev.callbacks, i) end function schedule(ev::AbstractEvent, delay::Number=zero(Float64); priority::Int=0, value::Any=nothing) state(ev) === processed && throw(EventProcessed(ev)) env = environment(ev) bev = ev.bev bev.value = value env.heap[bev] = EventKey(now(env) + delay, priority, env.sid+=one(UInt)) bev.state = scheduled ev end struct StopSimulation <: Exception value :: Any function StopSimulation(value::Any=nothing) new(value) end end function stop_simulation(ev::AbstractEvent) throw(StopSimulation(value(ev))) end function run(env::Environment, until::AbstractEvent) @callback stop_simulation(until) try while true step(env) end catch exc if isa(exc, StopSimulation) return exc.value else rethrow(exc) end end end
SimJulia
https://github.com/JuliaDynamics/ConcurrentSim.jl.git
[ "MIT" ]
0.8.2
ee1b863b5c9913ba40df8cd3bd7bb58837fb24c2
code
798
struct Event <: AbstractEvent bev :: BaseEvent function Event(env::Environment) new(BaseEvent(env)) end end function succeed(ev::Event; priority::Int=0, value::Any=nothing) :: Event state(ev) !== idle && throw(EventNotIdle(ev)) schedule(ev; priority=priority, value=value) end function fail(ev::Event, exc::Exception; priority::Int=0) :: Event succeed(ev; priority=priority, value=exc) end struct Timeout <: AbstractEvent bev :: BaseEvent function Timeout(env::Environment) new(BaseEvent(env)) end end function timeout(env::Environment, delay::Number=0; priority::Int=0, value::Any=nothing) schedule(Timeout(env), delay; priority=priority, value=value) end function run(env::Environment, until::Number=typemax(Float64)) run(env, timeout(env, until-now(env))) end
SimJulia
https://github.com/JuliaDynamics/ConcurrentSim.jl.git
[ "MIT" ]
0.8.2
ee1b863b5c9913ba40df8cd3bd7bb58837fb24c2
code
1679
struct StateValue state :: EVENT_STATE value :: Any function StateValue(state::EVENT_STATE, value::Any=nothing) new(state, value) end end struct Operator <: AbstractEvent bev :: BaseEvent eval :: Function function Operator(eval::Function, fev::AbstractEvent, events::AbstractEvent...) env = environment(fev) op = new(BaseEvent(env), eval) event_state_values = Dict{AbstractEvent, StateValue}() for ev in tuple(fev, events...) event_state_values[ev] = StateValue(state(ev)) @callback check(ev, op, event_state_values) end op end end function check(ev::AbstractEvent, op::Operator, event_state_values::Dict{AbstractEvent, StateValue}) val = value(ev) if state(op) === idle if isa(val, Exception) schedule(op; value=val) else event_state_values[ev] = StateValue(state(ev), val) op.eval(collect(values(event_state_values))) && schedule(op; value=event_state_values) end elseif state(op) === scheduled if isa(val, Exception) schedule(op; priority=typemax(Int), value=val) else event_state_values[ev] = StateValue(state(ev), val) end end end function eval_and(state_values::Vector{StateValue}) all(map((sv)->sv.state === processed, state_values)) end function eval_or(state_values::Vector{StateValue}) any(map((sv)->sv.state === processed, state_values)) end function (&)(ev1::AbstractEvent, ev2::AbstractEvent) Operator(eval_and, ev1, ev2) end function (|)(ev1::AbstractEvent, ev2::AbstractEvent) Operator(eval_or, ev1, ev2) end function AllOf(events...) Operator(eval_and,events...) end function AnyOf(events...) Operator(eval_or,events...) end
SimJulia
https://github.com/JuliaDynamics/ConcurrentSim.jl.git
[ "MIT" ]
0.8.2
ee1b863b5c9913ba40df8cd3bd7bb58837fb24c2
code
1814
struct Initialize <: AbstractEvent bev :: BaseEvent function Initialize(env::Environment) new(BaseEvent(env)) end end mutable struct Process <: DiscreteProcess bev :: BaseEvent fsmi :: ResumableFunctions.FiniteStateMachineIterator target :: AbstractEvent resume :: Function function Process(func::Function, env::Environment, args...; kwargs...) proc = new() proc.bev = BaseEvent(env) proc.fsmi = func(env, args...; kwargs...) proc.target = schedule(Initialize(env)) proc.resume = @callback execute(proc.target, proc) proc end end macro process(expr) expr.head !== :call && error("Expression is not a function call!") esc(:(Process($(expr.args...)))) end function execute(ev::AbstractEvent, proc::Process) try env = environment(ev) set_active_process(env, proc) target = proc.fsmi(value(ev)) reset_active_process(env) if proc.fsmi._state === 0xff schedule(proc; value=target) else proc.target = state(target) == processed ? timeout(env; value=value(target)) : target proc.resume = @callback execute(proc.target, proc) end catch exc rethrow(exc) end end struct Interrupt <: AbstractEvent bev :: BaseEvent function Interrupt(env::Environment) new(BaseEvent(env)) end end function execute_interrupt(ev::Interrupt, proc::Process) remove_callback(proc.resume, proc.target) execute(ev, proc) end function interrupt(proc::Process, cause::Any=nothing) env = environment(proc) if proc.fsmi._state !== 0xff proc.target isa Initialize && schedule(proc.target; priority=typemax(Int)) target = schedule(Interrupt(env); priority=typemax(Int), value=InterruptException(active_process(env), cause)) @callback execute_interrupt(target, proc) end timeout(env; priority=typemax(Int)) end
SimJulia
https://github.com/JuliaDynamics/ConcurrentSim.jl.git
[ "MIT" ]
0.8.2
ee1b863b5c9913ba40df8cd3bd7bb58837fb24c2
code
1497
abstract type AbstractProcess <: AbstractEvent end abstract type DiscreteProcess <: AbstractProcess end struct InterruptException <: Exception by :: AbstractProcess cause :: Any end struct EmptySchedule <: Exception end struct EventKey time :: Float64 priority :: Int id :: UInt end function isless(a::EventKey, b::EventKey) :: Bool (a.time < b.time) || (a.time === b.time && a.priority > b.priority) || (a.time === b.time && a.priority === b.priority && a.id < b.id) end mutable struct Simulation <: Environment time :: Float64 heap :: DataStructures.PriorityQueue{BaseEvent, EventKey} eid :: UInt sid :: UInt active_proc :: Union{AbstractProcess, Nothing} function Simulation(initial_time::Number=zero(Float64)) new(initial_time, DataStructures.PriorityQueue{BaseEvent, EventKey}(), zero(UInt), zero(UInt), nothing) end end function step(sim::Simulation) isempty(sim.heap) && throw(EmptySchedule()) (bev, key) = DataStructures.peek(sim.heap) DataStructures.dequeue!(sim.heap) sim.time = key.time bev.state = processed for callback in bev.callbacks callback() end end function now(sim::Simulation) sim.time end function now(ev::AbstractEvent) return now(environment(ev)) end function active_process(sim::Simulation) :: AbstractProcess sim.active_proc end function reset_active_process(sim::Simulation) sim.active_proc = nothing end function set_active_process(sim::Simulation, proc::AbstractProcess) sim.active_proc = proc end
SimJulia
https://github.com/JuliaDynamics/ConcurrentSim.jl.git
[ "MIT" ]
0.8.2
ee1b863b5c9913ba40df8cd3bd7bb58837fb24c2
code
1522
abstract type ResourceKey end abstract type AbstractResource end function show(io::IO, res::AbstractResource) print(io, "$(typeof(res))") end abstract type ResourceEvent <: AbstractEvent end struct Put <: ResourceEvent bev :: BaseEvent function Put(env::Environment) new(BaseEvent(env)) end end struct Get <: ResourceEvent bev :: BaseEvent function Get(env::Environment) new(BaseEvent(env)) end end function isless(a::ResourceKey, b::ResourceKey) (a.priority < b.priority) || (a.priority === b.priority && a.id < b.id) end function trigger_put(put_ev::ResourceEvent, res::AbstractResource) queue = DataStructures.PriorityQueue(res.put_queue) while length(queue) > 0 (put_ev, key) = DataStructures.peek(queue) proceed = do_put(res, put_ev, key) state(put_ev) === scheduled && DataStructures.dequeue!(res.put_queue, put_ev) proceed ? DataStructures.dequeue!(queue) : break end end function trigger_get(get_ev::ResourceEvent, res::AbstractResource) queue = DataStructures.PriorityQueue(res.get_queue) while length(queue) > 0 (get_ev, key) = DataStructures.peek(queue) proceed = do_get(res, get_ev, key) state(get_ev) === scheduled && DataStructures.dequeue!(res.get_queue, get_ev) proceed ? DataStructures.dequeue!(queue) : break end end function cancel(res::AbstractResource, put_ev::Put) DataStructures.dequeue!(res.put_queue, put_ev) end function cancel(res::AbstractResource, get_ev::Get) DataStructures.dequeue!(res.get_queue, get_ev) end
SimJulia
https://github.com/JuliaDynamics/ConcurrentSim.jl.git
[ "MIT" ]
0.8.2
ee1b863b5c9913ba40df8cd3bd7bb58837fb24c2
code
1816
struct ContainerKey{N<:Real} <: ResourceKey priority :: Int id :: UInt amount :: N end mutable struct Container{N<:Real} <: AbstractResource env :: Environment capacity :: N level :: N seid :: UInt put_queue :: DataStructures.PriorityQueue{Put, ContainerKey{N}} get_queue :: DataStructures.PriorityQueue{Get, ContainerKey{N}} function Container{N}(env::Environment, capacity::N=one(N); level::N=zero(N)) where {N<:Real} new(env, capacity, level, zero(UInt), DataStructures.PriorityQueue{Put, ContainerKey{N}}(), DataStructures.PriorityQueue{Get, ContainerKey{N}}()) end end function Container(env::Environment, capacity::N=one(N); level::N=zero(N)) where N<:Real Container{N}(env, capacity, level=level) end const Resource = Container{Int} function put(con::Container{N}, amount::N; priority::Int=0) where N<:Real put_ev = Put(con.env) con.put_queue[put_ev] = ContainerKey(priority, con.seid+=one(UInt), amount) @callback trigger_get(put_ev, con) trigger_put(put_ev, con) put_ev end request(res::Resource; priority::Int=0) = put(res, 1; priority=priority) function get(con::Container{N}, amount::N; priority::Int=0) where N<:Real get_ev = Get(con.env) con.get_queue[get_ev] = ContainerKey(priority, con.seid+=one(UInt), amount) @callback trigger_put(get_ev, con) trigger_get(get_ev, con) get_ev end release(res::Resource; priority::Int=0) = get(res, 1; priority=priority) function do_put(con::Container{N}, put_ev::Put, key::ContainerKey{N}) where N<:Real con.level + key.amount > con.capacity && return false schedule(put_ev) con.level += key.amount true end function do_get(con::Container{N}, get_ev::Get, key::ContainerKey{N}) where N<:Real con.level - key.amount < zero(N) && return false schedule(get_ev) con.level -= key.amount true end
SimJulia
https://github.com/JuliaDynamics/ConcurrentSim.jl.git
[ "MIT" ]
0.8.2
ee1b863b5c9913ba40df8cd3bd7bb58837fb24c2
code
1912
struct StorePutKey{T} <: ResourceKey priority :: Int id :: UInt item :: T StorePutKey{T}(priority, id, item) where T = new(priority, id, item) end struct StoreGetKey <: ResourceKey priority :: Int id :: UInt filter :: Function end mutable struct Store{T} <: AbstractResource env :: Environment capacity :: UInt load :: UInt items :: Dict{T, UInt} seid :: UInt put_queue :: DataStructures.PriorityQueue{Put, StorePutKey{T}} get_queue :: DataStructures.PriorityQueue{Get, StoreGetKey} function Store{T}(env::Environment; capacity::UInt=typemax(UInt)) where {T} new(env, capacity, zero(UInt), Dict{T, UInt}(), zero(UInt), DataStructures.PriorityQueue{Put, StorePutKey{T}}(), DataStructures.PriorityQueue{Get, StoreGetKey}()) end end function put(sto::Store{T}, item::T; priority::Int=0) where T put_ev = Put(sto.env) sto.put_queue[put_ev] = StorePutKey{T}(priority, sto.seid+=one(UInt), item) @callback trigger_get(put_ev, sto) trigger_put(put_ev, sto) put_ev end get_any_item(::T) where T = true function get(sto::Store{T}, filter::Function=get_any_item; priority::Int=0) where T get_ev = Get(sto.env) sto.get_queue[get_ev] = StoreGetKey(priority, sto.seid+=one(UInt), filter) @callback trigger_put(get_ev, sto) trigger_get(get_ev, sto) get_ev end function do_put(sto::Store{T}, put_ev::Put, key::StorePutKey{T}) where {T} if sto.load < sto.capacity sto.load += one(UInt) sto.items[key.item] = get(sto.items, key.item, zero(UInt)) + one(UInt) schedule(put_ev) end false end function do_get(sto::Store{T}, get_ev::Get, key::StoreGetKey) where {T} for (item, number) in sto.items if key.filter(item) sto.load -= one(UInt) if number === one(UInt) delete!(sto.items, item) else sto.items[item] = number - one(UInt) end schedule(get_ev; value=item) break end end true end
SimJulia
https://github.com/JuliaDynamics/ConcurrentSim.jl.git
[ "MIT" ]
0.8.2
ee1b863b5c9913ba40df8cd3bd7bb58837fb24c2
code
507
function Simulation(initial_time::DateTime) Simulation(Dates.datetime2epochms(initial_time)) end function run(env::Environment, until::DateTime) run(env, Dates.datetime2epochms(until)) end function timeout(env::Environment, delay::Period; priority::Int=0, value::Any=nothing) time = now(env) del = Dates.datetime2epochms(Dates.epochms2datetime(time)+delay)-time timeout(env, del; priority=priority, value=value) end function nowDatetime(env::Environment) Dates.epochms2datetime(now(env)) end
SimJulia
https://github.com/JuliaDynamics/ConcurrentSim.jl.git
[ "MIT" ]
0.8.2
ee1b863b5c9913ba40df8cd3bd7bb58837fb24c2
code
508
using SimJulia function test_callback(ev::Event) println("I am a callback function running in $(typeof(environment(ev)))") end sim = Simulation() ev = Event(sim) println(typeof(ev)) cb = @callback test_callback(ev) remove_callback(cb, ev) println(state(ev)) show(value(ev)) println() succeed(ev, value="Hi") @callback test_callback(ev) println(state(ev)) println(value(ev)) run(sim) try @callback test_callback(ev) catch exc println("$exc has been thrown!") end println(state(ev)) println(value(ev))
SimJulia
https://github.com/JuliaDynamics/ConcurrentSim.jl.git
[ "MIT" ]
0.8.2
ee1b863b5c9913ba40df8cd3bd7bb58837fb24c2
code
560
using SimJulia struct TestException <: Exception end function test_callback_event(ev::Event) println("Hi $ev has value $(value(ev))") end function test_callback_Timeout(ev::AbstractEvent) println("Hi $ev timed out at $(now(environment(ev)))") end sim = Simulation() ev1 = Event(sim) @callback test_callback_event(ev1) succeed(ev1, value="Succes") ev2 = Event(sim) @callback test_callback_event(ev2) fail(ev2, TestException()) try succeed(ev2) catch exc println("$exc has been thrown!") end @callback test_callback_Timeout(timeout(sim, 1)) run(sim)
SimJulia
https://github.com/JuliaDynamics/ConcurrentSim.jl.git
[ "MIT" ]
0.8.2
ee1b863b5c9913ba40df8cd3bd7bb58837fb24c2
code
1744
using SimJulia function and_callback(ev::AbstractEvent) println("Both events are triggered: $(value(ev))") end function or_callback(ev::AbstractEvent) println("One of both events is triggered: $(value(ev))") end function or_callback_succeed(ev::AbstractEvent, ev2::AbstractEvent) println("One of both events is triggered: $(value(ev))") succeed(ev2) end function or_callback_fail(ev::AbstractEvent, ev2::AbstractEvent) println("One of both events is triggered: $(value(ev))") fail(ev2, TestException()) end sim = Simulation() ev1 = timeout(sim, 1) ev2 = Event(sim) @callback and_callback(ev1 & ev2) @callback or_callback_succeed(ev1 | ev2, ev2) run(sim) sim = Simulation() ev1 = timeout(sim, 1, value=TestException()) ev2 = Event(sim) @callback or_callback_fail(ev1 | ev2, ev2) @callback and_callback(ev1 & ev2) run(sim) sim = Simulation() ev1 = timeout(sim) ev2 = timeout(sim, value=TestException()) @callback or_callback(ev1 | ev2) run(sim) sim = Simulation() ev1 = timeout(sim) ev2 = timeout(sim) @callback or_callback(ev1 | ev2) run(sim) sim = Simulation() ev1 = timeout(sim, 1) ev2 = Event(sim) ev3 = timeout(sim, 2) @callback and_callback(AllOf(ev1, ev2, ev3)) @callback or_callback_succeed(AnyOf(ev1, ev2, ev3), ev2) run(sim) sim = Simulation() ev1 = timeout(sim, 1, value=TestException()) ev2 = Event(sim) ev3 = Event(sim) @callback or_callback_fail(AnyOf(ev1, ev2, ev3), ev2) @callback and_callback(AllOf(ev1, ev2, ev3)) run(sim) sim = Simulation() ev1 = timeout(sim) ev2 = timeout(sim, value=TestException()) ev3 = timeout(sim) @callback or_callback(AnyOf(ev1, ev2, ev3)) run(sim) sim = Simulation() ev1 = timeout(sim) ev2 = timeout(sim) ev3 = timeout(sim) @callback or_callback(AnyOf(ev1, ev2, ev3)) run(sim)
SimJulia
https://github.com/JuliaDynamics/ConcurrentSim.jl.git
[ "MIT" ]
0.8.2
ee1b863b5c9913ba40df8cd3bd7bb58837fb24c2
code
1398
using SimJulia using ResumableFunctions @resumable function fibonnaci(sim::Simulation) a = 0 b = 1 while true println(a) @yield timeout(sim, 1) a, b = b, a+b end end @resumable function test_process(sim::Simulation, ev::AbstractEvent) @yield ev end @resumable function test_process_exception(sim::Simulation, ev::AbstractEvent) try value = @yield ev catch exc println("$exc has been thrown") end end @resumable function test_interrupter(sim::Simulation, proc::Process) @yield timeout(sim, 2) @yield interrupt(proc) end @resumable function test_interrupted(sim::Simulation) try @yield timeout(sim, 10) catch exc if isa(exc, SimJulia.InterruptException) println("$(active_process(sim)) interrupted") end end @yield timeout(sim, 10) throw(TestException()) end sim = Simulation() @process fibonnaci(sim) println(sim) run(sim, 10) sim = Simulation() @process test_process(sim, succeed(Event(sim))) run(sim) sim = Simulation() @process test_process_exception(sim, timeout(sim, 1, value=TestException())) try run(sim) catch exc println("$exc has been thrown") end sim = Simulation() @process test_process_exception(sim, timeout(sim, value=TestException())) run(sim) sim = Simulation() proc = @process test_interrupted(sim) @process test_interrupter(sim, proc) try run(sim) catch exc println("$exc has been thrown") end
SimJulia
https://github.com/JuliaDynamics/ConcurrentSim.jl.git
[ "MIT" ]
0.8.2
ee1b863b5c9913ba40df8cd3bd7bb58837fb24c2
code
262
testpath(f) = joinpath(dirname(@__FILE__), f) for test_file in [ "base.jl", "events.jl", "operators.jl", "simulations.jl", "processes.jl", "resources/containers.jl", "resources/stores.jl", "utils/time.jl", ] include(testpath(test_file)) end
SimJulia
https://github.com/JuliaDynamics/ConcurrentSim.jl.git
[ "MIT" ]
0.8.2
ee1b863b5c9913ba40df8cd3bd7bb58837fb24c2
code
761
using SimJulia struct TestException <: Exception end function test_callback(ev::AbstractEvent) println("Hi I timed out at $(now(ev))") end function test_callback_exception(ev::Event) throw(TestException()) end sim = Simulation() @callback test_callback(timeout(sim, 1)) @callback test_callback(timeout(sim, 3)) run(sim, 2) sim = Simulation() try run(sim, Event(sim)) catch exc println("$exc has been thrown!") end sim = Simulation(3) start_time = now(sim) @callback test_callback(timeout(sim, 1)) run(sim, start_time+2) println(now(sim)-start_time) sim = Simulation() start_time = now(sim) ev = Event(sim) @callback test_callback_exception(ev) succeed(ev) try run(sim) catch exc println("$exc has been thrown after $(now(sim)-start_time)!") end
SimJulia
https://github.com/JuliaDynamics/ConcurrentSim.jl.git
[ "MIT" ]
0.8.2
ee1b863b5c9913ba40df8cd3bd7bb58837fb24c2
code
1685
using SimJulia @resumable function client(sim::Simulation, res::Resource, i::Int, priority::Int) println("$(now(sim)), client $i is waiting") @yield request(res, priority=priority) println("$(now(sim)), client $i is being served") @yield timeout(sim, rand()) println("$(now(sim)), client $i has been served") @yield release(res) end @resumable function generate(sim::Simulation, res::Resource) for i in 1:10 @process client(sim, res, i, 10-i) @yield timeout(sim, 0.5*rand()) end end sim = Simulation() res = Resource(sim, 2; level=1) println(res) @process generate(sim, res) run(sim) @resumable function my_consumer(sim::Simulation, con::Container) for i in 1:10 amount = 3*rand() println("$(now(sim)), consumer is demanding $amount") @yield timeout(sim, 1.0*rand()) get_ev = get(con, amount) val = @yield get_ev | timeout(sim, rand()) if val[get_ev].state == SimJulia.processed println("$(now(sim)), consumer is being served, level is ", con.level) delay = 5.0*rand() @yield timeout(sim, delay) else println("$(now(sim)), consumer has timed out") cancel(con, get_ev) end end end @resumable function my_producer(sim::Simulation, con::Container) for i in 1:10 amount = 2*rand() println("$(now(sim)), producer is offering $amount") @yield timeout(sim, 1.0*rand()) @yield put(con, amount) level = con.level println("$(now(sim)), producer is being served, level is ", level) delay = 5.0*rand() @yield timeout(sim, delay) end end sim = Simulation() con = Container(sim, 10.0; level=5.0) @process my_consumer(sim, con) @process my_producer(sim, con) run(sim)
SimJulia
https://github.com/JuliaDynamics/ConcurrentSim.jl.git
[ "MIT" ]
0.8.2
ee1b863b5c9913ba40df8cd3bd7bb58837fb24c2
code
717
using SimJulia struct StoreObject i :: Int end @resumable function my_consumer(sim::Simulation, sto::Store) for j in 1:10 @yield timeout(sim, rand()) println("$(now(sim)), consumer is demanding object") obj = @yield get(sto) println("$(now(sim)), consumer is being served with object ", obj.i) end end @resumable function my_producer(sim::Simulation, sto::Store) for j in 1:10 println("$(now(sim)), producer is offering object $j") @yield put(sto, StoreObject(j)) println("$(now(sim)), producer is being served") @yield timeout(sim, 2*rand()) end end sim = Simulation() sto = Store{StoreObject}(sim) @process my_consumer(sim, sto) @process my_producer(sim, sto) run(sim)
SimJulia
https://github.com/JuliaDynamics/ConcurrentSim.jl.git
[ "MIT" ]
0.8.2
ee1b863b5c9913ba40df8cd3bd7bb58837fb24c2
code
294
using SimJulia using Dates @resumable function datetimetest(sim::Simulation) println(nowDatetime(sim)) @yield timeout(sim, Day(2)) println(nowDatetime(sim)) end datetime = now() sim = Simulation(datetime) @process datetimetest(sim) run(sim, datetime+Month(3)) println(nowDatetime(sim))
SimJulia
https://github.com/JuliaDynamics/ConcurrentSim.jl.git
[ "MIT" ]
0.8.2
ee1b863b5c9913ba40df8cd3bd7bb58837fb24c2
docs
4258
# SimJulia A discrete event process oriented simulation framework written in [Julia](http://julialang.org/) inspired by the Python library [SimPy](https://simpy.readthedocs.io/). ## Build Status & Coverage [![Build Status](https://github.com/benlauwens/SimJulia.jl/workflows/CI/badge.svg)](https://github.com/benlauwens/SimJulia.jl/actions?query=workflow%3ACI+branch%3Amaster) [![codecov](https://codecov.io/gh/BenLauwens/SimJulia.jl/branch/master/graph/badge.svg)](https://codecov.io/gh/BenLauwens/SimJulia.jl) ## Installation SimJulia.jl is a [registered package](http://pkg.julialang.org), and is installed by running ```julia julia> Pkg.add("SimJulia") ``` ## Documentation [![](https://img.shields.io/badge/docs-stable-blue.svg)](https://BenLauwens.github.io/SimJulia.jl/stable) [![](https://img.shields.io/badge/docs-latest-blue.svg)](https://BenLauwens.github.io/SimJulia.jl/latest) ## License [![License](http://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat)](LICENSE.md) ## Authors * Ben Lauwens, Royal Military Academy, Brussels, Belgium. ## Contributing * To discuss problems or feature requests, file an issue. For bugs, please include as much information as possible, including operating system, julia version, and version of the dependencies: `DataStructures` and `ResumableFunctions`. * To contribute, make a pull request. Contributions should include tests for any new features/bug fixes. ## Release Notes * v0.8.1 (2021) * some minor bug fixes * uses ResumableFunctions v0.6 or higher * v0.8 (2019) * adds support for Julia v1.2. * v0.7 (2018) * adds support for Julia v1.0 * v0.6 (2018) * adds support for Julia v0.7. * the `@oldprocess` macro and the `produce` / `consume` functions are removed because they are no longer supported. * v0.5 (2018) * The old way of making processes is deprecated in favor of the semi-coroutine approach as implemented in [ResumableFunctions](https://github.com/BenLauwens/ResumableFunctions.jl.git). The `@process` macro replaces the `@coroutine` macro. The old `@process` macro is temporarily renamed `@oldprocess` and will be removed when the infrastructure supporting the `produce` and the `consume` functions is no longer available in Julia. (DONE) * This version no longer integrates a continuous time solver. A continuous simulation framework based on [DISCO](http://www.akira.ruc.dk/~keld/research/DISCO/) and inspired by the standalone [QSS](https://sourceforge.net/projects/qssengine/) solver using SimJulia as its discrete-event engine can be found in the repository [QuantizedStateSystems](https://github.com/BenLauwens/QuantizedStateSystems.jl.git) (WIP): * Documentation is automated with [Documenter.jl](https://github.com/JuliaDocs/Documenter.jl) (WIP: Overview and Tutorial OK). * v0.4.1 (2017) * the `@resumable` and `@yield` macros are put in a seperate package [ResumableFunctions](https://github.com/BenLauwens/ResumableFunctions.jl.git): * Users have to take into account the following syntax change: `@yield return arg` is replaced by `@yield arg`. * v0.4 (2017) only supports Julia v0.6 and above. It is a complete rewrite: more julian and less pythonic. The discrete event features are on par with v0.3 (SimPy v3) and following features are added: * Scheduling of events can be done with `Base.Dates.Datetime` and `Base.Dates.Period` * Two ways of making `Processes` are provided: - using the existing concept of `Tasks` - using a novel finite-statemachine approach * A continuous time solver based on the standalone [QSS](https://sourceforge.net/projects/qssengine/) solver is implemented. Only non-stiff systems can be solved efficiently. * v0.3 (2015) synchronizes the API with SimPy v3 and is Julia v0.3, v0.4 and v0.5 compatible: * Documentation is available at [readthedocs](http://simjuliajl.readthedocs.org/en/latest/). * The continuous time solver is not implemented. * v0.2 (2014) introduces a continuous time solver inspired by the Simula library [DISCO](http://www.akira.ruc.dk/~keld/research/DISCO/) and is Julia v0.2 and v0.3 compatible. * v0.1 (2013) is a Julia clone of SimPy v2 and is Julia v0.2 compatible. ## Todo * Transparent statistics gathering for resources. * Update of documentation.
SimJulia
https://github.com/JuliaDynamics/ConcurrentSim.jl.git
[ "MIT" ]
0.8.2
ee1b863b5c9913ba40df8cd3bd7bb58837fb24c2
docs
1927
# Overview SimJulia is a discrete-event process-oriented simulation framework written in [Julia](http://julialang.org/) inspired by the Python library [SimPy](https://simpy.readthedocs.io/). Its process dispatcher is based on semi-coroutines scheduling as implemented in [ResumableFunctions](https://github.com/BenLauwens/ResumableFunctions.jl.git). A `Process` in SimJulia is defined by a `@resumable function` yielding `Events`. SimJulia provides three types of shared resources to model limited capacity congestion points: `Resources`, `Containers` and `Stores`. The API is modeled after the SimPy API but some specific Julia semantics are used. The documentation contains a tutorial, topical guides explaining key concepts, a number of examples and the API reference. The tutorial, the topical guides and some examples are borrowed from SimPy to allow a direct comparison and an easy migration path for users. The differences between SimJulia and SimPy are clearly documented. ## Example A short example simulating two clocks ticking in different time intervals looks like this: ```jldoctest julia> using ResumableFunctions julia> using SimJulia julia> @resumable function clock(sim::Simulation, name::String, tick::Float64) while true println(name, " ", now(sim)) @yield timeout(sim, tick) end end clock (generic function with 1 method) julia> sim = Simulation() SimJulia.Simulation time: 0.0 active_process: nothing julia> @process clock(sim, "fast", 0.5) SimJulia.Process 1 julia> @process clock(sim, "slow", 1.0) SimJulia.Process 3 julia> run(sim, 2) fast 0.0 slow 0.0 fast 0.5 slow 1.0 fast 1.0 fast 1.5 ``` ## Installation SimJulia is a registered package and can be installed by running: ```julia Pkg.add("SimJulia") ``` ## Authors * Ben Lauwens, Royal Military Academy, Brussels, Belgium. ## License SimJulia is licensed under the MIT "Expat" License.
SimJulia
https://github.com/JuliaDynamics/ConcurrentSim.jl.git
[ "MIT" ]
0.8.2
ee1b863b5c9913ba40df8cd3bd7bb58837fb24c2
docs
15094
# Tutorial ## Basic Concepts Simjulia is a discrete-event simulation library. The behavior of active components (like vehicles, customers or messages) is modeled with processes. All processes live in an environment. They interact with the environment and with each other via events. Processes are described by `@resumable` functions. You can call them process function. During their lifetime, they create events and `@yield` them in order to wait for them to be triggered. !!! note Detailed information about the `@resumable` and the `@yield` macros can be found in the documentation of [ResumableFunctions](https://github.com/BenLauwens/ResumableFunctions.jl.git). When a process yields an event, the process gets suspended. SimJulia resumes the process, when the event occurs (we say that the event is triggered). Multiple processes can wait for the same event. SimJulia resumes them in the same order in which they yielded that event. An important event type is the `timeout`. Events of this type are scheduled after a certain amount of (simulated) time has passed. They allow a process to sleep (or hold its state) for the given time. A `timeout` and all other events can be created by calling a constructor having the environment as first argument. ## Our First Process Our first example will be a car process. The car will alternately drive and park for a while. When it starts driving (or parking), it will print the current simulation time. So let’s start: ```jldoctest julia> using ResumableFunctions julia> using SimJulia julia> @resumable function car(env::Environment) while true println("Start parking at ", now(env)) parking_duration = 5 @yield timeout(env, parking_duration) println("Start driving at ", now(env)) trip_duration = 2 @yield timeout(env, trip_duration) end end car (generic function with 1 method) ``` Our car process requires a reference to an `Environment` in order to create new events. The car‘s behavior is described in an infinite loop. Remember, the `car` function is a `@resumable` function. Though it will never terminate, it will pass the control flow back to the simulation once a `@yield` statement is reached. Once the yielded event is triggered (“it occurs”), the simulation will resume the function at this statement. As said before, our car switches between the states parking and driving. It announces its new state by printing a message and the current simulation time (as returned by the function call `now`). It then calls the constructor `timeout` to create a timeout event. This event describes the point in time the car is done parking (or driving, respectively). By yielding the event, it signals the simulation that it wants to wait for the event to occur. Now that the behavior of our car has been modeled, lets create an instance of it and see how it behaves: ```@meta DocTestSetup = quote using ResumableFunctions using SimJulia @resumable function car(env::Environment) while true println("Start parking at ", now(env)) parking_duration = 5 @yield timeout(env, parking_duration) println("Start driving at ", now(env)) trip_duration = 2 @yield timeout(env, trip_duration) end end end ``` ```jldoctest julia> sim = Simulation() SimJulia.Simulation time: 0.0 active_process: nothing julia> @process car(sim) SimJulia.Process 1 julia> run(sim, 15) Start parking at 0.0 Start driving at 5.0 Start parking at 7.0 Start driving at 12.0 Start parking at 14.0 ``` ```@meta DocTestSetup = nothing ``` The first thing we need to do is to create an environment, e.g. an instance of `Simulation`. The macro `@process` having as argument a car process function call creates a process that is initialised and added to the environment automatically. Note, that at this time, none of the code of our process function is being executed. Its execution is merely scheduled at the current simulation time. The `Process` returned by the `@process` macro can be used for process interactions. Finally, we start the simulation by calling `run` and passing an end time to it. ## Process Interaction The `Process` instance that is returned by `@process` macro can be utilized for process interactions. The two most common examples for this are to wait for another process to finish and to interrupt another process while it is waiting for an event. ### Waiting for a Process As it happens, a SimJulia `Process` can be used like an event. If you yield it, you are resumed once the process has finished. Imagine a car-wash simulation where cars enter the car-wash and wait for the washing process to finish, or an airport simulation where passengers have to wait until a security check finishes. Lets assume that the car from our last example is an electric vehicle. Electric vehicles usually take a lot of time charging their batteries after a trip. They have to wait until their battery is charged before they can start driving again. We can model this with an additional charge process for our car. Therefore, we redefine our `car` process function and add a `charge` process function. A new charge process is started every time the vehicle starts parking. By yielding the `Process` instance that the `@process` macro returns, the `run` process starts waiting for it to finish: ```jldoctest julia> using ResumableFunctions julia> using SimJulia julia> @resumable function charge(env::Environment, duration::Number) @yield timeout(env, duration) end charge (generic function with 1 method) julia> @resumable function car(env::Environment) while true println("Start parking and charging at ", now(env)) charge_duration = 5 charge_process = @process charge(sim, charge_duration) @yield charge_process println("Start driving at ", now(env)) trip_duration = 2 @yield timeout(sim, trip_duration) end end car (generic function with 1 method) ``` ```@meta DocTestSetup = quote using ResumableFunctions using SimJulia @resumable function charge(env::Environment, duration::Number) @yield timeout(env, duration) end @resumable function car(env::Environment) while true println("Start parking and charging at ", now(env)) charge_duration = 5 charge_process = @process charge(sim, charge_duration) @yield charge_process println("Start driving at ", now(env)) trip_duration = 2 @yield timeout(sim, trip_duration) end end end ``` Starting the simulation is straightforward again: We create a `Simulation`, one (or more) cars and finally call `run`. ```jldoctest julia> sim = Simulation() SimJulia.Simulation time: 0.0 active_process: nothing julia> @process car(sim) SimJulia.Process 1 julia> run(sim, 15) Start parking and charging at 0.0 Start driving at 5.0 Start parking and charging at 7.0 Start driving at 12.0 Start parking and charging at 14.0 ``` ```@meta DocTestSetup = nothing ``` ### Interrupting Another Process Imagine, you don’t want to wait until your electric vehicle is fully charged but want to interrupt the charging process and just start driving instead. SimJulia allows you to interrupt a running process by calling the `interrupt` function: ```jldoctest julia> using ResumableFunctions julia> using SimJulia julia> @resumable function driver(env::Environment, car_process::Process) @yield timeout(env, 3) @yield interrupt(car_process) end driver (generic function with 1 method) ``` The driver process has a reference to the car process. After waiting for 3 time steps, it interrupts that process. Interrupts are thrown into process functions as `Interrupt` exceptions that can (should) be handled by the interrupted process. The process can then decide what to do next (e.g., continuing to wait for the original event or yielding a new event): ```@meta DocTestSetup = quote using ResumableFunctions using SimJulia end ``` ```jldoctest julia> @resumable function charge(env::Environment, duration::Number) @yield timeout(env, duration) end charge (generic function with 1 method) julia> @resumable function car(env::Environment) while true println("Start parking and charging at ", now(env)) charge_duration = 5 charge_process = @process charge(sim, charge_duration) try @yield charge_process catch println("Was interrupted. Hopefully, the battery is full enough ...") end println("Start driving at ", now(env)) trip_duration = 2 @yield timeout(sim, trip_duration) end end car (generic function with 1 method) ``` When you compare the output of this simulation with the previous example, you’ll notice that the car now starts driving at time 3 instead of 5: ```@meta DocTestSetup = quote using ResumableFunctions using SimJulia @resumable function driver(env::Environment, car_process::Process) @yield timeout(env, 3) @yield interrupt(car_process) end @resumable function charge(env::Environment, duration::Number) @yield timeout(env, duration) end @resumable function car(env::Environment) while true println("Start parking and charging at ", now(env)) charge_duration = 5 charge_process = @process charge(sim, charge_duration) try @yield charge_process catch println("Was interrupted. Hopefully, the battery is full enough ...") end println("Start driving at ", now(env)) trip_duration = 2 @yield timeout(sim, trip_duration) end end end ``` ```jldoctest julia> sim = Simulation() SimJulia.Simulation time: 0.0 active_process: nothing julia> car_process = @process car(sim) SimJulia.Process 1 julia> @process driver(sim, car_process) SimJulia.Process 3 julia> run(sim, 15) Start parking and charging at 0.0 Was interrupted. Hopefully, the battery is full enough ... Start driving at 3.0 Start parking and charging at 5.0 Start driving at 10.0 Start parking and charging at 12.0 ``` ```@meta DocTestSetup = nothing ``` ## Shared Resources SimJulia offers three types of resources that help you modeling problems, where multiple processes want to use a resource of limited capacity (e.g., cars at a fuel station with a limited number of fuel pumps) or classical producer-consumer problems. In this section, we’ll briefly introduce SimJulia’s `Resource` class. ### Basic Resource Usage We’ll slightly modify our electric vehicle process `car` that we introduced in the last sections. The car will now drive to a battery charging station (BCS) and request one of its two charging spots. If both of these spots are currently in use, it waits until one of them becomes available again. It then starts charging its battery and leaves the station afterwards: ```jldoctest julia> using ResumableFunctions julia> using SimJulia julia> @resumable function car(env::Environment, name::Int, bcs::Resource, driving_time::Number, charge_duration::Number) @yield timeout(sim, driving_time) println(name, " arriving at ", now(env)) @yield request(bcs) println(name, " starting to charge at ", now(env)) @yield timeout(sim, charge_duration) println(name, " leaving the bcs at ", now(env)) @yield release(bcs) end car (generic function with 1 method) ``` The resource’s `request` function generates an event that lets you wait until the resource becomes available again. If you are resumed, you “own” the resource until you release it. You are responsible to call `release` once you are done using the resource. When you release a resource, the next waiting process is resumed and now “owns” one of the resource’s slots. The basic `Resource` sorts waiting processes in a FIFO (first in—first out) way. A resource needs a reference to an `Environment` and a capacity when it is created: ```@meta DocTestSetup = quote using ResumableFunctions using SimJulia @resumable function car(env::Environment, name::Int, bcs::Resource, driving_time::Number, charge_duration::Number) @yield timeout(sim, driving_time) println(name, " arriving at ", now(env)) @yield request(bcs) println(name, " starting to charge at ", now(env)) @yield timeout(sim, charge_duration) println(name, " leaving the bcs at ", now(env)) @yield release(bcs) end end ``` ```jldoctest julia> sim = Simulation() SimJulia.Simulation time: 0.0 active_process: nothing julia> bcs = Resource(sim, 2) SimJulia.Container{Int64} ``` We can now create the car processes and pass a reference to our resource as well as some additional parameters to them ```@meta DocTestSetup = quote using ResumableFunctions using SimJulia @resumable function car(env::Environment, name::Int, bcs::Resource, driving_time::Number, charge_duration::Number) @yield timeout(sim, driving_time) println(name, " arriving at ", now(env)) @yield request(bcs) println(name, " starting to charge at ", now(env)) @yield timeout(sim, charge_duration) println(name, " leaving the bcs at ", now(env)) @yield release(bcs) end sim = Simulation() bcs = Resource(sim, 2) end ``` ```jldoctest julia> for i in 1:4 @process car(sim, i, bcs, 2i, 5) end julia> run(sim) 1 arriving at 2.0 1 starting to charge at 2.0 2 arriving at 4.0 2 starting to charge at 4.0 3 arriving at 6.0 1 leaving the bcs at 7.0 3 starting to charge at 7.0 4 arriving at 8.0 2 leaving the bcs at 9.0 4 starting to charge at 9.0 3 leaving the bcs at 12.0 4 leaving the bcs at 14.0 ``` Finally, we can start the simulation. Since the car processes all terminate on their own in this simulation, we don’t need to specify an until time — the simulation will automatically stop when there are no more events left: ```@meta DocTestSetup = quote using ResumableFunctions using SimJulia @resumable function car(env::Environment, name::Int, bcs::Resource, driving_time::Number, charge_duration::Number) @yield timeout(sim, driving_time) println(name, " arriving at ", now(env)) @yield request(bcs) println(name, " starting to charge at ", now(env)) @yield timeout(sim, charge_duration) println(name, " leaving the bcs at ", now(env)) @yield release(bcs) end sim = Simulation() bcs = Resource(sim, 2) for i in 1:4 @process car(sim, i, bcs, 2i, 5) end end ``` ```jldoctest julia> run(sim) 1 arriving at 2.0 1 starting to charge at 2.0 2 arriving at 4.0 2 starting to charge at 4.0 3 arriving at 6.0 1 leaving the bcs at 7.0 3 starting to charge at 7.0 4 arriving at 8.0 2 leaving the bcs at 9.0 4 starting to charge at 9.0 3 leaving the bcs at 12.0 4 leaving the bcs at 14.0 ``` ```@meta DocTestSetup = nothing ``` Note that the first two cars can start charging immediately after they arrive at the BCS, while cars 3 and 4 have to wait.
SimJulia
https://github.com/JuliaDynamics/ConcurrentSim.jl.git
[ "MIT" ]
0.8.2
ee1b863b5c9913ba40df8cd3bd7bb58837fb24c2
docs
3553
# Event Latency ## Description In this example we show how to separate the time delay between processes from the processes themselves. We model a communications channel, called a `Cable`, where a sender sends messages regularly each `SEND_PERIOD` time units and a receiver listens each `RECEIVE_PERIOD`. The messages in the cable have a delay fo `DELAY_DURATION` until they reach the recevier. ### Load Packages ```julia using SimJulia using ResumableFunctions import SimJulia.put import Base.get ``` ### Define Constants ```julia srand(8710) # set random number seed for reproducibility const SIM_DURATION = 100. const SEND_PERIOD = 5.0 const RECEIVE_PERIOD = 3.0; ``` ### Define Cable model The `Cable` contains reference to the simulation it is part of, the delay that messages experience, and a store that contains the sent messages ```julia mutable struct Cable env::Simulation delay::Float64 store::Store{String} function Cable(env::Simulation, delay::Float64) return new(env, delay, Store{String}(env)) end end; ``` The latency function is a generator which yields two events: first a `timeout` that represents the transmission delay, then a put event when the message gets stored in the store. ```julia @resumable function latency(env::Simulation, cable::Cable, value::String) @yield timeout(cable.env, cable.delay) @yield put(cable.store, value) end; ``` The `put` and `get` functions allow interaction with the cable (note that these are not `@resumable` because they need to return the result of the operation and not the operation itself). ```julia function put(cable::Cable, value::String) @process latency(cable.env, cable, value) # results in the scheduling of all events generated by latency end function get(cable::Cable) get(cable.store) # returns an element stored in the cable store end; ``` The `sender` and `receiver` generators yield events to the simulator. ```julia @resumable function sender(env::Simulation, cable::Cable) while true @yield timeout(env, SEND_PERIOD) value = "sender sent this at $(now(env))" put(cable, value) end end @resumable function receiver(env::Simulation, cable::Cable) while true @yield timeout(env, RECEIVE_PERIOD) msg = @yield get(cable) println("Received this at $(now(env)) while $msg") end end; ``` Create simulation, register events, and run! ```julia env = Simulation() cable = Cable(env, 10.) @process sender(env, cable) @process receiver(env, cable) run(env, SIM_DURATION) ``` Received this at 15.0 while sender sent this at 5.0 Received this at 20.0 while sender sent this at 10.0 Received this at 25.0 while sender sent this at 15.0 Received this at 30.0 while sender sent this at 20.0 Received this at 35.0 while sender sent this at 25.0 Received this at 40.0 while sender sent this at 30.0 Received this at 45.0 while sender sent this at 35.0 Received this at 50.0 while sender sent this at 40.0 Received this at 55.0 while sender sent this at 45.0 Received this at 60.0 while sender sent this at 50.0 Received this at 65.0 while sender sent this at 55.0 Received this at 70.0 while sender sent this at 60.0 Received this at 75.0 while sender sent this at 65.0 Received this at 80.0 while sender sent this at 70.0 Received this at 85.0 while sender sent this at 75.0 Received this at 90.0 while sender sent this at 80.0 Received this at 95.0 while sender sent this at 85.0
SimJulia
https://github.com/JuliaDynamics/ConcurrentSim.jl.git
[ "MIT" ]
0.8.2
ee1b863b5c9913ba40df8cd3bd7bb58837fb24c2
docs
3281
# Multi-server Queue ## Description An [M/M/c queue](https://en.wikipedia.org/wiki/M/M/c_queue) is a basic queue with _c_ identical servers, exponentially distributed interarrival times, and exponentially distributed service times for each server. The arrival rate is defined as _λ_ such that the interarrival time distribution has mean _1/λ_. Similarly, the service rate is defined as _μ_ such that the service time distribution has mean _1/μ_ (for each server). The overall traffic intensity of the queue is _ρ = λ / (c * μ)_. If the traffic intensity exceeds one, the queue is unstable and the queue length will grow indefinitely. ## Code ```julia #set simulation parameters Random.seed!(8710) # set random number seed for reproducibility num_customers = 10 # total number of customers generated # set queue parameters num_servers = 2 # number of servers mu = 1.0 / 2 # service rate lam = 0.9 # arrival rate arrival_dist = Exponential(1 / lam) # interarrival time distriubtion service_dist = Exponential(1 / mu) # service time distribution # define customer behavior @resumable function customer(env::Environment, server::Resource, id::Integer, t_a::Float64, d_s::Distribution) @yield timeout(env, t_a) # customer arrives println("Customer $id arrived: ", now(env)) @yield request(server) # customer starts service println("Customer $id entered service: ", now(env)) @yield timeout(env, rand(d_s)) # server is busy @yield release(server) # customer exits service println("Customer $id exited service: ", now(env)) end # setup and run simulation sim = Simulation() # initialize simulation environment server = Resource(sim, num_servers) # initialize servers arrival_time = 0.0 for i = 1:num_customers # initialize customers arrival_time += rand(arrival_dist) @process customer(sim, server, i, arrival_time, service_dist) end run(sim) # run simulation ## output # # Customer 1 arrived: 0.1229193244813443 # Customer 1 entered service: 0.1229193244813443 # Customer 2 arrived: 0.22607641035584877 # Customer 2 entered service: 0.22607641035584877 # Customer 3 arrived: 0.4570009029409502 # Customer 2 exited service: 1.7657345101378559 # Customer 3 entered service: 1.7657345101378559 # Customer 1 exited service: 2.154824561031012 # Customer 3 exited service: 2.2765287086137764 # Customer 4 arrived: 2.3661687470062995 # Customer 4 entered service: 2.3661687470062995 # Customer 5 arrived: 2.6110816119637885 # Customer 5 entered service: 2.6110816119637885 # Customer 5 exited service: 2.8017888690417583 # Customer 6 arrived: 3.019540357955037 # Customer 6 entered service: 3.019540357955037 # Customer 6 exited service: 3.351151832298383 # Customer 7 arrived: 3.5254699872847612 # Customer 7 entered service: 3.5254699872847612 # Customer 7 exited service: 4.261422043181396 # Customer 4 exited service: 4.602071952938201 # Customer 8 arrived: 7.27536704811686 # Customer 8 entered service: 7.27536704811686 # Customer 9 arrived: 7.491176033637809 # Customer 9 entered service: 7.491176033637809 # Customer 10 arrived: 8.39098457094977 # Customer 8 exited service: 8.683396356977969 # Customer 10 entered service: 8.683396356977969 # Customer 9 exited service: 8.7501656586875 # Customer 10 exited service: 9.049670951561666 ```
SimJulia
https://github.com/JuliaDynamics/ConcurrentSim.jl.git
[ "MIT" ]
0.8.2
ee1b863b5c9913ba40df8cd3bd7bb58837fb24c2
docs
3025
# Ross, Simulation 5th edition: ## A repair problem ### Source Ross, Simulation 5th edition, Section 7.7, p. 124-126 ### Description A system needs $n$ working machines to be operational. To guard against machine breakdown, additional machines are kept available as spares. Whenever a machine breaks down it is immediately replaced by a spare and is itself sent to the repair facility, which consists of a single repairperson who repairs failed machines one at a time. Once a failed machine has been repaired it becomes available as a spare to be used when the need arises. All repair times are independent random variables having the common distribution function $G$. Each time a machine is put into use the amount of time it functions before breaking down is a random variable, independent of the past, having distribution function $F$. The system is said to “crash” when a machine fails and no spares are available. Assuming that there are initially $n + s$ functional machines of which $n$ are put in use and $s$ are kept as spares, we are interested in simulating this system so as to approximate $E[T]$, where $T$ is the time at which the system crashes. ### Code ```jldoctest using Distributions using ResumableFunctions using SimJulia const RUNS = 5 const N = 10 const S = 3 const SEED = 150 const LAMBDA = 100 const MU = 1 srand(SEED) const F = Exponential(LAMBDA) const G = Exponential(MU) @resumable function machine(env::Environment, repair_facility::Resource, spares::Store{Process}) while true try @yield timeout(env, Inf) end @yield timeout(env, rand(F)) get_spare = get(spares) @yield get_spare | timeout(env) if state(get_spare) != SimJulia.idle @yield interrupt(value(get_spare)) else throw(StopSimulation("No more spares!")) end @yield request(repair_facility) @yield timeout(env, rand(G)) @yield release(repair_facility) @yield put(spares, active_process(env)) end end @resumable function start_sim(env::Environment, repair_facility::Resource, spares::Store{Process}) for i in 1:N proc = @process machine(env, repair_facility, spares) @yield interrupt(proc) end for i in 1:S proc = @process machine(env, repair_facility, spares) @yield put(spares, proc) end end function sim_repair() sim = Simulation() repair_facility = Resource(sim) spares = Store{Process}(sim) @process start_sim(sim, repair_facility, spares) msg = run(sim) stop_time = now(sim) println("At time $stop_time: $msg") stop_time end results = Float64[] for i in 1:RUNS push!(results, sim_repair()) end println("Average crash time: ", sum(results)/RUNS) # output At time 5573.772841846017: No more spares! At time 1438.0294516073466: No more spares! At time 7077.413276961621: No more spares! At time 7286.490682742159: No more spares! At time 6820.788098062124: No more spares! Average crash time: 5639.298870243853 ```
SimJulia
https://github.com/JuliaDynamics/ConcurrentSim.jl.git
[ "MIT" ]
0.8.2
ee1b863b5c9913ba40df8cd3bd7bb58837fb24c2
docs
3180
# SimJulia basics This guide describes the basic concepts of SimJulia: How does it work? What are processes, events and the environment? What can I do with them? ## How SimJulia works If you break SimJulia down, it is just an asynchronous event dispatcher. You generate events and schedule them at a given simulation time. Events are sorted by priority, simulation time, and an increasing event id. An event also has a list of callbacks, which are executed when the event is triggered and processed by the event loop. Events may also have a return value. The components involved in this are the `Environment`, events and the process functions that you write. Process functions implement your simulation model, that is, they define the behavior of your simulation. They are `@resumable` functions that `@yield` instances of `AbstractEvent`. The environment stores these events in its event list and keeps track of the current simulation time. If a process function yields an event, SimJulia adds the process to the event’s callbacks and suspends the process until the event is triggered and processed. When a process waiting for an event is resumed, it will also receive the event’s value. Here is a very simple example that illustrates all this: ```jldoctest using ResumableFunctions using SimJulia @resumable function example(env::Environment) event = timeout(env, 1, value=42) value = @yield event println("now=", now(env), ", value=", value) end sim = Simulation() @process example(sim) run(sim) # output now=1.0, value=42 ``` The `example` process function above first creates a `timeout` event. It passes the environment, a delay, and a value to it. The `timeout` schedules itself at `now + delay` (that’s why the environment is required); other event types usually schedule themselves at the current simulation time. The process function then yields the event and thus gets suspended. It is resumed, when SimJulia processes the `timeout` event. The process function also receives the event’s value (42) – this is, however, optional, so `@yield event` would have been okay if the you were not interested in the value or if the event had no value at all. Finally, the process function prints the current simulation time (that is accessible via the `now` function) and the `timeout`’s value. If all required process functions are defined, you can instantiate all objects for your simulation. In most cases, you start by creating an instance of `Environment`, e.g. a `Simulation`, because you’ll need to pass it around a lot when creating everything else. Starting a process function involves two things: - You have to call the macro `@process` with as argument a call to the process function. (This will not execute any code of that function yet.) This will schedule an initialisation event at the current simulation time which starts the execution of the process function. The process instance is also an event that is triggered when the process function returns. - Finally, you can start SimJulia’s event loop. By default, it will run as long as there are events in the event list, but you can also let it stop earlier by providing an until argument.
SimJulia
https://github.com/JuliaDynamics/ConcurrentSim.jl.git
[ "MIT" ]
0.8.2
ee1b863b5c9913ba40df8cd3bd7bb58837fb24c2
docs
5464
# Environments A simulation environment manages the simulation time as well as the scheduling and processing of events. It also provides means to step through or execute the simulation. The base type for all environments is `Environment`. “Normal” simulations use its subtype `Simulation`. ## Simulation control SimJulia is very flexible in terms of simulation execution. You can run your simulation until there are no more events, until a certain simulation time is reached, or until a certain event is triggered. You can also step through the simulation event by event. Furthermore, you can mix these things as you like. For example, you could run your simulation until an interesting event occurs. You could then step through the simulation event by event for a while; and finally run the simulation until there are no more events left and your processes have all terminated. The most important function here is `run`: - If you call it with an instance of the environment as the only argument (`run(env)`), it steps through the simulation until there are no more events left. If your processes run forever, this function will never terminate (unless you kill your script by e.g., pressing `Ctrl-C`). - In most cases it is advisable to stop your simulation when it reaches a certain simulation time. Therefore, you can pass the desired time via a second argument, e.g.: `run(env, 10)`. The simulation will then stop when the internal clock reaches 10 but will not process any events scheduled for time 10. This is similar to a new environment where the clock is 0 but (obviously) no events have yet been processed. If you want to integrate your simulation in a GUI and want to draw a process bar, you can repeatedly call this function with increasing until values and update your progress bar after each call: ```julia sim = Simulation() for t in 1:100 run(sim, t) update(progressbar, t) end ``` - Instead of passing a number as second argument to `run`, you can also pass any event to it. `run` will then return when the event has been processed. Assuming that the current time is 0, `run(env, timeout(env, 5))` is equivalent to `run(env, 5)`. You can also pass other types of events (remember, that a `Process` is an event, too): ```jldoctest using ResumableFunctions using SimJulia @resumable function my_process(env::Environment) @yield timeout(env, 1) "Monty Python's Flying Circus" end sim = Simulation() proc = @process my_process(sim) run(sim, proc) # output "Monty Python's Flying Circus" ``` To step through the simulation event by event, the environment offers `step`. This function processes the next scheduled event. It raises an `EmptySchedule` exception if no event is available. In a typical use case, you use this function in a loop like: ```julia while now(sim) < 10 step(sim) end ``` ## State access The environment allows you to get the current simulation time via the function `now`. The simulation time is a number without unit and is increased via `timeout` events. By default, the simulation starts at time 0, but you can pass an `initial_time` to the `Simulation` constructor to use something else. Note !!! note Although the simulation time is technically unitless, you can pretend that it is, for example, in milliseconds and use it like a timestamp returned by `Base.Dates.datetime2epochm` to calculate a date or the day of the week. The `Simulation` constructor and the `run` function accept as argument a `Base.Dates.DateTime` and the `timeout` constructor a `Base.Dates.Delay`. Together with the convenience function `nowDateTime` a simulation can transparantly schedule its events in seconds, minutes, hours, days, ... The function `active_process` is comparable to `Base.Libc.getpid` and returns the current active `Process`. If no process is active, a `NullException` is thrown. A process is active when its process function is being executed. It becomes inactive (or suspended) when it yields an event. Thus, it only makes sense to call this function from within a process function or a function that is called by your process function: ```jldoctest julia> using ResumableFunctions julia> using SimJulia julia> function subfunc(env::Environment) println(active_process(env)) end subfunc (generic function with 1 method) julia> @resumable function my_proc(env::Environment) while true println(active_process(env)) subfunc(env) @yield timeout(env, 1) end end my_proc (generic function with 1 method) julia> sim = Simulation() SimJulia.Simulation time: 0.0 active_process: nothing julia> @process my_proc(sim) SimJulia.Process 1 julia> active_process(sim) ERROR: NullException() [...] julia> SimJulia.step(sim) SimJulia.Process 1 SimJulia.Process 1 julia> active_process(sim) ERROR: NullException() [...] ``` An exemplary use case for this is the resource system: If a process function calls `request` to request a `Resource`, the resource determines the requesting process via `active_process`. ## Miscellaneous A generator function can have a return value: ```julia @resumable function my_proc(env::Environment) @yield timeout(sim, 1) 150 end ``` In SimJulia, this can be used to provide return values for processes that can be used by other processes: ```julia @resumable function other_proc(env::Environment) ret_val = @yield @process my_proc(env) @assert ret_val == 150 end ```
SimJulia
https://github.com/JuliaDynamics/ConcurrentSim.jl.git
[ "MIT" ]
0.8.2
ee1b863b5c9913ba40df8cd3bd7bb58837fb24c2
docs
2510
# Events SimJulia includes an extensive set of event types for various purposes. All of them are descendants of `AbstractEvent`. Here the following events are discussed: - `Event` - `timeout` - `Operator` The guide to resources describes the various resource events. ## Event basics SimJulia events are very similar – if not identical — to deferreds, futures or promises. Instances of the type AbstractEvent are used to describe any kind of events. Events can be in one of the following states. An event: - might happen (idle), - is going to happen (scheduled) or - has happened (processed). They traverse these states exactly once in that order. Events are also tightly bound to time and time causes events to advance their state. Initially, events are idle and the function `state` returns `SimJulia.idle`. If an event gets scheduled at a given time, it is inserted into SimJulia’s event queue. The function `state` returns `SimJulia.scheduled`. As long as the event is not processed, you can add callbacks to an event. Callbacks are function having an `AbstractEvent` as first parameter. An event becomes processed when SimJulia pops it from the event queue and calls all of its callbacks. It is now no longer possible to add callbacks. The function `state` returns `SimJulia.processed`. Events also have a value. The value can be set before or when the event is scheduled and can be retrieved via the function `value` or, within a process, by yielding the event (`value = @yield event`). ## Adding callbacks to an event “What? Callbacks? I’ve never seen no callbacks!”, you might think if you have worked your way through the tutorial. That’s on purpose. The most common way to add a callback to an event is yielding it from your process function (`@yield event`). This will add the process’ `resume` function as a callback. That’s how your process gets resumed when it yielded an event. However, you can add any function to the list of callbacks as long as it accepts `AbstractEvent` or a descendant as first parameter: ```jldoctest julia> using SimJulia julia> function my_callback(ev::AbstractEvent) println("Called back from ", ev) end my_callback (generic function with 1 method) julia> sim = Simulation() SimJulia.Simulation time: 0.0 active_process: nothing julia> ev = Event(sim) SimJulia.Event 1 julia> @callback my_callback(ev) (::#3) (generic function with 1 method) julia> succeed(ev) SimJulia.Event 1 julia> run(sim) Called back from SimJulia.Event 1 ```
SimJulia
https://github.com/JuliaDynamics/ConcurrentSim.jl.git
[ "MIT" ]
0.3.3
bc9ed807d18f9a7ef1aaa44c19d1c753afe5ea76
code
1201
module FaultTolerantControl # if you don't reexport `FlightSims`, many APIs, e.g., `State` would report an issue like: # ERROR: Define the structure of state for your environment # using Debugger # tmp using Reexport @reexport using FlightSims const FS = FlightSims # `import` will help you to automatically extend the imported methods import FlightSims: State, Params, Dynamics!, Dynamics import FlightSims: Command using LinearAlgebra using Convex, Mosek, MosekTools using Transducers, UnPack, ComponentArrays import SplitApplyCombine import MatrixEquations using NumericalIntegration using ControlSystems: ss, gram # Fault export AbstractFault, FaultSet export AbstractActuatorFault, LoE # FDI (fault detection and isoltion) export AbstractFDI, LPFFDI, DelayFDI # allocator export PseudoInverseAllocator, ConstrainedAllocator, AdaptiveAllocator # trajectory generation export Bezier # cost functional export PositionAngularVelocityCostFunctional export cost # reconfigurability export ssom, empirical_gramian, min_HSV include("utils.jl") include("costs.jl") include("reconfigurability.jl") include("faults.jl") include("environments/environments.jl") include("trajectory_generation.jl") end
FaultTolerantControl
https://github.com/JinraeKim/FaultTolerantControl.jl.git
[ "MIT" ]
0.3.3
bc9ed807d18f9a7ef1aaa44c19d1c753afe5ea76
code
1277
abstract type AbstractCostFunctional end """ Default weight: 1 for position, (1/π^2) for angular velocity (1 m ≈ 180 deg) # Notes - Q_p: weight matrix for running cost (position) - Q_ω: weight matrix for running cost (angular velocity) - F_p: weight matrix for terminal cost (position) - F_ω: weight matrix for terminal cost (angular velocity) """ struct PositionAngularVelocityCostFunctional <: AbstractCostFunctional Q_p::AbstractMatrix Q_ω::AbstractMatrix F_p::AbstractMatrix F_ω::AbstractMatrix function PositionAngularVelocityCostFunctional( Q_p=Matrix(I, 3, 3), Q_ω=Matrix(I, 3, 3), F_p=(1/π^2)*Matrix(I, 3, 3), F_ω=(1/π^2)*Matrix(I, 3, 3), ) new(Q_p, Q_ω, F_p, F_ω) end end """ ts: an array of time e_ps: an array of position error e_ωs: an array of angular velocity error """ function cost(cf::PositionAngularVelocityCostFunctional, ts::AbstractVector, e_ps::AbstractVector, e_ωs::AbstractVector, ) @unpack Q_p, Q_ω, F_p, F_ω = cf running_costs = zip(e_ps, e_ωs) |> MapSplat((e_p, e_ω) -> e_p'*Q_p*e_p + e_ω'*Q_ω*e_ω) |> collect e_p_f = e_ps[end] e_ω_f = e_ωs[end] terminal_cost = e_p_f'*F_p*e_p_f + e_ω_f'*F_ω*e_ω_f integrate(ts, running_costs) + terminal_cost end
FaultTolerantControl
https://github.com/JinraeKim/FaultTolerantControl.jl.git
[ "MIT" ]
0.3.3
bc9ed807d18f9a7ef1aaa44c19d1c753afe5ea76
code
2060
abstract type AbstractFault end abstract type AbstractActuatorFault <: AbstractFault end # API affect!(fault::AbstractActuatorFault, Λ, t) = error("Not implemented fault") # FaultSet FaultSet(args...) = AbstractFault[args...] function Affect!(faults::Vector{AbstractActuatorFault}) actuator_faults_groups = SplitApplyCombine.group(fault -> fault.index, faults) # actuator_faults groups classified by fault index return function (Λ, t) for actuator_faults_group in actuator_faults_groups last_actuator_fault = select_last_before_t(actuator_faults_group, t) affect!(last_actuator_fault, Λ, t) end end end # select_last """ Select the last fault (concerning the applied time) among given faults. """ function select_last_before_t(faults::Vector{T} where T <: AbstractFault, t) fault_times_less_than_t = faults |> Map(fault -> fault.time) |> Filter(<=(t)) |> collect if length(fault_times_less_than_t) == 0 # case 1: if there is no faults occured before t # return (t, u) -> u return NoFault() else # case 2: if there are some faults occured before t fault_last_indices = findall(fault -> fault.time == maximum(fault_times_less_than_t), faults) fault_last_idx = length(fault_last_indices) == 1 ? fault_last_indices[1] : error("Among given faults, more than one faults occured at the same time") return faults[fault_last_idx] end end struct NoFault <: AbstractFault end function affect!(fault::NoFault, Λ, t) end """ Loss of effectiveness (LoE). """ struct LoE <: AbstractActuatorFault time::Real index level::Real function LoE(time, index, level) @assert level >= 0.0 && level <= 1.0 new(time, index, level) end end """ # Variables Λ ∈ R^(n×n): effectiveness matrix _Λ ∈ R^n: effectiveness vector """ function affect!(fault::LoE, Λ, t) @unpack time, index, level = fault _Λ = ones(size(diag(Λ))) if t >= time _Λ[index] = level end Λ .= Λ * Diagonal(_Λ) |> Matrix end
FaultTolerantControl
https://github.com/JinraeKim/FaultTolerantControl.jl.git
[ "MIT" ]
0.3.3
bc9ed807d18f9a7ef1aaa44c19d1c753afe5ea76
code
4634
""" Get the smallest second-order mode (ssom) for linear time-invariant (LTI) systems. # Refs [1] N. E. Wu, K. Zhou, and G. Salomon, “Control Reconfigurability of Linear Time-Invariant Systems,” p. 5, 2000. """ function ssom(A, B, C, D=zeros(size(C)[1], size(B)[2])) # Note: ss, gram exported from `ControlSystems.jl` if all(real.(eigvals(A)) .< 0) # Hurwitz matrix sys = ss(A, B, C, D) Wc = gram(sys, :c) Wo = gram(sys, :o) # Hankel singular value (HSV) # TODO: HSV is only valid for stable `sys`; otherwise, `gram` does not work. return hsv_min = Wc*Wo |> LinearAlgebra.eigvals |> minimum |> sqrt else error("TODO: ssom for unstable systems has not been developed yet.") # TODO: [1, Eqs. (7-8)] end end """ empirical_gramian() A function for computation of controllability or observability gramian. # References [1] M. Tahavori and A. Hasan, “Fault recoverability for nonlinear systems with application to fault tolerant control of UAVs,” Aerosp. Sci. Technol., vol. 107, p. 106282, 2020, doi: 10.1016/j.ast.2020.106282. [2] C. Himpe, “emgr-The empirical Gramian framework,” Algorithms, vol. 11, no. 7, pp. 1–27, 2018, doi: 10.3390/a11070091. # Notes - f = function of (x, u, p, t) - g = function of (x, u, p, t) - pr = parameter vector(s), each column i sone parameter sample - xs = steady-state and nominal initial state x_0 - us = steady-state input - opt = :c for controllability gramian and :o for observability gramian """ function empirical_gramian(f::Function, g::Function, M::Int, N::Int, L::Int; opt::Symbol, dt::Real, tf::Real, pr::Matrix, xs::Vector, us::Vector, xm=1.0, um=1.0) @assert dt > 0 && tf > dt P, K = size(pr) ut = t -> (t <= dt) / dt up = t -> us R = L G(x, u, p, t) = x xm = ones(N, 1) * Matrix([-xm xm]) # initial-state scales um = ones(M, 1) * Matrix([-um um]) # input scales A = size(xm)[1] # Number of total states C = size(um)[2] # Number of input scales sets D = size(xm)[2] # Number of state scales sets if opt === :c # Empirical_ctrl_gramian Wc = 0 for k = 1:K for c = 1:C for m = 1:M if um[m, c] != 0 em = zeros(M+P) em[m] = um[m, c] umc(t) = ut(t) .* em[1:M] pmc = pr[:, k] + em[M+1:end] x = ssp2(f, G, dt, tf, xs, umc, pmc) x = x ./ um[m, c] Wc = Wc .+ x * x' # Question(why is this different dot(x, x')?) end end end end Wc = Wc * (dt / (C * K)) elseif opt === :o # Empirical_obsv_gramian Wo = 0 o = zeros(R*Int(floor(tf / dt) + 1), A) for k = 1:K for d = 1:D for a = 1:A if xm[a, d] != 0 en = zeros(N+P) en[a] = xm[a, d] xnd = xs + en[1:N] pnd = pr[:, k] + en[N+1:end] y = ssp2(f, g, dt, tf, xnd, up, pnd) y = y ./ xm[a, d] o[:, a] = vec(y) end end Wo = Wo .+ o' * o end end Wo = Wo * (dt / (D * K)) else error("opt must be either :c for controllability gramian, or :o for observability gramian") end end """ min_HSV() A function for computation of minimum Hankel Singular Value (HSV). """ function min_HSV(Wc, Wo) min_HSV = Wc*Wo |> LinearAlgebra.eigvals |> minimum |> sqrt end """ ssp2() A function for Low-Storage Strong-Stability-Preserving Second-Order Runge-Kutta. # References [1] https://gramian.de/ [2] https://github.com/gramian/emgr # Notes - STAGES = Configurable number of stages for enhanced stability - f = function of (x, u, p, t) - g = function of (x, u, p, t) """ function ssp2(f::Function, g::Function, dt, tf, x0, u, p; STAGES=3) nt = Int(floor(tf / dt) + 1) @assert nt > 0 y0 = g(x0, u(0), p, 0) y = zeros(length(y0), nt) y[:,1] = y0 xk1 = x0 xk2 = x0 for k = 2:nt tk = (k - 1.5) * dt uk = u(tk) for s = 1:(STAGES - 1) xk1 = xk1 + (dt / (STAGES - 1)) * f(xk1, uk, p, tk) end xk2 = xk2 + dt * f(xk1, uk, p, tk) xk2 = xk2 / STAGES xk2 = xk2 + xk1 * ((STAGES - 1) / STAGES) xk1 = xk2 y[:,k] = g(xk1, uk, p, tk) end y end
FaultTolerantControl
https://github.com/JinraeKim/FaultTolerantControl.jl.git
[ "MIT" ]
0.3.3
bc9ed807d18f9a7ef1aaa44c19d1c753afe5ea76
code
533
abstract type AbstractTrajectory end """ Bezier curve θ: a vector whose length is (N+1); each element can also be vector, e.g., θ = [[1, 2, 3], [2, 3, 4]] """ struct Bezier <: AbstractTrajectory θ::AbstractVector t0::Real tf::Real end function (bezier::Bezier)(t::Real) @unpack t0, tf, θ = bezier N = length(θ) -1 @assert t <= tf && t >= t0 s = (t-t0)/(tf-t0) basis = 0:N |> Map(i -> binomial(N, i) * s^i * (1-s)^(N-i)) |> collect basis .* θ |> sum # sum of N_C_i * s^(N-i) * (1-s)^i * θ_i end
FaultTolerantControl
https://github.com/JinraeKim/FaultTolerantControl.jl.git
[ "MIT" ]
0.3.3
bc9ed807d18f9a7ef1aaa44c19d1c753afe5ea76
code
347
T_u_inv(T) = [ 0 1/T 0; -1/T 0 0; 0 0 -1] T_u_inv_dot(T, Ṫ) = [ 0 -Ṫ/T^2 0; Ṫ/T^2 0 0; 0 0 0] T_ω(T) = [0 -T 0; T 0 0; 0 0 0] skew(x) = [ 0 -x[3] x[2]; x[3] 0 -x[1]; -x[2] x[1] 0]
FaultTolerantControl
https://github.com/JinraeKim/FaultTolerantControl.jl.git
[ "MIT" ]
0.3.3
bc9ed807d18f9a7ef1aaa44c19d1c753afe5ea76
code
160
include("FDI/FDI.jl") include("multicopters/multicopters.jl") include("allocators/allocators.jl") include("integrated_environments/integrated_environments.jl")
FaultTolerantControl
https://github.com/JinraeKim/FaultTolerantControl.jl.git
[ "MIT" ]
0.3.3
bc9ed807d18f9a7ef1aaa44c19d1c753afe5ea76
code
1273
""" FDI with simple time delay. Λ_func: function of `t`. """ struct DelayFDI <: AbstractFDI τ function DelayFDI(τ; verbose=false) if verbose && τ == 0.0 @warn("no delay") end @assert τ >= 0 new(τ) end end function Estimate(fdi::DelayFDI, Λ_func) @unpack τ = fdi return function (t) Λ̂ = Λ_func(t - τ) end end # function State(fdi::DelayFDI) # return function (dim_input::Int) # ComponentArray(Λ̂=ones(dim_input) |> Diagonal |> Matrix) # end # end # """ # Λ: effectiveness matrix # # Notes # For delayed FDI (DelayFDI), # the function of effectiveness matrix should be known. # For the explanation of the below implementation, # see https://discourse.julialang.org/t/differentialequations-jl-discrete-delay-problem/62829/10?u=ihany. # # NOTICE # For some technical issue, # the matrix-form state is dealt with by ComponentArray (default setting). # """ # function Dynamics!(fdi::DelayFDI, Λ_func) # @unpack τ = fdi # dim_input = Λ_func(0.0) |> length # auxiliary evaluation # dynamics! = function (dX, X, p, t) # dX.Λ̂ .= X.Λ̂ - Λ_func(t - τ) # nothing # end # ODEFunction(dynamics!, mass_matrix=zeros(dim_input) |> Diagonal |> Matrix) # end
FaultTolerantControl
https://github.com/JinraeKim/FaultTolerantControl.jl.git
[ "MIT" ]
0.3.3
bc9ed807d18f9a7ef1aaa44c19d1c753afe5ea76
code
89
abstract type AbstractFDI <: AbstractEnv end include("DelayFDI.jl") include("LPFFDI.jl")
FaultTolerantControl
https://github.com/JinraeKim/FaultTolerantControl.jl.git
[ "MIT" ]
0.3.3
bc9ed807d18f9a7ef1aaa44c19d1c753afe5ea76
code
429
""" Low pass filter (LPF) -like FDI. """ struct LPFFDI <: AbstractFDI τ function LPFFDI(τ) @assert τ > 0 new(τ) end end function State(fdi::LPFFDI) return function (dim_input::Int) Λ̂ = Diagonal(ones(dim_input)) end end """ Λ: effectiveness matrix """ function Dynamics!(fdi::LPFFDI) @unpack τ = fdi return function (dΛ̂, Λ̂, p, t; Λ) dΛ̂ .= (Λ - Λ̂) / τ end end
FaultTolerantControl
https://github.com/JinraeKim/FaultTolerantControl.jl.git
[ "MIT" ]
0.3.3
bc9ed807d18f9a7ef1aaa44c19d1c753afe5ea76
code
2344
""" # References - Controller [1] G. P. Falconi and F. Holzapfel, “Adaptive Fault Tolerant Control Allocation for a Hexacopter System,” Proc. Am. Control Conf., vol. 2016-July, pp. 6760–6766, 2016. - Reference model (e.g., xd, vd, ad, ad_dot, ad_ddot) [2] S. J. Su, Y. Y. Zhu, H. R. Wang, and C. Yun, “A Method to Construct a Reference Model for Model Reference Adaptive Control,” Adv. Mech. Eng., vol. 11, no. 11, pp. 1–9, 2019. """ struct AdaptiveAllocator <: AbstractEnv B B_pinv γ function AdaptiveAllocator(B, γ=1e-2) B_pinv = pinv(B) new(B, B_pinv, γ) end end function State(allocator::AdaptiveAllocator) return function (Θ̂=zeros(6, 4)) Θ̂ end end function Dynamics!(allocator::AdaptiveAllocator) @Loggable function dynamics!(dΘ̂, Θ̂, p, t; Θ̂̇) @log Θ̂ dΘ̂ .= Θ̂̇ end end """ Several functions are exported from `utils.jl`, e.g., T_u_inv(T). """ function Command(allocator::AdaptiveAllocator) @unpack B, γ = allocator return function (νd, e, zB, T, Θ̂, R, J, Ap, Bp, P, Kp, Kt, Kω) P̄ = [ P zeros(6, 6); zeros(6, 6) 0.5*Matrix(I, 6, 6)] θ_ėp = Bp θ_u̇1 = Kp * θ_ėp θ_ėt = θ_u̇1 θ_ëp = Ap * θ_ėp + Bp * θ_ėt θ_ü1 = Kp * θ_ëp θ_u̇2 = T_u_inv(T) * R * (2*Bp' * P * θ_ėp + θ_ü1 + Kt * θ_ėt) θ_ω̇d = [1 0 0; 0 1 0; 0 0 0] * θ_u̇2 B̄ = [-(θ_ėp*zB) zeros(6, 3); -(θ_u̇1*zB) zeros(3, 3); -(θ_ω̇d*zB) inv(J)] Θ̂̇ = γ * Proj_R( Θ̂, (νd * e' * P̄ * B̄ * B)' ) end end function Proj_R(C, Y) proj_R = zeros(size(Y)) for i in 1:size(Y)[1] ci = C[i, :] yi = Y[i, :] proj_R[i, :] = Proj(ci, yi) end proj_R end function Proj(θ, y; ϵ=1e-2, θ_max=1e5) f = ((1+ϵ) * norm(θ)^2 - θ_max^2) / (ϵ * θ_max^2) ∇f = (2*(1+ϵ) / (ϵ * θ_max^2)) * θ proj = nothing if f > 0 && ∇f' * y > 0 ∇f_unit = ∇f / norm(∇f) proj = y - dot(∇f, y) * ∇f_unit else proj = y end proj end function (allocator::AdaptiveAllocator)(ν, Θ̂) @unpack B_pinv = allocator u = (B_pinv + Θ̂) * ν end
FaultTolerantControl
https://github.com/JinraeKim/FaultTolerantControl.jl.git
[ "MIT" ]
0.3.3
bc9ed807d18f9a7ef1aaa44c19d1c753afe5ea76
code
1237
""" Constrained-optimisation-based control allocator. """ struct ConstrainedAllocator <: StaticAllocator B u_min u_max u function ConstrainedAllocator(B, u_min, u_max; p=Inf) @assert size(u_min) == size(u_max) dim_input = length(u_min) u = Convex.Variable(dim_input) new(B, u_min, u_max, u) end end """ # Variables ν: virtual input # Notes ν = B*u where u: control input """ function (allocator::ConstrainedAllocator)(ν, Λ=Diagonal(ones(size(ν))); p=Inf, silent_solver=true) @unpack u_min, u_max, u, B = allocator prob = minimize( norm(u, p) # sum(u) + 1e5*norm(ν - B*Λ*u, 1) # exact penalty method ) prob.constraints += [ u .>= u_min; # min u .<= u_max; # max # ν == B*Λ*u # equality; replaced by exact penalty method ] Convex.solve!(prob, # SCS.Optimizer(); Mosek.Optimizer(); # best silent_solver=silent_solver, verbose=false) u.value[:] # dim: n×1 -> n end
FaultTolerantControl
https://github.com/JinraeKim/FaultTolerantControl.jl.git
[ "MIT" ]
0.3.3
bc9ed807d18f9a7ef1aaa44c19d1c753afe5ea76
code
201
# abstract type AbstractAllocator end # abstract type StaticAllocator <: AbstractAllocator end # include("PseudoInverseAllocator.jl") include("ConstrainedAllocator.jl") include("AdaptiveAllocator.jl")
FaultTolerantControl
https://github.com/JinraeKim/FaultTolerantControl.jl.git
[ "MIT" ]
0.3.3
bc9ed807d18f9a7ef1aaa44c19d1c753afe5ea76
code
2724
abstract type AbstractControlSystem <: AbstractEnv end # BacksteppingControl_StaticAllocator_ControlSystem struct BacksteppingControl_StaticAllocator_ControlSystem <: AbstractControlSystem controller::BacksteppingPositionController allocator::StaticAllocator end function State(cs::BacksteppingControl_StaticAllocator_ControlSystem) @unpack controller, allocator = cs return function (pos0, m, g) x_controller = State(controller)(pos0, m, g) ComponentArray(controller=x_controller) end end function Command(cs::BacksteppingControl_StaticAllocator_ControlSystem) @unpack controller, allocator = cs return function (p, v, R, ω, xd, vd, ad, ȧd, äd, Td, m, J, g, Λ̂) νd, Ṫd, _... = Command(controller)(p, v, R, ω, xd, vd, ad, ȧd, äd, Td, m, J, g) u_cmd = allocator(νd, Λ̂) ComponentArray(νd=νd, Ṫd=Ṫd, u_cmd=u_cmd) end end function Dynamics!(cs::BacksteppingControl_StaticAllocator_ControlSystem) @unpack controller = cs @Loggable function dynamics!(dx, x, p, t; pos_cmd=nothing, Ṫd) @nested_log :controller Dynamics!(controller)(dx.controller, x.controller, p, t; pos_cmd=pos_cmd, Ṫd=Ṫd) end end # BacksteppingControl_AdaptiveAllocator_ControlSystem struct BacksteppingControl_AdaptiveAllocator_ControlSystem <: AbstractControlSystem controller::BacksteppingPositionController allocator::AdaptiveAllocator end function State(cs::BacksteppingControl_AdaptiveAllocator_ControlSystem) @unpack controller, allocator = cs return function (pos0, m, g; Θ̂=zeros(6, 4)) x_controller = State(controller)(pos0, m, g) x_allocator = State(allocator)(Θ̂) ComponentArray(controller=x_controller, allocator=x_allocator) end end function Command(cs::BacksteppingControl_AdaptiveAllocator_ControlSystem) @unpack controller, allocator = cs @unpack Ap, Bp, P, Kp, Kt, Kω = controller return function (p, v, R, ω, xd, vd, ad, ȧd, äd, Td, m, J, g, Λ̂, Θ̂) νd, Ṫd, e, zB, T = Command(controller)(p, v, R, ω, xd, vd, ad, ȧd, äd, Td, m, J, g) Θ̂̇ = Command(allocator)(νd, e, zB, T, Θ̂, R, J, Ap, Bp, P, Kp, Kt, Kω) u_cmd = allocator(νd, Θ̂) ComponentArray(νd=νd, Ṫd=Ṫd, u_cmd=u_cmd, Θ̂̇=Θ̂̇) end end function Dynamics!(cs::BacksteppingControl_AdaptiveAllocator_ControlSystem) @unpack controller, allocator = cs @Loggable function dynamics!(dx, x, p, t; pos_cmd=nothing, Ṫd, Θ̂̇) @nested_log :controller Dynamics!(controller)(dx.controller, x.controller, p, t; pos_cmd=pos_cmd, Ṫd=Ṫd) @nested_log :allocator Dynamics!(allocator)(dx.allocator, x.allocator, p, t; Θ̂̇=Θ̂̇) end end
FaultTolerantControl
https://github.com/JinraeKim/FaultTolerantControl.jl.git
[ "MIT" ]
0.3.3
bc9ed807d18f9a7ef1aaa44c19d1c753afe5ea76
code
3868
abstract type AbstractFeedbackSystem <: AbstractEnv end # DelayFDI_Plant_BacksteppingControl_StaticAllocator_ControlSystem struct DelayFDI_Plant_BacksteppingControl_StaticAllocator_ControlSystem <: AbstractFeedbackSystem plant::DelayFDI_Plant control_system::BacksteppingControl_StaticAllocator_ControlSystem end """ Multicopter + BacksteppingPositionController """ function State(env::DelayFDI_Plant_BacksteppingControl_StaticAllocator_ControlSystem) @unpack plant, control_system = env @unpack multicopter = plant @unpack controller = control_system @unpack m, g = multicopter return function (; args_multicopter=()) x_plant = State(plant)(; args_multicopter=args_multicopter) pos0 = copy(x_plant.multicopter.p) x_cs = State(control_system)(pos0, m, g) ComponentArray(plant=x_plant, control_system=x_cs) end end function Dynamics!(env::DelayFDI_Plant_BacksteppingControl_StaticAllocator_ControlSystem) @unpack plant, control_system = env effectiveness_matrix_functions = EffectivenessMatrixFunction(plant) @unpack Λ̂_func = effectiveness_matrix_functions @unpack controller, allocator = control_system @unpack multicopter = plant @unpack m, J, g = multicopter @Loggable function dynamics!(dx, x, p, t; pos_cmd=nothing) Λ̂ = Λ̂_func(t) @unpack p, v, R, ω = x.plant.multicopter @unpack ref_model, Td = x.control_system.controller xd, vd, ad, ȧd, äd = ref_model.x_0, ref_model.x_1, ref_model.x_2, ref_model.x_3, ref_model.x_4 command_info = Command(control_system)(p, v, R, ω, xd, vd, ad, ȧd, äd, Td, m, J, g, Λ̂) @unpack νd, Ṫd, u_cmd = command_info @log νd @nested_log :plant Dynamics!(plant)(dx.plant, x.plant, (), t; u=u_cmd) @nested_log :control_system Dynamics!(control_system)(dx.control_system, x.control_system, (), t; pos_cmd=pos_cmd, Ṫd=Ṫd) nothing end end # DelayFDI_Plant_BacksteppingControl_AdaptiveAllocator_ControlSystem struct DelayFDI_Plant_BacksteppingControl_AdaptiveAllocator_ControlSystem <: AbstractFeedbackSystem plant::DelayFDI_Plant control_system::BacksteppingControl_AdaptiveAllocator_ControlSystem end function State(env::DelayFDI_Plant_BacksteppingControl_AdaptiveAllocator_ControlSystem) @unpack plant, control_system = env @unpack multicopter = plant @unpack controller = control_system @unpack m, g = multicopter return function (; args_multicopter=()) x_plant = State(plant)(; args_multicopter=args_multicopter) pos0 = copy(x_plant.multicopter.p) x_cs = State(control_system)(pos0, m, g) ComponentArray(plant=x_plant, control_system=x_cs) end end function Dynamics!(env::DelayFDI_Plant_BacksteppingControl_AdaptiveAllocator_ControlSystem) @unpack plant, control_system = env effectiveness_matrix_functions = EffectivenessMatrixFunction(plant) @unpack Λ̂_func = effectiveness_matrix_functions @unpack controller, allocator = control_system @unpack multicopter = plant @unpack m, J, g = multicopter @Loggable function dynamics!(dx, x, p, t; pos_cmd=nothing) Λ̂ = Λ̂_func(t) @unpack p, v, R, ω = x.plant.multicopter @unpack ref_model, Td = x.control_system.controller Θ̂ = x.control_system.allocator xd, vd, ad, ȧd, äd = ref_model.x_0, ref_model.x_1, ref_model.x_2, ref_model.x_3, ref_model.x_4 command_info = Command(control_system)(p, v, R, ω, xd, vd, ad, ȧd, äd, Td, m, J, g, Λ̂, Θ̂) @unpack νd, Ṫd, u_cmd, Θ̂̇ = command_info @log νd @nested_log :plant Dynamics!(plant)(dx.plant, x.plant, (), t; u=u_cmd) @nested_log :control_system Dynamics!(control_system)(dx.control_system, x.control_system, (), t; pos_cmd=pos_cmd, Ṫd=Ṫd, Θ̂̇=Θ̂̇) nothing end end
FaultTolerantControl
https://github.com/JinraeKim/FaultTolerantControl.jl.git
[ "MIT" ]
0.3.3
bc9ed807d18f9a7ef1aaa44c19d1c753afe5ea76
code
82
include("plants.jl") include("control_systems.jl") include("feedback_systems.jl")
FaultTolerantControl
https://github.com/JinraeKim/FaultTolerantControl.jl.git
[ "MIT" ]
0.3.3
bc9ed807d18f9a7ef1aaa44c19d1c753afe5ea76
code
1758
abstract type AbstractPlant <: AbstractEnv end struct DelayFDI_Plant <: AbstractPlant multicopter::Multicopter fdi::DelayFDI faults::Vector{AbstractFault} end function State(env::DelayFDI_Plant) @unpack multicopter, fdi, faults = env return function (; args_multicopter=()) x_multicopter = State(multicopter)(args_multicopter...) ComponentArray(multicopter=x_multicopter) end end function EffectivenessMatrixFunction(env::DelayFDI_Plant) @unpack multicopter, fdi, faults = env @unpack dim_input = multicopter # actuator faults actuator_faults = faults |> Filter(fault -> typeof(fault) <: AbstractActuatorFault) |> collect affect_actuator! = Affect!(AbstractActuatorFault[actuator_faults...]) # effectiveness matrix Λ_func = function (t) Λ = ones(dim_input) |> Diagonal affect_actuator!(Λ, t) Λ end # delayed effectiveness matrix estimation Λ̂_func = Estimate(fdi, Λ_func) (; Λ_func=Λ_func, Λ̂_func=Λ̂_func) end function Dynamics!(env::DelayFDI_Plant) @unpack multicopter, fdi, faults = env effectiveness_matrix_functions = EffectivenessMatrixFunction(env) @unpack Λ_func, Λ̂_func = effectiveness_matrix_functions @Loggable function dynamics!(dX, X, p, t; u) Λ = Λ_func(t) @nested_log :FDI Λ̂ = Λ̂_func(t) # @nested_log :input u_saturated = pinv(Λ̂) * FlightSims.saturate(multicopter, Λ̂*u) # saturation considering fault # @nested_log :input u_saturated = u # saturation considering fault # @nested_log Dynamics!(multicopter)(dX.multicopter, X.multicopter, (), t; u=u_saturated, Λ=Λ) @nested_log Dynamics!(multicopter)(dX.multicopter, X.multicopter, (), t; u=u, Λ=Λ) end end
FaultTolerantControl
https://github.com/JinraeKim/FaultTolerantControl.jl.git