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.1.3
82d058ac0c22844b80c5bc098f17c7f7d5268f11
code
579
using Documenter, VarianceComponentModels ENV["DOCUMENTER_DEBUG"] = "true" makedocs( format = Documenter.HTML(), sitename = "VarianceComponentModels.jl", modules = [VarianceComponentModels], pages = Any[ "Home" => "index.md", "Manual" => Any[ "man/mle_reml.md", "man/heritability.md" ], "API" => "man/api.md" ] ) deploydocs( repo = "github.com/OpenMendel/VarianceComponentModels.jl.git", target = "build", # osname = "linux", # julia = "1.0", deps = nothing, make = nothing)
VarianceComponentModels
https://github.com/OpenMendel/VarianceComponentModels.jl.git
[ "MIT" ]
0.1.3
82d058ac0c22844b80c5bc098f17c7f7d5268f11
code
15870
module VarianceComponentModels using LinearAlgebra, Statistics, MathProgBase, Ipopt#, KNITRO#, Mosek#, Gurobi import Base: eltype, length, size, + export VarianceComponentModel, VarianceComponentVariate, TwoVarCompModelRotate, TwoVarCompVariateRotate, VarianceComponentAuxData, residual, residual!, nvarcomps, nmeanparams, nvarparams, nparams, mean!, mean, cov!, cov """ `VarianceComponentModel` stores the model parameters of a variance component model. # Fields - `B`: `p x d` mean parameters - `Σ`: tuple of `d x d` variance component parameters - `A`: constraint matrix for `vec(B)` - `sense`: vector of characters `'='`, `'<'` or `'>'` - `b`: constraint vector for `vec(B)` - `lb`: lower bounds for `vec(B)` - `ub`: upper bounds for `vec(B)` """ mutable struct VarianceComponentModel{T <: AbstractFloat, M, BT <: AbstractVecOrMat, ΣT <: AbstractMatrix} # model parameters B::BT Σ::NTuple{M, ΣT} # constraints: A * vec(B) sense b, lb ≤ vec(B) ≤ ub A::Matrix{T} sense::Union{Char, Vector{Char}} b::Union{T, Vector{T}} lb::Union{T, Vector{T}} ub::Union{T, Vector{T}} end """ VarianceComponentModel(B, Σ) VarianceComponentModel(B, Σ, A, sense, b, lb, ub) Default constructor of [`VarianceComponentModel`](@ref) type. """ function VarianceComponentModel( B::AbstractVecOrMat, Σ::NTuple{M, AbstractMatrix}, A::Matrix = zeros(eltype(B), 0, length(B)), sense::Union{Char, Vector{Char}} = Array{Char}(undef, 0), b::Union{Number, Vector} = zeros(eltype(B), 0), lb::Union{Number, Vector} = convert(eltype(B), -Inf), ub::Union{Number, Vector} = convert(eltype(B), Inf), ) where {M} VarianceComponentModel{eltype(B), M, typeof(B), eltype(Σ)}(B, Σ, A, sense, b, lb, ub) end """ VarianceComponentModel(Σ) Construct [`VarianceComponentModel`](@ref) from `Σ` alone. `B` is treated empty. """ function VarianceComponentModel(Σ::NTuple{M, AbstractMatrix}) where {M} B = zeros(eltype(Σ[1]), 0, size(Σ[1], 1)) VarianceComponentModel(B, Σ) end """ `TwoVarCompModelRotate` stores the rotated two variance component model. # Fields - `Brot`: rotated mean parameters `B * eigvec` - `eigval`: eigenvalues of `eig(Σ[1], Σ[2])` - `eigvec`: eigenvectors of `eig(Σ[1], Σ[2])` - `logdetΣ2`: log-determinant of `Σ[2]` """ struct TwoVarCompModelRotate{T <: AbstractFloat, BT <: AbstractVecOrMat} Brot::BT eigval::Vector{T} eigvec::Matrix{T} logdetΣ2::T end """ TwoVarCompModelRotate(Brot, eigval, eigvec, logdetΣ2) Default constructor of [`TwoVarCompModelRotate`](@ref) type. """ function TwoVarCompModelRotate( Brot::AbstractVecOrMat, eigval::Vector, eigvec::Matrix, logdetΣ2 ) TwoVarCompModelRotate{eltype(Brot), typeof(Brot)}(Brot, eigval, eigvec, logdetΣ2) end """ TwoVarCompModelRotate(twovarcomp) Constructor of [`TwoVarCompModelRotate`](@ref) instance from a [`TwoVarCompModelRotate`](@ref) instance itself. """ function TwoVarCompModelRotate( twovarcomp::TwoVarCompModelRotate{T}) where T <: AbstractFloat ## JK ### twovarcomp end """ TwoVarCompModelRotate(vcmodel) Constructor of a [`TwoVarCompModelRotate`](@ref) instance from a [`VarianceComponentModel`](@ref) instance. """ function TwoVarCompModelRotate(vcm::VarianceComponentModel{T, 2, BT, ΣT}) where {T, BT, ΣT} # generalized eigenvalue decomposition of (Σ1, Σ2) F = eigen(Symmetric(vcm.Σ[1]), Symmetric(vcm.Σ[2])) # output is of BlasFloat type λ = convert(Vector{T}, F.values) Φ = convert(Matrix{T}, F.vectors) # correct negative eigenvalues due to roundoff map!(x -> max(x, zero(T)), λ, λ) Brot = isempty(vcm.B) ? Array{T}(undef, size(vcm.B)) : vcm.B * Φ logdetΣ2 = convert(T, logdet(vcm.Σ[2])) TwoVarCompModelRotate{T, BT}(Brot, λ, Φ, logdetΣ2) #TwoVarCompModelRotate(Brot, λ, Φ, logdetΣ2) where {T, BT} end """ `VarianceComponentVariate` stores the data of a variance component model. # Feilds - `Y`: `n x d` responses - `X`: `n x p` predictors - `V`: tuple of `n x n` covariance matrices """ mutable struct VarianceComponentVariate{T <: AbstractFloat, M, YT <: AbstractVecOrMat, XT <: AbstractVecOrMat, VT <: AbstractMatrix} # data Y::YT X::XT V::NTuple{M, VT} end """ VarianceComponentVariate(Y, X, V) Default constructor of [`VarianceComponentVariate`](@ref) type. """ function VarianceComponentVariate( Y::AbstractVecOrMat, X::AbstractVecOrMat, V::NTuple{M, AbstractMatrix} ) where {M} VarianceComponentVariate{eltype(Y), M, typeof(Y), typeof(X), eltype(V)}(Y, X, V) end """ VarianceComponentVariate(Y, V) Constructor of a [`VarianceComponentVariate`](@ref) instance from `Y` and `V` alone. `X` is created empty. """ function VarianceComponentVariate( Y::AbstractVecOrMat, V::NTuple{M, AbstractMatrix} ) where {M} X = zeros(eltype(Y), size(Y, 1), 0) VarianceComponentVariate{eltype(Y), M, typeof(Y), typeof(X), eltype(V)}(Y, X, V) end """ `TwoVarCompVariateRotate` stores the rotated two variance component data. # Fields - `Yrot`: rotated responses `eigvec * Y` - `Xrot`: rotated covariates `eigvec * X` - `eigval`: eigenvalues of `eig(V[1], V[2])` - `eigvec`: eigenvectors of `eig(V[1], V[2])` - `logdetV2`: log-determinant of `V[2]` """ struct TwoVarCompVariateRotate{T <: AbstractFloat, YT <: AbstractVecOrMat, XT <: AbstractVecOrMat} # data Yrot::YT Xrot::XT eigval::Vector{T} eigvec::Matrix{T} logdetV2::T end """ TwoVarCompVariateRotate(Yrot, Xrot, eigval, eigvec,logdetV2) Default constructor of a [`TwoVarCompVariateRotate`](@ref) instance. """ function TwoVarCompVariateRotate( Yrot::AbstractVecOrMat, Xrot::AbstractVecOrMat, eigval::Vector, eigvec::Matrix, logdetV2::Real) ## JZ ### TwoVarCompVariateRotate{eltype(Yrot), typeof(Yrot), typeof(Xrot)}(Yrot, Xrot, eigval, eigvec, logdetV2) end """ TwoVarCompVariateRotate(twovarcomp) Constructor of a [`TwoVarCompVariateRotate`](@ref) instance from a [`TwoVarCompVariateRotate`](@ref) instance itself. """ function TwoVarCompVariateRotate( twovarcomp::TwoVarCompVariateRotate{T}) where T <: AbstractFloat ## JK ### twovarcomp end """ TwoVarCompVariateRotate(vcobs) Constructor of a [`TwoVarCompVariateRotate`](@ref) instance from a [`VarianceComponentVariate`](@ref) instance. """ function TwoVarCompVariateRotate(vcobs::VarianceComponentVariate{T, 2}) where T <: AbstractFloat zeroT = zero(T) # (generalized)-eigendecomposition of (V1, V2) if isa(vcobs.V[2], UniformScaling) || (isdiag(vcobs.V[2]) && norm(diag(vcobs.V[2]) .- one(T)) < 1.0e-8) F = eigen(Symmetric(vcobs.V[1])) deval = convert(Vector{T}, F.values) U = convert(Matrix{T}, F.vectors) logdetV2 = zero(T) else F = eigen(Symmetric(vcobs.V[1]), Symmetric(vcobs.V[2])) deval = convert(Vector{T}, F.values) U = convert(Matrix{T}, F.vectors) logdetV2 = convert(T, logdet(vcobs.V[2])) end # corect negative eigenvalues due to roundoff error @inbounds @simd for i in eachindex(deval) deval[i] = deval[i] > zeroT ? deval[i] : zeroT end # rotate responses Yrot = transpose(U) * vcobs.Y Xrot = isempty(vcobs.X) ? Array{T}(undef, size(Yrot, 1), 0) : transpose(U) * vcobs.X # output TwoVarCompVariateRotate(Yrot, Xrot, deval, U, logdetV2) end function TwoVarCompVariateRotate(vcdata::Array{T}) where T <: VarianceComponentVariate map(x -> TwoVarCompVariateRotate(x), vcdata) end """ VarianceComponentModel(vcobs) Construct a [`VarianceComponentModel`](@ref) instance from a [`VarianceComponentVariate`](@ref) instance. `B` is initialized to zero; `Σ` is initialized to a tupe of identity matrices. """ function VarianceComponentModel(vcobs::VarianceComponentVariate{T, M}) where {T, M} p, d, m = size(vcobs.X, 2), size(vcobs.Y, 2), length(vcobs.V) B = zeros(T, p, d) Σ = ntuple(x -> Matrix{T}(I, d, d), m)::NTuple{M, Matrix{T}} VarianceComponentModel(B, Σ) end """ VarianceComponentModel(vcobsrot) Construct [`VarianceComponentModel`](@ref) instance from a [`TwoVarCompVariateRotate`](@ref) instance. """ function VarianceComponentModel(vcobsrot::TwoVarCompVariateRotate) p, d = size(vcobsrot.Xrot, 2), size(vcobsrot.Yrot, 2) T = eltype(vcobsrot) B = zeros(T, p, d) Σ = (Matrix{T}(I, d, d), Matrix{T}(I, d, d)) VarianceComponentModel(B, Σ) end """ Auxillary data for variance component model. This can be used as pre-allocated intermediate variable in iterative algorithm. """ struct VarianceComponentAuxData{ T1 <: AbstractMatrix, T2 <: AbstractVector } res::T1 # same shape as response, p-by-d Xwork::T1 # nd-by-pd ywork::T2 # nd obswt::T2 # nd end function VarianceComponentAuxData(vcobs::VarianceComponentVariate) T = eltype(vcobs) res = zeros(T, size(vcobs.Y, 1), size(vcobs.Y, 2)) Xwork = zeros(T, length(vcobs.Y), nmeanparams(vcobs)) ywork = zeros(T, length(vcobs.Y)) obswt = zeros(T, length(vcobs.Y)) VarianceComponentAuxData{typeof(Xwork), typeof(ywork)}(res, Xwork, ywork, obswt) end function VarianceComponentAuxData(vcobsrot::TwoVarCompVariateRotate) T = eltype(vcobsrot) res = zeros(T, size(vcobsrot.Yrot, 1), size(vcobsrot.Yrot, 2)) Xwork = zeros(T, length(vcobsrot.Yrot), nmeanparams(vcobsrot)) ywork = zeros(T, length(vcobsrot.Yrot)) obswt = zeros(T, length(vcobsrot.Yrot)) VarianceComponentAuxData{typeof(Xwork), typeof(ywork)}(res, Xwork, ywork, obswt) end function VarianceComponentAuxData(vcdata::Array{T}) where T <: Union{VarianceComponentVariate, TwoVarCompVariateRotate} map(x -> VarianceComponentAuxData(x), vcdata) end """ eltype(vcm) eltype(vcobs) eltype(vcmrot) eltype(vcobsrot) Element type of variance component model or data. """ Base.eltype(vcm::VarianceComponentModel) = Base.eltype(vcm.B) Base.eltype(vcobs::VarianceComponentVariate) = Base.eltype(vcobs.Y) Base.eltype(vcmrot::TwoVarCompModelRotate) = Base.eltype(vcmrot.Brot) Base.eltype(vcobsrot::TwoVarCompVariateRotate) = Base.eltype(vcobsrot.Yrot) # Dimension of response, d """ length(vcm) length(vcobs) length(vcmrot) length(vcobsrot) Length `d` of response. """ length(vcm::VarianceComponentModel) = size(vcm.Σ[1], 1) length(vcobs::VarianceComponentVariate) = size(vcobs.Y, 2) length(vcmrot::TwoVarCompModelRotate) = length(vcmrot.eigval) length(vcobsrot::TwoVarCompVariateRotate) = size(vcobsrot.Yrot, 2) # Size of response, (n, d) """ size(vcobs) size(vcobsrot) Size `(n, d)` of the response matrix of a [`VarianceComponentVariate`](@ref) or [`TwoVarCompVariateRotate`](@ref). """ size(vcobs::VarianceComponentVariate) = size(vcobs.Y) size(vcobsrot::TwoVarCompVariateRotate) = size(vcobsrot.Yrot) # Number of variance components, m """ nvarcomps(vcm) nvarcomps(vcobs) nvarcomps(vcmrot) nvarcomps(vcobsrot) Number of varianece components. """ nvarcomps(vcm::VarianceComponentModel) = length(vcm.Σ) nvarcomps(vcobs::VarianceComponentVariate) = length(vcobs.V) nvarcomps(vcmrot::TwoVarCompModelRotate) = 2 nvarcomps(vcobsrot::TwoVarCompVariateRotate) = 2 # Number of mean parameters, p * d """ nmeanparams(vcm) nmeanparams(vcmrot) nmeanparams(vcobs) nmeanparams(vcobsrot) Number of mean parameters `p * d` of [`VarianceComponentModel`](@ref). """ nmeanparams(vcm::VarianceComponentModel) = length(vcm.B) nmeanparams(vcmrot::TwoVarCompModelRotate) = length(vcmrot.Brot) nmeanparams(vcobs::VarianceComponentVariate) = size(vcobs.X, 2) * size(vcobs.Y, 2) nmeanparams(vcobsrot::TwoVarCompVariateRotate) = size(vcobsrot.Xrot, 2) * size(vcobsrot.Yrot, 2) # Number of free parameters in Cholesky factors, m * d * (d + 1) / 2 """ nvarparams(vcm) Number of free parameters in Cholesky factors `m * d * (d + 1) / 2` of [`VarianceComponentModel`](@ref). """ nvarparams(vcm::Union{VarianceComponentModel, TwoVarCompModelRotate}) = nvarcomps(vcm) * binomial(length(vcm) + 1, 2) # Number of model parameters, p * d + m * d * (d + 1) / 2 """ nparams(vcm) Total number of model parameters `p * d + m * d * (d + 1) / 2` of [`VarianceComponentModel`](@ref). """ nparams(vcm::Union{VarianceComponentModel, TwoVarCompModelRotate}) = nmeanparams(vcm) + nvarparams(vcm) """ cov!(C, vcm, vcobs) Calculate the `nd x nd` covariance matrix of a [`VarianceComponentModel`](@ref) at a [`VarianceComponentVariate`](@ref) observation and over-write `C`. """ function cov!( C::AbstractMatrix, vcm::VarianceComponentModel, vcobs::VarianceComponentVariate ) fill!(C, zero(eltype(vcm))) for i in 1:length(vcm.Σ) kronaxpy!(vcm.Σ[i], vcobs.V[i], C) end return C end """ cov(vcm, vcobs) Calculate the `nd x nd` covariance matrix of a [`VarianceComponentModel`](@ref) at a [`VarianceComponentVariate`](@ref) observation. """ function cov( vcm::VarianceComponentModel, vcobs::VarianceComponentVariate ) n, d = size(vcobs) C = zeros(eltype(vcm), n * d, n * d) cov!(C, vcm, vcobs) end """ mean!(μ, vcm, vcobs) Calculate the `n x d` mean matrix of a a [`VarianceComponentModel`](@ref) at a [`VarianceComponentVariate`](@ref) observation and over-write `μ`. """ function mean!( μ::AbstractMatrix, vcm::VarianceComponentModel, vcobs::VarianceComponentVariate ) mul!(μ, vcobs.X, vcm.B) end """ mean(vcm, vcobs) Calculate the `n x d` mean matrix of a [`VarianceComponentModel`](@ref) at a [`VarianceComponentVariate`](@ref) observation. """ function mean(vcm::VarianceComponentModel, vcobs::VarianceComponentVariate) μ = zeros(eltype(vcobs), size(vcobs.Y)) mean!(μ, vcm, vcobs) end """ residual(vcm, vcobs) Residual of [`VarianceComponentVariate`](@ref) under [`VarianceComponentModel`](@ref). """ function residual(vcm::VarianceComponentModel, vcobs::VarianceComponentVariate) return isempty(vcobs.X) ? vcobs.Y : vcobs.Y - vcobs.X * vcm.B end function residual( vcm::T1, vcdata::Array{T2} ) where {T1 <: VarianceComponentModel, T2 <: VarianceComponentVariate} map(x -> residual(vcm, x), vcdata) end function residual!( resid::AbstractVecOrMat, vcm::VarianceComponentModel, vcobs::VarianceComponentVariate ) if isempty(vcobs.X) copyto!(resid, vcobs.Y) else oneT = one(eltype(vcm)) copyto!(resid, vcobs.Y) LinearAlgebra.BLAS.gemm!('N', 'N', -oneT, vcobs.X, vcm.B, oneT, resid) end resid end function residual!( resid::AbstractArray, vcm::T1, vcdata::Array{T2} ) where {T1 <: VarianceComponentModel, T2 <: VarianceComponentVariate} map(x -> residual!(x[1], vcm, x[2]), zip(resid, vcdata)) end """ residual(vcmrot, vcobsrot) Residual of [`TwoVarCompVariateRotate`](@ref) under [`TwoVarCompModelRotate`](@ref). """ function residual(vcmrot::TwoVarCompModelRotate, vcobsrot::TwoVarCompVariateRotate) if isempty(vcmrot.Brot) return vcobsrot.Yrot * vcmrot.eigvec else return vcobsrot.Yrot * vcmrot.eigvec - vcobsrot.Xrot * vcmrot.Brot end end function residual( vcmrot::T1, vcdatarot::Array{T2} ) where {T1 <: TwoVarCompModelRotate, T2 <: TwoVarCompVariateRotate} map(x -> residual(vcmrot, x), vcdatarot) end function residual!( resid::AbstractMatrix, vcmrot::TwoVarCompModelRotate, vcobsrot::TwoVarCompVariateRotate ) if isempty(vcmrot.Brot) mul!(resid, vcobsrot.Yrot, vcmrot.eigvec) else #copy!(resid, vcobsrot.Yrot * vcmrot.eigvec - vcobsrot.Xrot * vcmrot.Brot) oneT = one(eltype(vcmrot)) mul!(resid, vcobsrot.Yrot, vcmrot.eigvec) LinearAlgebra.BLAS.gemm!('N', 'N', -oneT, vcobsrot.Xrot, vcmrot.Brot, oneT, resid) end resid end function residual!( resid::Array{AbstractMatrix}, vcmrot::T1, vcdatarot::Array{T2}) where {T1 <: TwoVarCompModelRotate, T2 <: TwoVarCompVariateRotate} map!(x -> residual(vcmrot, x), resid, vcdatarot) end # utilities for multivariate calculus include("multivariate_calculus.jl") # source for fitting models with 2 variance components include("two_variance_component.jl") end # VarianceComponentModels
VarianceComponentModels
https://github.com/OpenMendel/VarianceComponentModels.jl.git
[ "MIT" ]
0.1.3
82d058ac0c22844b80c5bc098f17c7f7d5268f11
code
6199
# module MultivariateCalculus using SparseArrays export vech, trilind, triuind, commutation, spcommutation, duplication, spduplication, chol_gradient, chol_gradient!, kron_gradient, kron_gradient!, kronaxpy!, bump_diagonal!, clamp_diagonal! """ Vectorize the lower triangular part of a matrix. """ function vech(a::Union{Number, AbstractVecOrMat}) m, n = size(a) out = similar(a, convert(Int, (2m - n + 1) * n / 2)) ooffset, aoffset = 1, 1 for j = 1:n len = m - j + 1 # no. elements to copy in column j copyto!(out, ooffset, a, aoffset, len) ooffset += m - j + 1 aoffset += m + 1 end out end # a is a scalar or (column) vector vech(a::Union{Number, AbstractVector}) = copy(a) """ commutation(type, m[, n]) Create the `mn x mn` commutation matrix `K`, defined by `K * vec(A) = vec(A')` for any `m x n` matrix A. """ function commutation(t::Type, m::Integer, n::Integer) ((m < 0) || (n < 0)) && throw(ArgumentError("invalid Array dimensions")) mn = m * n reshape(kron(vec(Matrix{t}(I, m, m)), Matrix{t}(I, n, n)), mn, mn) end commutation(m::Integer, n::Integer) = commutation(Float64, m, n) commutation(t::Type, m::Integer) = commutation(t, m, m) commutation(m::Integer) = commutation(m, m) commutation(M::AbstractMatrix) = commutation(eltype(M), size(M, 1), size(M, 2)) """ spcommutation(type, m[, n]) Create the sparse `mn`-by-`mn` commutation matrix `K`, defined by `K * vec(A) = vec(A')` for any `m x n` matrix A. """ function spcommutation(t::Type, m::Integer, n::Integer) ((m < 0) || (n < 0)) && throw(ArgumentError("invalid Array dimensions")) mn = m * n reshape(kron(vec(sparse(t(1)I, m, m)), sparse(t(1)I, n, n)), mn, mn) end spcommutation(m::Integer, n::Integer) = spcommutation(Float64, m, n) spcommutation(t::Type, m::Integer) = spcommutation(t, m, m) spcommutation(m::Integer) = spcommutation(m, m) spcommutation(M::AbstractMatrix) = spcommutation(eltype(M), size(M, 1), size(M, 2)) """ trilind(m, n,[ k]) Linear indices of the lower triangular part of an `m x n` array. """ function trilind(m::Integer, n::Integer, k::Integer) (LinearIndices(tril(trues(m, n), k)))[findall(tril(trues(m, n), k))] end function trilind(m::Integer, n::Integer) (LinearIndices(tril(trues(m, n))))[findall(tril(trues(m, n)))] end function trilind(m::Integer) (LinearIndices(tril(trues(m, m))))[findall(tril(trues(m, m)))] end trilind(M::AbstractArray) = trilind(size(M, 1), size(M, 2)) trilind(M::AbstractArray, k::Integer) = trilind(size(M, 1), size(M, 2), k) """ triuind(m, n,[ k]) Linear indices of the upper triangular part of an `m x n` array. """ function triuind(m::Integer, n::Integer, k::Integer) (LinearIndices(triu(trues(m, n), k)))[findall(triu(trues(m, n), k))] end function triuind(m::Integer, n::Integer) (LinearIndices(triu(trues(m, n))))[findall(triu(trues(m, n)))] end function triuind(m::Integer) (LinearIndices(triu(trues(m, m))))[findall(triu(trues(m, m)))] end triuind(M::AbstractArray) = triuind(size(M, 1), size(M, 2)) triuind(M::AbstractArray, k::Integer) = triuind(size(M, 1), size(M, 2), k) """ spduplication(type, n) Create the sparse `n^2 x n(n+1)/2` duplication matrix, defined by `D * vech(A) = vec(A)` for any symmetric matrix. """ function spduplication(t::Type, n::Integer) imatrix = zeros(typeof(n), n, n) imatrix[trilind(n, n)] = 1:binomial(n + 1, 2) imatrix = imatrix + copy(transpose(tril(imatrix, -1))) sparse(1:n^2, vec(imatrix), one(t)) end spduplication(n::Integer) = spduplication(Float64, n) spduplication(M::AbstractMatrix) = spduplication(eltype(M), size(M, 1)) duplication(t::Type, n::Integer) = Matrix(spduplication(t, n)) duplication(n::Integer) = duplication(Float64, n) duplication(M::AbstractMatrix) = duplication(eltype(M), size(M, 1)) """ kron_gradient!(g, dM, Y) Compute the gradient `d / d vec(X)` from a vector of derivatives `dM` where `M=X⊗Y`, `n, q = size(X)`, and `p, r = size(Y)`. """ function kron_gradient!(g::VecOrMat{T}, dM::VecOrMat{T}, Y::Matrix{T}, n::Integer, q::Integer) where {T <: Real} p, r = size(Y) mul!(g, kron(sparse(I, n * q, n * q), vec(Y)'), (kron(sparse(I, q, q), spcommutation(n, r), sparse(I, p, p)) * dM)) end function kron_gradient(dM::VecOrMat{T}, Y::Matrix{T}, n::Integer, q::Integer) where {T <: Real} if ndims(dM) == 1 g = zeros(T, n * q) else g = zeros(T, n * q, size(dM, 2)) end kron_gradient!(g, dM, Y, n, q) end """ chol_gradient!(g, dM, L) Compute the gradient `d / d vech(L)` from a vector of derivatives `dM` where `M=L*L'`. # TODO make it more memory efficient """ function chol_gradient!(g::AbstractVecOrMat{T}, dM::AbstractVecOrMat{T}, L::AbstractMatrix{T}) where {T <: Real} n = size(L, 1) mul!(g, transpose(spduplication(n)), kron(L', sparse(1.0I, n, n)) * (dM + spcommutation(n) * dM)) end function chol_gradient(dM::AbstractVecOrMat{T}, L::AbstractMatrix{T}) where {T <: Real} n = size(L, 1) if ndims(dM) == 1 # vector g = zeros(T, binomial(n + 1, 2)) else # matrix g = zeros(T, binomial(n + 1, 2), size(dM, 2)) end chol_gradient!(g, dM, L) end """ kronaxpy!(A, X, Y) Overwrites `Y` with `A ⊗ X + Y`. Same as `Y += kron(A, X)` but more efficient. """ function kronaxpy!(A::AbstractVecOrMat{T}, X::AbstractVecOrMat{T}, Y::AbstractVecOrMat{T}) where {T <: Real} # retrieve matrix sizes m, n = size(A, 1), size(A, 2) p, q = size(X, 1), size(X, 2) # loop over (i,j) blocks of Y irange, jrange = 1:p, 1:q @inbounds for j in 1:n, i in 1:m a = A[i, j] irange = ((i - 1) * p + 1):(i * p) jrange = ((j - 1) * q + 1):(j * q) Yij = view(Y, irange, jrange) # view of (i, j)-block @simd for k in eachindex(Yij) Yij[k] += a * X[k] end end Y end """ Add `ϵ` to the diagonal entries of matrix `A`. """ function bump_diagonal!(A::Matrix{T}, ϵ::T) where {T} @inbounds @simd for i in 1:minimum(size(A)) A[i, i] += ϵ end A end """ Clamp the diagonal entries of matrix `A` to `[lo, hi]`. """ function clamp_diagonal!(A::Matrix{T}, lo::T, hi::T) where {T} @inbounds @simd for i in 1:minimum(size(A)) A[i, i] = clamp(A[i, i], lo, hi) end A end #end # module MultivariateCalculus
VarianceComponentModels
https://github.com/OpenMendel/VarianceComponentModels.jl.git
[ "MIT" ]
0.1.3
82d058ac0c22844b80c5bc098f17c7f7d5268f11
code
42087
import Printf export heritability, logpdf, gradient!, gradient, fisher_Σ!, fisher_Σ, fisher_B!, fisher_B, mle_fs!, mle_mm!, fit_mle!, fit_reml!, update_meanparam! #---------------------------------------------------------------------------# # Evaluate log-pdf #---------------------------------------------------------------------------# """ logpdf(vcmrot, vcobsrot) Calculate log-pdf of a [`TwoVarCompVariateRotate`](@ref) instance under a [`TwoVarCompModelRotate`](@ref). """ function logpdf( vcmrot::T1, vcobsrot::T2, vcaux::T3 = VarianceComponentAuxData(vcobsrot) ) where { T1 <: TwoVarCompModelRotate, T2 <: TwoVarCompVariateRotate, T3 <: VarianceComponentAuxData} n, d = size(vcobsrot.Yrot, 1), size(vcobsrot.Yrot, 2) T = eltype(vcmrot) zeroT, oneT = zero(T), one(T) residual!(vcaux.res, vcmrot, vcobsrot) # evaluate 2(log-likehood) objval = convert(T, - n * d * log(2π) - d * vcobsrot.logdetV2 - n * vcmrot.logdetΣ2) tmp, λj = zeroT, zeroT @inbounds for j in 1:d λj = vcmrot.eigval[j] @simd for i in 1:n tmp = oneT / (vcobsrot.eigval[i] * λj + oneT) objval += log(tmp) - tmp * vcaux.res[i, j]^2 end end objval /= 2 end """ logpdf(vcm, vcobsrot) Calculate log-pdf of a [`TwoVarCompVariateRotate`](@ref) instance under a [`VarianceComponentModel`](@ref). """ function logpdf( vcm::T1, vcobs::T2, vcaux::T3 = VarianceComponentAuxData(vcobs) ) where { T1 <: VarianceComponentModel, T2 <: TwoVarCompVariateRotate, T3 <: VarianceComponentAuxData} logpdf(TwoVarCompModelRotate(vcm), vcobs, vcaux) end function logpdf( vcm::T1, vcobs::T2, vcaux::T3 = VarianceComponentAuxData(vcobs) ) where { T1 <: VarianceComponentModel, T2 <: VarianceComponentVariate, T3 <: VarianceComponentAuxData} logpdf(TwoVarCompModelRotate(vcm), TwoVarCompVariateRotate(vcobs), vcaux) end """ Calculate log-pdf of an array of variance component instances. """ function logpdf( vcm::T1, vcdata::Array{T2}, vcaux::Array{T3} = VarianceComponentAuxData(vcdata) ) where { T1 <: Union{VarianceComponentModel, TwoVarCompModelRotate}, T2 <: Union{VarianceComponentVariate, TwoVarCompVariateRotate}, T3 <: VarianceComponentAuxData} mapreduce(x -> logpdf(vcm, x...), +, zip(vcdata, vcaux)) end #---------------------------------------------------------------------------# # Evaluate gradient #---------------------------------------------------------------------------# """ gradient!(∇, vcmrot, vcobsrot) Evaluate gradient of `Σ` at `vcmrot.Σ` and overwrite `∇`. # Input - `∇::Vector`: gradient vector. - `vcmrot`: *rotated* two variance component model [`TwoVarCompModelRotate`](@ref). - `vcobsrot`: *rotated* two variance component data [`TwoVarCompVariateRotate`](@ref). # Output - `∇`: gradient vector at `Σ = (Σ[1], Σ[2])`. # TODO - optimize computation """ function gradient!( ∇::AbstractVector{T}, vcmrot::TwoVarCompModelRotate{T}, vcobsrot::TwoVarCompVariateRotate{T}, vcaux::VarianceComponentAuxData = VarianceComponentAuxData(vcobsrot) ) where {T <: AbstractFloat} n, d = size(vcobsrot.Yrot, 1), size(vcobsrot.Yrot, 2) zeroT, oneT = zero(T), one(T) residual!(vcaux.res, vcmrot, vcobsrot) # gradient wrt Σ[2] tmp, λj, dg = zeroT, zeroT, zeros(T, d) @inbounds for j in 1:d λj = vcmrot.eigval[j] @simd for i in 1:n tmp = oneT / (vcobsrot.eigval[i] * λj + oneT) vcaux.res[i, j] *= tmp dg[j] += tmp end end N = transpose(vcaux.res) * vcaux.res @inbounds for j in 1:d N[j, j] -= dg[j] end #A_mul_Bt!(N, N, vcmrot.eigvec), A_mul_B!(N, vcmrot.eigvec, N) N = vcmrot.eigvec * N * vcmrot.eigvec' copyto!(∇, d^2 + 1, N, 1, d^2) # gradient wrt Σ[1] @inbounds for j in 1:d λj = vcmrot.eigval[j] dg[j] = zeroT @simd for i in 1:n tmp = vcobsrot.eigval[i] vcaux.res[i, j] *= √tmp dg[j] += tmp / (tmp * λj + oneT) end end mul!(N, transpose(vcaux.res), vcaux.res) @inbounds for j in 1:d N[j, j] -= dg[j] end #A_mul_Bt!(N, N, vcmrot.eigvec), A_mul_B!(N, vcmrot.eigvec, N) N = vcmrot.eigvec * N * vcmrot.eigvec' copyto!(∇, N) # scale by 0.5 rmul!(∇, 1//2) end # function gradient! """ gradient(vcmrot, vcobsrot) Evaluate gradient of `Σ` at `vcmrot.Σ` and overwrite `∇`. # Input - `vcmrot`: *rotated* two variance component model [`TwoVarCompModelRotate`](@ref). - `vcobsrot`: *rotated* two variance component data [`TwoVarCompVariateRotate`](@ref). # Output - `∇`: gradient vector at `Σ = (Σ[1], Σ[2])`. # TODO - optimize computation """ function gradient( vcmrot::TwoVarCompModelRotate{T}, vcobsrot::TwoVarCompVariateRotate{T}, vcaux::VarianceComponentAuxData = VarianceComponentAuxData(vcobsrot) ) where {T <: AbstractFloat} d = length(vcmrot) ∇ = zeros(T, 2d^2) gradient!(∇, vcmrot, vcobsrot, vcaux) end """ gradient!(∇, vcm, vcobsrot) Evaluate gradient of `Σ` at `vcmrot.Σ` and overwrite `∇`. # Input - `∇::Vector`: gradient vector. - `vcmrot`: two variance component model [`VarianceComponentModel`](@ref). - `vcobsrot`: *rotated* two variance component data [`TwoVarCompVariateRotate`](@ref). # Output - `∇`: gradient vector at `Σ = (Σ[1], Σ[2])`. # TODO - optimize computation """ function gradient!( ∇::AbstractVector{T}, vcm::VarianceComponentModel{T, 2}, vcobs::TwoVarCompVariateRotate{T}, vcaux::VarianceComponentAuxData = VarianceComponentAuxData(vcobs) ) where {T <: AbstractFloat} gradient!(∇, TwoVarCompModelRotate(vcm), vcobs, vcaux) end function gradient!( ∇::AbstractVector{T}, vcm::VarianceComponentModel{T, 2}, vcobs::VarianceComponentVariate{T, 2}, vcaux::VarianceComponentAuxData = VarianceComponentAuxData(vcobs) ) where {T <: AbstractFloat} gradient!(∇, TwoVarCompModelRotate(vcm), TwoVarCompVariateRotate(vcobs), vcaux) end """ gradient(vcm, vcobsrot) Evaluate gradient of `Σ` at `vcmrot.Σ` and overwrite `∇`. # Input - `vcmrot`: two variance component model [`VarianceComponentModel`](@ref). - `vcobsrot`: *rotated* two variance component data [`TwoVarCompVariateRotate`](@ref). # Output - `∇`: gradient vector at `Σ = (Σ[1], Σ[2])`. # TODO - optimize computation """ function gradient( vcm::VarianceComponentModel{T, 2}, vcobs::TwoVarCompVariateRotate, vcaux::VarianceComponentAuxData = VarianceComponentAuxData(vcobs) ) where {T <: AbstractFloat} gradient(TwoVarCompModelRotate(vcm), vcobs, vcaux) end function gradient( vcm::VarianceComponentModel{T, 2}, vcobs::VarianceComponentVariate{T, 2}, vcaux::VarianceComponentAuxData = VarianceComponentAuxData(vcobs) ) where {T <: AbstractFloat} gradient(TwoVarCompModelRotate(vcm), TwoVarCompVariateRotate(vcobs), vcaux) end function gradient!( ∇::AbstractVector, vcm::T1, vcdata::Array{T2}, vcaux::Array{T3} = VarianceComponentAuxData(vcdata)# map(x -> VarianceComponentAuxData(x), vcdata) ) where { T1 <: Union{VarianceComponentModel, TwoVarCompModelRotate}, T2 <: Union{VarianceComponentVariate, TwoVarCompVariateRotate}, T3 <: VarianceComponentAuxData} copyto!(∇, gradient(vcm, vcdata, vcaux)) end function gradient( vcm::T1, vcdata::Array{T2}, vcaux::Array{T3} = VarianceComponentAuxData(vcdata) ) where { T1 <: Union{VarianceComponentModel, TwoVarCompModelRotate}, T2 <: Union{VarianceComponentVariate, TwoVarCompVariateRotate}, T3 <: VarianceComponentAuxData} mapreduce(x -> gradient(vcm, x...), +, zip(vcdata, vcaux)) end #---------------------------------------------------------------------------# # Evaluate Fisher information matrix with respect to Σ #---------------------------------------------------------------------------# """ fisher_Σ!(H, vcmrot, vcobsrot) Calculate Fisher information matrix at `Σ = (Σ[1], Σ[2])` and overwrite `H` based on *rotated* two variance component model `vcmrot` and *rotated* two variance component data `vcobsrot`. # Input - `H`: Hessian matrix. - `vcmrot::TwoVarCompModelRotate`: *rotated* two variance component model. - `vcobsrot::TwoVarCompVariateRotate`: *rotated* two variance component data. # Output - `H`: Fisher information matrix at `Σ = (Σ[1], Σ[2])`. """ function fisher_Σ!( H::AbstractMatrix{T}, vcmrot::TwoVarCompModelRotate{T}, vcobsrot::TwoVarCompVariateRotate{T} ) where {T <: AbstractFloat} n, d = size(vcobsrot.Yrot, 1), size(vcobsrot.Yrot, 2) zeroT, oneT = zero(T), one(T) fill!(H, zeroT) # evaluate Hessian with respect to Σ[1], Σ[2] C = zeros(T, d, d) Φ2 = kron(vcmrot.eigvec, vcmrot.eigvec) # (1, 1) block λi, λj, deval = zeroT, zeroT, zeroT @inbounds for j in 1:d, i in j:d λi, λj = vcmrot.eigval[i], vcmrot.eigval[j] @simd for obs in 1:n deval = vcobsrot.eigval[obs] C[i, j] += deval * deval / (λi * deval + oneT) / (λj * deval + oneT) end end LinearAlgebra.copytri!(C, 'L') mul!(view(H, 1:d^2, 1:d^2), Φ2 * Diagonal(vec(C)), transpose(Φ2)) # (2, 1) block fill!(C, zeroT) @inbounds for j in 1:d, i in j:d λi, λj = vcmrot.eigval[i], vcmrot.eigval[j] @simd for obs in 1:n deval = vcobsrot.eigval[obs] C[i, j] += deval / (λi * deval + oneT) / (λj * deval + oneT) end end LinearAlgebra.copytri!(C, 'L') mul!(view(H, (d^2+1):(2d^2), 1:d^2), Φ2 * Diagonal(vec(C)), transpose(Φ2)) # d-by-d (2, 2) block fill!(C, zeroT) @inbounds for j in 1:d, i in j:d λi, λj = vcmrot.eigval[i], vcmrot.eigval[j] @simd for obs in 1:n deval = vcobsrot.eigval[obs] C[i, j] += oneT / (λi * deval + oneT) / (λj * deval + oneT) end end LinearAlgebra.copytri!(C, 'L') mul!(view(H, (d^2+1):(2d^2), (d^2+1):(2d^2)), Φ2 * Diagonal(vec(C)), transpose(Φ2)) # copy to upper triangular part LinearAlgebra.copytri!(H, 'L') rmul!(H, convert(T, 0.5)) # output return H end # function fisher! function fisher_Σ( vcmrot::TwoVarCompModelRotate{T}, vcobsrot::TwoVarCompVariateRotate{T} ) where {T <: AbstractFloat} d = length(vcmrot.eigval) H = zeros(T, 2d^2, 2d^2) fisher_Σ!(H, vcmrot, vcobsrot) end function fisher_Σ!( H::AbstractMatrix{T}, vcm::VarianceComponentModel{T, 2}, vcobsrot::TwoVarCompVariateRotate{T} ) where {T <: AbstractFloat} fisher_Σ!(H, TwoVarCompModelRotate(vcm), vcobsrot) end function fisher_Σ!( H::AbstractMatrix{T}, vcm::VarianceComponentModel{T, 2}, vcobsrot::VarianceComponentVariate{T, 2} ) where {T <: AbstractFloat} fisher_Σ!(H, TwoVarCompModelRotate(vcm), TwoVarCompVariateRotate(vcobsrot)) end function fisher_Σ( vcm::VarianceComponentModel{T, 2}, vcobsrot::VarianceComponentVariate{T, 2} ) where {T <: AbstractFloat} fisher_Σ(TwoVarCompModelRotate(vcm), TwoVarCompVariateRotate(vcobsrot)) end function fisher_Σ( vcm::VarianceComponentModel{T, 2}, vcobsrot::TwoVarCompVariateRotate{T} ) where {T <: AbstractFloat} fisher_Σ(TwoVarCompModelRotate(vcm), vcobsrot) end function fisher_Σ!( H::AbstractMatrix, vcm::T1, vcobs::Array{T2} ) where { T1 <: Union{VarianceComponentModel, TwoVarCompModelRotate}, T2 <: Union{VarianceComponentVariate, TwoVarCompVariateRotate}} copyto!(H, fisher_Σ(vcm, vcobs)) end function fisher_Σ( vcm::T1, vcobs::Array{T2} ) where { T1 <: Union{VarianceComponentModel, TwoVarCompModelRotate}, T2 <: Union{VarianceComponentVariate, TwoVarCompVariateRotate}} mapreduce(x -> fisher_Σ(vcm, x), +, vcobs) end #---------------------------------------------------------------------------# # Evaluate Fisher information matrix with respect to B #---------------------------------------------------------------------------# """ fisher_B!(H, vcmrot, vcobsrot) Calculate Fisher information matrix of `B` and overwrite `H` based on two variance component model `vcmrot` and *rotated* two variance component data `vcobsrot`. # Input - `H`: Hessian matrix. - `vcmrot::VarianceComponentModel{T, 2}`: two variance component model. - `vcobsrot::TwoVarCompVariateRotate`: *rotated* two variance component data. # Output - `H`: Fisher information matrix at `B`. """ function fisher_B!( H::AbstractMatrix{T}, vcmrot::TwoVarCompModelRotate{T}, vcobsrot::TwoVarCompVariateRotate{T}, vcaux::VarianceComponentAuxData = VarianceComponentAuxData(vcobsrot) ) where {T <: AbstractFloat} zeroT, oneT = zero(T), one(T) # working X fill!(vcaux.Xwork, zeroT) kronaxpy!(vcmrot.eigvec', vcobsrot.Xrot, vcaux.Xwork) # working weights fill!(vcaux.obswt, zeroT) kronaxpy!(vcobsrot.eigval, vcmrot.eigval, vcaux.obswt) @inbounds @simd for i in eachindex(vcaux.obswt) vcaux.obswt[i] = oneT / √(vcaux.obswt[i] + oneT) end # weighted least squares lmul!(Diagonal(vcaux.obswt), vcaux.Xwork) mul!(H, transpose(vcaux.Xwork), vcaux.Xwork) end function fisher_B( vcmrot::TwoVarCompModelRotate{T}, vcobsrot::TwoVarCompVariateRotate{T} ) where {T <: AbstractFloat} H = zeros(T, nmeanparams(vcmrot), nmeanparams(vcmrot)) fisher_B!(H, vcmrot, vcobsrot) end function fisher_B!( H::AbstractMatrix{T}, vcm::Union{VarianceComponentModel{T, 2}, TwoVarCompVariateRotate{T}}, vcobs::Union{TwoVarCompVariateRotate{T}, VarianceComponentVariate{T, 2}}, vcaux::VarianceComponentAuxData = VarianceComponentAuxData(vcobs) ) where {T <: AbstractFloat} fisher_B!(H, TwoVarCompModelRotate(vcm), TwoVarCompVariateRotate(vcobs), vcaux) end function fisher_B( vcm::T1, vcobs::T2, vcaux::T3 = VarianceComponentAuxData(vcobs) ) where { T1 <: Union{VarianceComponentModel, TwoVarCompModelRotate}, T2 <: Union{VarianceComponentVariate, TwoVarCompVariateRotate}, T3 <: VarianceComponentAuxData} H = zeros(eltype(vcm), nmeanparams(vcm), nmeanparams(vcm)) fisher_B!(H, TwoVarCompModelRotate(vcm), TwoVarCompVariateRotate(vcobs), vcaux) end function fisher_B!( H::AbstractMatrix, vcm::T1, vcdata::Array{T2}, vcaux::Array{T3} = VarianceComponentAuxData(vcdata) ) where { T1 <: Union{VarianceComponentModel, TwoVarCompModelRotate}, T2 <: Union{VarianceComponentVariate, TwoVarCompVariateRotate}, T3 <: VarianceComponentAuxData} copyto!(H, fisher_B(vcm, vcdata, vcaux)) end function fisher_B( vcm::T1, vcdata::Array{T2}, vcaux::Array{T3} = VarianceComponentAuxData(vcdata) ) where { T1 <: Union{VarianceComponentModel, TwoVarCompModelRotate}, T2 <: Union{VarianceComponentVariate, TwoVarCompVariateRotate}, T3 <: VarianceComponentAuxData} mapreduce(x -> fisher_B(vcm, x...), +, zip(vcdata, vcaux)) end #---------------------------------------------------------------------------# # Update mean parameters by quadratic programming #---------------------------------------------------------------------------# """ Compute the quadratic and linear parts of weighted least squares criterion. """ function suffstats_for_B( vcmrot::TwoVarCompModelRotate{T}, vcobsrot::TwoVarCompVariateRotate{T}, vcaux::VarianceComponentAuxData = VarianceComponentAuxData(vcobsrot) ) where {T <: AbstractFloat} zeroT, oneT = zero(T), one(T) # working weights fill!(vcaux.obswt, zeroT) kronaxpy!(vcmrot.eigval, vcobsrot.eigval, vcaux.obswt) @inbounds @simd for i in eachindex(vcaux.obswt) vcaux.obswt[i] = oneT / √(vcaux.obswt[i] + oneT) end # working X fill!(vcaux.Xwork, zeroT) kronaxpy!(vcmrot.eigvec', vcobsrot.Xrot, vcaux.Xwork) lmul!(Diagonal(vcaux.obswt), vcaux.Xwork) # working y mul!(vcaux.res, vcobsrot.Yrot, vcmrot.eigvec) @inbounds @simd for i in eachindex(vcaux.ywork) vcaux.ywork[i] = vcaux.res[i] * vcaux.obswt[i] end # output return transpose(vcaux.Xwork) * vcaux.Xwork, transpose(vcaux.Xwork) * vcaux.ywork end function suffstats_for_B( vcmrot::T1, vcdatarot::Array{T2}, vcaux::Array{T3} ) where { T1 <: TwoVarCompModelRotate, T2 <: TwoVarCompVariateRotate, T3 <: VarianceComponentAuxData} mapreduce(x -> suffstats_for_B(vcmrot, x...), +, zip(vcdatarot, vcaux)) end function +( x::Tuple{AbstractMatrix, AbstractVector}, y::Tuple{AbstractMatrix, AbstractVector} ) x[1] + y[1], x[2] + y[2] end """ Update mean parameters `vcm.B` by quadratic programming. ## Input - `vcm::VarianceComponentModel{T, 2}`: two variance component model - `vcdatarot::TwoVarCompVariateRotate`: *rotated* two variance component data - `qpsolver`: QP solver - `Q`: quadratic part in the QP - `c`: linear part in the QP ## Output - `vcm.B`: updated mean parameters """ function update_meanparam!( vcm::T1, vcdatarot::Union{T2, Array{T2}}, qpsolver::MathProgBase.SolverInterface.AbstractMathProgSolver = MathProgBase.defaultQPsolver, vcaux::Union{T3, Array{T3}} = VarianceComponentAuxData(vcdatarot) ) where { T1 <: VarianceComponentModel, T2 <: TwoVarCompVariateRotate, T3 <: VarianceComponentAuxData} # quick return if there is no mean parameters isempty(vcm.B) && return vcm.B # rotate the model vcmrot = TwoVarCompModelRotate(vcm) # accumlate the quadratic and linear parts of QP Q, c = suffstats_for_B(vcmrot, vcdatarot, vcaux) # quadratic programming qpsol = quadprog(-c, Q, vcm.A, vcm.sense, vcm.b, vcm.lb, vcm.ub, qpsolver) if qpsol.status ≠ :Optimal println("Error in quadratic programming $(qpsol.status)") end copyto!(vcm.B, qpsol.sol) return vcm.B end #---------------------------------------------------------------------------# # Fisher scoring algorithm #---------------------------------------------------------------------------# """ `TwoVarCompOptProb` holds data and model for solving two variance component problem # Fields - `vcmodel`: [`VarianceComponentModel`](@ref) - `qcdatarot`: [`TwoVarCompVariateRotate`](@ref) - `qpsolver`: `MathProgBase.SolverInterface.AbstractMathProgSolver` - `L`: working variable, a tuple of two Cholesky factors `(L[1], L[2])` - `∇Σ`: working variable, gradient with respect to `(Σ[1], Σ[2])` - `HΣ`: working variable, Hessian with respect to `(Σ[1], Σ[2])` - `HL`: working variable, Hessian with respect to `(L[1], L[2])` - `Q`: working variable, quadratic part of QP for updating `B` - `c`: working variable, linear part of QP for updating `B` """ mutable struct TwoVarCompOptProb{ T1 <: VarianceComponentModel, T2 <: Union{TwoVarCompVariateRotate, AbstractArray}, T3 <: AbstractMatrix, T4 <: AbstractVector, T5 <: Union{VarianceComponentAuxData, AbstractArray}} <: MathProgBase.AbstractNLPEvaluator # variance component model and data vcmodel::T1 vcdatarot::T2 # QP solver for updating B given Σ qpsolver::MathProgBase.SolverInterface.AbstractMathProgSolver # intermediate variables L::NTuple{2, T3} # Cholesky factors ∇Σ::T4 # graident wrt (Σ1, Σ2) HΣ::T3 # Hessian wrt (Σ1, Σ2) HL::T3 # Hessian wrt (L1, L2) vcaux::T5 end """ TwoVarCompOptProb(vcm, vcobsrot) TwoVarCompOptProb(vcm, vcobsrot, qpsolver) Constructor of [`TwoVarCompOptProb`](@ref) from [`VarianceComponentModel`](@ref) `vcm`, [`TwoVarCompVariateRotate`](@ref) `vcobsrot`, and input quadratic programming sovler `qpsolver`. """ function TwoVarCompOptProb( vcm::T1, vcdatarot::Union{T2, Array{T2}}, qpsolver::MathProgBase.SolverInterface.AbstractMathProgSolver = MathProgBase.defaultQPsolver ) where { T1 <: VarianceComponentModel, T2 <: TwoVarCompVariateRotate} T = eltype(vcm) d, pd = length(vcm), nmeanparams(vcm) # number of optimization parameters in variance nvar = nvarparams(vcm) # allocate intermediate variables L = (zeros(T, d, d), zeros(T, d, d)) ∇Σ = zeros(T, 2d^2) # graident wrt (Σ1, Σ2) HΣ = zeros(T, 2d^2, 2d^2) # Hessian wrt (Σ1, Σ2) HL = zeros(T, nvar, nvar) # Hessian wrt Ls vcaux = VarianceComponentAuxData(vcdatarot) # constructor TwoVarCompOptProb{typeof(vcm), typeof(vcdatarot), typeof(HΣ), typeof(∇Σ), typeof(vcaux)}(vcm, vcdatarot, qpsolver, L, ∇Σ, HΣ, HL, vcaux) end """ optimparam_to_vcparam(dd, x) Translate optimization variables `x` to variance component parmeters `dd.vcmodel.Σ` in [`TwoVarCompOptProb`](@ref). """ function optimparam_to_vcparam!(dd::TwoVarCompOptProb, x::Vector{T}) where {T} d = size(dd.L[1], 1) nvar = nvarparams(dd.vcmodel) nvarhalf = div(nvar, 2) # variance parameter dd.L[1][trilind(d)] = x[1:nvarhalf] dd.L[2][trilind(d)] = x[(nvarhalf+1):end] # exponentiate diagonal entries @inbounds @simd for i in 1:d dd.L[1][i, i] = exp(dd.L[1][i, i]) dd.L[2][i, i] = exp(dd.L[2][i, i]) end # Σi = Li Li' mul!(dd.vcmodel.Σ[1], dd.L[1], transpose(dd.L[1])) mul!(dd.vcmodel.Σ[2], dd.L[2], transpose(dd.L[2])) # make sure the last variance component is pos. def. ϵ = convert(T, 1e-8) clamp_diagonal!(dd.vcmodel.Σ[2], ϵ, T(Inf)) end function MathProgBase.initialize(dd::TwoVarCompOptProb, requested_features::Vector{Symbol}) for feat in requested_features if !(feat in [:Grad, :Jac, :Hess]) error("Unsupported feature $feat") end end end # function MathProgBase.initialize MathProgBase.features_available(dd::TwoVarCompOptProb) = [:Grad, :Jac, :Hess] MathProgBase.eval_g(dd::TwoVarCompOptProb, g, x) = nothing MathProgBase.jac_structure(dd::TwoVarCompOptProb) = Int[], Int[] MathProgBase.eval_jac_g(dd::TwoVarCompOptProb, J, x) = nothing function MathProgBase.eval_f(dd::TwoVarCompOptProb, x::Vector{T}) where {T} # update variance parameter from optim variable x optimparam_to_vcparam!(dd, x) # update mean parameters update_meanparam!(dd.vcmodel, dd.vcdatarot, dd.qpsolver, dd.vcaux) # evaluate profile log-pdf logpdf(dd.vcmodel, dd.vcdatarot, dd.vcaux) end # function MathProgBase.eval_f function MathProgBase.eval_grad_f( dd::TwoVarCompOptProb, grad_f::Vector{T}, x::Vector{T} ) where {T} d = size(dd.L[1], 1) nvar = nvarparams(dd.vcmodel) nvarhalf = div(nvar, 2) # update variance parameter from optim variable x optimparam_to_vcparam!(dd, x) # update mean parameters update_meanparam!(dd.vcmodel, dd.vcdatarot, dd.qpsolver, dd.vcaux) # gradient wrt (Σ[1], Σ[2]) gradient!(dd.∇Σ, dd.vcmodel, dd.vcdatarot, dd.vcaux) # chain rule for gradient wrt Cholesky factor chol_gradient!(view(grad_f, 1:nvarhalf), dd.∇Σ[1:d^2], dd.L[1]) chol_gradient!(view(grad_f, (nvarhalf+1):nvar), dd.∇Σ[(d^2+1):end], dd.L[2]) # chain rule for exponential of diagonal entries @inbounds for j in 1:d # linear index of diagonal entries of L1 idx = 1 + (j - 1) * d - div((j - 1) * (j - 2), 2) grad_f[idx] *= dd.L[1][j, j] # linear index of diagonal entries of L2 idx += nvarhalf grad_f[idx] *= dd.L[2][j, j] end return grad_f end # function MathProgBase.eval_grad_f function MathProgBase.hesslag_structure(dd::TwoVarCompOptProb) nvar = nvarparams(dd.vcmodel) # linear indices for variance parameters ## ind2sub((nvar, nvar), trilind(nvar)) #Tuple(CartesianIndices((nvar, nvar))[trilind(nvar)]) arr1, arr2 = Int64[], Int64[] for i in 1:nvar arr1 = vcat(arr1, i:nvar) arr2 = vcat(arr2, fill(i, nvar-i+1)) end return (arr1, arr2) end # function MathProgBase.hesslag_structure function MathProgBase.eval_hesslag(dd::TwoVarCompOptProb, H::Vector{T}, x::Vector{T}, σ::T, μ::Vector{T}) where {T} d = size(dd.L[1], 1) nvar = nvarparams(dd.vcmodel) nvarhalf = div(nvar, 2) # update variance parameter from optim variable x optimparam_to_vcparam!(dd, x) # update mean parameters update_meanparam!(dd.vcmodel, dd.vcdatarot, dd.qpsolver, dd.vcaux) # Hessian wrt (Σ1, Σ2) fisher_Σ!(dd.HΣ, dd.vcmodel, dd.vcdatarot) # chain rule for Hessian wrt Cholesky factor # only the lower left triangle # (1, 1) block chol_gradient!(view(dd.HL, 1:nvarhalf, 1:nvarhalf), chol_gradient(dd.HΣ[1:d^2, 1:d^2], dd.L[1])', dd.L[1]) # (2, 1) block chol_gradient!(view(dd.HL, nvarhalf+1:nvar, 1:nvarhalf), chol_gradient(dd.HΣ[(d^2+1):(2d^2), 1:d^2], dd.L[1])', dd.L[2]) # (2, 2) block chol_gradient!(view(dd.HL, nvarhalf+1:nvar, nvarhalf+1:nvar), chol_gradient(dd.HΣ[(d^2+1):(2d^2), (d^2+1):(2d^2)], dd.L[2])', dd.L[2]) # chain rule for exponential of diagonal entries @inbounds for j in 1:d # linear index of diagonal entries of L1 idx = 1 + (j - 1) * d - div((j - 1) * (j - 2), 2) for i in 1:nvar dd.HL[i, idx] *= dd.L[1][j, j] dd.HL[idx, i] *= dd.L[1][j, j] end # linear index of diagonal entries of L2 idx += nvarhalf for i in 1:nvar dd.HL[i, idx] *= dd.L[2][j, j] dd.HL[idx, i] *= dd.L[2][j, j] end end # output copyto!(H, vech(dd.HL)) rmul!(H, -σ) end """ mle_fs!(vcmodel, vcdatarot; maxiter, solver, qpsolver, verbose) Find MLE by Fisher scoring algorithm. # Input - `vcmodel`: two variane component model [`VarianceComponentModel`](@ref), with `vcmodel.B` and `vcmodel.Σ` used as starting point - `vcdatarot`: rotated two varianec component data [`TwoVarCompVariateRotate`](@ref) # Keyword - `maxiter::Int`: maximum number of iterations, default is 1000 - `solver::Symbol`: backend nonlinear programming solver, `:Ipopt` (default) or `:Knitro` - `qpsolver::Symbol`: backend quadratic programming solver, `:Ipopt` (default) or `:Gurobi` or `Mosek` - `verbose::Bool`: display information # Output - `maxlogl`: log-likelihood at solution - `vcmodel`: [`VarianceComponentModel`](@ref) with updated model parameters - `Σse=(Σse[1],Σse[2])`: standard errors of estimate `Σ=(Σ[1],Σ[2])` - `Σcov`: covariance matrix of estimate `Σ=(Σ[1],Σ[2])` - `Bse`: standard errors of estimate `B` - `Bcov`: covariance of estimate `B` """ function mle_fs!( vcmodel::T1, vcdatarot::Union{T2, Array{T2}}; maxiter::Integer = 1000, solver::Symbol = :Ipopt, qpsolver::Symbol = :Ipopt, verbose::Bool = true, ) where {T1<:VarianceComponentModel, T2<:TwoVarCompVariateRotate} T = eltype(vcmodel) d = length(vcmodel) Ltrilind = trilind(d, d) # number of mean parameters nmean = nmeanparams(vcmodel) # number of optimization parameters in Cholesky factors nvar = nvarparams(vcmodel) nvarhalf = div(nvar, 2) # pre-allocate variables for optimization zeroT = convert(T, 0) # data for the optimization problem if qpsolver == :Ipopt qs = IpoptSolver(print_level = 0) elseif qpsolver == :Gurobi qs = GurobiSolver(OutputFlag = 0) elseif qpsolver == :Mosek qs = MosekSolver(MSK_IPAR_LOG = 0) end dd = TwoVarCompOptProb(vcmodel, vcdatarot, qs) # set up MathProgBase interface if solver == :Ipopt # see http://www.coin-or.org/Ipopt/documentation/documentation.html for IPOPT solver = IpoptSolver( hessian_approximation = "exact", tol = 1.0e-8, # default is 1.0e-8 acceptable_tol = 1.0e-5, # default is 1.0e-6 max_iter = maxiter, # default is 3000 print_frequency_iter = 5, # default is 1 print_level = verbose ? 5 : 0, print_info_string = "yes", #nlp_scaling_method = "none", #derivative_test = "second-order", #linear_solver = "mumps", #linear_solver = "pardiso", mehrotra_algorithm = "yes", ) elseif solver == :Mosek # see http://docs.mosek.com/7.0/capi/Parameters.html for Mosek options solver = MosekSolver( MSK_IPAR_INTPNT_MAX_ITERATIONS = maxiter, MSK_DPAR_INTPNT_NL_TOL_REL_GAP = 1.0e-8, MSK_IPAR_LOG = verbose ? 10 : 0, # deafult value is 10 #MSK_IPAR_OPTIMIZER = MSK_OPTIMIZER_NONCONVEX, #MSK_IPAR_LOG_NONCONVEX = 20, #MSK_IPAR_NONCONVEX_MAX_ITERATIONS = 100, #MSK_DPAR_INTPNT_NL_TOL_NEAR_REL = 1e8, #MSK_IPAR_LOG_CHECK_CONVEXITY = 1, #MSK_IPAR_INFEAS_PREFER_PRIMAL = MSK_OFF ) elseif solver == :Knitro # see https://www.artelys.com/tools/knitro_doc/3_referenceManual/userOptions.html for Mosek options solver = KnitroSolver( KTR_PARAM_ALG = 0, KTR_PARAM_OUTLEV = verbose ? 2 : 0, #KTR_PARAM_MAXCGIT = 5, #KTR_PARAM_SCALE = 0, #KTR_PARAM_HONORBNDS = 1, #KTR_PARAM_GRADOPT = 1, #KTR_PARAM_HESSOPT = 1, #KTR_PARAM_DERIVCHECK = 3, #KTR_PARAM_TUNER = 1, #KTR_PARAM_MAXTIMECPU = 5.0, #KTR_PARAM_BAR_MURULE = 4, #KTR_PARAM_BAR_FEASIBLE = 3, #KTR_PARAM_BAR_FEASMODETOL = 1.0e-8, #KTR_PARAM_BAR_SWITCHRULE = 3, #KTR_PARAM_BAR_PENCONS = 2, #KTR_PARAM_BAR_DIRECTINTERVAL = 0, #KTR_PARAM_BAR_MAXBACKTRACK = 10, #KTR_PARAM_BAR_MAXCROSSIT = 5, #KTR_PARAM_BAR_MAXREFACTOR = 5, #KTR_PARAM_BAR_REFINEMENT = 1, #KTR_PARAM_BAR_WATCHDOG = 1, ) end m = MathProgBase.NonlinearModel(solver) # lower and upper bounds for variance parameter lb = zeros(nvar); fill!(lb, -T(Inf)) ub = zeros(nvar); fill!(ub, T(Inf)) MathProgBase.loadproblem!(m, nvar, 0, lb, ub, T[], T[], :Max, dd) # start point copyto!(dd.L[1], cholesky(vcmodel.Σ[1], Val(true)).L.data) copyto!(dd.L[2], cholesky(vcmodel.Σ[2], Val(true)).L.data) # reparameterize diagonal entries to exponential @inbounds @simd for i in 1:d dd.L[1][i, i] = log(dd.L[1][i, i] + convert(T, 1e-8)) dd.L[2][i, i] = log(dd.L[2][i, i] + convert(T, 1e-8)) end x0 = [vech(dd.L[1]); vech(dd.L[2])] MathProgBase.setwarmstart!(m, x0) # optimize MathProgBase.optimize!(m) stat = MathProgBase.status(m) x = MathProgBase.getsolution(m) # retrieve variance component parameters optimparam_to_vcparam!(dd, x) # update mean parameters update_meanparam!(dd.vcmodel, dd.vcdatarot, dd.qpsolver, dd.vcaux) # update final objective value maxlogl = logpdf(vcmodel, vcdatarot, dd.vcaux) # standard errors Bcov = zeros(T, nmean, nmean) Bcov = pinv(fisher_B(vcmodel, vcdatarot, dd.vcaux)) Bse = similar(vcmodel.B) copyto!(Bse, sqrt.(diag(Bcov))) Σcov = pinv(fisher_Σ(vcmodel, vcdatarot)) Σse = (zeros(T, d, d), zeros(T, d, d)) copyto!(Σse[1], sqrt.(diag(view(Σcov, 1:d^2, 1:d^2)))) copyto!(Σse[2], sqrt.(diag(view(Σcov, d^2+1:2d^2, d^2+1:2d^2)))) # output maxlogl, vcmodel, Σse, Σcov, Bse, Bcov end # function mle_fs #---------------------------------------------------------------------------# # MM algorithm #---------------------------------------------------------------------------# function suffstats_for_Σ!( vcmrot::TwoVarCompModelRotate, vcobsrot::TwoVarCompVariateRotate, vcaux::VarianceComponentAuxData = VarianceComponentAuxData(vcobsrot) ) T = eltype(vcmrot) n, d = size(vcobsrot.Yrot, 1), size(vcobsrot.Yrot, 2) A1, b1 = zeros(T, d, d), zeros(T, d) A2, b2 = zeros(T, d, d), zeros(T, d) zeroT, oneT = zero(T), one(T) λj, tmp = zeroT, zeroT # (rotated) residual residual!(vcaux.res, vcmrot, vcobsrot) # sufficient statistics for Σ2 @inbounds for j in 1:d λj = vcmrot.eigval[j] for i in 1:n tmp = oneT / (vcobsrot.eigval[i] * λj + oneT) vcaux.res[i, j] *= tmp b2[j] += tmp end end mul!(A2, transpose(vcaux.res), vcaux.res) # sufficient statistics for Σ1 @inbounds for j in 1:d λj = vcmrot.eigval[j] for i in 1:n tmp = vcobsrot.eigval[i] vcaux.res[i, j] *= √tmp * λj b1[j] += tmp / (tmp * λj + oneT) end end mul!(A1, transpose(vcaux.res), vcaux.res) # output return A1, b1, A2, b2 end function suffstats_for_Σ!( vcmrot::T1, vcdatarot::Array{T2}, vcaux::Array{T3} = VarianceComponentAuxData(vcdatarot) ) where { T1 <: TwoVarCompModelRotate, T2 <: TwoVarCompVariateRotate, T3 <: VarianceComponentAuxData} mapreduce(x -> suffstats_for_Σ!(vcmrot, x...), +, zip(vcdatarot, vcaux)) end function +( x::Tuple{AbstractMatrix, AbstractVector, AbstractMatrix, AbstractVector}, y::Tuple{AbstractMatrix, AbstractVector, AbstractMatrix, AbstractVector} ) x[1] + y[1], x[2] + y[2], x[3] + y[3], x[4] + y[4] end function mm_update_Σ!( vcm::T1, vcdatarot::Union{T2, Array{T2}}, vcaux::Union{T3, Array{T3}} = VarianceComponentAuxData(vcdatarot) ) where { T1 <: VarianceComponentModel, T2 <: TwoVarCompVariateRotate, T3 <: VarianceComponentAuxData} T, d = eltype(vcm), length(vcm) zeroT, oneT = zero(T), one(T) # eigen-decomposition of (vcm.Σ[1], vcm.Σ[2]) vcmrot = TwoVarCompModelRotate(vcm) # sufficient statistics for updating Σ1, Σ2 A1, b1, A2, b2 = suffstats_for_Σ!(vcmrot, vcdatarot, vcaux) @inbounds for j in 1:d b1[j] = √b1[j] b2[j] = √b2[j] end Φinv = inv(vcmrot.eigvec) # update Σ1 lmul!(Diagonal(b1), A1), rmul!(A1, Diagonal(b1)) storage = eigen!(Symmetric(A1)) @inbounds for i in 1:d storage.values[i] = storage.values[i] > zeroT ? √√storage.values[i] : zeroT end rmul!(storage.vectors, Diagonal(storage.values)) #scale!(storage.vectors, storage.values) lmul!(Diagonal(oneT ./ b1), storage.vectors) #scale!(storage.vectors, storage.values) mul!(vcm.Σ[1], transpose(Φinv), storage.vectors) copyto!(vcm.Σ[1], vcm.Σ[1] * transpose(vcm.Σ[1])) # update Σ2 lmul!(Diagonal(b2), A2), rmul!(A2, Diagonal(b2)) storage = eigen!(Symmetric(A2)) @inbounds for i in 1:d storage.values[i] = storage.values[i] > zeroT ? √√storage.values[i] : zeroT end rmul!(storage.vectors, Diagonal(storage.values)) #scale!(storage.vectors, storage.values) lmul!(Diagonal(oneT ./ b2), storage.vectors) #scale!(storage.vectors, storage.values) mul!(vcm.Σ[2], transpose(Φinv), storage.vectors) copyto!(vcm.Σ[2], vcm.Σ[2] * transpose(vcm.Σ[2])) end """ mle_mm!(vcmodel, vcdatarot; maxiter, qpsolver, verbose) Find MLE by minorization-maximization (MM) algorithm. # Input - `vcmodel`: two variane component model [`VarianceComponentModel`](@ref), with `vcmodel.B` and `vcmodel.Σ` used as starting point - `vcdatarot`: rotated two varianec component data [`TwoVarCompVariateRotate`](@ref) # Keyword - `maxiter::Int`: maximum number of iterations, default is 1000 - `qpsolver::Symbol`: backend quadratic programming solver, `:Ipopt` (default) or `:Gurobi` or `Mosek` - `verbose::Bool`: display information # Output - `maxlogl`: log-likelihood at solution - `vcmodel`: [`VarianceComponentModel`](@ref) with updated model parameters - `Σse=(Σse[1],Σse[2])`: standard errors of estimate `Σ=(Σ[1],Σ[2])` - `Σcov`: covariance matrix of estimate `Σ=(Σ[1],Σ[2])` - `Bse`: standard errors of estimate `B` - `Bcov`: covariance of estimate `B` # Reference - H. Zhou, L. Hu, J. Zhou, and K. Lange (2015) MM algorithms for variance components models. [http://arxiv.org/abs/1509.07426](http://arxiv.org/abs/1509.07426) """ function mle_mm!( vcm::T1, vcdatarot::Union{T2, Array{T2}}; maxiter::Integer = 10000, funtol::Real = convert(eltype(vcm), 1e-8), qpsolver::Symbol = :Ipopt, verbose::Bool = true, ) where {T1 <: VarianceComponentModel, T2 <: TwoVarCompVariateRotate} T, d, pd = eltype(vcm), length(vcm), nmeanparams(vcm) # set up QP solver if qpsolver == :Ipopt qs = IpoptSolver(print_level = 0) elseif qpsolver == :Gurobi qs = GurobiSolver(OutputFlag = 0) elseif qpsolver == :Mosek qs = MosekSolver(MSK_IPAR_LOG = 0) end # allocate intermediate variables vcaux = VarianceComponentAuxData(vcdatarot) # initial log-likelihood logl::T = logpdf(vcm, vcdatarot, vcaux) if verbose println() println(" MM Algorithm") println(" Iter Objective ") println("-------- -------------") Printf.@printf("%8.d %13.e\n", 0, logl) end # MM loop for iter in 1:maxiter # update Σ mm_update_Σ!(vcm, vcdatarot, vcaux) # make sure the last variance component is pos. def. ϵ = convert(T, 1e-8) clamp_diagonal!(vcm.Σ[2], ϵ, T(Inf)) # update mean parameters if pd > 0; update_meanparam!(vcm, vcdatarot, qs, vcaux); end # check convergence loglold = logl logl = logpdf(vcm, vcdatarot, vcaux) if verbose if (iter <= 10) || (iter > 10 && iter % 10 == 0) Printf.@printf("%8.d %13.e\n", iter, logl) end end if abs(logl - loglold) < funtol * (abs(logl) + one(T)) break end end if verbose; println(); end # standard errors Bcov = pinv(fisher_B(vcm, vcdatarot, vcaux)) Bse = similar(vcm.B) copyto!(Bse, sqrt.(diag(Bcov))) Σcov = pinv(fisher_Σ(vcm, vcdatarot)) Σse = (zeros(T, d, d), zeros(T, d, d)) copyto!(Σse[1], sqrt.(diag(view(Σcov, 1:d^2, 1:d^2)))) copyto!(Σse[2], sqrt.(diag(view(Σcov, d^2+1:2d^2, d^2+1:2d^2)))) # output logl, vcm, Σse, Σcov, Bse, Bcov end # function mle_mm #---------------------------------------------------------------------------# # Estimation gateway #---------------------------------------------------------------------------# """ fit_mle!(vcmodel, vcdata; algo) Find MLE of variane component model. # Input - `vcmodel`: two variane component model [`VarianceComponentModel`](@ref), with `vcmodel.B` and `vcmodel.Σ` used as starting point - `vcdata`: two varianec component data [`VarianceComponentVariate`](@ref) # Keyword - `algo::Symbol`: algorithm, `:FS` (Fisher scoring) for `:MM` (minorization-maximization algorithm) # Output - `maxlogl`: log-likelihood at solution - `vcmodel`: [`VarianceComponentModel`](@ref) with updated model parameters - `Σse=(Σse[1],Σse[2])`: standard errors of estimate `Σ=(Σ[1],Σ[2])` - `Σcov`: covariance matrix of estimate `Σ=(Σ[1],Σ[2])` - `Bse`: standard errors of estimate `B` - `Bcov`: covariance of estimate `B` """ function fit_mle!( vcmodel::T1, vcdata::Union{T2, Array{T2}}; algo::Symbol = :FS ) where {T1 <: VarianceComponentModel, T2 <: VarianceComponentVariate} # generalized-eigendecomposition and rotate data vcdatarot = TwoVarCompVariateRotate(vcdata) if algo == :FS return mle_fs!(vcmodel, vcdatarot) elseif algo == :MM return mle_mm!(vcmodel, vcdatarot) end end """ fit_reml!(vcmodel, vcdata; algo) Find restricted MLE (REML) of variane component model. # Input - `vcmodel`: two variane component model [`VarianceComponentModel`](@ref), with `vcmodel.B` and `vcmodel.Σ` used as starting point - `vcdata`: two varianec component data [`VarianceComponentVariate`](@ref) # Keyword - `algo::Symbol`: algorithm, `:FS` (Fisher scoring) for `:MM` (minorization-maximization algorithm) # Output - `maxlogl`: log-likelihood at solution - `vcmodel`: [`VarianceComponentModel`](@ref) with updated model parameters - `Σse=(Σse[1],Σse[2])`: standard errors of estimate `Σ=(Σ[1],Σ[2])` - `Σcov`: covariance matrix of estimate `Σ=(Σ[1],Σ[2])` - `Bse`: standard errors of estimate `B` - `Bcov`: covariance of estimate `B` """ function fit_reml!( vcmodel::T1, vcdata::Union{T2, Array{T2}}; algo::Symbol = :FS, qpsolver::Symbol = :Ipopt ) where { T1 <: VarianceComponentModel, T2 <: VarianceComponentVariate} T, d = eltype(vcmodel), length(vcmodel) vcaux = VarianceComponentAuxData(vcdata) # solve regular least squares problem if qpsolver == :Ipopt qs = IpoptSolver(print_level = 0) elseif qpsolver == :Gurobi qs = GurobiSolver(OutputFlag = 0) elseif qpsolver == :Mosek qs = MosekSolver(MSK_IPAR_LOG = 0) end if typeof(vcdata) <: AbstractArray Q = kron(Matrix{T}(I, d, d), mapreduce(x -> transpose(x.X) * x.X, +, vcdata)) c = vec(mapreduce(x -> transpose(x.X) * x.Y, +, vcdata)) else Q = kron(Matrix{T}(I, d, d), transpose(vcdata.X) * vcdata.X) c = vec(transpose(vcdata.X) * vcdata.Y) end qpsol = quadprog(-c, Q, vcmodel.A, vcmodel.sense, vcmodel.b, vcmodel.lb, vcmodel.ub, qs) if qpsol.status ≠ :Optimal println("Error in quadratic programming $(qpsol.status)") end copyto!(vcmodel.B, qpsol.sol) # use residuals as responses resdata = deepcopy(vcdata) if typeof(vcdata) <: AbstractArray for i in eachindex(resdata) residual!(resdata[i].Y, vcmodel, vcdata[i]) resdata[i].X = zeros(T, size(resdata[i].Y, 1), 0) end else residual!(resdata.Y, vcmodel, vcdata) resdata.X = zeros(T, size(resdata.Y, 1), 0) end resdatarot = TwoVarCompVariateRotate(resdata) resmodel = deepcopy(vcmodel) resmodel.B = zeros(T, 0, d) if algo == :FS _, _, Σse, Σcov, = mle_fs!(resmodel, resdatarot) elseif algo == :MM _, _, Σse, Σcov, = mle_mm!(resmodel, resdatarot) end # estimate mean parameters from covariance estimate copyto!(vcmodel.Σ[1], resmodel.Σ[1]), copyto!(vcmodel.Σ[2], resmodel.Σ[2]) vcdatarot = TwoVarCompVariateRotate(vcdata) update_meanparam!(vcmodel, vcdatarot, qs, vcaux) # standard errors and covariance of mean parameters Bcov = inv(fisher_B(vcmodel, vcdatarot, vcaux)) Bse = similar(vcmodel.B) copyto!(Bse, sqrt.(diag(Bcov))) ## output logpdf(vcmodel, vcdatarot), vcmodel, (Σse[1], Σse[2]), Σcov, Bse, Bcov end #---------------------------------------------------------------------------# # Heritability estimation #---------------------------------------------------------------------------# """ heritability(Σ, Σcov, which=1) Calcualte the heritability of each trait and its standard error from variance component estimates and their covariance. # Input - `Σ=(Σ[1], ..., Σ[m])`: estimate of `m` `d x d` variance components. - `Σcov`: `md^2 x md^2` covariance matrix of the variance component estiamte. - `which`: indicator which is the additive genetic variance component. # Output - `h`: estimated heritability of `d` traits. - `hse`: standard errors of the estiamted heritability. """ function heritability( Σ::NTuple{N, AbstractMatrix{T}}, Σcov::AbstractMatrix{T}, which::Integer = 1 ) where {T, N} d = size(Σ[1], 1) # number of traits m = length(Σ) # number of variance components @assert size(Σcov, 1) == m * d^2 "Dimensions don't match" h, hse = zeros(T, d), zeros(T, d) hgrad = zeros(T, m) for trait in 1:d σ2trait = [Σ[i][trait, trait] for i = 1:m] totalσ2trait = sum(σ2trait) # heritability h[trait] = σ2trait[which] / totalσ2trait # standard error of heritability by Delta method for i in 1:m if i == which hgrad[i] = (totalσ2trait - σ2trait[i]) / totalσ2trait^2 else hgrad[i] = - σ2trait[i] / totalσ2trait^2 end end dgidx = diagind(Σ[1])[trait] traitidx = dgidx:d^2:((m - 1) * d^2 + dgidx) hse[trait] = sqrt(dot(hgrad, view(Σcov, traitidx, traitidx) * hgrad)) end # output h, hse end # function heritability
VarianceComponentModels
https://github.com/OpenMendel/VarianceComponentModels.jl.git
[ "MIT" ]
0.1.3
82d058ac0c22844b80c5bc098f17c7f7d5268f11
code
3308
module MultivariateCalculusTest using VarianceComponentModels, LinearAlgebra, Random, Test Random.seed!(123) # test vech @testset "vech" begin a = reshape(1:9, 3, 3) vecha = vech(a) @test vecha[1] == a[1, 1] @test vecha[2] == a[2, 1] @test vecha[3] == a[3, 1] @test vecha[4] == a[2, 2] @test vecha[5] == a[3, 2] @test vecha[6] == a[3, 3] a = 1.0 @test vech(a) == a end # test trilind @testset "trilind" begin n = 3 A = randn(n, n) @test norm(vech(A) - A[trilind(A)]) ≈ 0.0 @test norm([2, 3, 6] - trilind(A, -1)) ≈ 0.0 end # test triuind @testset "triuind" begin n = 2 idx = triuind(n, n) @test length(idx) == binomial(n + 1, 2) @test idx[1] == 1 @test idx[2] == 3 @test idx[3] == 4 idx = triuind(n) @test length(idx) == binomial(n + 1, 2) @test idx[1] == 1 @test idx[2] == 3 @test idx[3] == 4 idx = triuind(randn(n, n)) @test length(idx) == binomial(n + 1, 2) @test idx[1] == 1 @test idx[2] == 3 @test idx[3] == 4 idx = triuind(randn(n, n), 1) @test length(idx) == binomial(n, 2) @test idx[1] == 3 end # test commutation @testset "commutation" begin m, n = 3, 2 A = randn(m, n) @test norm(commutation(m, n) * vec(A) - vec(A')) ≈ 0.0 @test norm(commutation(A) * vec(A) - vec(A')) ≈ 0.0 @test norm(spcommutation(m, n) * vec(A) - vec(A')) ≈ 0.0 @test norm(spcommutation(A) * vec(A) - vec(A')) ≈ 0.0 B = randn(m, m) @test norm(commutation(m) * vec(B) - vec(B')) ≈ 0.0 @test norm(commutation(eltype(B), m) * vec(B) - vec(B')) ≈ 0.0 @test norm(spcommutation(eltype(B), m) * vec(B) - vec(B')) ≈ 0.0 end # test duplication @testset "duplication" begin n = 3 A = randn(n, n) A = 0.5(A + A') # symmetrize @test norm(duplication(n) * vech(A) - vec(A)) ≈ 0.0 @test norm(duplication(A) * vech(A) - vec(A)) ≈ 0.0 @test norm(spduplication(n) * vech(A) - vec(A)) ≈ 0.0 @test norm(spduplication(A) * vech(A) - vec(A)) ≈ 0.0 end # test chol_gradient @testset "chol_gradient" begin n = 3 A = randn(n, n) A = 0.5(A + A') # symmetrize L = tril(randn(n, n)) # calculate gradient wrt L using chol_gradient dL1 = chol_gradient(vec(A), L) # alternative way to calculate gradient wrt L dL2 = 2.0vech((A * L) + L' * A' - Matrix(Diagonal(A * L))) @test norm(dL1 - dL2) ≈ 0.0 end # test kron_gradient @testset "kron_gradient" begin n, q, p, r = 2, 3, 4, 5 X = randn(n, q) Y = randn(p, r) M = kron(X, Y) # calculate gradient wrt X using kron_gradient dX1 = kron_gradient(vec(M), Y, n, q) # alternative way to calculate gradient wrt X dX2 = zero(X) for j = 1:q for i = 1:n dX2[i, j] = dot(Y, M[(i-1)*p+1:i*p, (j-1)*r+1:j*r]) end end @test norm(dX1 - vec(dX2)) < 1e-8 end # test duplication @testset "kronaxpy" begin m, n, p, q = 3, 4, 5, 6 A = randn(m, n) X = randn(p, q) Y = zeros(m * p, n * q) kronaxpy!(A, X, Y) @test norm(Y - kron(A, X)) ≈ 0.0 end # test bump_diagonal @testset "bump_diag" begin A = randn(3, 3) B = copy(A) bump_diagonal!(B, 1e-3) @test B[1, 1] - A[1, 1] ≈ 1e-3 @test B[2, 2] - A[2, 2] ≈ 1e-3 @test B[3, 3] - A[3, 3] ≈ 1e-3 end # test clamp_diagonal @testset "clamp_diag" begin n = 3 A = randn(n, n) B = copy(A) clamp_diagonal!(B, 0.0, 1.0) @test all(0.0 .≤ diag(B) .≤ 1.0) end end # module MultivariateCalculusTest
VarianceComponentModels
https://github.com/OpenMendel/VarianceComponentModels.jl.git
[ "MIT" ]
0.1.3
82d058ac0c22844b80c5bc098f17c7f7d5268f11
code
200
module VarianceComponentModelsTest include("multivariate_calculus_test.jl") include("variance_component_models_test.jl") include("two_variance_component_test.jl") #include("benchmark.jl") end
VarianceComponentModels
https://github.com/OpenMendel/VarianceComponentModels.jl.git
[ "MIT" ]
0.1.3
82d058ac0c22844b80c5bc098f17c7f7d5268f11
code
5902
module TwoVarianceComponentTest using VarianceComponentModels, MathProgBase, Ipopt, Random, Test, LinearAlgebra Random.seed!(123) # generate data from a d-variate response variane component model n = 100 # no. observations d = 2 # no. categories m = 2 # no. variance components p = 2 # no. covariates X = randn(n, p) B = ones(p, d) Σ = ntuple(x -> zeros(d, d), m) for i in 1:m Σi = randn(d, d) copyto!(Σ[i], Σi' * Σi) end ## make the first variance component 0 matrix #fill!(Σ[1], 0.0) V = ntuple(x -> zeros(n, n), m) for i = 1:m-1 Vi = randn(n, 50) copyto!(V[i], Vi * Vi') end copyto!(V[m], Matrix(I, n, n)) # form Ω Ω = zeros(n*d, n*d) for i = 1:m global Ω += kron(Σ[i], V[i]) end Ωchol = cholesky(Ω) Y = X * B + reshape(Ωchol.L * randn(n*d), n, d) @info "Forming VarianceComponentModel from data" @inferred VarianceComponentVariate(Y, X, V) vcdata = VarianceComponentVariate(Y, X, V) vcmodel = VarianceComponentModel(vcdata) @info "Pre-compute eigen-decomposition and rotate data" vcdatarot = TwoVarCompVariateRotate(vcdata) vcmodelrot = TwoVarCompModelRotate(vcmodel) @info "Evaluate log-pdf" #@code_warntype logpdf(vcmodelrot, vcdatarot) @inferred logpdf(vcmodelrot, vcdatarot) @test logpdf(vcmodel, vcdata) == logpdf(vcmodelrot, vcdatarot) @test (logpdf(vcmodelrot, [vcdatarot vcdatarot; vcdatarot vcdatarot]) - logpdf(vcmodel, [vcdata vcdata; vcdata vcdata])) ≈ 0.0 @info "Evaluate gradient" ∇ = zeros(2d^2) #@code_warntype gradient!(∇, vcmodelrot, vcdatarot) @inferred VarianceComponentModels.gradient!(∇, vcmodelrot, vcdatarot) @inferred VarianceComponentModels.gradient!(∇, vcmodel, vcdatarot) @inferred VarianceComponentModels.gradient!(∇, vcmodel, vcdata) @test norm(VarianceComponentModels.gradient(vcmodel, vcdata) - VarianceComponentModels.gradient(vcmodelrot, vcdatarot)) ≈ 0.0 @test norm(VarianceComponentModels.gradient(vcmodel, vcdata) - VarianceComponentModels.gradient(vcmodel, vcdatarot)) ≈ 0.0 @test norm(VarianceComponentModels.gradient(vcmodel, [vcdata vcdata]) - 2.0VarianceComponentModels.gradient(vcmodel, vcdata)) ≈ 0.0 @test norm(VarianceComponentModels.gradient(vcmodel, [vcdata vcdata]) - VarianceComponentModels.gradient(vcmodelrot, [vcdatarot vcdatarot])) ≈ 0.0 @info "Evaluate Fisher information matrix of Σ" H = zeros(2d^2, 2d^2) #@code_warntype fisher!(H, vcmodelrot, vcdatarot) @inferred fisher_Σ!(H, vcmodelrot, vcdatarot) @inferred fisher_Σ!(H, vcmodel, vcdata) @test norm(fisher_Σ(vcmodel, vcdata) - fisher_Σ(vcmodelrot, vcdatarot)) ≈ 0.0 @test norm(fisher_Σ(vcmodel, vcdata) - fisher_Σ(vcmodel, vcdatarot)) ≈ 0.0 @test norm(fisher_Σ(vcmodel, [vcdata vcdata]) - 2fisher_Σ(vcmodel, vcdata)) ≈ 0.0 @test norm(fisher_Σ(vcmodel, [vcdata vcdata]) - fisher_Σ(vcmodelrot, [vcdatarot vcdatarot])) ≈ 0.0 @info "Evaluate Fisher information matrix of B" H = zeros(p * d, p * d) #@code_warntype fisher_B!(H, vcmodelrot, vcdatarot) @inferred fisher_B!(H, vcmodelrot, vcdatarot) @inferred fisher_B!(H, vcmodel, vcdatarot) @inferred fisher_B!(H, vcmodel, vcdata) @test norm(fisher_B(vcmodel, vcdata) - fisher_B(vcmodelrot, vcdatarot)) ≈ 0.0 @test norm(fisher_B(vcmodel, vcdata) - fisher_B(vcmodel, vcdatarot)) ≈ 0.0 @test norm(fisher_B(vcmodel, [vcdata vcdata]) - 2.0fisher_B(vcmodel, vcdata)) ≈ 0.0 @test norm(fisher_B(vcmodel, [vcdata vcdata]) - fisher_B(vcmodelrot, [vcdatarot vcdatarot])) ≈ 0.0 @info "Find MLE using Fisher scoring" vcmfs = deepcopy(vcmodel) #@code_warntype mle_fs!(vcmfs, vcdatarot; solver = :Ipopt) #@inferred mle_fs!(vcmfs, vcdatarot; solver = :Ipopt) logl_fs, _, _, Σcov_fs, Bse_fs, = mle_fs!(vcmfs, vcdatarot; solver = :Ipopt) logl_fs_array, = mle_fs!(vcmfs, [vcdatarot vcdatarot]; solver = :Ipopt) @show vcmfs.B @show Bse_fs @show B @info "Find MLE using MM algorithm" vcmmm = deepcopy(vcmodel) #@code_warntype mle_mm!(vcmm, vcdatarot) #@inferred mle_mm!(vcmmm, vcdatarot) logl_mm, _, _, _, Bse_mm, = mle_mm!(vcmmm, vcdatarot) @test abs(logl_fs - logl_mm) / (abs(logl_fs) + 1.0) < 1.0e-4 @show vcmmm.B @show Bse_mm @show B vcmmm = deepcopy(vcmodel) logl_mm_array, = mle_mm!(vcmmm, [vcdatarot vcdatarot]) @test abs(logl_fs_array - logl_mm_array) / (abs(logl_fs_array) + 1.0) < 1.0e-4 @info "Find MLE using Fisher scoring (linear equality + box constraints)" vcmfs = deepcopy(vcmodel) vcmfs.A = [1.0 -1.0 zeros(1, p*d-2)] vcmfs.sense = '=' vcmfs.b = 0.0 vcmfs.lb = 0.0 vcmfs.ub = 1.0 logl_fs, _, _, Σcov_fs, Bse_fs, = mle_fs!(vcmfs, vcdatarot; solver = :Ipopt, qpsolver = :Ipopt) @show vcmfs.B @test vcmfs.B[1] ≈ vcmfs.B[2] @test all(vcmfs.B .≥ 0.0) @test all(vcmfs.B .≤ 1.0) @info "Find MLE using MM algorithm (linear equality + box constraints)" vcmm = deepcopy(vcmodel) vcmm.A = [1.0 -1.0 zeros(1, p*d-2)] vcmm.sense = '=' vcmm.b = 0.0 vcmm.lb = 0.0 vcmm.ub = 1.0 logl_mm, _, _, Σcov_mm = mle_mm!(vcmm, vcdatarot; qpsolver = :Ipopt) @show vcmm.B @test vcmm.B[1] ≈ vcmm.B[2] @test all(vcmm.B .≥ 0.0) @test all(vcmm.B .≤ 1.0) @test abs(logl_fs - logl_mm) / (abs(logl_fs) + 1.0) < 1.0e-4 @info "Heritability estimation" h, h_se = heritability(vcmfs.Σ, Σcov_fs) @show h, h_se @test all(0.0 .≤ h .≤ 1.0) @info "test fit_mle (FS)" vcmmle = deepcopy(vcmodel) logl_mle, _, _, Σcov_mle, Bse_mle, = fit_mle!(vcmmle, vcdata; algo = :FS) @show vcmmle.B, Bse_mle, B vcmle = deepcopy(vcmodel) fit_mle!(vcmmle, [vcdata vcdata]; algo = :FS) @info "test fit_mle (MM)" vcmmle = deepcopy(vcmodel) logl_mle, _, _, Σcov_mle, Bse_mle, = fit_mle!(vcmmle, vcdata; algo = :MM) @show vcmmle.B, Bse_mle, B @info "test fit_reml (FS)" vcmreml = deepcopy(vcmodel) logl_reml, _, _, Σcov_reml, Bse_reml, = fit_reml!(vcmreml, vcdata; algo = :FS) @show vcmreml.B, Bse_reml, B @info "test fit_reml (MM)" vcmreml = deepcopy(vcmodel) logl_reml, _, _, Σcov_reml, Bse_reml, = fit_reml!(vcmreml, vcdata; algo = :MM) @show vcmreml.B, Bse_reml, B end # module VarianceComponentTypeTest
VarianceComponentModels
https://github.com/OpenMendel/VarianceComponentModels.jl.git
[ "MIT" ]
0.1.3
82d058ac0c22844b80c5bc098f17c7f7d5268f11
code
4646
module VarianceComponentTypeTest using VarianceComponentModels, MathProgBase, Ipopt, LinearAlgebra, Random, Test Random.seed!(123) # generate data from a d-variate response variane component model n = 100 # no. observations d = 2 # no. categories m = 2 # no. variance components p = 2 # no. covariates X = randn(n, p) B = ones(p, d) Σ = ntuple(x -> zeros(d, d), m) for i in 1:m Σi = randn(d, d) copyto!(Σ[i], Σi' * Σi) end ## make the first variance component 0 matrix #fill!(Σ[1], 0.0) V = ntuple(x -> zeros(n, n), m) for i = 1:m-1 Vi = randn(n, 50) copyto!(V[i], Vi * Vi') end copyto!(V[m], Matrix(I, n, n)) # form Ω Ω = zeros(n*d, n*d) for i = 1:m global Ω += kron(Σ[i], V[i]) end Ωchol = cholesky(Ω) Y = X * B + reshape(Ωchol.L * randn(n*d), n, d) @info "VarianceComponentModel type" #@code_warntype VarianceComponentModel(B, Σ) @inferred VarianceComponentModel(B, Σ) #@code_warntype VarianceComponentModel(Σ) @inferred VarianceComponentModel(Σ) vcmodel = VarianceComponentModel(Σ) @test isempty(vcmodel.B) @info "TwoVarCompModelRotate type" F = eigen(Σ[1], Σ[2]) #@code_warntype TwoVarCompModelRotate(B * F.vectors, F.values, F.vectors, logdet(Σ[2])) @inferred TwoVarCompModelRotate(B * F.vectors, F.values, F.vectors, logdet(Σ[2])) @info "VarianceComponentVariate type" #@code_warntype VarianceComponentVariate(Y, V) @inferred VarianceComponentVariate(Y, V) vcdata = VarianceComponentVariate(Y, V) @test isempty(vcdata.X) @info "Forming VarianceComponentModel from data" vcdata = VarianceComponentVariate(Y, X, V) #@code_warntype VarianceComponentVariate(Y, X, V) @inferred VarianceComponentVariate(Y, X, V) vcdata = VarianceComponentVariate(Y, X, V) #@code_warntype VarianceComponentModel(vcdata) @inferred VarianceComponentModel(vcdata) vcmodel = VarianceComponentModel(vcdata) @test norm(vcmodel.B) ≈ 0.0 @test norm(vcmodel.Σ[1] - Matrix(I, d, d)) ≈ 0.0 @test norm(vcmodel.Σ[2] - Matrix(I, d, d)) ≈ 0.0 @info "Pre-compute eigen-decomposition and rotate data" #@code_warntype TwoVarCompVariateRotate(vcdata) @inferred TwoVarCompVariateRotate(vcdata) vcdatarot = TwoVarCompVariateRotate(vcdata) #@code_warntype TwoVarCompModelRotate(vcmodel) @inferred TwoVarCompModelRotate(vcmodel) vcmodelrot = TwoVarCompModelRotate(vcmodel) @info "Test generalized eigen-decomposition" vcdatacopy = deepcopy(vcdata) rmul!(vcdatacopy.V[2], 2.0) # V[2] = 2I vcdatacopyrot = TwoVarCompVariateRotate(vcdatacopy) @test vcdatacopyrot.logdetV2 ≈ n * log(2.0) # det(V[2]) = 2^n @info "VarianceComponentModel from TwoVarCompVariateRotate" @inferred VarianceComponentModel(vcdatarot) vcmodelfromrot = VarianceComponentModel(vcdatarot) @test size(vcmodelfromrot.B, 1) == p @test size(vcmodelfromrot.B, 2) == d @test length(vcmodelfromrot.Σ) == m @info "VarianceComponentAuxData from VarianceComponentVariate" vcobsaux1 = VarianceComponentAuxData(vcdata) vcobsaux2 = VarianceComponentAuxData(vcdatarot) @test size(vcobsaux1.res) == size(vcobsaux2.res) @test size(vcobsaux1.Xwork) == size(vcobsaux2.Xwork) @test size(vcobsaux1.ywork) == size(vcobsaux2.ywork) @test size(vcobsaux1.obswt) == size(vcobsaux2.obswt) @info "Query functions" @test eltype(vcmodel) == eltype(B) @test eltype(vcdata) == eltype(Y) @test eltype(vcmodelrot) == eltype(vcmodel) @test eltype(vcdatarot) == eltype(vcdata) @test length(vcmodel) == d @test length(vcdata) == d @test length(vcmodelrot) == d @test length(vcdatarot) == d @test size(vcdata) == (n, d) @test size(vcdatarot) == (n, d) @test nvarcomps(vcmodel) == m @test nvarcomps(vcdata) == m @test nvarcomps(vcmodelrot) == m @test nvarcomps(vcdatarot) == m @test nmeanparams(vcmodel) == p * d @test nmeanparams(vcmodelrot) == p * d @test nmeanparams(vcdata) == p * d @test nmeanparams(vcdatarot) == p * d @test nvarparams(vcmodel) == m * binomial(d + 1, 2) @test nvarparams(vcmodelrot) == m * binomial(d + 1, 2) @test nparams(vcmodel) == p * d + m * binomial(d + 1, 2) @test nparams(vcmodelrot) == p * d + m * binomial(d + 1, 2) @info "Mean, covariance, and residual of model" #@code_warntype mean(vcmodel, vcdata) @inferred mean(vcmodel, vcdata) μ = mean(vcmodel, vcdata) @test size(μ, 1) == n @test size(μ, 2) == d #@code_warntype cov(vcmodel, vcdata) @inferred cov(vcmodel, vcdata) Ω = cov(vcmodel, vcdata) @test size(Ω, 1) == n * d @test size(Ω, 2) == n * d #@code_warntype residual(vcmodel, vcdata) @inferred residual(vcmodel, vcdata) res = residual(vcmodel, vcdata) @test size(res, 1) == n @test size(res, 2) == d @inferred residual(vcmodelrot, vcdatarot) resrot = residual(vcmodelrot, vcdatarot) @test size(resrot, 1) == n @test size(resrot, 2) == d end # module VarianceComponentTypeTest
VarianceComponentModels
https://github.com/OpenMendel/VarianceComponentModels.jl.git
[ "MIT" ]
0.1.3
82d058ac0c22844b80c5bc098f17c7f7d5268f11
docs
2419
# VarianceComponentModels | **Documentation** | **Build Status** | **Code Coverage** | |-------------------|------------------|--------------------| | [![](https://img.shields.io/badge/docs-current-blue.svg)](https://openmendel.github.io/VarianceComponentModels.jl/latest/) | [![Build Status](https://travis-ci.org/OpenMendel/VarianceComponentModels.jl.svg?branch=master)](https://travis-ci.org/OpenMendel/VarianceComponentModels.jl) [![Build status](https://ci.appveyor.com/api/projects/status/5yyf2m4y8p68glbh/branch/master?svg=true)](https://ci.appveyor.com/project/Hua-Zhou/variancecomponentmodels-jl-cw40h/branch/master) | [![Coverage Status](https://coveralls.io/repos/github/OpenMendel/VarianceComponentModels.jl/badge.svg?branch=master)](https://coveralls.io/github/OpenMendel/VarianceComponentModels.jl?branch=master) [![codecov](https://codecov.io/gh/OpenMendel/VarianceComponentModels.jl/branch/master/graph/badge.svg)](https://codecov.io/gh/OpenMendel/VarianceComponentModels.jl) | This [Julia](http://julialang.org/) package provides computational routines for fitting and testing variance component models. VarianceComponentModels is one package of the umbrella [OpenMendel](https://openmendel.github.io) project. ## Installation This package requires Julia v0.7.0 or later, which can be obtained from https://julialang.org/downloads/ or by building Julia from the sources in the https://github.com/JuliaLang/julia repository. This package is registered in the default Julia package registry, and can be installed through standard package installation procedure: e.g., running the following code in Julia REPL. ```julia using Pkg pkg"add VarianceComponentModels" ``` ## Citation If you use [OpenMendel](https://openmendel.github.io) analysis packages in your research, please cite the following reference in the resulting publications: *Zhou, H., Sinsheimer, J., German, C., Ji, S., Bates, D., Chu, B. B., Keys, K., Kim, J., Ko, S., Mosher, G., Papp, J., Sobel, E., Zhai, J., Zhou, J., and Lange, K. (2020). OPENMENDEL: a cooperative programming project for statistical genetics, Human Genetics, 139(1):61-71.* <!--- ## Contributing We welcome contributions to this Open Source project. To contribute, follow this procedure ... ---> ## Acknowledgments This project is supported by the National Institutes of Health under NIGMS awards R01GM053275 and R25GM103774 and NHGRI award R01HG006139.
VarianceComponentModels
https://github.com/OpenMendel/VarianceComponentModels.jl.git
[ "MIT" ]
0.1.3
82d058ac0c22844b80c5bc098f17c7f7d5268f11
docs
1818
# VarianceComponentModels.jl *Utilities for fitting and testing variance component models* VarianceComponentModels.jl implements computation routines for fitting and testing variance component model of form $\text{vec}(Y) \sim \text{Normal}(X B, \Sigma_1 \otimes V_1 + \cdots + \Sigma_m \otimes V_m),$ where $\otimes$ is the [Kronecker product](https://en.wikipedia.org/wiki/Kronecker_product). In this model, **data** is represented by * `Y`: `n x d` response matrix * `X`: `n x p` covariate matrix * `V=(V1,...,Vm)`: a tuple `m` `n x n` covariance matrices and **parameters** are * `B`: `p x d` mean parameter matrix * `Σ=(Σ1,...,Σm)`: a tuple of `m` `d x d` variance components ## Package Features - Maximum likelihood estimation (MLE) and restricted maximum likelihood estimation (REML) of mean parameters `B` and variance component parameters `Σ` - Allow constrains in the mean parameters `B` - Choice of optimization algorithms: [Fisher scoring](https://books.google.com/books?id=QYqeYTftPNwC&lpg=PP1&pg=PA142#v=onepage&q&f=false) and [minorization-maximization algorithm](http://arxiv.org/abs/1509.07426) - [Heritability analysis](@ref) in genetics ## Installation This package requires Julia v0.7.0 or later, which can be obtained from https://julialang.org/downloads/ or by building Julia from the sources in the https://github.com/JuliaLang/julia repository. The package has not yet been registered and must be installed using the repository location. Start julia and use the `]` key to switch to the package manager REPL ```julia (v1.2) pkg> add https://github.com/OpenMendel/VarianceComponentModels.jl.git ``` Use the backspace key to return to the Julia REPL. ## Manual Outline ```@contents Pages = [ "man/mle_reml.md", "man/heritability.md", ] Depth = 2 ```
VarianceComponentModels
https://github.com/OpenMendel/VarianceComponentModels.jl.git
[ "MIT" ]
0.1.3
82d058ac0c22844b80c5bc098f17c7f7d5268f11
docs
301
# API Documentation for `VarianceComponentModels.jl`'s types and methods. ## Index ```@index Pages = ["api.md"] ``` ## Types ```@docs VarianceComponentModel VarianceComponentVariate TwoVarCompModelRotate TwoVarCompVariateRotate ``` ## Functions ```@docs mle_fs! mle_mm! fit_mle! fit_reml! ```
VarianceComponentModels
https://github.com/OpenMendel/VarianceComponentModels.jl.git
[ "MIT" ]
0.1.3
82d058ac0c22844b80c5bc098f17c7f7d5268f11
docs
60625
# Heritability Analysis As an application of the variance component model, this note demonstrates the workflow for heritability analysis in genetics, using a sample data set `cg10k` with **6,670** individuals and **630,860** SNPs. Person IDs and phenotype names are masked for privacy. `cg10k.bed`, `cg10k.bim`, and `cg10k.fam` is a set of Plink files in binary format. `cg10k_traits.txt` contains 13 phenotypes of the 6,670 individuals. ```julia ;ls cg10k.bed cg10k.bim cg10k.fam cg10k_traits.txt ``` cg10k.bed cg10k.bim cg10k.fam cg10k_traits.txt Machine information: ```julia versioninfo() ``` Julia Version 1.1.0 Commit 80516ca202 (2019-01-21 21:24 UTC) Platform Info: OS: macOS (x86_64-apple-darwin14.5.0) CPU: Intel(R) Core(TM) i5-6267U CPU @ 2.90GHz WORD_SIZE: 64 LIBM: libopenlibm LLVM: libLLVM-6.0.1 (ORCJIT, skylake) ## Read in binary SNP data We will use the [`SnpArrays.jl`](https://github.com/OpenMendel/SnpArrays.jl) package to read in binary SNP data and compute the empirical kinship matrix. The package has not yet been registered and must be installed using the repository location. Start julia and use the `]` key to switch to the package manager REPL ```julia (v0.7) pkg> add https://github.com/OpenMendel/SnpArrays.jl.git#juliav0.7 ``` Use the backspace key to return to the Julia REPL. ```julia using SnpArrays ``` ```julia # read in genotype data from Plink binary file (~50 secs on my laptop) @time cg10k = SnpArray("cg10k.bed") ``` 0.030779 seconds (54 allocations: 19.467 MiB, 28.08% gc time) 6670×630860 SnpArray: 0x02 0x02 0x03 0x03 0x02 0x03 … 0x02 0x03 0x03 0x03 0x03 0x03 0x03 0x03 0x02 0x03 0x02 0x03 0x03 0x02 0x02 0x03 0x02 0x01 0x03 0x03 0x02 0x03 0x02 0x03 0x03 0x03 0x03 0x03 0x03 0x03 0x03 0x03 0x03 0x03 0x03 0x03 0x03 0x02 0x02 0x02 0x02 0x03 0x03 0x03 0x03 0x03 0x03 0x03 0x03 0x03 0x03 0x03 0x03 0x02 0x02 0x02 0x03 0x03 0x02 0x03 … 0x03 0x03 0x03 0x03 0x03 0x03 0x00 0x00 0x03 0x03 0x00 0x03 0x03 0x02 0x03 0x03 0x03 0x03 0x03 0x03 0x03 0x03 0x03 0x02 0x03 0x03 0x03 0x03 0x03 0x02 0x03 0x03 0x02 0x03 0x02 0x03 0x02 0x02 0x03 0x03 0x03 0x03 0x03 0x03 0x03 0x00 0x03 0x03 0x02 0x02 0x03 0x03 0x02 0x03 0x03 0x03 0x02 0x03 0x02 0x02 … 0x02 0x03 0x03 0x03 0x03 0x03 0x02 0x02 0x03 0x03 0x02 0x03 0x02 0x03 0x03 0x03 0x03 0x02 0x03 0x03 0x03 0x00 0x03 0x03 0x03 0x03 0x03 0x03 0x03 0x02 ⋮ ⋮ ⋱ ⋮ 0x02 0x02 0x03 0x03 0x02 0x03 0x03 0x02 0x03 0x03 0x02 0x02 0x02 0x02 0x02 0x03 0x00 0x02 0x02 0x03 0x03 0x03 0x02 0x03 0x03 0x03 0x02 0x02 0x02 0x03 … 0x03 0x02 0x03 0x03 0x02 0x03 0x02 0x02 0x03 0x03 0x02 0x03 0x03 0x02 0x03 0x03 0x03 0x02 0x03 0x03 0x03 0x02 0x03 0x02 0x03 0x03 0x03 0x03 0x02 0x03 0x03 0x03 0x01 0x02 0x02 0x01 0x03 0x00 0x00 0x02 0x00 0x02 0x03 0x03 0x03 0x02 0x03 0x03 0x03 0x03 0x03 0x03 0x03 0x02 0x03 0x03 0x02 0x02 0x02 0x03 … 0x00 0x03 0x03 0x03 0x03 0x03 0x03 0x03 0x03 0x02 0x02 0x03 0x02 0x02 0x02 0x02 0x02 0x03 0x03 0x03 0x03 0x02 0x03 0x02 0x02 0x03 0x02 0x03 0x03 0x02 0x02 0x02 0x03 0x03 0x02 0x03 0x03 0x03 0x01 0x03 0x03 0x03 0x03 0x03 0x03 0x03 0x03 0x02 0x03 0x00 0x03 0x03 0x03 0x03 ## Summary statistics of SNP data ```julia people, snps = size(cg10k) ``` (6670, 630860) The positions of the missing data are evaluated by ```julia mp = missingpos(cg10k) ``` 6670×630860 SparseArrays.SparseMatrixCSC{Bool,Int32} with 5524131 stored entries: [5688 , 1] = true [6445 , 1] = true [109 , 3] = true [189 , 3] = true [216 , 3] = true [254 , 3] = true [331 , 3] = true [522 , 3] = true [525 , 3] = true [597 , 3] = true [619 , 3] = true [672 , 3] = true ⋮ [4929 , 630860] = true [5594 , 630860] = true [5650 , 630860] = true [5780 , 630860] = true [5854 , 630860] = true [5867 , 630860] = true [6084 , 630860] = true [6175 , 630860] = true [6178 , 630860] = true [6239 , 630860] = true [6478 , 630860] = true [6511 , 630860] = true The number of missing data values in each column can be evaluated as ```julia missings_by_snp = sum(mp, dims=1) ``` 1×630860 Array{Int64,2}: 2 0 132 77 0 27 2 2 6 27 2 … 6 4 5 11 0 0 4 29 0 5 43 Minor allele frequencies (MAF) for each SNP. ```julia maf_cg10k = maf(cg10k) ``` 630860-element Array{Float64,1}: 0.1699160167966407 0.17098950524737633 0.11402569593147749 0.2686940694676172 0.21926536731634183 0.23934969140448592 0.19061187762447507 0.20200959808038388 0.027160864345738278 0.2997139846454915 0.24625074985003004 0.05555555555555558 0.3659067046647667 ⋮ 0.22547254725472543 0.4035864345738295 0.20799579957995795 0.44801200300075017 0.2954647845021775 0.14265367316341826 0.1709145427286357 0.2814281428142814 0.06113537117903933 0.052473763118440764 0.13930982745686427 0.1324128564961521 ```julia # 5 number summary and average MAF (minor allele frequencies) using Statistics Statistics.quantile(maf_cg10k, [0.0 .25 .5 .75 1.0]), mean(maf_cg10k) ``` ([0.00841726 0.124063 … 0.364253 0.5], 0.24536516625042462) ```julia #using Pkg #pkg "add Plots" #pkg"add PyPlot" using Plots gr(size=(600,500), html_output_format=:png) histogram(maf_cg10k, xlab = "Minor Allele Frequency (MAF)", label = "MAF") ``` ![png](fig1_heritability.png) ```julia # proportion of missing genotypes sum(missings_by_snp) / length(cg10k) ``` 0.0013128198764010824 ```julia # proportion of rare SNPs with maf < 0.05 count(!iszero, maf_cg10k .< 0.05) / length(maf_cg10k) ``` 0.07228069619249913 ## Empirical kinship matrix We estimate empirical kinship based on all SNPs by the genetic relation matrix (GRM). Missing genotypes are imputed on the fly by drawing according to the minor allele frequencies. ```julia ## GRM using SNPs with maf > 0.01 (default) (~10 mins on my laptop) using Random Random.seed!(123) @time Φgrm = grm(cg10k; method = :GRM) ``` 568.176660 seconds (2.91 M allocations: 494.981 MiB, 0.40% gc time) 6670×6670 Array{Float64,2}: 0.502735 0.00328112 -6.79435e-5 … -6.09591e-5 -0.00277687 0.00328112 0.49807 -0.00195548 0.000884994 0.00341591 -6.79435e-5 -0.00195548 0.492348 0.000198191 -0.000337529 0.00087876 -0.00322605 -0.00192088 -0.00235314 -0.00124267 -5.03227e-5 -0.00352498 0.00184588 0.00219109 -0.00163189 0.00203199 0.000597697 0.00251237 … 0.00088428 2.21226e-5 0.000560862 0.00244517 -0.00183233 0.00120214 -0.00120686 -0.000656949 0.00322249 -0.00101472 0.00355832 -0.000240444 -0.00103874 -0.00125164 -0.000599731 0.00176492 0.00176928 -0.00137058 0.00209596 0.000146711 -0.0014453 -0.00103066 -0.00209312 0.000140721 -0.000442031 … -0.000214963 -0.00107391 0.000933587 0.00168842 0.00185731 -0.000787908 -0.00311063 0.000334572 -0.000886623 0.00304182 0.000752285 -0.00123334 ⋮ ⋱ 0.00298109 0.00121739 0.00102822 9.66935e-6 0.00306953 -0.00209728 0.00271452 -0.00182325 -0.00108139 0.00366901 0.000549425 -0.00244419 -0.00301368 … -0.000631961 0.00215641 -0.00423362 -0.00208073 -0.00107904 -0.000619315 -0.000593852 -0.00326697 -0.000769552 0.00310511 0.000520658 -0.000113441 0.000430563 -0.0020236 0.00265425 -0.00635493 -0.00520252 0.00218746 0.000798767 -0.00105684 -0.000918245 -0.00061484 -0.00230525 -0.000101149 0.000117936 … 0.000879829 -0.00233479 -0.00201305 0.00233864 -0.00134496 0.00197044 -0.000486275 -0.000990534 -0.000924159 -9.12302e-5 0.00122311 -0.00298296 -6.09591e-5 0.000884994 0.000198191 0.499289 0.000481492 -0.00277687 0.00341591 -0.000337529 0.000481492 0.499799 ## Phenotypes Read in the phenotype data and compute descriptive statistics. ```julia #using Pkg #pkg"add CSV DataFrames" #using CSV, DataFrames cg10k_trait = CSV.File("cg10k_traits.txt"; delim = ' ') |> DataFrame names!(cg10k_trait, [:FID; :IID; :Trait1; :Trait2; :Trait3; :Trait4; :Trait5; :Trait6; :Trait7; :Trait8; :Trait9; :Trait10; :Trait11; :Trait12; :Trait13]) # do not display FID and IID for privacy cg10k_trait[:, 3:end] ``` <table class="data-frame"><thead><tr><th></th><th>Trait1</th><th>Trait2</th><th>Trait3</th><th>Trait4</th><th>Trait5</th><th>Trait6</th><th>Trait7</th><th>Trait8</th><th>Trait9</th><th>Trait10</th><th>Trait11</th><th>Trait12</th><th>Trait13</th></tr><tr><th></th><th>Float64⍰</th><th>Float64⍰</th><th>Float64⍰</th><th>Float64⍰</th><th>Float64⍰</th><th>Float64⍰</th><th>Float64⍰</th><th>Float64⍰</th><th>Float64⍰</th><th>Float64⍰</th><th>Float64⍰</th><th>Float64⍰</th><th>Float64⍰</th></tr></thead><tbody><p>6,670 rows × 13 columns</p><tr><th>1</th><td>-1.81573</td><td>-0.94615</td><td>1.11363</td><td>-2.09867</td><td>0.744417</td><td>0.00139172</td><td>0.934732</td><td>-1.22677</td><td>1.11608</td><td>-0.443628</td><td>0.824466</td><td>-1.02853</td><td>-0.394049</td></tr><tr><th>2</th><td>-1.2444</td><td>0.10966</td><td>0.467119</td><td>-1.62131</td><td>1.05668</td><td>0.978947</td><td>1.00015</td><td>0.324874</td><td>1.16232</td><td>2.69227</td><td>3.08264</td><td>1.09065</td><td>0.0256616</td></tr><tr><th>3</th><td>1.45567</td><td>1.53867</td><td>1.09403</td><td>0.586655</td><td>-0.327965</td><td>-0.303377</td><td>-0.0334355</td><td>-0.464463</td><td>-0.33194</td><td>-0.486839</td><td>-1.10649</td><td>-1.42016</td><td>-0.687463</td></tr><tr><th>4</th><td>-0.768809</td><td>0.513491</td><td>0.244263</td><td>-1.3174</td><td>1.19394</td><td>1.17344</td><td>1.08737</td><td>0.536023</td><td>0.802759</td><td>0.234159</td><td>0.394175</td><td>-0.767366</td><td>0.0635386</td></tr><tr><th>5</th><td>-0.264415</td><td>-0.34824</td><td>-0.0239065</td><td>0.00473916</td><td>1.25619</td><td>1.20389</td><td>1.29801</td><td>0.310114</td><td>0.62616</td><td>0.899289</td><td>0.549968</td><td>0.540688</td><td>0.179675</td></tr><tr><th>6</th><td>-1.37617</td><td>-1.47192</td><td>0.29118</td><td>-0.803111</td><td>-0.26424</td><td>-0.260573</td><td>-0.165372</td><td>-0.219257</td><td>1.04702</td><td>-0.0985816</td><td>0.947393</td><td>0.594015</td><td>0.245407</td></tr><tr><th>7</th><td>0.100942</td><td>-0.191616</td><td>-0.567421</td><td>0.378571</td><td>-0.246656</td><td>-0.608811</td><td>0.189081</td><td>-1.27078</td><td>-0.452476</td><td>0.702563</td><td>0.332636</td><td>0.00269165</td><td>0.317117</td></tr><tr><th>8</th><td>-0.319818</td><td>1.35774</td><td>0.81869</td><td>-1.15566</td><td>0.634484</td><td>0.291462</td><td>0.933324</td><td>-0.741083</td><td>0.647478</td><td>-0.970878</td><td>0.220861</td><td>0.852512</td><td>-0.225905</td></tr><tr><th>9</th><td>-0.288334</td><td>0.566083</td><td>0.254958</td><td>-0.652578</td><td>0.668922</td><td>0.978309</td><td>0.122863</td><td>1.47909</td><td>0.0672132</td><td>0.0795904</td><td>0.167532</td><td>0.246916</td><td>0.539933</td></tr><tr><th>10</th><td>-1.1576</td><td>-0.781199</td><td>-0.595808</td><td>-1.00555</td><td>0.789829</td><td>0.571058</td><td>0.951304</td><td>-0.295963</td><td>0.99042</td><td>0.561309</td><td>0.7331</td><td>-1.73468</td><td>-1.35278</td></tr><tr><th>11</th><td>0.740569</td><td>1.40874</td><td>0.73469</td><td>0.0208323</td><td>-0.337441</td><td>-0.458304</td><td>-0.142583</td><td>-0.580392</td><td>-0.684685</td><td>-0.00785381</td><td>-0.712244</td><td>-0.313346</td><td>-0.345419</td></tr><tr><th>12</th><td>-0.675892</td><td>0.279893</td><td>0.267916</td><td>-1.04104</td><td>0.910742</td><td>0.866028</td><td>1.07414</td><td>0.0381751</td><td>0.766355</td><td>-0.340118</td><td>-0.809014</td><td>0.548522</td><td>-0.0201829</td></tr><tr><th>13</th><td>-0.79541</td><td>-0.69999</td><td>0.39913</td><td>-0.510476</td><td>1.51552</td><td>1.28743</td><td>1.53772</td><td>0.133989</td><td>1.02026</td><td>0.499019</td><td>-0.369483</td><td>-1.10153</td><td>-0.598132</td></tr><tr><th>14</th><td>-0.193483</td><td>-0.286021</td><td>-0.691494</td><td>0.0131582</td><td>1.52337</td><td>1.40106</td><td>1.53115</td><td>0.333066</td><td>1.04372</td><td>0.163207</td><td>-0.422884</td><td>-0.383528</td><td>-0.489222</td></tr><tr><th>15</th><td>0.151246</td><td>2.09185</td><td>2.038</td><td>-1.12475</td><td>1.66557</td><td>1.62536</td><td>1.58751</td><td>0.635852</td><td>0.842578</td><td>0.450762</td><td>-1.39479</td><td>-0.560984</td><td>0.28935</td></tr><tr><th>16</th><td>-0.464609</td><td>0.361277</td><td>1.23277</td><td>-0.826034</td><td>1.43475</td><td>1.74452</td><td>0.211097</td><td>2.64816</td><td>1.02511</td><td>0.119757</td><td>0.0596832</td><td>-0.631232</td><td>-0.207879</td></tr><tr><th>17</th><td>-0.732977</td><td>-0.526223</td><td>0.616579</td><td>-0.55448</td><td>0.947485</td><td>0.936833</td><td>0.972517</td><td>0.290251</td><td>1.01285</td><td>0.516207</td><td>-0.0300689</td><td>0.878732</td><td>0.450255</td></tr><tr><th>18</th><td>-0.167326</td><td>0.175327</td><td>0.287468</td><td>-0.402653</td><td>0.551182</td><td>0.522205</td><td>0.436838</td><td>0.299565</td><td>0.58311</td><td>-0.704416</td><td>-0.73081</td><td>-1.95141</td><td>-0.933505</td></tr><tr><th>19</th><td>1.41159</td><td>1.78722</td><td>0.843976</td><td>0.481278</td><td>-0.0887674</td><td>-0.499578</td><td>0.304196</td><td>-1.23884</td><td>-0.153476</td><td>-0.870486</td><td>0.0955473</td><td>-0.983708</td><td>-0.356345</td></tr><tr><th>20</th><td>-1.42997</td><td>-0.490147</td><td>0.27273</td><td>-1.6103</td><td>0.990788</td><td>0.711688</td><td>1.18858</td><td>-0.371229</td><td>1.24703</td><td>-0.0389162</td><td>0.883496</td><td>2.58988</td><td>3.3354</td></tr><tr><th>21</th><td>-0.147247</td><td>0.123284</td><td>0.617549</td><td>-0.187131</td><td>0.256438</td><td>0.17795</td><td>0.412612</td><td>-0.244809</td><td>0.0947625</td><td>0.723017</td><td>-0.683948</td><td>0.0873751</td><td>-0.26221</td></tr><tr><th>22</th><td>-0.187113</td><td>-0.270777</td><td>-1.01557</td><td>0.0602851</td><td>0.27242</td><td>0.869133</td><td>-0.657519</td><td>2.32389</td><td>-0.999936</td><td>1.44672</td><td>0.971158</td><td>-0.358748</td><td>-0.439658</td></tr><tr><th>23</th><td>-1.82434</td><td>-0.93348</td><td>1.29474</td><td>-1.94545</td><td>0.335847</td><td>0.359202</td><td>0.513653</td><td>-0.0731977</td><td>1.57139</td><td>1.53329</td><td>1.82077</td><td>2.2274</td><td>1.50063</td></tr><tr><th>24</th><td>-2.29344</td><td>-2.49162</td><td>0.40384</td><td>-2.36488</td><td>1.41053</td><td>1.42244</td><td>1.17024</td><td>0.844767</td><td>1.79027</td><td>0.648182</td><td>-0.0857231</td><td>-1.0279</td><td>0.491288</td></tr><tr><th>25</th><td>-0.434136</td><td>0.740882</td><td>0.699576</td><td>-1.02406</td><td>0.759529</td><td>0.956656</td><td>0.6333</td><td>0.770734</td><td>0.824989</td><td>1.84287</td><td>1.91046</td><td>-0.502317</td><td>0.13267</td></tr><tr><th>26</th><td>-2.1921</td><td>-2.49466</td><td>0.354855</td><td>-1.93156</td><td>0.941979</td><td>0.978917</td><td>0.89486</td><td>0.463239</td><td>1.12537</td><td>1.70528</td><td>0.717793</td><td>0.645888</td><td>0.783968</td></tr><tr><th>27</th><td>-1.46602</td><td>-1.24922</td><td>0.307978</td><td>-1.55097</td><td>0.618908</td><td>0.662508</td><td>0.475957</td><td>0.484719</td><td>0.401565</td><td>0.55988</td><td>-0.376938</td><td>-0.933983</td><td>0.390013</td></tr><tr><th>28</th><td>-1.83318</td><td>-1.53269</td><td>2.55674</td><td>-1.51828</td><td>0.78941</td><td>0.908748</td><td>0.649972</td><td>0.668374</td><td>1.20058</td><td>0.277963</td><td>1.2505</td><td>3.3137</td><td>2.22036</td></tr><tr><th>29</th><td>-0.784547</td><td>0.276583</td><td>3.01105</td><td>-1.11979</td><td>0.920824</td><td>0.750218</td><td>1.26154</td><td>-0.403364</td><td>0.400667</td><td>-0.217598</td><td>-0.72467</td><td>-0.391945</td><td>-0.650024</td></tr><tr><th>30</th><td>0.464456</td><td>1.33264</td><td>-1.2306</td><td>-0.357976</td><td>1.1825</td><td>1.54316</td><td>-0.60339</td><td>3.38309</td><td>0.823741</td><td>-0.129951</td><td>-0.65798</td><td>-0.499535</td><td>-0.414477</td></tr><tr><th>&vellip;</th><td>&vellip;</td><td>&vellip;</td><td>&vellip;</td><td>&vellip;</td><td>&vellip;</td><td>&vellip;</td><td>&vellip;</td><td>&vellip;</td><td>&vellip;</td><td>&vellip;</td><td>&vellip;</td><td>&vellip;</td><td>&vellip;</td></tr></tbody></table> ```julia describe(cg10k_trait[:, 3:end]) ``` <table class="data-frame"><thead><tr><th></th><th>variable</th><th>mean</th><th>min</th><th>median</th><th>max</th><th>nunique</th><th>nmissing</th><th>eltype</th></tr><tr><th></th><th>Symbol</th><th>Float64</th><th>Float64</th><th>Float64</th><th>Float64</th><th>Nothing</th><th>Int64</th><th>DataType</th></tr></thead><tbody><p>13 rows × 8 columns</p><tr><th>1</th><td>Trait1</td><td>0.00221138</td><td>-3.20413</td><td>0.12501</td><td>3.4794</td><td></td><td>0</td><td>Float64</td></tr><tr><th>2</th><td>Trait2</td><td>0.00135253</td><td>-3.51166</td><td>0.0335173</td><td>4.91342</td><td></td><td>0</td><td>Float64</td></tr><tr><th>3</th><td>Trait3</td><td>-0.00129591</td><td>-3.93844</td><td>-0.000782162</td><td>7.9163</td><td></td><td>0</td><td>Float64</td></tr><tr><th>4</th><td>Trait4</td><td>0.00230893</td><td>-3.6084</td><td>0.228165</td><td>3.12769</td><td></td><td>0</td><td>Float64</td></tr><tr><th>5</th><td>Trait5</td><td>-0.00179039</td><td>-4.14875</td><td>0.0310343</td><td>2.71718</td><td></td><td>0</td><td>Float64</td></tr><tr><th>6</th><td>Trait6</td><td>-0.00119598</td><td>-3.82479</td><td>0.036242</td><td>2.58973</td><td></td><td>0</td><td>Float64</td></tr><tr><th>7</th><td>Trait7</td><td>-0.00198906</td><td>-4.27246</td><td>0.069801</td><td>2.65378</td><td></td><td>0</td><td>Float64</td></tr><tr><th>8</th><td>Trait8</td><td>0.000614075</td><td>-5.62549</td><td>-0.0386301</td><td>5.8057</td><td></td><td>0</td><td>Float64</td></tr><tr><th>9</th><td>Trait9</td><td>-0.00180965</td><td>-5.38197</td><td>0.106571</td><td>2.57194</td><td></td><td>0</td><td>Float64</td></tr><tr><th>10</th><td>Trait10</td><td>-0.000437029</td><td>-3.54851</td><td>-0.0966507</td><td>6.53782</td><td></td><td>0</td><td>Float64</td></tr><tr><th>11</th><td>Trait11</td><td>-0.000615918</td><td>-3.26491</td><td>-0.0680437</td><td>4.26241</td><td></td><td>0</td><td>Float64</td></tr><tr><th>12</th><td>Trait12</td><td>-0.000588783</td><td>-8.85191</td><td>-0.141099</td><td>13.2114</td><td></td><td>0</td><td>Float64</td></tr><tr><th>13</th><td>Trait13</td><td>-0.000151238</td><td>-5.5921</td><td>-0.141022</td><td>24.1744</td><td></td><td>0</td><td>Float64</td></tr></tbody></table> ```julia Y = convert(Matrix{Float64}, cg10k_trait[:, 3:15]) histogram(Y, layout = 13) ``` ![png](fig2_heritability.png) ## Pre-processing data for heritability analysis To prepare variance component model fitting, we form an instance of `VarianceComponentVariate`. The two variance components are $(2\Phi, I)$. ```julia using VarianceComponentModels, LinearAlgebra # form data as VarianceComponentVariate cg10kdata = VarianceComponentVariate(Y, (2Φgrm, Matrix(1.0I, size(Y, 1), size(Y, 1)))) fieldnames(typeof(cg10kdata)) ``` (:Y, :X, :V) ```julia cg10kdata ``` VarianceComponentVariate{Float64,2,Array{Float64,2},Array{Float64,2},Array{Float64,2}}([-1.81573 -0.94615 … -1.02853 -0.394049; -1.2444 0.10966 … 1.09065 0.0256616; … ; 0.886626 0.487408 … -0.636874 -0.439825; -1.24394 0.213697 … 0.299931 0.392809], Array{Float64}(6670,0), ([1.00547 0.00656224 … -0.000121918 -0.00555374; 0.00656224 0.99614 … 0.00176999 0.00683183; … ; -0.000121918 0.00176999 … 0.998578 0.000962983; -0.00555374 0.00683183 … 0.000962983 0.999599], [1.0 0.0 … 0.0 0.0; 0.0 1.0 … 0.0 0.0; … ; 0.0 0.0 … 1.0 0.0; 0.0 0.0 … 0.0 1.0])) Before fitting the variance component model, we pre-compute the eigen-decomposition of $2\Phi_{\text{GRM}}$, the rotated responses, and the constant part in log-likelihood, and store them as a `TwoVarCompVariateRotate` instance, which is re-used in various variane component estimation procedures. ```julia # pre-compute eigen-decomposition (~50 secs on my laptop) @time cg10kdata_rotated = TwoVarCompVariateRotate(cg10kdata) fieldnames(typeof(cg10kdata_rotated)) ``` 49.812646 seconds (1.74 M allocations: 1.080 GiB, 0.33% gc time) (:Yrot, :Xrot, :eigval, :eigvec, :logdetV2) ## Save intermediate results We don't want to re-compute SnpArray and empirical kinship matrices again and again for heritibility analysis. To load workspace ```julia #pkg"add FileIO JLD2" using JLD2 @save "cg10k.jld2" varinfo() ``` | name | size | summary | |:----------------- | ------------:|:-------------------------------------------------------------------------------------- | | Base | | Module | | Core | | Module | | Main | | Module | | Plots | 2.988 MiB | Module | | PyPlot | 782.799 KiB | Module | | Y | 677.461 KiB | 6670×13 Array{Float64,2} | | cg10k | 1022.983 MiB | 6670×630860 SnpArray | | cg10k_trait | 1.605 MiB | 6670×15 DataFrame | | cg10kdata | 679.508 MiB | VarianceComponentVariate{Float64,2,Array{Float64,2},Array{Float64,2},Array{Float64,2}} | | cg10kdata_rotated | 340.136 MiB | TwoVarCompVariateRotate{Float64,Array{Float64,2},Array{Float64,2}} | | maf_cg10k | 4.813 MiB | 630860-element Array{Float64,1} | | missings_by_snp | 4.813 MiB | 1×630860 Array{Int64,2} | | mp | 28.748 MiB | 6670×630860 SparseArrays.SparseMatrixCSC{Bool,Int32} | | people | 8 bytes | Int64 | | snps | 8 bytes | Int64 | | startupfile | 57 bytes | String | | Φgrm | 339.423 MiB | 6670×6670 Array{Float64,2} | ```julia using SnpArrays, JLD2, DataFrames, VarianceComponentModels, Plots pyplot() @load "cg10k.jld2" varinfo() ``` ┌ Warning: type SparseArrays.SparseMatrixCSC{Bool,Int32} does not exist in workspace; reconstructing └ @ JLD2 /Users/juhyun-kim/.julia/packages/JLD2/KjBIK/src/data.jl:1153 | name | size | summary | |:----------------- | ------------:|:------------------------------------------------------------------------------------------- | | Base | | Module | | Core | | Module | | Main | | Module | | Plots | 2.988 MiB | Module | | PyPlot | 782.799 KiB | Module | | Y | 677.461 KiB | 6670×13 Array{Float64,2} | | cg10k | 1022.983 MiB | 6670×630860 SnpArray | | cg10k_trait | 1.605 MiB | 6670×15 DataFrame | | cg10kdata | 679.508 MiB | VarianceComponentVariate{Float64,2,Array{Float64,2},Array{Float64,2},Array{Float64,2}} | | cg10kdata_rotated | 340.136 MiB | TwoVarCompVariateRotate{Float64,Array{Float64,2},Array{Float64,2}} | | maf_cg10k | 4.813 MiB | 630860-element Array{Float64,1} | | missings_by_snp | 4.813 MiB | 1×630860 Array{Int64,2} | | mp | 28.748 MiB | getfield(JLD2.ReconstructedTypes, Symbol("##SparseArrays.SparseMatrixCSC{Bool,Int32}#386")) | | people | 8 bytes | Int64 | | snps | 8 bytes | Int64 | | startupfile | 57 bytes | String | | Φgrm | 339.423 MiB | 6670×6670 Array{Float64,2} | ## Heritability of single traits We use Fisher scoring algorithm to fit variance component model for each single trait. ```julia # heritability from single trait analysis hST = zeros(13) # standard errors of estimated heritability hST_se = zeros(13) # additive genetic effects σ2a = zeros(13) # enviromental effects σ2e = zeros(13) @time for trait in 1:13 println(names(cg10k_trait)[trait + 2]) # form data set for trait j traitj_data = TwoVarCompVariateRotate(cg10kdata_rotated.Yrot[:, trait], cg10kdata_rotated.Xrot, cg10kdata_rotated.eigval, cg10kdata_rotated.eigvec, cg10kdata_rotated.logdetV2) # initialize model parameters traitj_model = VarianceComponentModel(traitj_data) # estimate variance components _, _, _, Σcov, _, _ = mle_fs!(traitj_model, traitj_data; solver=:Ipopt, verbose=false) σ2a[trait] = traitj_model.Σ[1][1] σ2e[trait] = traitj_model.Σ[2][1] @show σ2a[trait], σ2e[trait] h, hse = heritability(traitj_model.Σ, Σcov) hST[trait] = h[1] hST_se[trait] = hse[1] end ``` Trait1 ****************************************************************************** This program contains Ipopt, a library for large-scale nonlinear optimization. Ipopt is released as open source code under the Eclipse Public License (EPL). For more information visit http://projects.coin-or.org/Ipopt ****************************************************************************** (σ2a[trait], σ2e[trait]) = (0.2594760477653529, 0.7375938878381831) Trait2 (σ2a[trait], σ2e[trait]) = (0.18588150448760332, 0.8137880281704619) Trait3 (σ2a[trait], σ2e[trait]) = (0.31960937565352526, 0.6795300238388766) Trait4 (σ2a[trait], σ2e[trait]) = (0.26578244697498915, 0.7304994606945259) Trait5 (σ2a[trait], σ2e[trait]) = (0.28143198005767217, 0.7169747061764987) Trait6 (σ2a[trait], σ2e[trait]) = (0.2830055131241748, 0.7168800753377107) Trait7 (σ2a[trait], σ2e[trait]) = (0.2156542141311619, 0.7816910320891676) Trait8 (σ2a[trait], σ2e[trait]) = (0.19408878271207824, 0.8058201577783562) Trait9 (σ2a[trait], σ2e[trait]) = (0.24746236011763145, 0.7512222977091793) Trait10 (σ2a[trait], σ2e[trait]) = (0.0992417256213392, 0.9007769787053657) Trait11 (σ2a[trait], σ2e[trait]) = (0.1645726648140337, 0.8343110221526228) Trait12 (σ2a[trait], σ2e[trait]) = (0.0822495659186408, 0.9166483378364408) Trait13 (σ2a[trait], σ2e[trait]) = (0.05687679106195183, 0.9424058676223598) 6.203222 seconds (12.80 M allocations: 621.516 MiB, 7.13% gc time) ```julia # heritability and standard errors [hST'; hST_se'] ``` 2×13 Array{Float64,2}: 0.260239 0.185943 0.319885 … 0.164757 0.0823403 0.0569176 0.0799434 0.08689 0.0739664 0.0887138 0.0944375 0.0953072 ## Pairwise traits Joint analysis of multiple traits is subject to intensive research recently. Following code snippet does joint analysis of all pairs of traits, a total of 78 bivariate variane component models. ```julia # additive genetic effects (2x2 psd matrices) from bavariate trait analysis; Σa = Array{Matrix{Float64}}(undef, 13, 13) # environmental effects (2x2 psd matrices) from bavariate trait analysis; Σe = Array{Matrix{Float64}}(undef, 13, 13) @time for i in 1:13 for j in (i+1):13 println(names(cg10k_trait)[i + 2], names(cg10k_trait)[j + 2]) # form data set for (trait1, trait2) traitij_data = TwoVarCompVariateRotate(cg10kdata_rotated.Yrot[:, [i;j]], cg10kdata_rotated.Xrot, cg10kdata_rotated.eigval, cg10kdata_rotated.eigvec, cg10kdata_rotated.logdetV2) # initialize model parameters traitij_model = VarianceComponentModel(traitij_data) # estimate variance components mle_fs!(traitij_model, traitij_data; solver=:Ipopt, verbose=false) Σa[i, j] = traitij_model.Σ[1] Σe[i, j] = traitij_model.Σ[2] @show Σa[i, j], Σe[i, j] end end ``` Trait1Trait2 (Σa[i, j], Σe[i, j]) = ([0.258529 0.173943; 0.173943 0.184525], [0.738519 0.58639; 0.58639 0.815122]) Trait1Trait3 (Σa[i, j], Σe[i, j]) = ([0.259934 -0.0139395; -0.0139395 0.320025], [0.737149 -0.120342; -0.120342 0.67913]) Trait1Trait4 (Σa[i, j], Σe[i, j]) = ([0.259307 0.222267; 0.222267 0.265791], [0.737759 0.600077; 0.600077 0.730492]) Trait1Trait5 (Σa[i, j], Σe[i, j]) = ([0.259264 -0.147125; -0.147125 0.282102], [0.737798 -0.254669; -0.254669 0.716327]) Trait1Trait6 (Σa[i, j], Σe[i, j]) = ([0.259171 -0.129519; -0.129519 0.283267], [0.73789 -0.231373; -0.231373 0.716628]) Trait1Trait7 (Σa[i, j], Σe[i, j]) = ([0.258784 -0.140357; -0.140357 0.21535], [0.738269 -0.197894; -0.197894 0.782002]) Trait1Trait8 (Σa[i, j], Σe[i, j]) = ([0.259467 -0.0336174; -0.0336174 0.194107], [0.737603 -0.12623; -0.12623 0.805802]) Trait1Trait9 (Σa[i, j], Σe[i, j]) = ([0.261524 -0.204467; -0.204467 0.246378], [0.735632 -0.308118; -0.308118 0.752288]) Trait1Trait10 (Σa[i, j], Σe[i, j]) = ([0.259326 -0.0987008; -0.0987008 0.0962217], [0.73774 -0.304854; -0.304854 0.90378]) Trait1Trait11 (Σa[i, j], Σe[i, j]) = ([0.259194 -0.137578; -0.137578 0.162813], [0.737868 -0.36076; -0.36076 0.836058]) Trait1Trait12 (Σa[i, j], Σe[i, j]) = ([0.26168 -0.145305; -0.145305 0.0806851], [0.735514 -0.0421192; -0.0421192 0.918294]) Trait1Trait13 (Σa[i, j], Σe[i, j]) = ([0.260776 -0.108277; -0.108277 0.0513909], [0.736359 -0.114756; -0.114756 0.947913]) Trait2Trait3 (Σa[i, j], Σe[i, j]) = ([0.185992 0.14505; 0.14505 0.321413], [0.813678 0.0987898; 0.0987898 0.677805]) Trait2Trait4 (Σa[i, j], Σe[i, j]) = ([0.18554 0.074367; 0.074367 0.26577], [0.814123 0.22144; 0.22144 0.730512]) Trait2Trait5 (Σa[i, j], Σe[i, j]) = ([0.185854 -0.0115021; -0.0115021 0.281443], [0.813815 -0.0368393; -0.0368393 0.716964]) Trait2Trait6 (Σa[i, j], Σe[i, j]) = ([0.185903 -0.00350261; -0.00350261 0.283064], [0.813767 -0.0207933; -0.0207933 0.716823]) Trait2Trait7 (Σa[i, j], Σe[i, j]) = ([0.185498 -0.0301226; -0.0301226 0.215413], [0.814164 -0.00124563; -0.00124563 0.781929]) Trait2Trait8 (Σa[i, j], Σe[i, j]) = ([0.186397 0.032688; 0.032688 0.194625], [0.813285 -0.0321045; -0.0321045 0.805301]) Trait2Trait9 (Σa[i, j], Σe[i, j]) = ([0.184426 -0.084907; -0.084907 0.246288], [0.815228 -0.0814978; -0.0814978 0.752373]) Trait2Trait10 (Σa[i, j], Σe[i, j]) = ([0.18604 -0.123261; -0.123261 0.0992567], [0.813659 -0.273285; -0.273285 0.90084]) Trait2Trait11 (Σa[i, j], Σe[i, j]) = ([0.184894 -0.116422; -0.116422 0.165892], [0.814757 -0.297755; -0.297755 0.833033]) Trait2Trait12 (Σa[i, j], Σe[i, j]) = ([0.185297 -0.0908872; -0.0908872 0.0814927], [0.814404 0.0456529; 0.0456529 0.917465]) Trait2Trait13 (Σa[i, j], Σe[i, j]) = ([0.185348 -0.07104; -0.07104 0.0546791], [0.814367 0.0740412; 0.0740412 0.944638]) Trait3Trait4 (Σa[i, j], Σe[i, j]) = ([0.319575 -0.15468; -0.15468 0.265006], [0.679563 -0.303309; -0.303309 0.731254]) Trait3Trait5 (Σa[i, j], Σe[i, j]) = ([0.320016 0.184736; 0.184736 0.282719], [0.679136 0.336276; 0.336276 0.715725]) Trait3Trait6 (Σa[i, j], Σe[i, j]) = ([0.320608 0.166929; 0.166929 0.285124], [0.678565 0.297633; 0.297633 0.714823]) Trait3Trait7 (Σa[i, j], Σe[i, j]) = ([0.319614 0.167317; 0.167317 0.215458], [0.679526 0.346897; 0.346897 0.781883]) Trait3Trait8 (Σa[i, j], Σe[i, j]) = ([0.321532 0.0573397; 0.0573397 0.197221], [0.677674 0.0445311; 0.0445311 0.802757]) Trait3Trait9 (Σa[i, j], Σe[i, j]) = ([0.319777 0.138268; 0.138268 0.246547], [0.679369 0.266317; 0.266317 0.752112]) Trait3Trait10 (Σa[i, j], Σe[i, j]) = ([0.319905 -0.0779601; -0.0779601 0.100192], [0.679245 -0.141562; -0.141562 0.899839]) Trait3Trait11 (Σa[i, j], Σe[i, j]) = ([0.318882 -0.0177352; -0.0177352 0.164446], [0.680233 -0.114434; -0.114434 0.834435]) Trait3Trait12 (Σa[i, j], Σe[i, j]) = ([0.321958 0.0844644; 0.0844644 0.0863388], [0.67727 0.034186; 0.034186 0.912603]) Trait3Trait13 (Σa[i, j], Σe[i, j]) = ([0.32405 0.109731; 0.109731 0.0613165], [0.675287 -0.00619989; -0.00619989 0.938011]) Trait4Trait5 (Σa[i, j], Σe[i, j]) = ([0.26593 -0.216116; -0.216116 0.283173], [0.730347 -0.376697; -0.376697 0.715289]) Trait4Trait6 (Σa[i, j], Σe[i, j]) = ([0.266395 -0.200793; -0.200793 0.284547], [0.729899 -0.346915; -0.346915 0.715387]) Trait4Trait7 (Σa[i, j], Σe[i, j]) = ([0.264731 -0.182912; -0.182912 0.21441], [0.731526 -0.326257; -0.326257 0.782928]) Trait4Trait8 (Σa[i, j], Σe[i, j]) = ([0.266914 -0.0976281; -0.0976281 0.196119], [0.729401 -0.150498; -0.150498 0.803836]) Trait4Trait9 (Σa[i, j], Σe[i, j]) = ([0.270267 -0.227463; -0.227463 0.247665], [0.726155 -0.415849; -0.415849 0.751008]) Trait4Trait10 (Σa[i, j], Σe[i, j]) = ([0.265756 -0.0339156; -0.0339156 0.0987618], [0.730536 -0.227666; -0.227666 0.901251]) Trait4Trait11 (Σa[i, j], Σe[i, j]) = ([0.265858 -0.0963336; -0.0963336 0.163013], [0.730427 -0.273145; -0.273145 0.835846]) Trait4Trait12 (Σa[i, j], Σe[i, j]) = ([0.268394 -0.141452; -0.141452 0.0796851], [0.72801 -0.0831954; -0.0831954 0.919263]) Trait4Trait13 (Σa[i, j], Σe[i, j]) = ([0.266334 -0.0971798; -0.0971798 0.0541478], [0.729966 -0.226082; -0.226082 0.945138]) Trait5Trait6 (Σa[i, j], Σe[i, j]) = ([0.281794 0.281033; 0.281033 0.282364], [0.716628 0.660607; 0.660607 0.717505]) Trait5Trait7 (Σa[i, j], Σe[i, j]) = ([0.281023 0.232223; 0.232223 0.211943], [0.717383 0.67449; 0.67449 0.785343]) Trait5Trait8 (Σa[i, j], Σe[i, j]) = ([0.281551 0.164011; 0.164011 0.192737], [0.716865 0.221187; 0.221187 0.807144]) Trait5Trait9 (Σa[i, j], Σe[i, j]) = ([0.284085 0.244479; 0.244479 0.240901], [0.714415 0.508795; 0.508795 0.757606]) Trait5Trait10 (Σa[i, j], Σe[i, j]) = ([0.281993 -0.0460624; -0.0460624 0.100628], [0.716433 -0.0574194; -0.0574194 0.899407]) Trait5Trait11 (Σa[i, j], Σe[i, j]) = ([0.280652 0.0199425; 0.0199425 0.163738], [0.717732 -0.0349079; -0.0349079 0.83513]) Trait5Trait12 (Σa[i, j], Σe[i, j]) = ([0.281652 0.0612882; 0.0612882 0.0820476], [0.716765 0.0533362; 0.0533362 0.916851]) Trait5Trait13 (Σa[i, j], Σe[i, j]) = ([0.282494 0.0696137; 0.0696137 0.0570685], [0.715955 0.0537392; 0.0537392 0.942222]) Trait6Trait7 (Σa[i, j], Σe[i, j]) = ([0.283018 0.220794; 0.220794 0.214128], [0.716868 0.58124; 0.58124 0.783191]) Trait6Trait8 (Σa[i, j], Σe[i, j]) = ([0.283018 0.183995; 0.183995 0.192405], [0.716869 0.436926; 0.436926 0.807474]) Trait6Trait9 (Σa[i, j], Σe[i, j]) = ([0.285057 0.234311; 0.234311 0.24283], [0.714902 0.477263; 0.477263 0.755728]) Trait6Trait10 (Σa[i, j], Σe[i, j]) = ([0.283699 -0.0433873; -0.0433873 0.101183], [0.716209 -0.0593852; -0.0593852 0.89886]) Trait6Trait11 (Σa[i, j], Σe[i, j]) = ([0.281626 0.027639; 0.027639 0.163178], [0.718219 -0.0520113; -0.0520113 0.83568]) Trait6Trait12 (Σa[i, j], Σe[i, j]) = ([0.283196 0.0569533; 0.0569533 0.0819944], [0.716699 0.0481832; 0.0481832 0.916905]) Trait6Trait13 (Σa[i, j], Σe[i, j]) = ([0.283862 0.0600111; 0.0600111 0.0571748], [0.716057 0.0544601; 0.0544601 0.942116]) Trait7Trait8 (Σa[i, j], Σe[i, j]) = ([0.214129 0.0883281; 0.0883281 0.192399], [0.78319 -0.0565873; -0.0565873 0.80748]) Trait7Trait9 (Σa[i, j], Σe[i, j]) = ([0.219059 0.217228; 0.217228 0.243722], [0.778422 0.463004; 0.463004 0.754868]) Trait7Trait10 (Σa[i, j], Σe[i, j]) = ([0.216477 -0.042081; -0.042081 0.101258], [0.78089 -0.0859952; -0.0859952 0.898786]) Trait7Trait11 (Σa[i, j], Σe[i, j]) = ([0.214308 0.0205244; 0.0205244 0.163203], [0.783006 -0.0479474; -0.0479474 0.835656]) Trait7Trait12 (Σa[i, j], Σe[i, j]) = ([0.215192 0.0752708; 0.0752708 0.0802075], [0.782157 0.0353123; 0.0353123 0.918686]) Trait7Trait13 (Σa[i, j], Σe[i, j]) = ([0.216198 0.0740251; 0.0740251 0.0547527], [0.781186 0.0399163; 0.0399163 0.944534]) Trait8Trait9 (Σa[i, j], Σe[i, j]) = ([0.194551 0.112282; 0.112282 0.246832], [0.805384 0.185461; 0.185461 0.751837]) Trait8Trait10 (Σa[i, j], Σe[i, j]) = ([0.194399 -0.0154035; -0.0154035 0.0995883], [0.805519 0.0117323; 0.0117323 0.900435]) Trait8Trait11 (Σa[i, j], Σe[i, j]) = ([0.193837 0.022072; 0.022072 0.164393], [0.806067 -0.0267843; -0.0267843 0.834489]) Trait8Trait12 (Σa[i, j], Σe[i, j]) = ([0.193914 -0.00259164; -0.00259164 0.0821237], [0.805992 0.0333257; 0.0333257 0.916773]) Trait8Trait13 (Σa[i, j], Σe[i, j]) = ([0.193913 0.00330925; 0.00330925 0.0569126], [0.805993 0.0386552; 0.0386552 0.94237]) Trait9Trait10 (Σa[i, j], Σe[i, j]) = ([0.246837 -0.00323396; -0.00323396 0.0989732], [0.751834 0.074992; 0.074992 0.901043]) Trait9Trait11 (Σa[i, j], Σe[i, j]) = ([0.247395 0.0305136; 0.0305136 0.164575], [0.751288 0.153633; 0.153633 0.834308]) Trait9Trait12 (Σa[i, j], Σe[i, j]) = ([0.249928 0.0844216; 0.0844216 0.0880992], [0.748829 0.108018; 0.108018 0.910884]) Trait9Trait13 (Σa[i, j], Σe[i, j]) = ([0.248998 0.0925603; 0.0925603 0.0580327], [0.749747 0.0992651; 0.0992651 0.94131]) Trait10Trait11 (Σa[i, j], Σe[i, j]) = ([0.0923059 0.0990858; 0.0990858 0.164638], [0.907657 0.475503; 0.475503 0.834248]) Trait10Trait12 (Σa[i, j], Σe[i, j]) = ([0.0957712 0.0574496; 0.0574496 0.0785646], [0.904228 0.0843534; 0.0843534 0.920326]) Trait10Trait13 (Σa[i, j], Σe[i, j]) = ([0.100109 -0.0266483; -0.0266483 0.0578511], [0.899941 0.164674; 0.164674 0.941451]) Trait11Trait12 (Σa[i, j], Σe[i, j]) = ([0.163544 0.0571549; 0.0571549 0.0784378], [0.835325 0.145549; 0.145549 0.920432]) Trait11Trait13 (Σa[i, j], Σe[i, j]) = ([0.164571 -0.00169939; -0.00169939 0.0575331], [0.834326 0.200725; 0.200725 0.941755]) Trait12Trait13 (Σa[i, j], Σe[i, j]) = ([0.08398 0.0685417; 0.0685417 0.0559416], [0.91494 0.573206; 0.573206 0.943343]) 4.430316 seconds (4.62 M allocations: 310.482 MiB, 3.51% gc time) ## 3-trait analysis Researchers want to jointly analyze traits 5-7. Our strategy is to try both Fisher scoring and MM algorithm with different starting point, and choose the best local optimum. We first form the data set and run Fisher scoring, which yields a final objective value -1.4700991+04. ```julia traitidx = 5:7 # form data set trait57_data = TwoVarCompVariateRotate(cg10kdata_rotated.Yrot[:, traitidx], cg10kdata_rotated.Xrot, cg10kdata_rotated.eigval, cg10kdata_rotated.eigvec, cg10kdata_rotated.logdetV2) # initialize model parameters trait57_model = VarianceComponentModel(trait57_data) # estimate variance components @time mle_fs!(trait57_model, trait57_data; solver=:Ipopt, verbose=true) trait57_model ``` This is Ipopt version 3.12.10, running with linear solver mumps. NOTE: Other linear solvers might be more efficient (see Ipopt documentation). Number of nonzeros in equality constraint Jacobian...: 0 Number of nonzeros in inequality constraint Jacobian.: 0 Number of nonzeros in Lagrangian Hessian.............: 78 Total number of variables............................: 12 variables with only lower bounds: 0 variables with lower and upper bounds: 0 variables with only upper bounds: 0 Total number of equality constraints.................: 0 Total number of inequality constraints...............: 0 inequality constraints with only lower bounds: 0 inequality constraints with lower and upper bounds: 0 inequality constraints with only upper bounds: 0 iter objective inf_pr inf_du lg(mu) ||d|| lg(rg) alpha_du alpha_pr ls 0 3.0244169e+04 0.00e+00 1.00e+02 0.0 0.00e+00 - 0.00e+00 0.00e+00 0 5 1.6834042e+04 0.00e+00 4.07e+02 -11.0 3.66e-01 - 1.00e+00 1.00e+00f 1 MaxS 10 1.4744248e+04 0.00e+00 1.12e+02 -11.0 2.36e-01 - 1.00e+00 1.00e+00f 1 MaxS 15 1.4701415e+04 0.00e+00 1.25e+01 -11.0 1.08e-01 -4.5 1.00e+00 1.00e+00f 1 MaxS 20 1.4700955e+04 0.00e+00 6.34e-01 -11.0 1.66e-04 -6.9 1.00e+00 1.00e+00f 1 MaxS 25 1.4700954e+04 0.00e+00 2.63e-02 -11.0 7.01e-06 -9.2 1.00e+00 1.00e+00f 1 MaxS 30 1.4700954e+04 0.00e+00 1.09e-03 -11.0 2.90e-07 -11.6 1.00e+00 1.00e+00f 1 MaxS 35 1.4700954e+04 0.00e+00 4.49e-05 -11.0 1.20e-08 -14.0 1.00e+00 1.00e+00f 1 MaxS 40 1.4700954e+04 0.00e+00 1.86e-06 -11.0 4.96e-10 -16.4 1.00e+00 1.00e+00f 1 MaxSA 45 1.4700954e+04 0.00e+00 7.67e-08 -11.0 2.05e-11 -18.8 1.00e+00 1.00e+00h 1 MaxSA iter objective inf_pr inf_du lg(mu) ||d|| lg(rg) alpha_du alpha_pr ls Number of Iterations....: 49 (scaled) (unscaled) Objective...............: 4.4662368766169095e+02 1.4700954216526397e+04 Dual infeasibility......: 5.8982229663448267e-09 1.9414444012378635e-07 Constraint violation....: 0.0000000000000000e+00 0.0000000000000000e+00 Complementarity.........: 0.0000000000000000e+00 0.0000000000000000e+00 Overall NLP error.......: 5.8982229663448267e-09 1.9414444012378635e-07 Number of objective function evaluations = 50 Number of objective gradient evaluations = 50 Number of equality constraint evaluations = 0 Number of inequality constraint evaluations = 0 Number of equality constraint Jacobian evaluations = 0 Number of inequality constraint Jacobian evaluations = 0 Number of Lagrangian Hessian evaluations = 49 Total CPU secs in IPOPT (w/o function evaluations) = 0.019 Total CPU secs in NLP function evaluations = 0.054 EXIT: Optimal Solution Found. 0.084479 seconds (46.62 k allocations: 5.057 MiB) VarianceComponentModel{Float64,2,Array{Float64,2},Array{Float64,2}}(Array{Float64}(0,3), ([0.28137 0.280153 0.232512; 0.280153 0.284916 0.220363; 0.232512 0.220363 0.212921], [0.717042 0.661484 0.674207; 0.661484 0.714964 0.581648; 0.674207 0.581648 0.784373]), Array{Float64}(0,0), Char[], Float64[], -Inf, Inf) We then run the MM algorithm, starting from the Fisher scoring answer. MM finds an improved solution with objective value 8.955397e+03. ```julia # trait59_model contains the fitted model by Fisher scoring now @time mle_mm!(trait57_model, trait57_data; verbose=true) trait57_model ``` MM Algorithm Iter Objective -------- ------------- 0 -1.470095e+04 1 -1.470095e+04 0.505115 seconds (1.01 M allocations: 50.370 MiB, 5.09% gc time) VarianceComponentModel{Float64,2,Array{Float64,2},Array{Float64,2}}(Array{Float64}(0,3), ([0.28137 0.280153 0.232512; 0.280153 0.284916 0.220363; 0.232512 0.220363 0.212921], [0.717042 0.661484 0.674207; 0.661484 0.714964 0.581648; 0.674207 0.581648 0.784373]), Array{Float64}(0,0), Char[], Float64[], -Inf, Inf) Do another run of MM algorithm from default starting point. It leads to a slightly better local optimum -1.470104e+04, slighly worse than the Fisher scoring result. Follow up anlaysis should use the Fisher scoring result. ```julia # default starting point trait57_model = VarianceComponentModel(trait57_data) @time _, _, _, Σcov, = mle_mm!(trait57_model, trait57_data; verbose=true) trait57_model ``` MM Algorithm Iter Objective -------- ------------- 0 -3.024417e+04 1 -2.040172e+04 2 -1.656053e+04 3 -1.528554e+04 4 -1.491023e+04 5 -1.480677e+04 6 -1.477849e+04 7 -1.477005e+04 8 -1.476675e+04 9 -1.476478e+04 10 -1.476318e+04 20 -1.475020e+04 30 -1.474023e+04 40 -1.473255e+04 50 -1.472662e+04 60 -1.472201e+04 70 -1.471839e+04 80 -1.471554e+04 90 -1.471326e+04 100 -1.471142e+04 110 -1.470993e+04 120 -1.470871e+04 130 -1.470770e+04 140 -1.470686e+04 150 -1.470616e+04 160 -1.470557e+04 170 -1.470506e+04 180 -1.470463e+04 190 -1.470426e+04 200 -1.470394e+04 210 -1.470366e+04 220 -1.470342e+04 230 -1.470321e+04 240 -1.470302e+04 250 -1.470285e+04 260 -1.470270e+04 270 -1.470257e+04 280 -1.470245e+04 290 -1.470234e+04 300 -1.470225e+04 310 -1.470216e+04 320 -1.470208e+04 330 -1.470201e+04 340 -1.470195e+04 350 -1.470189e+04 360 -1.470183e+04 370 -1.470178e+04 380 -1.470173e+04 390 -1.470169e+04 400 -1.470165e+04 410 -1.470162e+04 420 -1.470158e+04 430 -1.470155e+04 440 -1.470152e+04 450 -1.470149e+04 460 -1.470147e+04 470 -1.470144e+04 480 -1.470142e+04 490 -1.470140e+04 500 -1.470138e+04 510 -1.470136e+04 520 -1.470134e+04 530 -1.470132e+04 540 -1.470131e+04 550 -1.470129e+04 560 -1.470128e+04 570 -1.470127e+04 580 -1.470125e+04 590 -1.470124e+04 600 -1.470123e+04 610 -1.470122e+04 620 -1.470121e+04 630 -1.470120e+04 640 -1.470119e+04 650 -1.470118e+04 660 -1.470117e+04 670 -1.470116e+04 680 -1.470116e+04 690 -1.470115e+04 700 -1.470114e+04 710 -1.470113e+04 720 -1.470113e+04 730 -1.470112e+04 740 -1.470112e+04 750 -1.470111e+04 760 -1.470110e+04 770 -1.470110e+04 780 -1.470109e+04 790 -1.470109e+04 800 -1.470108e+04 810 -1.470108e+04 820 -1.470108e+04 830 -1.470107e+04 840 -1.470107e+04 850 -1.470106e+04 860 -1.470106e+04 870 -1.470106e+04 880 -1.470105e+04 890 -1.470105e+04 900 -1.470105e+04 910 -1.470104e+04 920 -1.470104e+04 930 -1.470104e+04 940 -1.470103e+04 950 -1.470103e+04 960 -1.470103e+04 970 -1.470103e+04 980 -1.470102e+04 990 -1.470102e+04 1000 -1.470102e+04 1010 -1.470102e+04 1020 -1.470102e+04 1030 -1.470101e+04 1040 -1.470101e+04 1050 -1.470101e+04 1060 -1.470101e+04 1070 -1.470101e+04 1080 -1.470101e+04 1090 -1.470100e+04 1100 -1.470100e+04 1110 -1.470100e+04 0.744170 seconds (134.31 k allocations: 13.430 MiB, 1.57% gc time) VarianceComponentModel{Float64,2,Array{Float64,2},Array{Float64,2}}(Array{Float64}(0,3), ([0.281394 0.280169 0.232564; 0.280169 0.285001 0.220511; 0.232564 0.220511 0.213147], [0.717018 0.661467 0.674155; 0.661467 0.714877 0.581502; 0.674155 0.581502 0.784149]), Array{Float64}(0,0), Char[], Float64[], -Inf, Inf) Heritability from 3-variate estimate and their standard errors. ```julia h, hse = heritability(trait57_model.Σ, Σcov) [h'; hse'] ``` 2×3 Array{Float64,2}: 0.281842 0.285036 0.213725 0.0777056 0.0772501 0.0840114 ## 13-trait joint analysis In some situations, such as studying the genetic covariance, we need to jointly analyze 13 traits. We first try the **Fisher scoring algorithm**. ```julia # initialize model parameters traitall_model = VarianceComponentModel(cg10kdata_rotated) # estimate variance components using Fisher scoring algorithm @time mle_fs!(traitall_model, cg10kdata_rotated; solver=:Ipopt, verbose=true) ``` This is Ipopt version 3.12.10, running with linear solver mumps. NOTE: Other linear solvers might be more efficient (see Ipopt documentation). Number of nonzeros in equality constraint Jacobian...: 0 Number of nonzeros in inequality constraint Jacobian.: 0 Number of nonzeros in Lagrangian Hessian.............: 16653 Total number of variables............................: 182 variables with only lower bounds: 0 variables with lower and upper bounds: 0 variables with only upper bounds: 0 Total number of equality constraints.................: 0 Total number of inequality constraints...............: 0 inequality constraints with only lower bounds: 0 inequality constraints with lower and upper bounds: 0 inequality constraints with only upper bounds: 0 iter objective inf_pr inf_du lg(mu) ||d|| lg(rg) alpha_du alpha_pr ls 0 1.3111983e+05 0.00e+00 1.00e+02 0.0 0.00e+00 - 0.00e+00 0.00e+00 0 5 8.2228529e+04 0.00e+00 6.03e+02 -11.0 2.42e+00 - 1.00e+00 1.00e+00f 1 MaxS 10 1.2570490e+05 0.00e+00 9.38e+02 -11.0 6.72e+01 -5.4 1.00e+00 1.00e+00h 1 MaxS PosDefException: matrix is not positive definite; Cholesky factorization failed. Stacktrace: [1] chkposdef at /Users/osx/buildbot/slave/package_osx64/build/usr/share/julia/stdlib/v1.1/LinearAlgebra/src/lapack.jl:50 [inlined] [2] sygvd!(::Int64, ::Char, ::Char, ::Array{Float64,2}, ::Array{Float64,2}) at /Users/osx/buildbot/slave/package_osx64/build/usr/share/julia/stdlib/v1.1/LinearAlgebra/src/lapack.jl:5075 [3] eigen! at /Users/osx/buildbot/slave/package_osx64/build/usr/share/julia/stdlib/v1.1/LinearAlgebra/src/symmetric.jl:646 [inlined] [4] eigen(::Symmetric{Float64,Array{Float64,2}}, ::Symmetric{Float64,Array{Float64,2}}) at /Users/osx/buildbot/slave/package_osx64/build/usr/share/julia/stdlib/v1.1/LinearAlgebra/src/eigen.jl:383 [5] TwoVarCompModelRotate(::VarianceComponentModel{Float64,2,Array{Float64,2},Array{Float64,2}}) at /Users/juhyun-kim/.julia/packages/VarianceComponentModels/Mh6LK/src/VarianceComponentModels.jl:119 [6] logpdf at /Users/juhyun-kim/.julia/packages/VarianceComponentModels/Mh6LK/src/two_variance_component.jl:62 [inlined] [7] eval_f(::VarianceComponentModels.TwoVarCompOptProb{VarianceComponentModel{Float64,2,Array{Float64,2},Array{Float64,2}},TwoVarCompVariateRotate{Float64,Array{Float64,2},Array{Float64,2}},Array{Float64,2},Array{Float64,1},VarianceComponentAuxData{Array{Float64,2},Array{Float64,1}}}, ::Array{Float64,1}) at /Users/juhyun-kim/.julia/packages/VarianceComponentModels/Mh6LK/src/two_variance_component.jl:731 [8] (::getfield(Ipopt, Symbol("#eval_f_cb#6")){VarianceComponentModels.TwoVarCompOptProb{VarianceComponentModel{Float64,2,Array{Float64,2},Array{Float64,2}},TwoVarCompVariateRotate{Float64,Array{Float64,2},Array{Float64,2}},Array{Float64,2},Array{Float64,1},VarianceComponentAuxData{Array{Float64,2},Array{Float64,1}}}})(::Array{Float64,1}) at /Users/juhyun-kim/.julia/packages/Ipopt/f6QJl/src/MPB_wrapper.jl:64 [9] eval_f_wrapper(::Int32, ::Ptr{Float64}, ::Int32, ::Ptr{Float64}, ::Ptr{Nothing}) at /Users/juhyun-kim/.julia/packages/Ipopt/f6QJl/src/Ipopt.jl:128 [10] solveProblem(::Ipopt.IpoptProblem) at /Users/juhyun-kim/.julia/packages/Ipopt/f6QJl/src/Ipopt.jl:346 [11] optimize!(::Ipopt.IpoptMathProgModel) at /Users/juhyun-kim/.julia/packages/Ipopt/f6QJl/src/MPB_wrapper.jl:141 [12] #mle_fs!#27(::Int64, ::Symbol, ::Symbol, ::Bool, ::Function, ::VarianceComponentModel{Float64,2,Array{Float64,2},Array{Float64,2}}, ::TwoVarCompVariateRotate{Float64,Array{Float64,2},Array{Float64,2}}) at /Users/juhyun-kim/.julia/packages/VarianceComponentModels/Mh6LK/src/two_variance_component.jl:949 [13] (::getfield(VarianceComponentModels, Symbol("#kw##mle_fs!")))(::NamedTuple{(:solver, :verbose),Tuple{Symbol,Bool}}, ::typeof(mle_fs!), ::VarianceComponentModel{Float64,2,Array{Float64,2},Array{Float64,2}}, ::TwoVarCompVariateRotate{Float64,Array{Float64,2},Array{Float64,2}}) at ./none:0 [14] top-level scope at util.jl:156 [15] top-level scope at In[54]:3 From the output we can see the Fisher scoring algorithm ran into some numerical issues. Let's try the **MM algorithm**. ```julia # reset model parameters traitall_model = VarianceComponentModel(cg10kdata_rotated) # estimate variance components using Fisher scoring algorithm @time mle_mm!(traitall_model, cg10kdata_rotated; verbose=true) ``` MM Algorithm Iter Objective -------- ------------- 0 -1.311198e+05 1 -8.001595e+04 2 -5.806836e+04 3 -4.926167e+04 4 -4.611163e+04 5 -4.511722e+04 6 -4.482795e+04 7 -4.474405e+04 8 -4.471603e+04 9 -4.470277e+04 10 -4.469345e+04 20 -4.462308e+04 30 -4.456930e+04 40 -4.452802e+04 50 -4.449620e+04 60 -4.447148e+04 70 -4.445209e+04 80 -4.443672e+04 90 -4.442442e+04 100 -4.441448e+04 110 -4.440635e+04 120 -4.439966e+04 130 -4.439409e+04 140 -4.438943e+04 150 -4.438549e+04 160 -4.438215e+04 170 -4.437928e+04 180 -4.437682e+04 190 -4.437469e+04 200 -4.437283e+04 210 -4.437121e+04 220 -4.436978e+04 230 -4.436853e+04 240 -4.436742e+04 250 -4.436643e+04 260 -4.436555e+04 270 -4.436476e+04 280 -4.436406e+04 290 -4.436342e+04 300 -4.436285e+04 310 -4.436234e+04 320 -4.436187e+04 330 -4.436144e+04 340 -4.436106e+04 350 -4.436071e+04 360 -4.436039e+04 370 -4.436009e+04 380 -4.435982e+04 390 -4.435957e+04 400 -4.435935e+04 410 -4.435914e+04 420 -4.435895e+04 430 -4.435877e+04 440 -4.435860e+04 450 -4.435845e+04 460 -4.435831e+04 470 -4.435818e+04 480 -4.435806e+04 490 -4.435794e+04 500 -4.435784e+04 510 -4.435774e+04 520 -4.435765e+04 530 -4.435757e+04 540 -4.435749e+04 550 -4.435741e+04 560 -4.435734e+04 570 -4.435728e+04 580 -4.435722e+04 590 -4.435716e+04 600 -4.435711e+04 610 -4.435706e+04 620 -4.435701e+04 630 -4.435696e+04 640 -4.435692e+04 650 -4.435688e+04 660 -4.435685e+04 670 -4.435681e+04 680 -4.435678e+04 690 -4.435675e+04 700 -4.435672e+04 710 -4.435669e+04 720 -4.435666e+04 730 -4.435664e+04 740 -4.435662e+04 750 -4.435659e+04 760 -4.435657e+04 770 -4.435655e+04 780 -4.435653e+04 790 -4.435652e+04 800 -4.435650e+04 810 -4.435648e+04 820 -4.435647e+04 830 -4.435645e+04 840 -4.435644e+04 850 -4.435643e+04 860 -4.435641e+04 870 -4.435640e+04 880 -4.435639e+04 890 -4.435638e+04 900 -4.435637e+04 910 -4.435636e+04 920 -4.435635e+04 930 -4.435634e+04 940 -4.435633e+04 950 -4.435633e+04 960 -4.435632e+04 970 -4.435631e+04 980 -4.435630e+04 990 -4.435630e+04 1000 -4.435629e+04 1010 -4.435628e+04 1020 -4.435628e+04 1030 -4.435627e+04 1040 -4.435627e+04 1050 -4.435626e+04 1060 -4.435626e+04 1070 -4.435625e+04 1080 -4.435625e+04 3.314963 seconds (131.35 k allocations: 65.449 MiB, 0.65% gc time) (-44356.24416259489, VarianceComponentModel{Float64,2,Array{Float64,2},Array{Float64,2}}(Array{Float64}(0,13), ([0.272112 0.190023 … -0.128464 -0.0976418; 0.190023 0.216814 … -0.0687833 -0.04341; … ; -0.128464 -0.0687833 … 0.116994 0.0900933; -0.0976418 -0.04341 … 0.0900933 0.105876], [0.725183 0.570497 … -0.0589748 -0.125486; 0.570497 0.783023 … 0.0235685 0.0464638; … ; -0.0589748 0.0235685 … 0.882056 0.551829; -0.125486 0.0464638 … 0.551829 0.893642]), Array{Float64}(0,0), Char[], Float64[], -Inf, Inf), ([0.0111603 0.013107 … 0.0128915 0.0127587; 0.0131027 0.0151631 … 0.017153 0.0171359; … ; 0.0128908 0.017153 … 0.0174176 0.018212; 0.0127586 0.0171361 … 0.0182122 0.0188002], [0.0112235 0.0133041 … 0.0130038 0.0127778; 0.0133005 0.0158053 … 0.0178518 0.0177823; … ; 0.0130043 0.0178518 … 0.0179557 0.0187638; 0.0127775 0.0177823 … 0.0187637 0.0193477]), [0.000124552 7.23469e-5 … -3.6584e-7 -1.40474e-5; 7.23585e-5 0.00017168 … -2.04611e-5 -3.18804e-6; … ; -3.70686e-7 -2.04634e-5 … 0.000352082 -1.46096e-5; -1.4039e-5 -3.1795e-6 … -1.46073e-5 0.000374334], Array{Float64}(0,13), Array{Float64}(0,0)) It converges after ~1000 iterations. ## Save analysis results ```julia #using JLD2, FileIO #save("copd.jld2") #varinfo() ```
VarianceComponentModels
https://github.com/OpenMendel/VarianceComponentModels.jl.git
[ "MIT" ]
0.1.3
82d058ac0c22844b80c5bc098f17c7f7d5268f11
docs
22621
# MLE and REML Machine information ```julia versioninfo() ``` Julia Version 1.1.0 Commit 80516ca202 (2019-01-21 21:24 UTC) Platform Info: OS: macOS (x86_64-apple-darwin14.5.0) CPU: Intel(R) Core(TM) i5-6267U CPU @ 2.90GHz WORD_SIZE: 64 LIBM: libopenlibm LLVM: libLLVM-6.0.1 (ORCJIT, skylake) ## Demo data For demonstration, we generate a random data set. ```julia # generate data from a d-variate response variane component model using Random, LinearAlgebra Random.seed!(123) n = 1000 # no. observations d = 2 # dimension of responses m = 2 # no. variance components p = 2 # no. covariates # n-by-p design matrix X = randn(n, p) # p-by-d mean component regression coefficient B = ones(p, d) # a tuple of m covariance matrices V = ntuple(x -> zeros(n, n), m) for i = 1:m-1 Vi = randn(n, 50) copyto!(V[i], Vi * Vi') end copyto!(V[m], Matrix(I, n, n)) # last covarianec matrix is idendity # a tuple of m d-by-d variance component parameters Σ = ntuple(x -> zeros(d, d), m) for i in 1:m Σi = randn(d, d) copyto!(Σ[i], Σi' * Σi) end # form overall nd-by-nd covariance matrix Ω Ω = zeros(n * d, n * d) for i = 1:m Ω += kron(Σ[i], V[i]) end Ωchol = cholesky(Ω) # n-by-d responses Y = X * B + reshape(Ωchol.L * randn(n*d), n, d); ``` ## Maximum likelihood estimation (MLE) To find the MLE of parameters $(B,\Sigma_1,\ldots,\Sigma_m)$, we take 3 steps: **Step 1 (Construct data)**. Construct an instance of `VarianceComponentVariate`, which consists fields * `Y`: $n$-by-$d$ responses * `X`: $n$-by-$p$ covariate matrix * `V=(V[1],...,V[m])`: a tuple of $n$-by-$n$ covariance matrices. The last covariance matrix must be positive definite and usually is the identity matrix. ```julia using VarianceComponentModels vcdata = VarianceComponentVariate(Y, X, V) fieldnames(typeof(vcdata)) ``` (:Y, :X, :V) In the absence of covariates $X$, we can simply initialize by `vcdata = VarianceComponentVariate(Y, V)`. **Step 2 (Construct a model)**. Construct an instance of `VarianceComponentModel`, which consists of fields * `B`: $n$-by-$p$ mean regression coefficients * `Σ=(Σ[1],...,Σ[m])`: variane component parameters respectively. When constructed from a `VarianceComponentVariate` instance, the mean parameters $B$ are initialized to be zero and the tuple of variance component parameters $\Sigma$ to be `(eye(d),...,eye(d))`. ```julia vcmodel = VarianceComponentModel(vcdata) fieldnames(typeof(vcmodel)) ``` (:B, :Σ, :A, :sense, :b, :lb, :ub) ```julia vcmodel ``` VarianceComponentModel{Float64,2,Array{Float64,2},Array{Float64,2}}([0.0 0.0; 0.0 0.0], ([1.0 0.0; 0.0 1.0], [1.0 0.0; 0.0 1.0]), Array{Float64}(0,4), Char[], Float64[], -Inf, Inf) The remaining fields `A`, `sense`, `b`, `lb`, `ub` specify (optional) constraints on the mean parameters `B`: $A * \text{vec}(B) \,\, =(\text{or } \ge \text{or } \le) \,\, b$ $lb \le \text{vec}(B) \le ub$ `A` is an constraint matrix with $pd$ columns, `sense` is a vector of charaters taking values `'<'`, `'='` or `'>'`, and `lb` and `ub` are the lower and upper bounds for `vec(B)`. By default, `A`, `sense`, `b` are empty, `lb` is `-Inf`, and `ub` is `Inf`. If any constraits are non-trivial, final estimates of `B` are enforced to satisfy them. When a better initial guess is available, we can initialize by calling `vcmodel=VarianceComponentModel(B0, Σ0)` directly. **Step 3 (Fit model)**. Call optmization routine `fit_mle!`. The keywork `algo` dictates the optimization algorithm: `:MM` (minorization-maximization algorithm) or `:FS` (Fisher scoring algorithm). ```julia vcmodel_mle = deepcopy(vcmodel) @time logl, vcmodel_mle, Σse, Σcov, Bse, Bcov = fit_mle!(vcmodel_mle, vcdata; algo = :MM); ``` MM Algorithm Iter Objective -------- ------------- 0 -6.253551e+03 ****************************************************************************** This program contains Ipopt, a library for large-scale nonlinear optimization. Ipopt is released as open source code under the Eclipse Public License (EPL). For more information visit http://projects.coin-or.org/Ipopt ****************************************************************************** 1 -3.881454e+03 2 -3.853179e+03 3 -3.846525e+03 4 -3.844906e+03 5 -3.844506e+03 6 -3.844406e+03 7 -3.844381e+03 8 -3.844375e+03 9 -3.844374e+03 10 -3.844373e+03 5.031460 seconds (11.29 M allocations: 568.015 MiB, 4.78% gc time) The output of `fit_mle!` contains * final log-likelihood ```julia logl ``` -3844.3731814180887 * fitted model ```julia fieldnames(typeof(vcmodel_mle)) ``` (:B, :Σ, :A, :sense, :b, :lb, :ub) ```julia vcmodel_mle ``` VarianceComponentModel{Float64,2,Array{Float64,2},Array{Float64,2}}([1.092 1.04727; 0.955346 1.01632], ([0.380637 -0.305465; -0.305465 4.51938], [1.84009 0.265569; 0.265569 2.17275]), Array{Float64}(0,4), Char[], Float64[], -Inf, Inf) * standard errors of the estimated varianec component parameters ```julia Σse ``` ([0.0765136 0.263047; 0.263047 0.904332], [0.0844292 0.0917441; 0.0917441 0.0996927]) * covariance matrix of the variance component parameters estimates ```julia Σcov ``` 8×8 Array{Float64,2}: 0.00585433 -0.00467019 -0.00467019 … -1.07903e-6 -1.557e-7 -0.00467019 0.0691937 0.00372555 -1.557e-7 -1.27444e-6 -0.00467019 0.00372555 0.0691937 -8.83212e-6 -1.27444e-6 0.00372555 -0.055198 -0.055198 -1.27444e-6 -1.04316e-5 -7.4779e-6 -1.07903e-6 -1.07903e-6 0.00102878 0.000148477 -1.07903e-6 -8.83212e-6 -1.557e-7 … 0.000148477 0.00121477 -1.07903e-6 -1.557e-7 -8.83212e-6 0.00841698 0.00121477 -1.557e-7 -1.27444e-6 -1.27444e-6 0.00121477 0.00993864 * standard errors of the estimated mean parameters ```julia Bse ``` 2×2 Array{Float64,2}: 0.0425562 0.0483834 0.0430596 0.0492809 * covariance matrix of the mean parameter estimates ```julia Bcov ``` 4×4 Array{Float64,2}: 0.00181103 -1.96485e-5 0.000243441 -4.38252e-6 -1.96485e-5 0.00185413 -4.38252e-6 0.000246407 0.000243441 -4.38252e-6 0.00234096 -5.73331e-6 -4.38252e-6 0.000246407 -5.73331e-6 0.00242861 ## Restricted maximum likelihood estimation (REML) [REML (restricted maximum likelihood estimation)](https://en.wikipedia.org/wiki/Restricted_maximum_likelihood) is a popular alternative to the MLE. To find the REML of a variane component model, we replace the above step 3 by **Step 3**. Call optmization routine `fit_reml!`. ```julia vcmodel_reml = deepcopy(vcmodel) @time logl, vcmodel_reml, Σse, Σcov, Bse, Bcov = fit_reml!(vcmodel_reml, vcdata; algo = :MM); ``` MM Algorithm Iter Objective -------- ------------- 0 -4.215053e+03 1 -3.925799e+03 2 -3.865114e+03 3 -3.851105e+03 4 -3.847732e+03 5 -3.846903e+03 6 -3.846698e+03 7 -3.846647e+03 8 -3.846634e+03 9 -3.846631e+03 10 -3.846630e+03 0.726373 seconds (388.90 k allocations: 82.673 MiB, 13.22% gc time) The output of `fit_reml!` contains * the final log-likelihood at REML estimate ```julia logl ``` -3844.3777179025055 * REML estimates ```julia fieldnames(typeof(vcmodel_reml)) ``` (:B, :Σ, :A, :sense, :b, :lb, :ub) ```julia vcmodel_reml ``` VarianceComponentModel{Float64,2,Array{Float64,2},Array{Float64,2}}([1.092 1.04727; 0.955345 1.01632], ([0.380594 -0.305485; -0.305485 4.51994], [1.84285 0.261963; 0.261963 2.17842]), Array{Float64}(0,4), Char[], Float64[], -Inf, Inf) * standard errors of the estimated variance component parameters ```julia Σse ``` ([0.0765055 0.26305; 0.26305 0.904446], [0.0845559 0.0919325; 0.0919325 0.0999526]) * covariance matrix of the variance component parameters estimates ```julia Σcov ``` 8×8 Array{Float64,2}: 0.0058531 -0.00467005 -0.00467005 … -1.06597e-6 -1.51499e-7 -0.00467005 0.0691951 0.00372613 -1.51499e-7 -1.26041e-6 -0.00467005 0.00372613 0.0691951 -8.86843e-6 -1.26041e-6 0.00372613 -0.0552092 -0.0552092 -1.26041e-6 -1.0486e-5 -7.50035e-6 -1.06597e-6 -1.06597e-6 0.00101633 0.000144472 -1.06597e-6 -8.86843e-6 -1.51499e-7 … 0.000144472 0.0012014 -1.06597e-6 -1.51499e-7 -8.86843e-6 0.00845158 0.0012014 -1.51499e-7 -1.26041e-6 -1.26041e-6 0.0012014 0.00999052 * standard errors of the estimated mean parameters ```julia Bse ``` 2×2 Array{Float64,2}: 0.0425881 0.0484485 0.0430919 0.0493475 * covariance matrix of the mean parameter estimates ```julia Bcov ``` 4×4 Array{Float64,2}: 0.00181375 -1.96783e-5 0.000239868 -4.34611e-6 -1.96783e-5 0.00185691 -4.34611e-6 0.000242745 0.000239868 -4.34611e-6 0.00234726 -5.73082e-6 -4.34611e-6 0.000242745 -5.73082e-6 0.00243518 ## Optimization algorithms Finding the MLE or REML of variance component models is a non-trivial nonlinear optimization problem. The main complications are the non-convexity of objective function and the positive semi-definiteness constraint of variane component parameters $\Sigma_1,\ldots,\Sigma_m$. In specific applications, users should try different algorithms with different starting points in order to find a better solution. Here are some tips for efficient computation. In general the optimization algorithm needs to invert the $nd$ by $nd$ overall covariance matrix $\Omega = \Sigma_1 \otimes V_1 + \cdots + \Sigma_m \otimes V_m$ in each iteration. Inverting a matrix is an expensive operation with $O(n^3 d^3)$ floating operations. When there are only **two** varianec components ($m=2$), this tedious task can be avoided by taking one (generalized) eigendecomposion of $(V_1, V_2)$ and rotating data $(Y, X)$ by the eigen-vectors. ```julia vcdatarot = TwoVarCompVariateRotate(vcdata) fieldnames(typeof(vcdatarot)) ``` (:Yrot, :Xrot, :eigval, :eigvec, :logdetV2) Two optimization algorithms are implemented: [Fisher scoring](https://books.google.com/books?id=QYqeYTftPNwC&lpg=PP1&pg=PA142#v=onepage&q&f=false) (`mle_fs!`) and the [minorization-maximization (MM) algorithm](http://arxiv.org/abs/1509.07426) (`mle_mm!`). Both take the rotated data as input. These two functions give finer control of the optimization algorithms. Generally speaking, MM algorithm is more stable while Fisher scoring (if it converges) yields more accurate answer. ```julia vcmodel_mm = deepcopy(vcmodel) @time mle_mm!(vcmodel_mm, vcdatarot; maxiter=10000, funtol=1e-8, verbose = true); ``` MM Algorithm Iter Objective -------- ------------- 0 -6.253551e+03 1 -3.881454e+03 2 -3.853179e+03 3 -3.846525e+03 4 -3.844906e+03 5 -3.844506e+03 6 -3.844406e+03 7 -3.844381e+03 8 -3.844375e+03 9 -3.844374e+03 10 -3.844373e+03 0.055578 seconds (21.91 k allocations: 1.394 MiB) ```julia # MM estimates vcmodel_mm.B ``` 2×2 Array{Float64,2}: 1.092 1.04727 0.955346 1.01632 ```julia # MM estimates vcmodel_mm.Σ ``` ([0.380637 -0.305465; -0.305465 4.51938], [1.84009 0.265569; 0.265569 2.17275]) Fisher scoring (`mle_fs!`) uses either [Ipopt.jl](https://github.com/JuliaOpt/Ipopt.jl) (keyword `solver=:Ipopt`) or [KNITRO.jl](https://github.com/JuliaOpt/KNITRO.jl) (keyword `solver=:Knitro`) as the backend solver. Ipopt is open source and installation of [Ipopt.jl](https://github.com/JuliaOpt/Ipopt.jl) package alone is sufficient. ```julia # Fisher scoring using Ipopt vcmodel_ipopt = deepcopy(vcmodel) @time mle_fs!(vcmodel_ipopt, vcdatarot; solver=:Ipopt, maxiter=1000, verbose=true); ``` This is Ipopt version 3.12.10, running with linear solver mumps. NOTE: Other linear solvers might be more efficient (see Ipopt documentation). Number of nonzeros in equality constraint Jacobian...: 0 Number of nonzeros in inequality constraint Jacobian.: 0 Number of nonzeros in Lagrangian Hessian.............: 21 Total number of variables............................: 6 variables with only lower bounds: 0 variables with lower and upper bounds: 0 variables with only upper bounds: 0 Total number of equality constraints.................: 0 Total number of inequality constraints...............: 0 inequality constraints with only lower bounds: 0 inequality constraints with lower and upper bounds: 0 inequality constraints with only upper bounds: 0 iter objective inf_pr inf_du lg(mu) ||d|| lg(rg) alpha_du alpha_pr ls 0 4.2109423e+03 0.00e+00 1.00e+02 0.0 0.00e+00 - 0.00e+00 0.00e+00 0 5 3.8445586e+03 0.00e+00 7.87e-01 -11.0 4.94e-02 - 1.00e+00 1.00e+00f 1 MaxS 10 3.8443870e+03 0.00e+00 2.25e-01 -11.0 1.38e-02 - 1.00e+00 1.00e+00f 1 MaxS 15 3.8443742e+03 0.00e+00 6.23e-02 -11.0 3.78e-03 - 1.00e+00 1.00e+00f 1 MaxS 20 3.8443733e+03 0.00e+00 1.70e-02 -11.0 1.03e-03 - 1.00e+00 1.00e+00f 1 MaxS 25 3.8443732e+03 0.00e+00 4.61e-03 -11.0 2.79e-04 - 1.00e+00 1.00e+00f 1 MaxS 30 3.8443732e+03 0.00e+00 1.25e-03 -11.0 7.56e-05 - 1.00e+00 1.00e+00f 1 MaxS 35 3.8443732e+03 0.00e+00 3.39e-04 -11.0 2.05e-05 - 1.00e+00 1.00e+00f 1 MaxS 40 3.8443732e+03 0.00e+00 9.19e-05 -11.0 5.55e-06 - 1.00e+00 1.00e+00f 1 MaxS 45 3.8443732e+03 0.00e+00 2.49e-05 -11.0 1.51e-06 - 1.00e+00 1.00e+00f 1 MaxS iter objective inf_pr inf_du lg(mu) ||d|| lg(rg) alpha_du alpha_pr ls 50 3.8443732e+03 0.00e+00 6.76e-06 -11.0 4.08e-07 - 1.00e+00 1.00e+00f 1 MaxSA 55 3.8443732e+03 0.00e+00 1.83e-06 -11.0 1.11e-07 - 1.00e+00 1.00e+00f 1 MaxSA 60 3.8443732e+03 0.00e+00 4.97e-07 -11.0 3.00e-08 - 1.00e+00 1.00e+00h 1 MaxSA Number of Iterations....: 63 (scaled) (unscaled) Objective...............: 3.4496886481728791e+02 3.8443731733053728e+03 Dual infeasibility......: 2.2693631660531264e-07 2.5290047206674095e-06 Constraint violation....: 0.0000000000000000e+00 0.0000000000000000e+00 Complementarity.........: 0.0000000000000000e+00 0.0000000000000000e+00 Overall NLP error.......: 2.2693631660531264e-07 2.5290047206674095e-06 Number of objective function evaluations = 64 Number of objective gradient evaluations = 64 Number of equality constraint evaluations = 0 Number of inequality constraint evaluations = 0 Number of equality constraint Jacobian evaluations = 0 Number of inequality constraint Jacobian evaluations = 0 Number of Lagrangian Hessian evaluations = 63 Total CPU secs in IPOPT (w/o function evaluations) = 1.739 Total CPU secs in NLP function evaluations = 0.293 EXIT: Solved To Acceptable Level. 2.745554 seconds (4.30 M allocations: 210.935 MiB, 2.63% gc time) ```julia # Ipopt estimates vcmodel_ipopt.B ``` 2×2 Array{Float64,2}: 1.092 1.04727 0.955346 1.01632 ```julia # Ipopt estimates vcmodel_ipopt.Σ ``` ([0.380552 -0.305594; -0.305594 4.52106], [1.84008 0.265385; 0.265385 2.17287]) Knitro is a commercial software and users need to follow instructions at [KNITRO.jl](https://github.com/JuliaOpt/KNITRO.jl) for proper functioning. Following code invokes Knitro as the backend optimization solver. ```julia using KNITRO # Fisher scoring using Knitro vcmodel_knitro = deepcopy(vcmodel) @time mle_fs!(vcmodel_knitro, vcdatarot; solver=:Knitro, maxiter=1000, verbose=true); # Knitro estimates vcmodel_knitro.B # Knitro estimates vcmodel_knitro.Σ ``` ## Starting point Here are a few strategies for successful optimization. * For $d>1$ (multivariate response), initialize $B, \Sigma$ from univariate estimates. * Use REML estimate as starting point for MLE. * When there are only $m=2$ variance components, pre-compute `TwoVarCompVariateRotate` and use it for optimization. ## Constrained estimation of `B` Many applications invoke constraints on the mean parameters `B`. For demonstration, we enforce `B[1,1]=B[1,2]` and all entries of `B` are within [0, 2]. ```julia # set up constraints on B vcmodel_constr = deepcopy(vcmodel) vcmodel_constr.A = [1.0 0.0 -1.0 0.0] vcmodel_constr.sense = '=' vcmodel_constr.b = 0.0 vcmodel_constr.lb = 0.0 vcmodel_constr.ub = 2.0 vcmodel_constr ``` VarianceComponentModel{Float64,2,Array{Float64,2},Array{Float64,2}}([0.0 0.0; 0.0 0.0], ([1.0 0.0; 0.0 1.0], [1.0 0.0; 0.0 1.0]), [1.0 0.0 -1.0 0.0], '=', 0.0, 0.0, 2.0) We first try the MM algorithm. ```julia # MM algorithm for constrained estimation of B @time mle_mm!(vcmodel_constr, vcdatarot; maxiter=10000, funtol=1e-8, verbose = true); ``` MM Algorithm Iter Objective -------- ------------- 0 -6.253551e+03 1 -3.881820e+03 2 -3.853477e+03 3 -3.846807e+03 4 -3.845184e+03 5 -3.844783e+03 6 -3.844683e+03 7 -3.844658e+03 8 -3.844652e+03 9 -3.844650e+03 10 -3.844650e+03 0.185885 seconds (179.51 k allocations: 9.295 MiB) ```julia fieldnames(typeof(vcmodel_constr)) ``` (:B, :Σ, :A, :sense, :b, :lb, :ub) ```julia vcmodel_constr.B ``` 2×2 Array{Float64,2}: 1.07177 1.07177 0.955683 1.01591 ```julia vcmodel_constr.Σ ``` ([0.380624 -0.305498; -0.305498 4.51948], [1.84051 0.265065; 0.265065 2.17336]) Now let's try Fisher scoring. ```julia # Fisher scoring using Ipopt for constrained estimation of B vcmodel_constr = deepcopy(vcmodel) vcmodel_constr.A = [1.0 0.0 -1.0 0.0] vcmodel_constr.sense = '=' vcmodel_constr.b = 0.0 vcmodel_constr.lb = 0.0 vcmodel_constr.ub = 2.0 vcmodel_constr @time mle_fs!(vcmodel_constr, vcdatarot; solver=:Ipopt, maxiter=1000, verbose=true); ``` This is Ipopt version 3.12.10, running with linear solver mumps. NOTE: Other linear solvers might be more efficient (see Ipopt documentation). Number of nonzeros in equality constraint Jacobian...: 0 Number of nonzeros in inequality constraint Jacobian.: 0 Number of nonzeros in Lagrangian Hessian.............: 21 Total number of variables............................: 6 variables with only lower bounds: 0 variables with lower and upper bounds: 0 variables with only upper bounds: 0 Total number of equality constraints.................: 0 Total number of inequality constraints...............: 0 inequality constraints with only lower bounds: 0 inequality constraints with lower and upper bounds: 0 inequality constraints with only upper bounds: 0 iter objective inf_pr inf_du lg(mu) ||d|| lg(rg) alpha_du alpha_pr ls 0 4.2114270e+03 0.00e+00 1.00e+02 0.0 0.00e+00 - 0.00e+00 0.00e+00 0 5 3.8448353e+03 0.00e+00 7.87e-01 -11.0 4.94e-02 - 1.00e+00 1.00e+00f 1 MaxS 10 3.8446636e+03 0.00e+00 2.25e-01 -11.0 1.38e-02 - 1.00e+00 1.00e+00f 1 MaxS 15 3.8446509e+03 0.00e+00 6.23e-02 -11.0 3.78e-03 - 1.00e+00 1.00e+00f 1 MaxS 20 3.8446499e+03 0.00e+00 1.70e-02 -11.0 1.03e-03 - 1.00e+00 1.00e+00f 1 MaxS 25 3.8446498e+03 0.00e+00 4.61e-03 -11.0 2.79e-04 - 1.00e+00 1.00e+00f 1 MaxS 30 3.8446498e+03 0.00e+00 1.25e-03 -11.0 7.56e-05 - 1.00e+00 1.00e+00f 1 MaxS 35 3.8446498e+03 0.00e+00 3.39e-04 -11.0 2.05e-05 - 1.00e+00 1.00e+00f 1 MaxS 40 3.8446498e+03 0.00e+00 9.19e-05 -11.0 5.56e-06 - 1.00e+00 1.00e+00f 1 MaxS 45 3.8446498e+03 0.00e+00 2.49e-05 -11.0 1.51e-06 - 1.00e+00 1.00e+00f 1 MaxS iter objective inf_pr inf_du lg(mu) ||d|| lg(rg) alpha_du alpha_pr ls 50 3.8446498e+03 0.00e+00 6.76e-06 -11.0 4.08e-07 - 1.00e+00 1.00e+00f 1 MaxSA 55 3.8446498e+03 0.00e+00 1.83e-06 -11.0 1.11e-07 - 1.00e+00 1.00e+00f 1 MaxSA 60 3.8446498e+03 0.00e+00 4.97e-07 -11.0 3.00e-08 - 1.00e+00 1.00e+00f 1 MaxSA Number of Iterations....: 63 (scaled) (unscaled) Objective...............: 3.4484507551949685e+02 3.8446498170293398e+03 Dual infeasibility......: 2.2694405475622814e-07 2.5301808856629548e-06 Constraint violation....: 0.0000000000000000e+00 0.0000000000000000e+00 Complementarity.........: 0.0000000000000000e+00 0.0000000000000000e+00 Overall NLP error.......: 2.2694405475622814e-07 2.5301808856629548e-06 Number of objective function evaluations = 64 Number of objective gradient evaluations = 64 Number of equality constraint evaluations = 0 Number of inequality constraint evaluations = 0 Number of equality constraint Jacobian evaluations = 0 Number of inequality constraint Jacobian evaluations = 0 Number of Lagrangian Hessian evaluations = 63 Total CPU secs in IPOPT (w/o function evaluations) = 0.028 Total CPU secs in NLP function evaluations = 0.634 EXIT: Solved To Acceptable Level. 0.760983 seconds (102.63 k allocations: 8.135 MiB) ```julia vcmodel_constr.B ``` 2×2 Array{Float64,2}: 1.07177 1.07177 0.955683 1.01591 ```julia vcmodel_constr.Σ ``` ([0.380539 -0.305626; -0.305626 4.52116], [1.8405 0.264881; 0.264881 2.17348])
VarianceComponentModels
https://github.com/OpenMendel/VarianceComponentModels.jl.git
[ "MIT" ]
0.5.1
70638af651f5f32f82bc390c67c25dfe97fe7e3e
code
663
module ExtensibleUnions export addtounion!, # extensible_unions.jl extensiblefunction!, # extensible_functions.jl extensibleunion!, # extensible_unions.jl isextensiblefunction, # extensible_functions.jl isextensibleunion # extensible_unions.jl const _registry_extensibleunion_to_genericfunctions = Dict{Any, Any}() const _registry_extensibleunion_to_members = Dict{Any, Any}() const _registry_genericfunctions_to_extensibleunions = Dict{Any, Any}() include("code_transformation.jl") include("extensible_functions.jl") include("extensible_unions.jl") include("init.jl") include("reset.jl") include("update_methods.jl") end # module
ExtensibleUnions
https://github.com/bcbi/ExtensibleUnions.jl.git
[ "MIT" ]
0.5.1
70638af651f5f32f82bc390c67c25dfe97fe7e3e
code
3134
# All or most of the code in this file is taken from: # 1. https://github.com/NHDaly/DeepcopyModules.jl (license: MIT) # 2. https://github.com/perrutquist/CodeTransformation.jl (license: MIT) """ jl_method_def(argdata, ci, mod) - C function wrapper This is a wrapper of the C function with the same name, found in the Julia source tree at julia/src/method.c Use `addmethod!` or `codetransform!` instead of calling this function directly. """ jl_method_def(argdata::Core.SimpleVector, ci::Core.CodeInfo, mod::Module) = ccall(:jl_method_def, Cvoid, (Core.SimpleVector, Any, Ptr{Module}), argdata, ci, pointer_from_objref(mod)) # `argdata` is `Core.svec(Core.svec(types...), Core.svec(typevars...))` "Recursively get the typevars from a `UnionAll` type" typevars(T::UnionAll) = (T.var, typevars(T.body)...) typevars(T::DataType) = () @nospecialize # the below functions need not specialize on arguments "Get the module of a function" getmodule(F::Type{<:Function}) = F.name.mt.module getmodule(f::Function) = getmodule(typeof(f)) "Create a call singature" makesig(f::Function, args) = Tuple{typeof(f), args...} """ argdata(sig[, f]) Turn a call signature into the 'argdata' `Core.svec` that `jl_method_def` uses When a function is given in the second argument, it replaces the one in the call signature. """ argdata(sig) = Core.svec(Base.unwrap_unionall(sig).parameters::Core.SimpleVector, Core.svec(typevars(sig)...)) argdata(sig, f::Function) = Core.svec(Core.svec(typeof(f), Base.unwrap_unionall(sig).parameters[2:end]...), Core.svec(typevars(sig)...)) """ addmethod!(f, argtypes, ci) Add a method to a function. The types of the arguments is given as a `Tuple`. Example: ``` g(x) = x + 13 ci = code_lowered(g)[1] function f end addmethod!(f, (Any,), ci) f(1) # returns 14 ``` """ addmethod!(f::Function, argtypes::Tuple, ci::Core.CodeInfo) = addmethod!(makesig(f, argtypes), ci) """ addmethod(sig, ci) Alternative syntax where the call signature is a `Tuple` type. Example: ``` addmethod!(Tuple{typeof(f), Any}, ci) ``` """ function addmethod!(sig::Type{<:Tuple{F, Vararg}}, ci::Core.CodeInfo) where {F<:Function} jl_method_def(argdata(sig), ci, getmodule(F)) end @specialize # restore default """ codetransform!(tr, dst, src) Apply a code transformation function `tr` on the methods of a function `src`, adding the transformed methods to another function `dst`. Example: Search-and-replace a constant in a function. ``` g(x) = x + 13 function e end codetransform!(g => e) do ci for ex in ci.code if ex isa Expr map!(x -> x === 13 ? 7 : x, ex.args, ex.args) end end ci end e(1) # returns 8 ``` """ function codetransform!(tr::Function, @nospecialize(dst::Function), @nospecialize(src::Function)) mod = getmodule(dst) for m in methods(src).ms ci = Base.uncompressed_ast(m) ci = tr(ci) jl_method_def(argdata(m.sig, dst), ci, mod) end end "Alternative syntax: codetransform!(tr, src => dst)" codetransform!(tr::Function, @nospecialize(p::Pair{<:Function, <:Function})) = codetransform!(tr, p.second, p.first)
ExtensibleUnions
https://github.com/bcbi/ExtensibleUnions.jl.git
[ "MIT" ]
0.5.1
70638af651f5f32f82bc390c67c25dfe97fe7e3e
code
1153
function extensiblefunction!(@nospecialize(f::Function), varargs...) return extensiblefunction!(f, varargs) end function extensiblefunction!(@nospecialize(f::Function), @nospecialize(varargs::Tuple)) global _registry_extensibleunion_to_genericfunctions global _registry_genericfunctions_to_extensibleunions if !haskey(_registry_genericfunctions_to_extensibleunions, f) _registry_genericfunctions_to_extensibleunions[f] = Set{Any}() end for i = 1:length(varargs) if isextensibleunion(varargs[i]) push!(_registry_extensibleunion_to_genericfunctions[varargs[i]], f) push!(_registry_genericfunctions_to_extensibleunions[f], varargs[i]) else throw(ArgumentError( "Argument is not a registered extensible union.")) end end _update_all_methods_for_extensiblefunction!(f) return f end function isextensiblefunction(@nospecialize(f::Function)) global _registry_genericfunctions_to_extensibleunions return haskey(_registry_genericfunctions_to_extensibleunions, f) end
ExtensibleUnions
https://github.com/bcbi/ExtensibleUnions.jl.git
[ "MIT" ]
0.5.1
70638af651f5f32f82bc390c67c25dfe97fe7e3e
code
2348
function extensibleunion!(@nospecialize(u)) global _registry_extensibleunion_to_genericfunctions global _registry_extensibleunion_to_members if !isconcretetype(u) throw(ArgumentError("The provided type must be a concrete type")) end if !isstructtype(u) throw(ArgumentError("The provided type must be a struct type")) end if length(fieldnames(u)) > 0 throw(ArgumentError("The provided type must have no fields")) end if u.mutable throw(ArgumentError("The provided type must be an immutable type")) end if !(supertype(u) === Any) throw(ArgumentError( "The immediate supertype of the provided type must be Any")) end if !haskey(_registry_extensibleunion_to_members, u) _registry_extensibleunion_to_genericfunctions[u] = Set{Any}() _registry_extensibleunion_to_members[u] = Set{Any}([u]) end _update_all_methods_for_extensibleunion!(u) return u end function isextensibleunion(@nospecialize(u)) global _registry_extensibleunion_to_members return haskey(_registry_extensibleunion_to_members, u) end function addtounion!(@nospecialize(u), varargs...) return addtounion!(u, varargs) end function addtounion!(@nospecialize(u), @nospecialize(varargs::Tuple)) global _registry_extensibleunion_to_members if isextensibleunion(u) old_members_set = deepcopy(_registry_extensibleunion_to_members[u]) for i = 1:length(varargs) push!(_registry_extensibleunion_to_members[u], varargs[i]) end new_members_set = deepcopy(_registry_extensibleunion_to_members[u]) old_members_union = _set_to_union(old_members_set) new_members_union = _set_to_union(new_members_set) _update_all_methods_for_extensibleunion!(u, old_members_union => new_members_union) else throw(ArgumentError( "First argument must be a registered extensible union.")) end end function unioncurrentlycontains(@nospecialize(u), @nospecialize(t)) global _registry_extensibleunion_to_members if isextensibleunion(u) return t in _registry_extensibleunion_to_members[u] else throw(ArgumentError( "First argument must be a registered extensible union.")) end end
ExtensibleUnions
https://github.com/bcbi/ExtensibleUnions.jl.git
[ "MIT" ]
0.5.1
70638af651f5f32f82bc390c67c25dfe97fe7e3e
code
372
function __init__() global _registry_extensibleunion_to_genericfunctions global _registry_extensibleunion_to_members global _registry_genericfunctions_to_extensibleunions empty!(_registry_extensibleunion_to_genericfunctions) empty!(_registry_extensibleunion_to_members) empty!(_registry_genericfunctions_to_extensibleunions) return nothing end
ExtensibleUnions
https://github.com/bcbi/ExtensibleUnions.jl.git
[ "MIT" ]
0.5.1
70638af651f5f32f82bc390c67c25dfe97fe7e3e
code
378
function _unsafe_reset!() global _registry_extensibleunion_to_genericfunctions global _registry_extensibleunion_to_members global _registry_genericfunctions_to_extensibleunions empty!(_registry_extensibleunion_to_genericfunctions) empty!(_registry_extensibleunion_to_members) empty!(_registry_genericfunctions_to_extensibleunions) return nothing end
ExtensibleUnions
https://github.com/bcbi/ExtensibleUnions.jl.git
[ "MIT" ]
0.5.1
70638af651f5f32f82bc390c67c25dfe97fe7e3e
code
6531
function _update_all_methods_for_extensibleunion!(@nospecialize(u)) global _registry_extensibleunion_to_genericfunctions for f in _registry_extensibleunion_to_genericfunctions[u] _update_all_methods_for_extensiblefunction!(f) end return u end function _update_all_methods_for_extensibleunion!(@nospecialize(u), p::Pair) global _registry_extensibleunion_to_genericfunctions for f in _registry_extensibleunion_to_genericfunctions[u] _update_all_methods_for_extensiblefunction!(f, p) end return u end function _update_all_methods_for_extensiblefunction!(@nospecialize(f)) global _registry_genericfunctions_to_extensibleunions extensibleunions_for_this_genericfunction = _registry_genericfunctions_to_extensibleunions[f] for met in methods(f).ms _update_single_method!(f, met.sig, extensibleunions_for_this_genericfunction) end return f end function _update_all_methods_for_extensiblefunction!(@nospecialize(f), p::Pair) global _registry_genericfunctions_to_extensibleunions extensibleunions_for_this_genericfunction = _registry_genericfunctions_to_extensibleunions[f] for met in methods(f).ms _update_single_method!(f, met.sig, extensibleunions_for_this_genericfunction, p) end return f end function _update_single_method!(@nospecialize(f::Function), @nospecialize(oldsig::Type{<:Tuple}), @nospecialize(unions::Set)) global _registry_extensibleunion_to_members newsig = _replace_types(oldsig) for u in unions newsig = _replace_types(newsig, u => _set_to_union(_registry_extensibleunion_to_members[u])) end if oldsig == newsig else oldsig_tuple = tuple(oldsig.types[2:end]...) newsig_tuple = tuple(newsig.types[2:end]...) @assert length(code_lowered(f, oldsig_tuple)) == 1 codeinfo = code_lowered(f, oldsig_tuple)[1] @assert length(methods(f, oldsig_tuple).ms) == 1 oldmet = methods(f, oldsig_tuple).ms[1] Base.delete_method(oldmet) addmethod!(f, newsig_tuple, codeinfo) end return f end function _update_single_method!(@nospecialize(f::Function), @nospecialize(oldsig::Type{<:Tuple}), @nospecialize(unions::Set), p::Pair) global _registry_extensibleunion_to_members newsig = _replace_types(oldsig, p) for u in unions newsig = _replace_types(newsig, u => _set_to_union(_registry_extensibleunion_to_members[u])) end if oldsig == newsig else oldsig_tuple = tuple(oldsig.types[2:end]...) newsig_tuple = tuple(newsig.types[2:end]...) @assert length(code_lowered(f, oldsig_tuple)) == 1 codeinfo = code_lowered(f, oldsig_tuple)[1] @assert length(methods(f, oldsig_tuple).ms) == 1 oldmet = methods(f, oldsig_tuple).ms[1] Base.delete_method(oldmet) addmethod!(f, newsig_tuple, codeinfo) end return f end function _update_single_method!(@nospecialize(f::Function), @nospecialize(oldsig::Type{<:UnionAll}), @nospecialize(unions::Set)) throw(MethodError("Not yet implemented for when sig is a UnionAll")) end function _update_single_method!(@nospecialize(f::Function), @nospecialize(oldsig::Type{<:UnionAll}), @nospecialize(unions::Set), p::Pair) throw(MethodError("Not yet implemented for when sig is a UnionAll")) end function _replace_types(sig::Type{<:UnionAll}) throw(MethodError("Not yet implemented for when sig is a UnionAll")) end function _replace_types(sig::Type{<:UnionAll}, p::Pair) throw(MethodError("Not yet implemented for when sig is a UnionAll")) end # function _replace_types(sig::Core.SimpleVector) # v = Any[sig.types...] # for i = 2:length(v) # v[i] = _replace_types(v[i]) # end # return Core.svec(v...) # end # function _replace_types(sig::Core.SimpleVector, p::Pair) # v = Any[sig.types...] # for i = 2:length(v) # v[i] = _replace_types(v[i], p) # end # return Core.svec(v...) # end _peel_unionall(sig) = sig function _peel_unionall(sig::UnionAll) while sig isa UnionAll sig = sig.body end sig end @inline _replace_types(sig::TypeVar) = _replace_types(sig.ub) function _replace_types(sig::Type{<:Tuple}) v = Any[_peel_unionall(sig).types...] for i = 2:length(v) v[i] = _replace_types(v[i]) end return Tuple{v...} end @inline _replace_types(sig::UnionAll, p::Pair) = _replace_types(sig.body, p) @inline _replace_types(sig::TypeVar, p::Pair) = _replace_types(sig.ub, p) function _replace_types(sig::Type{<:Tuple}, p::Pair) v = Any[_peel_unionall(sig).types...] for i = 2:length(v) v[i] = _replace_types(v[i], p) end return Tuple{v...} end function _replace_types(::Type{Union{}}) return Union{} end function _replace_types(sig::Type{Union{}}, p::Pair) if sig == p[1] return p[2] else return sig end end function _replace_types(sig::Union) union_length = Base.unionlen(sig) old_union_members = Base.uniontypes(sig) new_union_members = Vector{Any}(undef, union_length) for i = 1:union_length new_union_members[i] = _replace_types(old_union_members[i]) end new_union = Union{new_union_members...} return new_union end function _replace_types(sig::Union, p::Pair) if sig == p[1] return p[2] else union_length = Base.unionlen(sig) old_union_members = Base.uniontypes(sig) new_union_members = Vector{Any}(undef, union_length) for i = 1:union_length new_union_members[i] = _replace_types(old_union_members[i], p) end new_union = Union{new_union_members...} return new_union end end function _replace_types(sig::Type) return sig end function _replace_types(sig::Type, p::Pair) if sig == p[1] return p[2] else return sig end end function _set_to_union(s::Set) result = Union{} for member in s result = Union{result, member} end return result end
ExtensibleUnions
https://github.com/bcbi/ExtensibleUnions.jl.git
[ "MIT" ]
0.5.1
70638af651f5f32f82bc390c67c25dfe97fe7e3e
code
1608
using ExtensibleUnions using Test using Traceur macro genstruct!(list) x = gensym() y = quote struct $(x) end push!($(list), $(x)) end return y end # macro genfunc!(list) # x = gensym() # y = quote # function $(x) end # push!($(list), $(x)) # end # return y # end @testset "ExtensibleUnions.jl" begin @testset "Unit tests" begin @testset "test_code_transformation.jl" begin include("test_code_transformation.jl") end @testset "test_extensible_functions.jl" begin include("test_extensible_functions.jl") end @testset "test_extensible_unions.jl" begin include("test_extensible_unions.jl") end @testset "test_inferred.jl" begin include("test_inferred.jl") end @testset "test_traceur.jl" begin include("test_traceur.jl") end @testset "test_update_methods.jl" begin include("test_update_methods.jl") end end @testset "Integration tests" begin @testset "test_examples.jl" begin include("test_examples.jl") end end @testset "reset.jl" begin @testset "ExtensibleUnions._unsafe_reset!()" begin ExtensibleUnions._unsafe_reset!() @test isempty(ExtensibleUnions._registry_extensibleunion_to_genericfunctions) @test isempty(ExtensibleUnions._registry_extensibleunion_to_members) @test isempty(ExtensibleUnions._registry_genericfunctions_to_extensibleunions) end end end
ExtensibleUnions
https://github.com/bcbi/ExtensibleUnions.jl.git
[ "MIT" ]
0.5.1
70638af651f5f32f82bc390c67c25dfe97fe7e3e
code
1316
using ExtensibleUnions using Test # Most of the code in this file is taken from: # 1. https://github.com/NHDaly/DeepcopyModules.jl (license: MIT) # 2. https://github.com/perrutquist/CodeTransformation.jl (license: MIT) @test ExtensibleUnions.getmodule(typeof(sin)) === Base @test ExtensibleUnions.getmodule(sin) === Base let # Test example from docstring to ExtensibleUnions.addmethod! g(x) = x + 13 ci = code_lowered(g)[1] function f end ExtensibleUnions.addmethod!(f, (Any,), ci) @test f(1) === 14 # Alternative syntax function f2 end @test ExtensibleUnions.makesig(f2, (Any,)) === Tuple{typeof(f2), Any} ExtensibleUnions.addmethod!(Tuple{typeof(f2), Any}, ci) @test f2(1) === 14 end let # Test example from docstring to codetransform! g(x) = x + 13 function e end ExtensibleUnions.codetransform!(g => e) do ci for ex in ci.code if ex isa Expr map!(x -> x === 13 ? 7 : x, ex.args, ex.args) end end ci end @test e(1) === 8 @test g(1) === 14 end let a = Vector{T} where T b = ExtensibleUnions.typevars(a) @test b isa Tuple @test length(b) == 1 @test b[1] isa TypeVar @test b[1].name == :T @test b[1].lb === Union{} @test b[1].ub === Any end
ExtensibleUnions
https://github.com/bcbi/ExtensibleUnions.jl.git
[ "MIT" ]
0.5.1
70638af651f5f32f82bc390c67c25dfe97fe7e3e
code
4320
using ExtensibleUnions using Test using Traceur abstract type AbstractCar end abstract type AbstractFireEngine end struct RedCar <: AbstractCar end struct BlueCar <: AbstractCar x end struct LadderTruck{T} <: AbstractFireEngine x::T end mutable struct WaterTender{T} <: AbstractFireEngine x::T y::T end struct RedColorTrait end struct BlueColorTrait end extensibleunion!(RedColorTrait) extensibleunion!(BlueColorTrait) describe(x) = "I don't know anything about this object" methods(describe) @test length(methods(describe)) == 1 @test @inferred describe(RedCar()) == "I don't know anything about this object" @test @inferred describe(BlueCar(1)) == "I don't know anything about this object" @test @inferred describe(LadderTruck{Int}(2)) == "I don't know anything about this object" @test @inferred describe(WaterTender{Int}(3,4)) == "I don't know anything about this object" @check describe(RedCar()) nowarn=[describe] maxdepth=typemax(Int) @check describe(BlueCar(1)) nowarn=[describe] maxdepth=typemax(Int) @check describe(LadderTruck{Int}(2)) nowarn=[describe] maxdepth=typemax(Int) @check describe(WaterTender{Int}(3,4)) nowarn=[describe] maxdepth=typemax(Int) describe(x::RedColorTrait) = "The color of this object is red" extensiblefunction!(describe, RedColorTrait) @test length(methods(describe)) == 2 describe(x::BlueColorTrait) = "The color of this object is blue" extensiblefunction!(describe, BlueColorTrait) @test length(methods(describe)) == 3 methods(describe) @test length(methods(describe)) == 3 @test @inferred describe(RedCar()) == "I don't know anything about this object" @test @inferred describe(BlueCar(1)) == "I don't know anything about this object" @test @inferred describe(LadderTruck{Int}(2)) == "I don't know anything about this object" @test @inferred describe(WaterTender{Int}(3,4)) == "I don't know anything about this object" @check describe(RedCar()) nowarn=[describe] maxdepth=typemax(Int) @check describe(BlueCar(1)) nowarn=[describe] maxdepth=typemax(Int) @check describe(LadderTruck{Int}(2)) nowarn=[describe] maxdepth=typemax(Int) @check describe(WaterTender{Int}(3,4)) nowarn=[describe] maxdepth=typemax(Int) addtounion!(RedColorTrait, RedCar) methods(describe) @test length(methods(describe)) == 3 @test @inferred describe(RedCar()) == "The color of this object is red" @test @inferred describe(BlueCar(1)) == "I don't know anything about this object" @test @inferred describe(LadderTruck{Int}(2)) == "I don't know anything about this object" @test @inferred describe(WaterTender{Int}(3,4)) == "I don't know anything about this object" @check describe(RedCar()) nowarn=[describe] maxdepth=typemax(Int) @check describe(BlueCar(1)) nowarn=[describe] maxdepth=typemax(Int) @check describe(LadderTruck{Int}(2)) nowarn=[describe] maxdepth=typemax(Int) @check describe(WaterTender{Int}(3,4)) nowarn=[describe] maxdepth=typemax(Int) addtounion!(BlueColorTrait, BlueCar) methods(describe) @test length(methods(describe)) == 3 @test @inferred describe(RedCar()) == "The color of this object is red" @test @inferred describe(BlueCar(1)) == "The color of this object is blue" @test @inferred describe(LadderTruck{Int}(2)) == "I don't know anything about this object" @test @inferred describe(WaterTender{Int}(3,4)) == "I don't know anything about this object" @check describe(RedCar()) nowarn=[describe] maxdepth=typemax(Int) @check describe(BlueCar(1)) nowarn=[describe] maxdepth=typemax(Int) @check describe(LadderTruck{Int}(2)) nowarn=[describe] maxdepth=typemax(Int) @check describe(WaterTender{Int}(3,4)) nowarn=[describe] maxdepth=typemax(Int) addtounion!(RedColorTrait, AbstractFireEngine) methods(describe) @test length(methods(describe)) == 3 @test @inferred describe(RedCar()) == "The color of this object is red" @test @inferred describe(BlueCar(1)) == "The color of this object is blue" @test @inferred describe(LadderTruck{Int}(2)) == "The color of this object is red" @test @inferred describe(WaterTender{Int}(3,4)) == "The color of this object is red" @check describe(RedCar()) nowarn=[describe] maxdepth=typemax(Int) @check describe(BlueCar(1)) nowarn=[describe] maxdepth=typemax(Int) @check describe(LadderTruck{Int}(2)) nowarn=[describe] maxdepth=typemax(Int) @check describe(WaterTender{Int}(3,4)) nowarn=[describe] maxdepth=typemax(Int)
ExtensibleUnions
https://github.com/bcbi/ExtensibleUnions.jl.git
[ "MIT" ]
0.5.1
70638af651f5f32f82bc390c67c25dfe97fe7e3e
code
491
using ExtensibleUnions using Test struct S5 end function f1 end @test !isextensibleunion(S5) @test !isextensiblefunction(f1) extensiblefunction!(f1) @test isextensiblefunction(f1) @test_throws ArgumentError extensiblefunction!(f1, S5) @test !isextensibleunion(S5) extensibleunion!(S5) @test isextensibleunion(S5) extensiblefunction!(f1, S5) @test isextensiblefunction(f1) extensiblefunction!(f1, S5) @test isextensiblefunction(f1) extensiblefunction!(f1, S5) @test isextensiblefunction(f1)
ExtensibleUnions
https://github.com/bcbi/ExtensibleUnions.jl.git
[ "MIT" ]
0.5.1
70638af651f5f32f82bc390c67c25dfe97fe7e3e
code
1560
using ExtensibleUnions using Test abstract type A1 end @test_throws ArgumentError extensibleunion!(A1) @test_throws ArgumentError extensibleunion!(Int) struct S1 x end @test_throws ArgumentError extensibleunion!(S1) mutable struct S2 end @test_throws ArgumentError extensibleunion!(S2) abstract type A2 end struct S3 <: A2 end @test_throws ArgumentError extensibleunion!(S3) struct S4 end @test !isextensibleunion(S4) extensibleunion!(S4) @test isextensibleunion(S4) extensibleunion!(S4) @test isextensibleunion(S4) extensibleunion!(S4) @test isextensibleunion(S4) struct S6 end extensibleunion!(S6) @test !ExtensibleUnions.unioncurrentlycontains(S6, String) addtounion!(S6, String) @test ExtensibleUnions.unioncurrentlycontains(S6, String) struct S7 end extensibleunion!(S7) @test !ExtensibleUnions.unioncurrentlycontains(S7, String) addtounion!(S7, String) @test ExtensibleUnions.unioncurrentlycontains(S7, String) struct S8 end @test_throws ArgumentError addtounion!(S8) @test_throws ArgumentError ExtensibleUnions.unioncurrentlycontains(S8, String) let struct MyUnion end extensibleunion!(MyUnion) struct Foo end addtounion!(MyUnion, Foo) foo(x::Tuple{Int, T}) where {T} = x[1] foo(::MyUnion) = "boo!" extensiblefunction!(foo, MyUnion) @test foo(Foo()) == "boo!" end let a = Vector{T} where T ExtensibleUnions._replace_types(a) ExtensibleUnions._replace_types(a.var) ExtensibleUnions._replace_types(a, nothing => nothing) ExtensibleUnions._replace_types(a.var, nothing => nothing) end
ExtensibleUnions
https://github.com/bcbi/ExtensibleUnions.jl.git
[ "MIT" ]
0.5.1
70638af651f5f32f82bc390c67c25dfe97fe7e3e
code
34
using ExtensibleUnions using Test
ExtensibleUnions
https://github.com/bcbi/ExtensibleUnions.jl.git
[ "MIT" ]
0.5.1
70638af651f5f32f82bc390c67c25dfe97fe7e3e
code
48
using ExtensibleUnions using Test using Traceur
ExtensibleUnions
https://github.com/bcbi/ExtensibleUnions.jl.git
[ "MIT" ]
0.5.1
70638af651f5f32f82bc390c67c25dfe97fe7e3e
code
3879
using ExtensibleUnions using Test function f1 end ExtensibleUnions._update_all_methods_for_extensiblefunction!(f1) b = Type{Vector{T} where T} @test_throws MethodError ExtensibleUnions._update_single_method!(f1, b, Set()) @test_throws MethodError ExtensibleUnions._update_single_method!(f1, b, Set(), nothing => nothing) @test_throws MethodError ExtensibleUnions._replace_types(b) @test_throws MethodError ExtensibleUnions._replace_types(b, nothing => nothing) @test ExtensibleUnions._replace_types(Union{}) == Union{} @test ExtensibleUnions._replace_types(Union{}, Union{} => Union{Float32, String}) == Union{Float32, String} @test ExtensibleUnions._replace_types(Union{}, Union{Float32, String} => Union{Float32, Int32, String}) == Union{} @test ExtensibleUnions._replace_types(Union{Int32}) == Union{Int32} @test ExtensibleUnions._replace_types(Union{Int32}, Int32 => Float32) == Union{Float32} @test ExtensibleUnions._replace_types(Union{Int32, Float32}) == Union{Int32, Float32} @test ExtensibleUnions._replace_types(Union{Int32, Float32}, Union{Int32, Float32} => Union{String, Symbol}) == Union{String, Symbol} @test ExtensibleUnions._replace_types(Union{Int32, Float32}, Float32 => String) == Union{Int32, String} @test ExtensibleUnions._replace_types(Union{Int32, Float32, AbstractString}) == Union{Int32, Float32, AbstractString} @test ExtensibleUnions._replace_types(Union{Int32, Float32, AbstractString}, Float32 => Symbol) == Union{Int32, Symbol, AbstractString} @test ExtensibleUnions._replace_types(Union{Int32, Float32, AbstractString}, Union{Int32, Float32, AbstractString} => Symbol) == Symbol @test ExtensibleUnions._replace_types(Union{Int32, Float32, AbstractString, Symbol}) == Union{Int32, Float32, AbstractString, Symbol} @test ExtensibleUnions._replace_types(Union{Int32, Float32, AbstractString, Symbol}, Float32 => Char) == Union{Int32, Char, AbstractString, Symbol} @test ExtensibleUnions._replace_types(Union{Int32, Float32, AbstractString, Symbol}, Union{Int32, Float32, AbstractString, Symbol} => Union{Int32, Float32, AbstractString, Symbol, Char}) == Union{Int32, Float32, AbstractString, Symbol, Char} structlist = Any[] @genstruct!(structlist) @genstruct!(structlist) @genstruct!(structlist) @genstruct!(structlist) @genstruct!(structlist) @genstruct!(structlist) @genstruct!(structlist) # funclist = Any[] # @genfunc!(funclist) # @genfunc!(funclist) FooTrait = structlist[1] BarTrait = structlist[2] BazTrait = structlist[3] extensibleunion!(FooTrait) extensibleunion!(BarTrait) ExtensibleUnions._update_all_methods_for_extensibleunion!(FooTrait) ExtensibleUnions._update_all_methods_for_extensibleunion!(BarTrait, nothing=>nothing) StructA = structlist[4] StructB = structlist[5] StructC = structlist[6] StructD = structlist[7] # f = funclist[1] # g = funclist[2] function f end function g end f(x::FooTrait) = "foo" f(x::BarTrait) = "bar" extensiblefunction!(f, FooTrait, BarTrait) extensiblefunction!(f, (FooTrait, BarTrait,)) ExtensibleUnions._update_all_methods_for_extensibleunion!(FooTrait) ExtensibleUnions._update_all_methods_for_extensibleunion!(BarTrait, nothing=>nothing) ExtensibleUnions._update_all_methods_for_extensiblefunction!(f) addtounion!(FooTrait, StructA) addtounion!(FooTrait, StructB) addtounion!(FooTrait, StructC) addtounion!(FooTrait, StructD) addtounion!(BarTrait, StructA) addtounion!(BarTrait, StructB) addtounion!(BarTrait, StructC) addtounion!(BarTrait, StructD) ExtensibleUnions._update_all_methods_for_extensibleunion!(FooTrait) ExtensibleUnions._update_all_methods_for_extensibleunion!(BarTrait, nothing=>nothing) ExtensibleUnions._update_all_methods_for_extensiblefunction!(f) g(x::BazTrait) = "baz" ExtensibleUnions._registry_extensibleunion_to_members[BazTrait] = Set(Any[StructA, StructB, StructC, StructD]) ExtensibleUnions._update_single_method!(g, Tuple{typeof(g), BazTrait}, Set(Any[BazTrait]))
ExtensibleUnions
https://github.com/bcbi/ExtensibleUnions.jl.git
[ "MIT" ]
0.5.1
70638af651f5f32f82bc390c67c25dfe97fe7e3e
docs
5400
# ExtensibleUnions [![Build Status](https://travis-ci.com/bcbi/ExtensibleUnions.jl.svg?branch=master)](https://travis-ci.com/bcbi/ExtensibleUnions.jl/branches) [![Codecov](https://codecov.io/gh/bcbi/ExtensibleUnions.jl/branch/master/graph/badge.svg)](https://codecov.io/gh/bcbi/ExtensibleUnions.jl) ```julia julia> import Pkg; Pkg.add("ExtensibleUnions") ``` ExtensibleUnions adds abstract multiple inheritance to Julia in the form of extensible (mutable) type unions. **Warning: ExtensibleUnions is an experimental package. Do not use ExtensibleUnions in any production code.** ## Usage Create a new extensible union: ```julia struct MyUnion end extensibleunion!(MyUnion) ``` Add methods that dispatch on extensible unions: ```julia f(x::MyUnion1, y, z, ...) = ... f(x, y::MyUnion2, z, ...) = ... extensiblefunction!(f, MyUnion1, MyUnion2, ...) ``` Add types to an extensible union: ```julia addtounion!(MyUnion, SomeType1, SomeType2, ...) ``` At any later time, you can add more types to an extensible union: ```julia addtounion!(MyUnion, SomeType3, SomeType4, ...) ``` ## Examples ### Example 1 ```julia julia> using ExtensibleUnions julia> abstract type AbstractCar end julia> abstract type AbstractFireEngine end julia> struct RedCar <: AbstractCar end julia> struct BlueCar <: AbstractCar x end julia> struct LadderTruck{T} <: AbstractFireEngine x::T end julia> mutable struct WaterTender{T} <: AbstractFireEngine x::T y::T end julia> struct RedColorTrait end julia> struct BlueColorTrait end julia> extensibleunion!(RedColorTrait) RedColorTrait julia> extensibleunion!(BlueColorTrait) BlueColorTrait julia> describe(x) = "I don't know anything about this object" describe (generic function with 1 method) julia> methods(describe) # 1 method for generic function "describe": [1] describe(x) in Main at REPL[12]:1 julia> describe(RedCar()) "I don't know anything about this object" julia> describe(BlueCar(1)) "I don't know anything about this object" julia> describe(LadderTruck{Int}(2)) "I don't know anything about this object" julia> describe(WaterTender{Int}(3,4)) "I don't know anything about this object" julia> describe(x::RedColorTrait) = "The color of this object is red" describe (generic function with 2 methods) julia> extensiblefunction!(describe, RedColorTrait) describe (generic function with 2 methods) julia> describe(x::BlueColorTrait) = "The color of this object is blue" describe (generic function with 3 methods) julia> extensiblefunction!(describe, BlueColorTrait) describe (generic function with 3 methods) julia> methods(describe) # 3 methods for generic function "describe": [1] describe(x::BlueColorTrait) in Main at REPL[20]:1 [2] describe(x::RedColorTrait) in Main at REPL[18]:1 [3] describe(x) in Main at REPL[12]:1 julia> describe(RedCar()) "I don't know anything about this object" julia> describe(BlueCar(1)) "I don't know anything about this object" julia> describe(LadderTruck{Int}(2)) "I don't know anything about this object" julia> describe(WaterTender{Int}(3,4)) "I don't know anything about this object" julia> addtounion!(RedColorTrait, RedCar) RedColorTrait julia> methods(describe) # 3 methods for generic function "describe": [1] describe(x::BlueColorTrait) in Main at REPL[20]:1 [2] describe(x::Union{RedCar, RedColorTrait}) in Main at REPL[18]:1 [3] describe(x) in Main at REPL[12]:1 julia> describe(RedCar()) "The color of this object is red" julia> describe(BlueCar(1)) "I don't know anything about this object" julia> describe(LadderTruck{Int}(2)) "I don't know anything about this object" julia> describe(WaterTender{Int}(3,4)) "I don't know anything about this object" julia> addtounion!(BlueColorTrait, BlueCar) BlueColorTrait julia> methods(describe) # 3 methods for generic function "describe": [1] describe(x::Union{RedCar, RedColorTrait}) in Main at REPL[18]:1 [2] describe(x::Union{BlueColorTrait, BlueCar}) in Main at REPL[20]:1 [3] describe(x) in Main at REPL[12]:1 julia> describe(RedCar()) "The color of this object is red" julia> describe(BlueCar(1)) "The color of this object is blue" julia> describe(LadderTruck{Int}(2)) "I don't know anything about this object" julia> describe(WaterTender{Int}(3,4)) "I don't know anything about this object" julia> addtounion!(RedColorTrait, AbstractFireEngine) RedColorTrait julia> methods(describe) # 3 methods for generic function "describe": [1] describe(x::Union{BlueColorTrait, BlueCar}) in Main at REPL[20]:1 [2] describe(x::Union{RedCar, RedColorTrait, AbstractFireEngine}) in Main at REPL[18]:1 [3] describe(x) in Main at REPL[12]:1 julia> describe(RedCar()) "The color of this object is red" julia> describe(BlueCar(1)) "The color of this object is blue" julia> describe(LadderTruck{Int}(2)) "The color of this object is red" julia> describe(WaterTender{Int}(3,4)) "The color of this object is red" ``` ## Acknowledgements Some of the code in this package is taken from: 1. [https://github.com/NHDaly/DeepcopyModules.jl](https://github.com/NHDaly/DeepcopyModules.jl) (license: MIT) 2. [https://github.com/perrutquist/CodeTransformation.jl](https://github.com/perrutquist/CodeTransformation.jl) (license: MIT) ## Related Work 1. [https://github.com/rofinn/Interfaces.jl](https://github.com/rofinn/Interfaces.jl): An implementation of interfaces for Julia
ExtensibleUnions
https://github.com/bcbi/ExtensibleUnions.jl.git
[ "BSD-3-Clause" ]
2.2.2
d83d40d4553ac35482d51360735140b1a5818808
code
877
using MParT using Documenter DocMeta.setdocmeta!(MParT, :DocTestSetup, :(using MParT); recursive=true) makedocs(; modules=[MParT], authors="MIT UQGroup", repo="https://github.com/MeasureTransport/MParT.jl/blob/{commit}{path}#{line}", sitename="MParT.jl", format=Documenter.HTML(; prettyurls=get(ENV, "CI", "false") == "true", canonical="https://MeasureTransport.github.io/MParT.jl", edit_link="main", assets=String[], ), pages=[ "Home" => "index.md", "Map Functionality" => "map.md", "MultiIndices" => "multiindex.md", "Map Training" => [ "Traditional training" => "trainmap.md", "Adaptive training" => "adaptivemap.md" ], "Extras" => "extras.md" ], ) deploydocs(; repo="github.com/MeasureTransport/MParT.jl", devbranch="main", )
MParT
https://github.com/MeasureTransport/MParT.jl.git
[ "BSD-3-Clause" ]
2.2.2
d83d40d4553ac35482d51360735140b1a5818808
code
13115
# Wrapping code to make the Julia module usable module MParT using CxxWrap using MParT_jll import Libdl @wrapmodule ()->libmpartjl :MParT_julia_module import Base: getindex, lastindex, show, iterate, vec ConditionalMapBasePtr = CxxWrap.StdLib.SharedPtr{<:ConditionalMapBase} for op = (:Evaluate, :Gradient, :Inverse, :inputDim, :outputDim, :LogDeterminant, :LogDeterminantCoeffGrad, :LogDeterminantInputGrad, :numCoeffs, :CoeffMap, :CoeffGrad, :SetCoeffs, :TestError) eval(quote $op(obj::CxxWrap.StdLib.SharedPtr, args...) = $op(obj[], args...) end) end function __init__() @initcxx threads = get(ENV, "KOKKOS_NUM_THREADS", nothing) opts = StdVector{StdString}() if !isnothing(threads) push!(opts, StdString("kokkos_num_threads")) push!(opts, StdString(string(threads))) end length(opts) > 0 && @info "Using MParT options: "*join(string.(opts),", ") Initialize(opts) end """ Concurrency() See how many threads MParT is using. """ Concurrency function Base.iterate(mset::MultiIndexSet) Size(mset) < 1 && return nothing mset[1],2 end function Base.iterate(mset::MultiIndexSet,state::Int) state > Size(mset) && return nothing return mset[state], state+1 end """ Size(mset::MultiIndexSet) Number of MultiIndex objects in a MultiIndexSet `mset`. """ Size """ MultiIndexSet(A::AbstractVecOrMat{<:Integer}) Create a set of MultiIndices from the rows of `A`. These indices represent a basis for a multivariate expansion or, further, monotone expansion. Each element of the set is a MultiIndex representing one basis function via the degrees in each dimension. # Example ```jldoctest julia> # Functions like: c_1xy^2z^3 + c_2xyz + c_3 julia> A = [1 2 3;1 1 1; 0 0 0]; julia> mset = MultiIndexSet(A); ``` See also [`MultiIndex`](@ref), [`FixedMultiIndexSet`](@ref), [`Fix`](@ref) """ MultiIndexSet """ FixedMultiIndexSet(dim::Int, p::Int) Creates a FixedMultiIndexSet with dimension `dim` and total order `p`. A FixedMultiIndexSet is just a compressed, efficient way of representing a MultiIndexSet, but without as many bells and whistles. See also: [`MultiIndex`](@ref), [`MultiIndexSet`](@ref) """ FixedMultiIndexSet """ CreateTotalOrder(dim::Int, p::Int) Creates a total order `p` MultiIndexSet object in dimension `dim`. See also: [`MultiIndexSet`](@ref) """ CreateTotalOrder """ Fix(mset::MultiIndexSet, compress::Bool = true) Take `mset` and turn it into a `FixedMultiIndexSet` that can be `compress`ed. See also [`MultiIndex`](@ref), [`MultiIndexSet`](@ref), [`FixedMultiIndexSet`](@ref) """ Fix(mset::MultiIndexSet) = Fix(mset, true) MultiIndexSet(A::AbstractMatrix{<:Integer}) = MultiIndexSet(Cint.(collect(A))) MultiIndexSet(A::AbstractVector{<:Integer}) = MultiIndexSet(Cint.(collect(reshape(A, length(A), 1)))) Base.getindex(A::MultiIndex, i::AbstractVector{<:Integer}) = getindex.((A,), i) Base.lastindex(A::MultiIndex) = length(A) Base.vec(A::MultiIndex) = Int.(ToVector(A)) # Not implemented yet # Base.getindex(A::CxxWrap.reference_type_union(MParT.TriangularMap), s::Base.UnitRange) = Slice(A, first(s), last(s)) """ Evaluate(map, points) Evaluates the function `map` at `points`, where each column of `points` is a different sample. If `map` ``:\\mathbb{R}^m\\to\\mathbb{R}^n``, then `points` ``\\in\\mathbb{R}^m\\times\\mathbb{R}^k``, where ``k`` is the number of points. """ Evaluate """ Inverse(map, y, x) If `map` represents function ``T(y,x)``, then this function calculates ``T(y,\\cdot)^{-1}(x)``. If `map` is square, **you still require `y`**, but it can be a 0 x k matrix. """ Inverse """ MapOptions(;kwargs...) Creates options for parameterized map. All possible keyword arguments are in example, with some important arguments described below. See C++ documentation for an exhaustive description. # Arguments - `basisType::String`: Includes "ProbabilistHermite", "PhysicistHermite", "HermiteFunctions" - `basisLB::Float64`,`basisUB::Float64`: The bounds for where we start linearizing the map. These default to infinities, but often making the data near the origin and setting them to a small finite number (e.g. +-3) works well. # Example ```jldoctest julia> MapOptions(basisType="HermiteFunctions", basisLB=-3., basisUB=3.) basisType = HermiteFunctions basisLB = -3 basisUB = 3 basisNorm = true posFuncType = SoftPlus quadType = AdaptiveSimpson quadAbsTol = 1e-06 quadRelTol = 1e-06 quadMaxSub = 30 quadMinSub = 0 quadPts = 5 contDeriv = true nugget = 0 ``` See also [`CreateComponent`](@ref), [`TriangularMap`](@ref), [`CreateTriangular`](@ref) """ function MapOptions(;kwargs...) opts = __MapOptions() for kwarg in kwargs field = Symbol("__"*string(first(kwarg))*"!") value = last(kwarg) if value isa String value = MParT.eval(Meta.parse("__"*value)) end getfield(MParT, field)(opts, value) end opts end """ `TrainOptions(;kwargs...)` Creates options for using `TrainMap` to train a transport map. See example for possible arguments. # Examples ```jldoctest julia> TrainOptions(opt_alg="LD_SLSQP", opt_maxeval = 1_000_000) opt_alg = LD_SLSQP opt_stopval = -inf opt_ftol_rel = 0.001 opt_ftol_abs = 0.001 opt_xtol_rel = 0.0001 opt_xtol_abs = 0.0001 opt_maxeval = 1000000 opt_maxtime = inf verbose = 0 ``` See also [`TrainMap`](@ref), [`CreateGaussianKLObjective`](@ref) """ function TrainOptions(;kwargs...) opts = __TrainOptions() for kwarg in kwargs field = Symbol("__"*string(first(kwarg))*"!") value = last(kwarg) getfield(MParT, field)(opts, value) end opts end """ CreateGaussianKLObjective(train) CreateGaussianKLObjective(train, outputDim) CreateGaussianKLObjective(train, test) CreateGaussianKLObjective(train, test, outputDim) Create an objective for the optimization problem of training a transport map. Currently only supports variational simulation-based inference, i.e. creating a map that uses samples `train` from target distribution and a Gaussian reference distribution of dimension `outputDim`. If `outputDim` is zero, this is equivalent to when `outputDim == size(train,1)`. # Arguments - `train::Matrix{Float64}`: mandatory training dataset - `test::Matrix{Float64}`: optional test dataset - `outputDim::Int = 0`: Dimensions of output of map # Examples ```jldoctest julia> using Random; rng = Random.Xoshiro(1); julia> # Replace RNG type with MersenneTwister for <1.7 julia> N, inDim, outDim = 1000, 4, 2; julia> samples = 2*randn(rng, inDim, N) .+ 5; julia> obj1 = CreateGaussianKLObjective(samples); julia> obj2 = CreateGaussianKLObjective(samples, outDim); julia> train, test = samples[:,1:500], samples[:,501:end]; julia> obj3 = CreateGaussianKLObjective(train, test); julia> obj4 = CreateGaussianKLObjective(train, test, outDim); ``` See also [`TrainMap`](@ref), [`TrainOptions`](@ref) """ CreateGaussianKLObjective CreateGaussianKLObjective(train::Matrix{Float64}) = CreateGaussianKLObjective(train,0) CreateGaussianKLObjective(train::Matrix{Float64},test::Matrix{Float64}) = CreateGaussianKLObjective(train,test,0) """ TestError(obj::MapObjective, map) Uses the test dataset in obj to evaluate the error of `map`. """ TestError """ `ATMOptions(;kwargs...)` Options for using the Adaptive Transport Map algorithm from [Baptista, et al.](https://arxiv.org/pdf/2009.10303.pdf) Inherits all keywords from `MapOptions` and `TrainOptions`, plus the arguments below. # Arguments - `maxPatience::Int`: Number of "stationary" algorithm iterations tolerated - `maxSize::Int`: the _total_ number of multiindices in the _entire map_ that the algorithm is allowed to add. Should be larger than the sum of the sizes of all multiindex sets across all dimensions for the map - `maxDegrees::MultiIndex`: The maximum degree of any expansion term for each dimension (should be length of dimensions of the map) # Examples ```jldoctest julia> maxDegrees = MultiIndex(2,3); # limit both dimensions by order 3 julia> ATMOptions(maxDegrees=maxDegrees); ``` See also [`TrainMapAdaptive`](@ref), [`TrainOptions`](@ref), [`MapOptions`](@ref) """ function ATMOptions(;kwargs...) opts = __ATMOptions() for kwarg in kwargs field = Symbol("__"*string(first(kwarg))*"!") value = last(kwarg) if value isa String && !startswith(value, "opt") && value != "verbose" value = MParT.eval(Meta.parse("__"*value)) end getfield(MParT, field)(opts, value) end opts end # To print MapOptions, TrainOptions objects Base.show(io::IO,::MIME"text/plain", opts::__MapOptions) = print(io,string(opts)) Base.show(io::IO,::MIME"text/plain", opts::__TrainOptions) = print(io,string(opts)) Base.show(io::IO,::MIME"text/plain",opts::__ATMOptions) = print(io, string(opts)) """ DeserializeMap(filename::String) REQUIRES CEREAL INSTALLATION. Deserializes a map and returns its input dimension, output dimension, and coefficient. """ function DeserializeMap(filename::String) dims = Cint[0,0] coeffs = __DeserializeMap(filename, dims); dims[1], dims[2], coeffs end """ Deserialize(obj, filename) Deserializes `filename` and puts the contents in `obj`. REQUIRES CEREAL INSTALLATION. The object `obj` can be of type `MapOptions` or `FixedMultiIndexSet`. This will create a new pointer-- other objects with the same pointer will not be modified, but the contents of `obj` will now point to the deserialized object. """ Deserialize """ Serialize(obj, filename) Serializes `obj` into file `filename`. REQUIRES CEREAL INSTALLATION. """ Serialize """ TrainMap(map, obj::MapObjective, opts::TrainOptions) Trains `map` according to the objective `obj` with training options `opts`. """ TrainMap """ TrainMapAdaptive(msets, objective, options) Implements the ATM algorithm [Baptista, et al.](https://arxiv.org/pdf/2009.10303.pdf) Takes in initial guess of multiindex sets for each output dimension and adapts those sets to better approximate the probability distribution of interest using monotone transport maps. # Examples """ function TrainMapAdaptive(msets::Vector{<:MultiIndexSet},obj::CxxWrap.StdLib.SharedPtr{<:MapObjective}, opts::__ATMOptions) msets_vec = [CxxRef(mset) for mset in msets] TrainMapAdaptive(msets_vec, obj, opts) end """ TriangularMap(maps::Vector, move_coeffs::Bool = true) Creates a `TriangularMap` from a vector of `ConditionalMapBase` objects. TODO: The new object takes ownership of the coeffs of the maps in `maps` if `move_coeffs` is true. # Examples ```jldoctest julia> dim, order = 5, 3; julia> msets = [FixedMultiIndexSet(d, order) for d in 1:dim]; julia> opts = MapOptions(); julia> components = [CreateComponent(mset, opts) for mset in msets]; julia> trimap = TriangularMap(components); ``` """ function TriangularMap(maps::Vector, move_coeffs::Bool = true) maps = StdVector([map for map in maps]) TriangularMap(maps, move_coeffs) end """ CreateTriangular(inDim::Int, outDim::Int, p::Int, opts::MapOptions) Creates a total order `p` map with dimensions `inDim` and `outDim` with specifications `opts`. """ CreateTriangular """ CreateComponent(mset::FixedMultiIndexSet, opts::MapOptions) Create a single-output component with approximation order given by `mset` and specified by `opts` """ CreateComponent """ ComposedMap(maps::Vector) Creates a `ComposedMap` from a vector of `ConditionalMapBase` objects. """ # TODO: Example function ComposedMap(maps::Vector{<:ConditionalMapBasePtr}) maps_std = StdVector([map for map in maps]) ComposedMap(maps_std) end """ MultiIndex(A::AbstractVector{<:Int}) MultiIndex defines the order of one term of a function expansion for each dimensions. # Example ```jldoctest julia> degrees = [3,2,1]; # Represents polynomial basis function similar to x^3y^2z^1 julia> midx = MultiIndex(degrees); julia> midx[3] 0x00000001 ``` See also [`MultiIndexSet`](@ref), [`FixedMultiIndexSet`](@ref), [`Fix`](@ref) """ MultiIndex(A::AbstractVector{<:Int}) = MultiIndex(StdVector(Cuint.(A))) # MultiIndex-related exports export MultiIndex, MultiIndexSet, FixedMultiIndexSet export Fix, CreateTotalOrder, Size, addto! # ParameterizedFunctionBase-related exports export CoeffMap, SetCoeffs, numCoeffs, inputDim, outputDim export Evaluate, CoeffGrad, Gradient # ConditionalMapBase-related exports export ConditionalMapBasePtr, GetBaseFunction, LogDeterminant, LogDeterminantCoeffGrad, Inverse # TriangularMap-related exports export TriangularMap, InverseInplace, GetComponent # AffineMap-related exports export AffineMap, AffineFunction # ComposedMap-related exports export ComposedMap # MapFactory-related exports export CreateComponent, CreateTriangular # MapOptions-related exports export MapOptions # Serialization-related exports export Serialize, Deserialize, DeserializeMap # Map training related exports export CreateGaussianKLObjective, TrainOptions, TrainMap, TestError # ATM-related exports export TrainMapAdaptive, ATMOptions # Other important utils export Concurrency end
MParT
https://github.com/MeasureTransport/MParT.jl.git
[ "BSD-3-Clause" ]
2.2.2
d83d40d4553ac35482d51360735140b1a5818808
code
1316
using MParT using Distributions, LinearAlgebra, Statistics using Optimization, OptimizationOptimJL ## Geometry num_points = 1000 xmin, xmax = 0,4 x = collect(range(xmin, xmax, length=num_points)') # Measurements noisesd = 0.4 # Notes: data might not be monotone bc of the noise # but we assume the true underlying function is monotone y_true = 2*(x .> 2) y_noise = noisesd*randn(1,num_points) y_measured = y_true + y_noise # Create MultiIndexSet multis = collect(reshape(0:5,6,1)) mset = MultiIndexSet(multis) fixed_mset = Fix(mset, true) # Set MapOptions and make map opts = MapOptions() monotoneMap = CreateComponent(fixed_mset, opts) ## Least Squares objective function objective(coeffs,p) monotoneMap, x, y_measured = p SetCoeffs(monotoneMap, coeffs) map_of_x = Evaluate(monotoneMap, x) norm(map_of_x - y_measured)^2/size(x,2) end # Before Optimization map_of_x_before = Evaluate(monotoneMap, x) u0 = CoeffMap(monotoneMap) p = (monotoneMap, x, y_measured) fcn = OptimizationFunction(objective) prob = OptimizationProblem(fcn, u0, p) # Optimize sol = solve(prob, NelderMead()) u_final = sol.u SetCoeffs(monotoneMap, u_final) ## After Optimization map_of_x_after = Evaluate(monotoneMap, x) error_after = objective(u_final, p) tol = 0.5 @test abs(sqrt(error_after) - noisesd)/noisesd < tol
MParT
https://github.com/MeasureTransport/MParT.jl.git
[ "BSD-3-Clause" ]
2.2.2
d83d40d4553ac35482d51360735140b1a5818808
code
1681
using MParT using Distributions, LinearAlgebra, Statistics using Optimization, OptimizationOptimJL ## num_points = 1000 z = randn(2,num_points) x1 = z[1,:] x2 = z[2,:] + z[1,:].^2 x = collect([x1 x2]') test_n_pts = 10_000 test_z = randn(2,test_n_pts) test_x1 = test_z[1,:] test_x2 = test_z[2,:] + test_z[1,:].^2 test_x = collect([test_x1 test_x2]') # For computing reference density reference_density = MvNormal(I(2)) ## Set up map and initialize coefficients opts = MapOptions() tri_map = CreateTriangular(2,2,2,opts) coeffs = zeros(numCoeffs(tri_map)) function obj(coeffs, p) tri_map, x, reference_density = p SetCoeffs(tri_map, coeffs) map_of_x = Evaluate(tri_map, x) ref_density_of_map_of_x = logpdf(reference_density, map_of_x) log_det = LogDeterminant(tri_map, x) -sum(ref_density_of_map_of_x + log_det)/num_points end function grad_obj(g, coeffs, p) tri_map, x = p SetCoeffs(tri_map, coeffs) map_of_x = Evaluate(tri_map, x) grad_ref_density_of_map_of_x = -CoeffGrad(tri_map, x, map_of_x) grad_log_det = LogDeterminantCoeffGrad(tri_map, x) g .= -vec(sum(grad_ref_density_of_map_of_x + grad_log_det, dims=2))/num_points end ## Plot before Optimization u0 = CoeffMap(tri_map) p = (tri_map, x, reference_density) fcn = OptimizationFunction(obj, grad = grad_obj) prob = OptimizationProblem(fcn, u0, p, g_tol = 1e-16) ## Optimize sol = solve(prob, BFGS()) u_final = sol.u SetCoeffs(tri_map, u_final) map_of_test_x = Evaluate(tri_map, test_x) mean_of_map = mean(map_of_test_x, dims=2) cov_of_map = cov(map_of_test_x, dims=2) ## Test (heuristics) tol = 0.5 @test norm(mean_of_map) < tol @test norm(cov_of_map - I(2)) < tol
MParT
https://github.com/MeasureTransport/MParT.jl.git
[ "BSD-3-Clause" ]
2.2.2
d83d40d4553ac35482d51360735140b1a5818808
code
2104
using MParT using Distributions, LinearAlgebra, Statistics, CxxWrap A = Float64[1 2; 4 5] b = Float64[5, 6] N_samples = 1000 a_map1 = AffineMap(A, b) a_map2 = AffineMap(A) a_map3 = AffineMap(b) a_fun = AffineFunction(A, b) c_map = ComposedMap(StdVector(MParT.ConditionalMapBase[a_map2, a_map3])) ## Test the eval x = randn(size(A, 2), N_samples) y_true = A * x .+ b y1 = Evaluate(a_map1, x) y2 = Evaluate(a_map2, x) y3 = Evaluate(a_map3, y2) y_fun = Evaluate(a_fun, x) y_c = Evaluate(c_map, x) @test y1 ≈ y_true @test y3 ≈ y_true @test y_c ≈ y_true @test y_fun ≈ y_true ## Test the gradient sens = randn(size(A, 1), N_samples) g1 = Gradient(a_map1, x, sens) g2 = Gradient(a_map2, x, sens) g3 = Gradient(a_map3, x, sens) g_fun = Gradient(a_fun, x, sens) g_c = Gradient(c_map, x, sens) @test g1 ≈ A'sens @test g2 ≈ A'sens @test g3 ≈ sens @test g_c ≈ A'sens @test g_fun ≈ A'sens ## Test the log determinant true_ld = log(abs(det(A[:, end-size(A, 1)+1:end]))) ld1 = LogDeterminant(a_map1, x) ld2 = LogDeterminant(a_map2, x) ld3 = LogDeterminant(a_map3, x) ld_c = LogDeterminant(c_map, x) @test ld1 ≈ fill(true_ld, size(x,2)) @test ld2 ≈ fill(true_ld, size(x,2)) @test ld3 ≈ zeros(size(x,2)) @test ld_c ≈ fill(true_ld, size(x,2)) ## Rectangular A A = Float64[1 2 3; 4 5 6] b = Float64[5, 6] a_rect1 = AffineMap(A, b) a_rect2 = AffineMap(A) a_funr = AffineFunction(A, b) ## Test the eval x = randn(size(A, 2), N_samples) y_true = A * x .+ b y1 = Evaluate(a_rect1, x) y2 = Evaluate(a_rect2, x) y3 = Evaluate(a_map3, y2) y_fun = Evaluate(a_funr, x) @test y1 ≈ y_true @test y3 ≈ y_true @test y_fun ≈ y_true ## Test the gradient sens = randn(size(A, 1), N_samples) g1 = Gradient(a_rect1, x, sens) g2 = Gradient(a_rect2, x, sens) g_fun = Gradient(a_funr, x, sens) @test g1 ≈ A'sens @test g2 ≈ A'sens @test g_fun ≈ A'sens ## Test the log determinant true_ld = log(abs(det(A[:, end-size(A, 1)+1:end]))) ld1 = LogDeterminant(a_rect1, x) ld2 = LogDeterminant(a_rect2, x) ld3 = LogDeterminant(a_map3, x) @test ld1 ≈ fill(true_ld, size(x,2)) @test ld2 ≈ fill(true_ld, size(x,2)) @test ld3 ≈ zeros(size(x,2))
MParT
https://github.com/MeasureTransport/MParT.jl.git
[ "BSD-3-Clause" ]
2.2.2
d83d40d4553ac35482d51360735140b1a5818808
code
1649
# MultiIndex test multis = [0 1; 2 0] msetFromArray = MultiIndexSet(multis) dim = 3 power = 4 msetTotalOrder = CreateTotalOrder(dim, power) function test_max_degrees() @test Int.(MParT.MaxOrders(msetFromArray)) == [2, 1] @test Int.(MParT.MaxOrders(msetTotalOrder)) == [4, 4, 4] end function test_reduced_margin() msetTotalOrder2 = CreateTotalOrder(dim, power+1) msetTotalOrder_rm = MParT.ReducedMargin(msetTotalOrder) @test length(msetTotalOrder_rm) == Size(msetTotalOrder2) - Size(msetTotalOrder) @test all([sum(midx) == power+1 for midx in msetTotalOrder_rm]) msetTotalOrder_rm_dim = MParT.ReducedMarginDim(msetTotalOrder,2) @test all([sum(midx) == power+1 for midx in msetTotalOrder_rm_dim]) @test length(msetTotalOrder_rm_dim) < length(msetTotalOrder_rm) # Tests weird memory bug where ReducedDim returns objects that get garbage collected dims_add = [1, 2] # Without the additional constructor, the MultiIndex objects get gc'd msetTotalOrder_rm_dim = reduce(vcat, MultiIndex.(MParT.ReducedMarginDim(msetTotalOrder, d)) for d in dims_add) mset_strings = string.(string.(msetTotalOrder_rm_dim)) # Just test that things don't crash, i.e. we didn't segfault @test mset_strings[1] isa AbstractString end function test_at() @test msetFromArray[1] == MultiIndex([0, 1]) @test msetFromArray[2] == MultiIndex([2, 0]) @test msetTotalOrder[1] == MultiIndex([0, 0, 0]) @test msetTotalOrder[2] == MultiIndex([0, 0, 1]) last_idx = Size(msetTotalOrder) @test msetTotalOrder[last_idx] == MultiIndex([4, 0, 0]) end test_max_degrees() test_reduced_margin() test_at()
MParT
https://github.com/MeasureTransport/MParT.jl.git
[ "BSD-3-Clause" ]
2.2.2
d83d40d4553ac35482d51360735140b1a5818808
code
496
using Test, MParT @testset "MParT.jl" begin # @testset "Affine, Composed Map" begin # This test doesn't work due to weird constructor # include("mapTypeTest.jl") # end @testset "MultiIndex" begin include("multiindex.jl") end @testset "Monotone Least Squares" begin include("MLS.jl") end @testset "2D Banana From Samples" begin include("banana2D.jl") end @testset "TrainMap" begin include("trainMapTest.jl") end end
MParT
https://github.com/MeasureTransport/MParT.jl.git
[ "BSD-3-Clause" ]
2.2.2
d83d40d4553ac35482d51360735140b1a5818808
code
1466
using Distributions function KS_statistic(map, samples) pullback_evals = Evaluate(map,samples) ## Perform Kolmogorov-Smirnov test sorted_samples = sort(pullback_evals[:]) dist = Normal() samps_cdf = cdf.((dist,),sorted_samples) samps_ecdf = (1:length(sorted_samples))/length(sorted_samples) maximum(abs.(samps_cdf - samps_ecdf)) end ## Create data dim = 2 N=20_000 N_test = N÷5 data = randn(dim+1,N) target = collect(hcat(data[1,:],data[2,:], data[3,:] + data[2,:].^2)') test = target[:,1:N_test] train = target[:,N_test+1:end] ## Create objective and map obj1 = CreateGaussianKLObjective(train,test,1) obj2 = CreateGaussianKLObjective(train,test,2) obj3 = CreateGaussianKLObjective(train,test) map_options = MapOptions() max_order = 2 map1 = CreateComponent(FixedMultiIndexSet(dim+1,max_order),map_options) map2 = CreateTriangular(dim+1,dim,max_order,map_options) map3 = CreateTriangular(dim+1,dim+1,max_order,map_options) ## Train the map train_options = TrainOptions() TrainMap(map1, obj1, train_options) TrainMap(map2, obj2, train_options) TrainMap(map3, obj3, train_options) ## Check the testing and training error @test TestError(obj1, map1) < 5. @test TestError(obj2, map2) < 5. @test TestError(obj3, map3) < 5. ## Evaluate test samples after training KS_stat1 = KS_statistic(map1,test) KS_stat2 = KS_statistic(map2,test) KS_stat3 = KS_statistic(map3,test) ## @test KS_stat1 < 0.1 @test KS_stat2 < 0.1 @test KS_stat3 < 0.1
MParT
https://github.com/MeasureTransport/MParT.jl.git
[ "BSD-3-Clause" ]
2.2.2
d83d40d4553ac35482d51360735140b1a5818808
docs
434
# MParT [![Stable](https://img.shields.io/badge/docs-stable-blue.svg)](https://MeasureTransport.github.io/MParT.jl/stable/) [![Dev](https://img.shields.io/badge/docs-dev-blue.svg)](https://MeasureTransport.github.io/MParT.jl/dev/) [![Build Status](https://github.com/MeasureTransport/MParT.jl/actions/workflows/CI.yml/badge.svg?branch=main)](https://github.com/MeasureTransport/MParT.jl/actions/workflows/CI.yml?query=branch%3Amain)
MParT
https://github.com/MeasureTransport/MParT.jl.git
[ "BSD-3-Clause" ]
2.2.2
d83d40d4553ac35482d51360735140b1a5818808
docs
112
```@meta CurrentModule = MParT ``` # _Adaptive_ Map Training Routines ```@docs TrainMapAdaptive ATMOptions ```
MParT
https://github.com/MeasureTransport/MParT.jl.git
[ "BSD-3-Clause" ]
2.2.2
d83d40d4553ac35482d51360735140b1a5818808
docs
119
```@meta CurrentModule = MParT ``` # Routines not available via Pkg ```@docs Serialize Deserialize DeserializeMap ```
MParT
https://github.com/MeasureTransport/MParT.jl.git
[ "BSD-3-Clause" ]
2.2.2
d83d40d4553ac35482d51360735140b1a5818808
docs
654
```@meta CurrentModule = MParT ``` # MParT Documentation for [MParT.jl](https://github.com/MeasureTransport/MParT.jl). This documentation is incomplete and only features some basic functionality. For documentation of all functions as well as source installation instructions, other binding information, and many examples, please look at the [C++ documentation](https://measuretransport.github.io/MParT/). If there's a function there unavailable in Julia, please let the developers know via a GitHub issue. ```@contents Pages = ["multiindex.md", "map.md", "trainmap.md", "adaptivemap.md", "extras.md"] ``` # General Utilities ```@docs Concurrency ```
MParT
https://github.com/MeasureTransport/MParT.jl.git
[ "BSD-3-Clause" ]
2.2.2
d83d40d4553ac35482d51360735140b1a5818808
docs
157
```@meta CurrentModule = MParT ``` # Basic map Routines ```@docs Evaluate Inverse ComposedMap MapOptions TriangularMap CreateTriangular CreateComponent ```
MParT
https://github.com/MeasureTransport/MParT.jl.git
[ "BSD-3-Clause" ]
2.2.2
d83d40d4553ac35482d51360735140b1a5818808
docs
149
```@meta CurrentModule = MParT ``` # MultiIndex-related routines ```@docs MultiIndex MultiIndexSet FixedMultiIndexSet Fix CreateTotalOrder Size ```
MParT
https://github.com/MeasureTransport/MParT.jl.git
[ "BSD-3-Clause" ]
2.2.2
d83d40d4553ac35482d51360735140b1a5818808
docs
131
```@meta CurrentModule = MParT ``` # Map Training Routines ```@docs CreateGaussianKLObjective TrainOptions TrainMap TestError ```
MParT
https://github.com/MeasureTransport/MParT.jl.git
[ "MIT" ]
0.11.0
0aa4c2634bd49313759411a3c22b3f0338b7739e
code
733
using QuantumESPRESSO using Documenter DocMeta.setdocmeta!(QuantumESPRESSO, :DocTestSetup, :(using QuantumESPRESSO); recursive=true) makedocs(; modules=[QuantumESPRESSO], authors="singularitti <[email protected]> and contributors", repo="https://github.com/MineralsCloud/QuantumESPRESSO.jl/blob/{commit}{path}#{line}", sitename="QuantumESPRESSO.jl", format=Documenter.HTML(; prettyurls=get(ENV, "CI", "false") == "true", canonical="https://MineralsCloud.github.io/QuantumESPRESSO.jl", edit_link="main", assets=String[], ), pages=[ "Home" => "index.md", ], ) deploydocs(; repo="github.com/MineralsCloud/QuantumESPRESSO.jl", devbranch="main", )
QuantumESPRESSO
https://github.com/MineralsCloud/QuantumESPRESSO.jl.git
[ "MIT" ]
0.11.0
0aa4c2634bd49313759411a3c22b3f0338b7739e
code
89
module Commands using Reexport: @reexport @reexport using QuantumESPRESSOCommands end
QuantumESPRESSO
https://github.com/MineralsCloud/QuantumESPRESSO.jl.git
[ "MIT" ]
0.11.0
0aa4c2634bd49313759411a3c22b3f0338b7739e
code
135
module PHonon using Reexport: @reexport @reexport using QuantumESPRESSOBase.PHonon @reexport using QuantumESPRESSOParser.PHonon end
QuantumESPRESSO
https://github.com/MineralsCloud/QuantumESPRESSO.jl.git
[ "MIT" ]
0.11.0
0aa4c2634bd49313759411a3c22b3f0338b7739e
code
179
module PWscf using Reexport: @reexport @reexport using QuantumESPRESSOBase.PWscf @reexport using QuantumESPRESSOParser.PWscf @reexport using QuantumESPRESSOFormatter.PWscf end
QuantumESPRESSO
https://github.com/MineralsCloud/QuantumESPRESSO.jl.git
[ "MIT" ]
0.11.0
0aa4c2634bd49313759411a3c22b3f0338b7739e
code
290
module QuantumESPRESSO using Reexport: @reexport @reexport using QuantumESPRESSOBase @reexport using QuantumESPRESSOParser @reexport using QuantumESPRESSOParser: InvalidInput @reexport using QuantumESPRESSOFormatter include("PWscf.jl") include("PHonon.jl") # include("Commands.jl") end
QuantumESPRESSO
https://github.com/MineralsCloud/QuantumESPRESSO.jl.git
[ "MIT" ]
0.11.0
0aa4c2634bd49313759411a3c22b3f0338b7739e
code
74
using QuantumESPRESSO using Test @testset "QuantumESPRESSO.jl" begin end
QuantumESPRESSO
https://github.com/MineralsCloud/QuantumESPRESSO.jl.git
[ "MIT" ]
0.11.0
0aa4c2634bd49313759411a3c22b3f0338b7739e
docs
5226
# Contributor Covenant Code of Conduct ## Our Pledge We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. ## Our Standards Examples of behavior that contributes to a positive environment for our community include: * Demonstrating empathy and kindness toward other people * Being respectful of differing opinions, viewpoints, and experiences * Giving and gracefully accepting constructive feedback * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience * Focusing on what is best not just for us as individuals, but for the overall community Examples of unacceptable behavior include: * The use of sexualized language or imagery, and sexual attention or advances of any kind * Trolling, insulting or derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or email address, without their explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting ## Enforcement Responsibilities Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful. Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate. ## Scope This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at [email protected]. All complaints will be reviewed and investigated promptly and fairly. All community leaders are obligated to respect the privacy and security of the reporter of any incident. ## Enforcement Guidelines Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct: ### 1. Correction **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community. **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested. ### 2. Warning **Community Impact**: A violation through a single incident or series of actions. **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban. ### 3. Temporary Ban **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior. **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban. ### 4. Permanent Ban **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals. **Consequence**: A permanent ban from any sort of public interaction within the community. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0, available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity). [homepage]: https://www.contributor-covenant.org For answers to common questions about this code of conduct, see the FAQ at https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
QuantumESPRESSO
https://github.com/MineralsCloud/QuantumESPRESSO.jl.git
[ "MIT" ]
0.11.0
0aa4c2634bd49313759411a3c22b3f0338b7739e
docs
4687
<div align="center"> <img src="https://raw.githubusercontent.com/MineralsCloud/QuantumESPRESSO.jl/master/docs/src/assets/logo.png" height="200"><br> </div> # QuantumESPRESSO | **Documentation** | **Build Status** | **Others** | | :--------------------------------------------------------------------------------: | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | :---------------------------------------------------------------------------------------: | | [![Stable][docs-stable-img]][docs-stable-url] [![Dev][docs-dev-img]][docs-dev-url] | [![Build Status][gha-img]][gha-url] [![Build Status][appveyor-img]][appveyor-url] [![Build Status][cirrus-img]][cirrus-url] [![pipeline status][gitlab-img]][gitlab-url] [![Coverage][codecov-img]][codecov-url] | [![GitHub license][license-img]][license-url] [![Code Style: Blue][style-img]][style-url] | [docs-stable-img]: https://img.shields.io/badge/docs-stable-blue.svg [docs-stable-url]: https://MineralsCloud.github.io/QuantumESPRESSO.jl/stable [docs-dev-img]: https://img.shields.io/badge/docs-dev-blue.svg [docs-dev-url]: https://MineralsCloud.github.io/QuantumESPRESSO.jl/dev [gha-img]: https://github.com/MineralsCloud/QuantumESPRESSO.jl/workflows/CI/badge.svg [gha-url]: https://github.com/MineralsCloud/QuantumESPRESSO.jl/actions [appveyor-img]: https://ci.appveyor.com/api/projects/status/github/MineralsCloud/QuantumESPRESSO.jl?svg=true [appveyor-url]: https://ci.appveyor.com/project/singularitti/QuantumESPRESSO-jl [cirrus-img]: https://api.cirrus-ci.com/github/MineralsCloud/QuantumESPRESSO.jl.svg [cirrus-url]: https://cirrus-ci.com/github/MineralsCloud/QuantumESPRESSO.jl [gitlab-img]: https://gitlab.com/singularitti/QuantumESPRESSO.jl/badges/main/pipeline.svg [gitlab-url]: https://gitlab.com/singularitti/QuantumESPRESSO.jl/-/pipelines [codecov-img]: https://codecov.io/gh/MineralsCloud/QuantumESPRESSO.jl/branch/main/graph/badge.svg [codecov-url]: https://codecov.io/gh/MineralsCloud/QuantumESPRESSO.jl [license-img]: https://img.shields.io/github/license/MineralsCloud/QuantumESPRESSO.jl [license-url]: https://github.com/MineralsCloud/QuantumESPRESSO.jl/blob/main/LICENSE [style-img]: https://img.shields.io/badge/code%20style-blue-4495d1.svg [style-url]: https://github.com/invenia/BlueStyle QuantumESPRESSO.jl is simply a wrapper of the types, methods, and commands defined in [QuantumESPRESSOBase.jl](https://github.com/MineralsCloud/QuantumESPRESSOBase.jl), [QuantumESPRESSOParser.jl](https://github.com/MineralsCloud/QuantumESPRESSOParser.jl), [QuantumESPRESSOFormatter.jl](https://github.com/MineralsCloud/QuantumESPRESSOFormatter.jl), and [QuantumESPRESSOCommands.jl](https://github.com/MineralsCloud/QuantumESPRESSOCommands.jl) under a common namespace. The code is [hosted on GitHub](https://github.com/MineralsCloud/QuantumESPRESSO.jl), with some continuous integration services to test its validity. This repository is created and maintained by [@singularitti](https://github.com/singularitti). You are very welcome to contribute. ## Installation The package can be installed with the Julia package manager. From the Julia REPL, type `]` to enter the Pkg REPL mode and run: ``` pkg> add QuantumESPRESSO ``` Or, equivalently, via the [`Pkg` API](https://pkgdocs.julialang.org/v1/getting-started/): ```julia julia> import Pkg; Pkg.add("QuantumESPRESSO") ``` ## Documentation - [**STABLE**][docs-stable-url] — **documentation of the most recently tagged version.** - [**DEV**][docs-dev-url] — _documentation of the in-development version._ ## Project status The package is tested against, and being developed for, Julia `1.6` and above on Linux, macOS, and Windows. ## Questions and contributions You are welcome to post usage questions on [our discussion page][discussions-url]. Contributions are very welcome, as are feature requests and suggestions. Please open an [issue][issues-url] if you encounter any problems. The [Contributing](@ref) page has guidelines that should be followed when opening pull requests and contributing code. [discussions-url]: https://github.com/MineralsCloud/QuantumESPRESSO.jl/discussions [issues-url]: https://github.com/MineralsCloud/QuantumESPRESSO.jl/issues
QuantumESPRESSO
https://github.com/MineralsCloud/QuantumESPRESSO.jl.git
[ "MIT" ]
0.11.0
0aa4c2634bd49313759411a3c22b3f0338b7739e
docs
2475
```@meta CurrentModule = QuantumESPRESSO ``` # QuantumESPRESSO Documentation for [QuantumESPRESSO](https://github.com/MineralsCloud/QuantumESPRESSO.jl). QuantumESPRESSO.jl is simply a wrapper of the types, methods, and commands defined in [QuantumESPRESSOBase.jl](https://github.com/MineralsCloud/QuantumESPRESSOBase.jl), [QuantumESPRESSOParser.jl](https://github.com/MineralsCloud/QuantumESPRESSOParser.jl), [QuantumESPRESSOFormatter.jl](https://github.com/MineralsCloud/QuantumESPRESSOFormatter.jl), and [QuantumESPRESSOCommands.jl](https://github.com/MineralsCloud/QuantumESPRESSOCommands.jl) under a common namespace. See the [Index](@ref main-index) for the complete list of documented functions and types. The code is [hosted on GitHub](https://github.com/MineralsCloud/QuantumESPRESSO.jl), with some continuous integration services to test its validity. This repository is created and maintained by [@singularitti](https://github.com/singularitti). You are very welcome to contribute. ## Installation The package can be installed with the Julia package manager. From the Julia REPL, type `]` to enter the Pkg REPL mode and run: ```julia pkg> add QuantumESPRESSO ``` Or, equivalently, via the `Pkg` API: ```@repl import Pkg; Pkg.add("QuantumESPRESSO") ``` ## Documentation - [**STABLE**](https://MineralsCloud.github.io/QuantumESPRESSO.jl/stable) — **documentation of the most recently tagged version.** - [**DEV**](https://MineralsCloud.github.io/QuantumESPRESSO.jl/dev) — _documentation of the in-development version._ ## Project status The package is tested against, and being developed for, Julia `1.6` and above on Linux, macOS, and Windows. ## Questions and contributions Usage questions can be posted on [our discussion page](https://github.com/MineralsCloud/QuantumESPRESSO.jl/discussions). Contributions are very welcome, as are feature requests and suggestions. Please open an [issue](https://github.com/MineralsCloud/QuantumESPRESSO.jl/issues) if you encounter any problems. The [Contributing](@ref) page has a few guidelines that should be followed when opening pull requests and contributing code. ## Manual outline ```@contents Pages = [ "installation.md", "developers/contributing.md", "developers/style-guide.md", "developers/design-principles.md", "troubleshooting.md", ] Depth = 3 ``` ## Library outline ```@contents Pages = ["public.md"] ``` ### [Index](@id main-index) ```@index Pages = ["public.md"] ```
QuantumESPRESSO
https://github.com/MineralsCloud/QuantumESPRESSO.jl.git
[ "MIT" ]
0.11.0
0aa4c2634bd49313759411a3c22b3f0338b7739e
docs
5297
# [Installation Guide](@id installation) ```@contents Pages = ["installation.md"] Depth = 2 ``` Here are the installation instructions for package [QuantumESPRESSO](https://github.com/MineralsCloud/QuantumESPRESSO.jl). If you have trouble installing it, please refer to our [Troubleshooting](@ref) page for more information. ## Install Julia First, you should install [Julia](https://julialang.org/). We recommend downloading it from [its official website](https://julialang.org/downloads/). Please follow the detailed instructions on its website if you have to [build Julia from source](https://docs.julialang.org/en/v1/devdocs/build/build/). Some computing centers provide preinstalled Julia. Please contact your administrator for more information in that case. Here's some additional information on [how to set up Julia on HPC systems](https://github.com/hlrs-tasc/julia-on-hpc-systems). If you have [Homebrew](https://brew.sh) installed, [open `Terminal.app`](https://support.apple.com/guide/terminal/open-or-quit-terminal-apd5265185d-f365-44cb-8b09-71a064a42125/mac) and type ```bash brew install julia ``` to install it as a [formula](https://docs.brew.sh/Formula-Cookbook). If you are also using macOS and want to install it as a prebuilt binary app, type ```bash brew install --cask julia ``` instead. If you want to install multiple Julia versions in the same operating system, a recommended way is to use a version manager such as [`juliaup`](https://github.com/JuliaLang/juliaup). First, [install `juliaup`](https://github.com/JuliaLang/juliaup#installation). Then, run ```bash juliaup add release juliaup default release ``` to configure the `julia` command to start the latest stable version of Julia (this is also the default value). There is a [short video introduction to `juliaup`](https://youtu.be/14zfdbzq5BM) made by its authors. ### Which version should I pick? You can install the "Current stable release" or the "Long-term support (LTS) release". - The "Current stable release" is the latest release of Julia. It has access to newer features, and is likely faster. - The "Long-term support release" is an older version of Julia that has continued to receive bug and security fixes. However, it may not have the latest features or performance improvements. For most users, you should install the "Current stable release", and whenever Julia releases a new version of the current stable release, you should update your version of Julia. Note that any code you write on one version of the current stable release will continue to work on all subsequent releases. For users in restricted software environments (e.g., your enterprise IT controls what software you can install), you may be better off installing the long-term support release because you will not have to update Julia as frequently. Versions higher than `v1.3`, especially `v1.6`, are strongly recommended. This package may not work on `v1.0` and below. Since the Julia team has set `v1.6` as the LTS release, we will gradually drop support for versions below `v1.6`. Julia and Julia packages support multiple operating systems and CPU architectures; check [this table](https://julialang.org/downloads/#supported_platforms) to see if it can be installed on your machine. For Mac computers with M-series processors, this package and its dependencies may not work. Please install the Intel-compatible version of Julia (for macOS x86-64) if any platform-related error occurs. ## Install QuantumESPRESSO Now I am using [macOS](https://en.wikipedia.org/wiki/MacOS) as a standard platform to explain the following steps: 1. Open `Terminal.app`, and type `julia` to start an interactive session (known as the [REPL](https://docs.julialang.org/en/v1/stdlib/REPL/)). 2. Run the following commands and wait for them to finish: ```julia-repl julia> using Pkg julia> Pkg.update() julia> Pkg.add("QuantumESPRESSO") ``` 3. Run ```julia-repl julia> using QuantumESPRESSO ``` and have fun! 4. While using, please keep this Julia session alive. Restarting might cost some time. If you want to install the latest in-development (probably buggy) version of QuantumESPRESSO, type ```@repl using Pkg Pkg.update() pkg"add https://github.com/MineralsCloud/QuantumESPRESSO.jl" ``` in the second step above. ## Update QuantumESPRESSO Please [watch](https://docs.github.com/en/account-and-profile/managing-subscriptions-and-notifications-on-github/setting-up-notifications/configuring-notifications#configuring-your-watch-settings-for-an-individual-repository) our [GitHub repository](https://github.com/MineralsCloud/QuantumESPRESSO.jl) for new releases. Once we release a new version, you can update QuantumESPRESSO by typing ```@repl using Pkg Pkg.update("QuantumESPRESSO") Pkg.gc() ``` in the Julia REPL. ## Uninstall and reinstall QuantumESPRESSO Sometimes errors may occur if the package is not properly installed. In this case, you may want to uninstall and reinstall the package. Here is how to do that: 1. To uninstall, in a Julia session, run ```julia-repl julia> using Pkg julia> Pkg.rm("QuantumESPRESSO") julia> Pkg.gc() ``` 2. Press `ctrl+d` to quit the current session. Start a new Julia session and reinstall QuantumESPRESSO.
QuantumESPRESSO
https://github.com/MineralsCloud/QuantumESPRESSO.jl.git
[ "MIT" ]
0.11.0
0aa4c2634bd49313759411a3c22b3f0338b7739e
docs
2153
# Troubleshooting ```@contents Pages = ["troubleshooting.md"] Depth = 2 ``` This page collects some possible errors you may encounter and trick how to fix them. If you have some questions about how to use this code, you are welcome to [discuss with us](https://github.com/MineralsCloud/QuantumESPRESSO.jl/discussions). If you have additional tips, please either [report an issue](https://github.com/MineralsCloud/QuantumESPRESSO.jl/issues/new) or [submit a PR](https://github.com/MineralsCloud/QuantumESPRESSO.jl/compare) with suggestions. ## Installation problems ### Cannot find the `julia` executable Make sure you have Julia installed in your environment. Please download the latest [stable version](https://julialang.org/downloads/#current_stable_release) for your platform. If you are using a *nix system, the recommended way is to use [Juliaup](https://github.com/JuliaLang/juliaup). If you do not want to install Juliaup or you are using other platforms that Julia supports, download the corresponding binaries. Then, create a symbolic link to the Julia executable. If the path is not in your `$PATH` environment variable, export it to your `$PATH`. Some clusters, like [Habanero](https://confluence.columbia.edu/confluence/display/rcs/Habanero+HPC+Cluster+User+Documentation), [Comet](https://www.sdsc.edu/support/user_guides/comet.html), or [Expanse](https://www.sdsc.edu/services/hpc/expanse/index.html), already have Julia installed as a module, you may just `module load julia` to use it. If not, either install by yourself or contact your administrator. ## Loading QuantumESPRESSO ### Julia compiles/loads slow First, we recommend you download the latest version of Julia. Usually, the newest version has the best performance. If you just want Julia to do a simple task and only once, you could start the Julia REPL with ```bash julia --compile=min ``` to minimize compilation or ```bash julia --optimize=0 ``` to minimize optimizations, or just use both. Or you could make a system image and run with ```bash julia --sysimage custom-image.so ``` See [Fredrik Ekre's talk](https://youtu.be/IuwxE3m0_QQ?t=313) for details.
QuantumESPRESSO
https://github.com/MineralsCloud/QuantumESPRESSO.jl.git
[ "MIT" ]
0.11.0
0aa4c2634bd49313759411a3c22b3f0338b7739e
docs
8770
# Contributing ```@contents Pages = ["contributing.md"] Depth = 2 ``` Welcome! This document explains some ways you can contribute to QuantumESPRESSO. ## Code of conduct This project and everyone participating in it is governed by the [Contributor Covenant Code of Conduct](https://github.com/MineralsCloud/.github/blob/main/CODE_OF_CONDUCT.md). By participating, you are expected to uphold this code. ## Join the community forum First up, join the [community forum](https://github.com/MineralsCloud/QuantumESPRESSO.jl/discussions). The forum is a good place to ask questions about how to use QuantumESPRESSO. You can also use the forum to discuss possible feature requests and bugs before raising a GitHub issue (more on this below). Aside from asking questions, the easiest way you can contribute to QuantumESPRESSO is to help answer questions on the forum! ## Improve the documentation Chances are, if you asked (or answered) a question on the community forum, then it is a sign that the [documentation](https://MineralsCloud.github.io/QuantumESPRESSO.jl/dev/) could be improved. Moreover, since it is your question, you are probably the best-placed person to improve it! The docs are written in Markdown and are built using [Documenter.jl](https://github.com/JuliaDocs/Documenter.jl). You can find the source of all the docs [here](https://github.com/MineralsCloud/QuantumESPRESSO.jl/tree/main/docs). If your change is small (like fixing typos or one or two sentence corrections), the easiest way to do this is via GitHub's online editor. (GitHub has [help](https://help.github.com/articles/editing-files-in-another-user-s-repository/) on how to do this.) If your change is larger or touches multiple files, you will need to make the change locally and then use Git to submit a [pull request](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/about-pull-requests). (See [Contribute code to QuantumESPRESSO](@ref) below for more on this.) ## File a bug report Another way to contribute to QuantumESPRESSO is to file [bug reports](https://github.com/MineralsCloud/QuantumESPRESSO.jl/issues/new?template=bug_report.md). Make sure you read the info in the box where you write the body of the issue before posting. You can also find a copy of that info [here](https://github.com/MineralsCloud/QuantumESPRESSO.jl/blob/main/.github/ISSUE_TEMPLATE/bug_report.md). !!! tip If you're unsure whether you have a real bug, post on the [community forum](https://github.com/MineralsCloud/QuantumESPRESSO.jl/discussions) first. Someone will either help you fix the problem or let you know the most appropriate place to open a bug report. ## Contribute code to QuantumESPRESSO Finally, you can also contribute code to QuantumESPRESSO! !!! warning If you do not have experience with Git, GitHub, and Julia development, the first steps can be a little daunting. However, there are lots of tutorials available online, including: - [GitHub](https://guides.github.com/activities/hello-world/) - [Git and GitHub](https://try.github.io/) - [Git](https://git-scm.com/book/en/v2) - [Julia package development](https://docs.julialang.org/en/v1/stdlib/Pkg/#Developing-packages-1) Once you are familiar with Git and GitHub, the workflow for contributing code to QuantumESPRESSO is similar to the following: ### Step 1: decide what to work on The first step is to find an [open issue](https://github.com/MineralsCloud/QuantumESPRESSO.jl/issues) (or open a new one) for the problem you want to solve. Then, _before_ spending too much time on it, discuss what you are planning to do in the issue to see if other contributors are fine with your proposed changes. Getting feedback early can improve code quality and avoid time spent writing code that does not get merged into QuantumESPRESSO. !!! tip At this point, remember to be patient and polite; you may get a _lot_ of comments on your issue! However, do not be afraid! Comments mean that people are willing to help you improve the code that you are contributing to QuantumESPRESSO. ### Step 2: fork QuantumESPRESSO Go to [https://github.com/MineralsCloud/QuantumESPRESSO.jl](https://github.com/MineralsCloud/QuantumESPRESSO.jl) and click the "Fork" button in the top-right corner. This will create a copy of QuantumESPRESSO under your GitHub account. ### Step 3: install QuantumESPRESSO locally Similar to [Installation](@ref), open the Julia REPL and run: ```@repl using Pkg Pkg.update() Pkg.develop("QuantumESPRESSO") ``` Then the package will be cloned to your local machine. On *nix systems, the default path is `~/.julia/dev/QuantumESPRESSO` unless you modify the [`JULIA_DEPOT_PATH`](http://docs.julialang.org/en/v1/manual/environment-variables/#JULIA_DEPOT_PATH-1) environment variable. If you're on Windows, this will be `C:\\Users\\<my_name>\\.julia\\dev\\QuantumESPRESSO`. In the following text, we will call it `PKGROOT`. Go to `PKGROOT`, start a new Julia session, and run ```@repl using Pkg Pkg.instantiate() ``` to instantiate the project. ### Step 4: checkout a new branch !!! note In the following, replace any instance of `GITHUB_ACCOUNT` with your GitHub username. The next step is to check out a development branch. In a terminal (or command prompt on Windows), run: ```bash cd ~/.julia/dev/QuantumESPRESSO git remote add GITHUB_ACCOUNT https://github.com/GITHUB_ACCOUNT/QuantumESPRESSO.jl.git git checkout main git pull git checkout -b my_new_branch ``` ### Step 5: make changes Now make any changes to the source code inside the `~/.julia/dev/QuantumESPRESSO` directory. Make sure you: - Follow our [Style Guide](@ref style) and [Run JuliaFormatter](@ref). - Add tests and documentation for any changes or new features. !!! tip When you change the source code, you'll need to restart Julia for the changes to take effect. This is a pain, so install [Revise.jl](https://github.com/timholy/Revise.jl). ### Step 6a: test your code changes To test that your changes work, run the QuantumESPRESSO test-suite by opening Julia and running: ```julia-repl julia> cd(joinpath(DEPOT_PATH[1], "dev", "QuantumESPRESSO")) julia> using Pkg julia> Pkg.activate(".") Activating new project at `~/.julia/dev/QuantumESPRESSO` julia> Pkg.test() ``` !!! warning Running the tests might take a long time. !!! tip If you are using Revise.jl, you can also run the tests by calling `include`: ```julia-repl include("test/runtests.jl") ``` This can be faster if you want to re-run the tests multiple times. ### Step 6b: test your documentation changes Open Julia, then run: ```julia-repl julia> cd(joinpath(DEPOT_PATH[1], "dev", "QuantumESPRESSO", "docs")) julia> using Pkg julia> Pkg.activate(".") Activating new project at `~/.julia/dev/QuantumESPRESSO/docs` julia> include("src/make.jl") ``` After a while, a folder `PKGROOT/docs/build` will appear. Open `PKGROOT/docs/build/index.html` with your favorite browser, and have fun! !!! warning Building the documentation might take a long time. !!! tip If there's a problem with the tests that you don't know how to fix, don't worry. Continue to step 5, and one of the QuantumESPRESSO contributors will comment on your pull request, telling you how to fix things. ### Step 7: make a pull request Once you've made changes, you're ready to push the changes to GitHub. Run: ```bash cd ~/.julia/dev/QuantumESPRESSO git add . git commit -m "A descriptive message of the changes" git push -u GITHUB_ACCOUNT my_new_branch ``` Then go to [https://github.com/MineralsCloud/QuantumESPRESSO.jl/pulls](https://github.com/MineralsCloud/QuantumESPRESSO.jl/pulls) and follow the instructions that pop up to open a pull request. ### Step 8: respond to comments At this point, remember to be patient and polite; you may get a _lot_ of comments on your pull request! However, do not be afraid! A lot of comments means that people are willing to help you improve the code that you are contributing to QuantumESPRESSO. To respond to the comments, go back to step 5, make any changes, test the changes in step 6, and then make a new commit in step 7. Your PR will automatically update. ### Step 9: cleaning up Once the PR is merged, clean-up your Git repository, ready for the next contribution! ```bash cd ~/.julia/dev/QuantumESPRESSO git checkout main git pull ``` !!! note If you have suggestions to improve this guide, please make a pull request! It's particularly helpful if you do this after your first pull request because you'll know all the parts that could be explained better. Thanks for contributing to QuantumESPRESSO!
QuantumESPRESSO
https://github.com/MineralsCloud/QuantumESPRESSO.jl.git
[ "MIT" ]
0.11.0
0aa4c2634bd49313759411a3c22b3f0338b7739e
docs
15260
# Design Principles ```@contents Pages = ["design-principles.md"] Depth = 2 ``` We adopt some [`SciML`](https://sciml.ai/) design [guidelines](https://github.com/SciML/SciMLStyle) here. Please read it before contributing! ## Consistency vs adherence According to PEP8: > A style guide is about consistency. Consistency with this style guide is important. > Consistency within a project is more important. Consistency within one module or function is the most important. > > However, know when to be inconsistent—sometimes style guide recommendations just aren't > applicable. When in doubt, use your best judgment. Look at other examples and decide what > looks best. And don’t hesitate to ask! ## Community contribution guidelines For a comprehensive set of community contribution guidelines, refer to [ColPrac](https://github.com/SciML/ColPrac). A relevant point to highlight PRs should do one thing. In the context of style, this means that PRs which update the style of a package's code should not be mixed with fundamental code contributions. This separation makes it easier to ensure that large style improvement are isolated from substantive (and potentially breaking) code changes. ## Open source contributions are allowed to start small and grow over time If the standard for code contributions is that every PR needs to support every possible input type that anyone can think of, the barrier would be too high for newcomers. Instead, the principle is to be as correct as possible to begin with, and grow the generic support over time. All recommended functionality should be tested, any known generality issues should be documented in an issue (and with a `@test_broken` test when possible). ## Generic code is preferred unless code is known to be specific For example, the code: ```@repl function f(A, B) for i in 1:length(A) A[i] = A[i] + B[i] end end ``` would not be preferred for two reasons. One is that it assumes `A` uses one-based indexing, which would fail in cases like [OffsetArrays](https://github.com/JuliaArrays/OffsetArrays.jl) and [FFTViews](https://github.com/JuliaArrays/FFTViews.jl). Another issue is that it requires indexing, while not all array types support indexing (for example, [CuArrays](https://github.com/JuliaGPU/CuArrays.jl)). A more generic compatible implementation of this function would be to use broadcast, for example: ```@repl function f(A, B) @. A = A + B end ``` which would allow support for a wider variety of array types. ## Internal types should match the types used by users when possible If `f(A)` takes the input of some collections and computes an output from those collections, then it should be expected that if the user gives `A` as an `Array`, the computation should be done via `Array`s. If `A` was a `CuArray`, then it should be expected that the computation should be internally done using a `CuArray` (or appropriately error if not supported). For these reasons, constructing arrays via generic methods, like `similar(A)`, is preferred when writing `f` instead of using non-generic constructors like `Array(undef,size(A))` unless the function is documented as being non-generic. ## Trait definition and adherence to generic interface is preferred when possible Julia provides many interfaces, for example: - [Iteration](https://docs.julialang.org/en/v1/manual/interfaces/#man-interface-iteration) - [Indexing](https://docs.julialang.org/en/v1/manual/interfaces/#Indexing) - [Broadcast](https://docs.julialang.org/en/v1/manual/interfaces/#man-interfaces-broadcasting) Those interfaces should be followed when possible. For example, when defining broadcast overloads, one should implement a `BroadcastStyle` as suggested by the documentation instead of simply attempting to bypass the broadcast system via `copyto!` overloads. When interface functions are missing, these should be added to Base Julia or an interface package, like [ArrayInterface.jl](https://github.com/JuliaArrays/ArrayInterface.jl). Such traits should be declared and used when appropriate. For example, if a line of code requires mutation, the trait `ArrayInterface.ismutable(A)` should be checked before attempting to mutate, and informative error messages should be written to capture the immutable case (or, an alternative code which does not mutate should be given). One example of this principle is demonstrated in the generation of Jacobian matrices. In many scientific applications, one may wish to generate a Jacobian cache from the user's input `u0`. A naive way to generate this Jacobian is `J = similar(u0,length(u0),length(u0))`. However, this will generate a Jacobian `J` such that `J isa Matrix`. ## Macros should be limited and only be used for syntactic sugar Macros define new syntax, and for this reason they tend to be less composable than other coding styles and require prior familiarity to be easily understood. One principle to keep in mind is, "can the person reading the code easily picture what code is being generated?". For example, a user of Soss.jl may not know what code is being generated by: ```julia @model (x, α) begin σ ~ Exponential() β ~ Normal() y ~ For(x) do xj Normal(α + β * xj, σ) end return y end ``` and thus using such a macro as the interface is not preferred when possible. However, a macro like [`@muladd`](https://github.com/SciML/MuladdMacro.jl) is trivial to picture on a code (it recursively transforms `a*b + c` to `muladd(a,b,c)` for more [accuracy and efficiency](https://en.wikipedia.org/wiki/Multiply%E2%80%93accumulate_operation)), so using such a macro for example: ```julia julia> @macroexpand(@muladd k3 = f(t + c3 * dt, @. uprev + dt * (a031 * k1 + a032 * k2))) :(k3 = f((muladd)(c3, dt, t), (muladd).(dt, (muladd).(a032, k2, (*).(a031, k1)), uprev))) ``` is recommended. Some macros in this category are: - `@inbounds` - [`@muladd`](https://github.com/SciML/MuladdMacro.jl) - `@view` - [`@named`](https://github.com/SciML/ModelingToolkit.jl) - `@.` - [`@..`](https://github.com/YingboMa/FastBroadcast.jl) Some performance macros, like `@simd`, `@threads`, or [`@turbo` from LoopVectorization.jl](https://github.com/JuliaSIMD/LoopVectorization.jl), make an exception in that their generated code may be foreign to many users. However, they still are classified as appropriate uses as they are syntactic sugar since they do (or should) not change the behavior of the program in measurable ways other than performance. ## Errors should be caught as high as possible, and error messages should be contextualized for newcomers Whenever possible, defensive programming should be used to check for potential errors before they are encountered deeper within a package. For example, if one knows that `f(u0,p)` will error unless `u0` is the size of `p`, this should be caught at the start of the function to throw a domain specific error, for example "parameters and initial condition should be the same size". ## Subpackaging and interface packages is preferred over conditional modules via Requires.jl Requires.jl should be avoided at all costs. If an interface package exists, such as [ChainRulesCore.jl](https://github.com/JuliaDiff/ChainRulesCore.jl) for defining automatic differentiation rules without requiring a dependency on the whole ChainRules.jl system, or [RecipesBase.jl](https://github.com/JuliaPlots/RecipesBase.jl) which allows for defining Plots.jl plot recipes without a dependency on Plots.jl, a direct dependency on these interface packages is preferred. Otherwise, instead of resorting to a conditional dependency using Requires.jl, it is preferred one creates subpackages, i.e. smaller independent packages kept within the same Github repository with independent versioning and package management. An example of this is seen in [Optimization.jl](https://github.com/SciML/Optimization.jl) which has subpackages like [OptimizationBBO.jl](https://github.com/SciML/Optimization.jl/tree/master/lib/OptimizationBBO) for BlackBoxOptim.jl support. Some important interface packages to know about are: - [ChainRulesCore.jl](https://github.com/JuliaDiff/ChainRulesCore.jl) - [RecipesBase.jl](https://github.com/JuliaPlots/RecipesBase.jl) - [ArrayInterface.jl](https://github.com/JuliaArrays/ArrayInterface.jl) - [CommonSolve.jl](https://github.com/SciML/CommonSolve.jl) - [SciMLBase.jl](https://github.com/SciML/SciMLBase.jl) ## Functions should either attempt to be non-allocating and reuse caches, or treat inputs as immutable Mutating codes and non-mutating codes fall into different worlds. When a code is fully immutable, the compiler can better reason about dependencies, optimize the code, and check for correctness. However, many times a code making the fullest use of mutation can outperform even what the best compilers of today can generate. That said, the worst of all worlds is when code mixes mutation with non-mutating code. Not only is this a mishmash of coding styles, it has the potential non-locality and compiler proof issues of mutating code while not fully benefiting from the mutation. ## Out-of-place and immutability is preferred when sufficient performant Mutation is used to get more performance by decreasing the amount of heap allocations. However, if it's not helpful for heap allocations in a given spot, do not use mutation. Mutation is scary and should be avoided unless it gives an immediate benefit. For example, if matrices are sufficiently large, then `A*B` is as fast as `mul!(C,A,B)`, and thus writing `A*B` is preferred (unless the rest of the function is being careful about being fully non-allocating, in which case this should be `mul!` for consistency). Similarly, when defining types, using `struct` is preferred to `mutable struct` unless mutating the struct is a common occurrence. Even if mutating the struct is a common occurrence, see whether using [Setfield.jl](https://github.com/jw3126/Setfield.jl) is sufficient. The compiler will optimize the construction of immutable structs, and thus this can be more efficient if it's not too much of a code hassle. ## Tests should attempt to cover a wide gamut of input types Code coverage numbers are meaningless if one does not consider the input types. For example, one can hit all the code with `Array`, but that does not test whether `CuArray` is compatible! Thus, it's always good to think of coverage not in terms of lines of code but in terms of type coverage. A good list of number types to think about are: - `Float64` - `Float32` - `Complex` - [`Dual`](https://github.com/JuliaDiff/ForwardDiff.jl) - `BigFloat` Array types to think about testing are: - `Array` - [`OffsetArray`](https://github.com/JuliaArrays/OffsetArrays.jl) - [`CuArray`](https://github.com/JuliaGPU/CUDA.jl) ## When in doubt, a submodule should become a subpackage or separate package Keep packages to one core idea. If there's something separate enough to be a submodule, could it instead be a separate well-tested and documented package to be used by other packages? Most likely yes. ## Globals should be avoided whenever possible Global variables should be avoided whenever possible. When required, global variables should be constants and have an all uppercase name separated with underscores (e.g. `MY_CONSTANT`). They should be defined at the top of the file, immediately after imports and exports but before an `__init__` function. If you truly want mutable global style behavior you may want to look into mutable containers. ## Type-stable and type-grounded code is preferred wherever possible Type-stable and type-grounded code helps the compiler create not only more optimized code, but also faster to compile code. Always keep containers well-typed, functions specializing on the appropriate arguments, and types concrete. ## Closures should be avoided whenever possible Closures can cause accidental type instabilities that are difficult to track down and debug; in the long run it saves time to always program defensively and avoid writing closures in the first place, even when a particular closure would not have been problematic. A similar argument applies to reading code with closures; if someone is looking for type instabilities, this is faster to do when code does not contain closures. See examples [here](https://discourse.julialang.org/t/are-closures-should-be-avoided-whenever-possible-still-valid-in-julia-v1-9/95893/5). Furthermore, if you want to update variables in an outer scope, do so explicitly with `Ref`s or self defined structs. ## Numerical functionality should use the appropriate generic numerical interfaces While you can use `A\b` to do a linear solve inside a package, that does not mean that you should. This interface is only sufficient for performing factorizations, and so that limits the scaling choices, the types of `A` that can be supported, etc. Instead, linear solves within packages should use LinearSolve.jl. Similarly, nonlinear solves should use NonlinearSolve.jl. Optimization should use Optimization.jl. Etc. This allows the full generic choice to be given to the user without depending on every solver package (effectively recreating the generic interfaces within each package). ## Functions should capture one underlying principle Functions mean one thing. Every dispatch of `+` should be "the meaning of addition on these types". While in theory you could add dispatches to `+` that mean something different, that will fail in generic code for which `+` means addition. Thus, for generic code to work, code needs to adhere to one meaning for each function. Every dispatch should be an instantiation of that meaning. ## Internal choices should be exposed as options whenever possible Whenever possible, numerical values and choices within scripts should be exposed as options to the user. This promotes code reusability beyond the few cases the author may have expected. ## Prefer code reuse over rewrites whenever possible If a package has a function you need, use the package. Add a dependency if you need to. If the function is missing a feature, prefer to add that feature to said package and then add it as a dependency. If the dependency is potentially troublesome, for example because it has a high load time, prefer to spend time helping said package fix these issues and add the dependency. Only when it does not seem possible to make the package "good enough" should using the package be abandoned. If it is abandoned, consider building a new package for this functionality as you need it, and then make it a dependency. ## Prefer to not shadow functions Two functions can have the same name in Julia by having different namespaces. For example, `X.f` and `Y.f` can be two different functions, with different dispatches, but the same name. This should be avoided whenever possible. Instead of creating `MyPackage.sort`, consider adding dispatches to `Base.sort` for your types if these new dispatches match the underlying principle of the function. If it doesn't, prefer to use a different name. While using `MyPackage.sort` is not conflicting, it is going to be confusing for most people unfamiliar with your code, so `MyPackage.special_sort` would be more helpful to newcomers reading the code.
QuantumESPRESSO
https://github.com/MineralsCloud/QuantumESPRESSO.jl.git
[ "MIT" ]
0.11.0
0aa4c2634bd49313759411a3c22b3f0338b7739e
docs
2239
# [Style Guide](@id style) This section describes the coding style rules that apply to our code and that we recommend you to use it also. In some cases, our style guide diverges from Julia's official [Style Guide](https://docs.julialang.org/en/v1/manual/style-guide/) (Please read it!). All such cases will be explicitly noted and justified. Our style guide adopts many recommendations from the [BlueStyle](https://github.com/invenia/BlueStyle). Please read the [BlueStyle](https://github.com/invenia/BlueStyle) before contributing to this package. If not following, your pull requests may not be accepted. !!! info The style guide is always a work in progress, and not all QuantumESPRESSO code follows the rules. When modifying QuantumESPRESSO, please fix the style violations of the surrounding code (i.e., leave the code tidier than when you started). If large changes are needed, consider separating them into another pull request. ## Formatting ### Run JuliaFormatter QuantumESPRESSO uses [JuliaFormatter](https://github.com/domluna/JuliaFormatter.jl) as an auto-formatting tool. We use the options contained in [`.JuliaFormatter.toml`](https://github.com/MineralsCloud/QuantumESPRESSO.jl/blob/main/.JuliaFormatter.toml). To format your code, `cd` to the QuantumESPRESSO directory, then run: ```@repl using Pkg Pkg.add("JuliaFormatter") using JuliaFormatter: format format("docs") format("src") format("test") ``` !!! info A continuous integration check verifies that all PRs made to QuantumESPRESSO have passed the formatter. The following sections outline extra style guide points that are not fixed automatically by JuliaFormatter. ### Use the Julia extension for Visual Studio Code Please use [Visual Studio Code](https://code.visualstudio.com/) with the [Julia extension](https://marketplace.visualstudio.com/items?itemName=julialang.language-julia) to edit, format, and test your code. We do not recommend using other editors to edit your code for the time being. This extension already has [JuliaFormatter](https://github.com/domluna/JuliaFormatter.jl) integrated. So to format your code, follow the steps listed [here](https://www.julia-vscode.org/docs/stable/userguide/formatter/).
QuantumESPRESSO
https://github.com/MineralsCloud/QuantumESPRESSO.jl.git
[ "MIT" ]
0.3.0
5a68b010397628a31464a42666493d2035871e22
code
241
using Justly using Documenter: deploydocs, makedocs makedocs( sitename = "Justly.jl", modules = [Justly], doctest = false, pages = ["Public interface" => "index.md"], ) deploydocs(repo = "github.com/bramtayl/Justly.jl.git")
Justly
https://github.com/bramtayl/Justly.jl.git
[ "MIT" ]
0.3.0
5a68b010397628a31464a42666493d2035871e22
code
2675
mutable struct Chord modulation::Modulation words::String notes::Vector{Note} # separate list model for qml notes_model::ListModel note_cursor::Int end export Chord function Chord( instruments; modulation = Modulation(), words = "", notes = Note[], note_cursor = 0, ) Chord(modulation, words, notes, make_list_model(notes, instruments), note_cursor) end function as_dict(chord::Chord) Dict( "modulation" => as_dict(chord.modulation), "words" => chord.words, "notes" => map(as_dict, chord.notes), ) end function from_dict(::Type{Chord}, dict, instruments) Chord( instruments; modulation = from_dict(Modulation, dict["modulation"]), words = dict["words"], notes = map(dict["notes"]) do dict from_dict(Note, dict, instruments) end, ) end function make_list_model(chords::Vector{Chord}, instruments) list_model = ListModel(chords, false) # convert ints back and forth to floats for qml # direct access to interval fields for qml addrole( list_model, "numerator", item -> float(item.modulation.interval.numerator), (list, new_value, index) -> list[index].modulation.interval.numerator = round(Int, new_value), ) addrole( list_model, "denominator", item -> float(item.modulation.interval.denominator), (list, new_value, index) -> list[index].modulation.interval.denominator = round(Int, new_value), ) addrole( list_model, "octave", item -> float(item.modulation.interval.octave), (list, new_value, index) -> list[index].modulation.interval.octave = round(Int, new_value), ) addrole( list_model, "beats", item -> float(item.modulation.beats), (list, new_value, index) -> list[index].modulation.beats = round(Int, new_value), ) addrole( list_model, "note_cursor", item -> float(item.note_cursor), (list, new_value, index) -> list[index].note_cursor = round(Int, new_value), ) addrole( list_model, "volume", item -> item.modulation.volume, (list, new_value, index) -> list[index].modulation.volume = new_value, ) addrole( list_model, "words", item -> item.words, (list, new_value, index) -> list[index].words = new_value, ) addrole(list_model, "notes_model", item -> item.notes_model) setconstructor(list_model, let instruments = instruments () -> Chord(instruments) end) list_model end
Justly
https://github.com/bramtayl/Justly.jl.git
[ "MIT" ]
0.3.0
5a68b010397628a31464a42666493d2035871e22
code
4633
""" default_wave(x) A wave with many overtones, namely, sin(x) + 0.2sin(2x) + 0.166sin(3x) + 0.133sin(4x) + 0.1sin(5x) + 0.066sin(6x) + 0.033sin(7x) """ function default_wave(x) sin(x) + 0.2sin(2x) + 0.166sin(3x) + 0.133sin(4x) + 0.1sin(5x) + 0.066sin(6x) + 0.033sin(7x) end export default_wave const INSTRUMENT_ARGUMENT_TYPES = (AudioSchedule, typeof(0.0s), typeof(1.0s), Float64, typeof(440.0Hz)) """ pulse!(audio_schedule, start_time, duration, volume, frequency; ramp_duration = 0.07s, decay_rate = -4/s ) A function for an [`Instrument`](@ref). Uses the wave function [`default_wave`](@ref). Add an envelope with an exponential `decay_rate` and ramps of `ramp_duration` at the beginning and end. """ function pulse!( audio_schedule, start_time, duration, volume, frequency; ramp_duration = 0.07s, decay_rate = -4 / s, ) sustain_duration = duration - ramp_duration push!( audio_schedule, Map(default_wave, Cycles(frequency)), start_time, if duration < ramp_duration @envelope(0, Line => duration / 2, volume, Line => duration / 2, 0) else @envelope( 0, Line => ramp_duration, volume, Grow => sustain_duration, volume * exp(sustain_duration * decay_rate), Line => ramp_duration, 0 ) end, ) end precompile(pulse!, INSTRUMENT_ARGUMENT_TYPES) export pulse! """ sustain!(audio_schedule, start_time, duration, volume, frequency; ramp_duration = 0.07s ) A function for an [`Instrument`](@ref). Uses the wave function [`default_wave`](@ref). Add an envelope with ramps of `ramp_duration` at the beginning and end. """ function sustain!( audio_schedule, start_time, duration, volume, frequency; ramp_duration = 0.07s, ) sustain_duration = duration - ramp_duration push!( audio_schedule, Map(default_wave, Cycles(frequency)), start_time, if duration < ramp_duration @envelope(0, Line => duration / 2, volume, Line => duration / 2, 0) else @envelope( 0, Line => ramp_duration, volume, Line => sustain_duration, volume, Line => ramp_duration, 0 ) end, ) end precompile(sustain!, INSTRUMENT_ARGUMENT_TYPES) """ Instrument(note_function!, name) Use an `Instrument` to play a note in the style of an instrument. `note_function!` will be called as follows: note_function!(audio_schedule, start_time, duration, volume, frequency) where - `audio_schedule` is an `AudioSchedules.AudioSchedule` to add the note to. - `start_time` is a start time in seconds, like `0.0s`. - `duration` is a duration in seconds, like `1.0s` - `volume` is a ratio between 0 and 1. - `frequency` is the frequency of the note in hertz, like `440.0Hz`. """ struct Instrument note_function!::FunctionWrapper{Nothing, Tuple{INSTRUMENT_ARGUMENT_TYPES...}} name::String end export Instrument function make_list_model(instruments::Vector{Instrument}) list_model = ListModel(instruments, false) addrole(list_model, "text", instrument -> instrument.name) list_model end function get_instrument_number(instruments, instrument) instrument_number = findfirst( let instrument = instrument possible_instrument -> possible_instrument === instrument end, instruments, ) if instrument_number === nothing throw(ArgumentError("Instrument \"$(instrument.instrument_name)\" not found!")) else instrument_number end end function get_instrument(instruments, instrument_name) instrument_number = findfirst(let instrument_name = instrument_name instrument -> instrument.name == instrument_name end, instruments) if instrument_number === nothing throw(ArgumentError("Instrument \"$instrument_name\" not found!")) else instrument_number end instruments[instrument_number] end """ DEFAULT_INSTRUMENTS The default [`Instrument`]s available in [`read_justly`](@ref) and [`edit_justly`](@ref), namely, ```julia [Instrument(pulse!, "pulse!"), Instrument(sustain!, "sustain!")] ``` See [`pulse!`](@ref) and [`sustain!`](@ref). """ const DEFAULT_INSTRUMENTS = [Instrument(pulse!, "pulse!"), Instrument(sustain!, "sustain!")] export DEFAULT_INSTRUMENTS
Justly
https://github.com/bramtayl/Justly.jl.git
[ "MIT" ]
0.3.0
5a68b010397628a31464a42666493d2035871e22
code
683
mutable struct Interval numerator::Int denominator::Int octave::Int end function Interval(; numerator = 1, denominator = 1, octave = 0) Interval(numerator, denominator, octave) end function Rational(interval::Interval) interval.numerator // interval.denominator * (2 // 1)^interval.octave end function as_dict(interval::Interval) Dict( "numerator" => interval.numerator, "denominator" => interval.denominator, "octave" => interval.octave, ) end function from_dict(::Type{Interval}, dict) Interval( numerator = dict["numerator"], denominator = dict["denominator"], octave = dict["octave"], ) end
Justly
https://github.com/bramtayl/Justly.jl.git
[ "MIT" ]
0.3.0
5a68b010397628a31464a42666493d2035871e22
code
4941
module Justly import AudioSchedules: AudioSchedule using AudioSchedules: compile, Cycles, @envelope, Grow, Line, make_series, Map, Scale, write_buffer, write_series! import Base: parse, print, push!, Rational, show using Base: catch_backtrace using Base.Meta: ParseError using Base.Threads: @spawn using FunctionWrappers: FunctionWrapper using Observables: Observable using PortAudio: Buffer, PortAudioStream using QML: addrole, exec, JuliaPropertyMap, ListModel, loadqml, # to avoid QML bug QML, qmlfunction, setconstructor using Qt5QuickControls2_jll: Qt5QuickControls2_jll using YAML: load_file, write_file using Unitful: Hz, s # reexport to avoid a QML bug export QML include("Instrument.jl") include("Interval.jl") include("Modulation.jl") include("Note.jl") include("Chord.jl") include("Song.jl") function add_press!(audio_schedule, song, press_type, @nospecialize press_arguments) if press_type == "play notes" add_notes!(audio_schedule, song, press_arguments...) elseif press_type == "play chords" add_chords!(audio_schedule, song, press_arguments...) else throw(ArgumentError("Press type \"$press_type\" not recognized")) end end function consume!(presses, stream, song, audio_schedule) precompiling_observable = song.precompiling_observable for (press_type, press_arguments) in presses audio_schedule.is_on[] = true add_press!(audio_schedule, song, press_type, press_arguments) precompiling_observable[] = true compile(stream, audio_schedule) precompiling_observable[] = false GC.enable(false) write(stream, audio_schedule) GC.enable(true) empty!(audio_schedule) end end """ function edit_justly(song_file, instruments = DEFAULT_INSTRUMENTS; test = false ) Use to edit songs interactively. The interface might be slow at first while Julia is compiling. - `song_file` is a YAML file. Will be created if it doesn't exist. - `instruments` are a vector of [`Instrument`](@ref)s, with the default [`DEFAULT_INSTRUMENTS`](@ref). For more information, see the `README`. ```julia julia> using Justly julia> edit_justly(joinpath(pkgdir(Justly), "examples", "simple.yml")) ``` """ function edit_justly(song_file, instruments = DEFAULT_INSTRUMENTS; test = false) song = if isfile(song_file) read_justly(song_file, instruments) else dir_name = dirname(song_file) if !(isempty(dir_name)) && !(isdir(dir_name)) throw(ArgumentError("Folder doesn't exist!")) end @info "Creating file $song_file" Song(instruments) end instruments = song.instruments presses = Channel{Tuple{String, Tuple}}(0) stream = PortAudioStream(0, 1; latency = 0.2, warn_xruns = false) try audio_schedule = AudioSchedule(; sample_rate = (stream.sample_rate)Hz) # precompile the whole song push!(audio_schedule, song) compile(stream, audio_schedule) empty!(audio_schedule) consume_task = @spawn consume!($presses, $stream, $song, $audio_schedule) try qmlfunction( "press", let presses = presses (action_type, arguments...) -> put!(presses, (action_type, arguments)) end, ) qmlfunction("release", let is_on = audio_schedule.is_on () -> is_on[] = false end) loadqml( joinpath(@__DIR__, "Song.qml"); test = test, chords_model = make_list_model(song.chords, instruments), instruments_model = make_list_model(instruments), empty_notes_model = make_list_model(Note[], instruments), julia_arguments = JuliaPropertyMap( "volume" => song.volume_observable, "frequency" => song.frequency_observable, "tempo" => song.tempo_observable, "precompiling" => song.precompiling_observable, ), ) exec() if test # precompile before each play # play the second note of the second chord put!(presses, ("play notes", (2, 2, 2))) # play the second chord put!(presses, ("play chords", (2, 2))) # play starting with the second chord put!(presses, ("play chords", (2,))) end catch an_error showerror(stdout, an_error, catch_backtrace()) finally close(presses) wait(consume_task) end finally close(stream) end write_justly(song_file, song) end export edit_justly precompile(edit_justly, (String,)) end # TODO: # undo/redo # copy/paste # change tempo?
Justly
https://github.com/bramtayl/Justly.jl.git
[ "MIT" ]
0.3.0
5a68b010397628a31464a42666493d2035871e22
code
585
mutable struct Modulation interval::Interval beats::Int volume::Float64 end function Modulation(; interval = Interval(), beats = 1, volume = 1) Modulation(interval, beats, volume) end function as_dict(modulation::Modulation) Dict( "interval" => as_dict(modulation.interval), "beats" => modulation.beats, "volume" => modulation.volume, ) end function from_dict(::Type{Modulation}, dict) Modulation( interval = from_dict(Interval, dict["interval"]), beats = dict["beats"], volume = dict["volume"], ) end
Justly
https://github.com/bramtayl/Justly.jl.git
[ "MIT" ]
0.3.0
5a68b010397628a31464a42666493d2035871e22
code
2372
mutable struct Note instrument::Instrument interval::Interval beats::Int volume::Float64 end function Note(instrument; interval = Interval(), beats = 1, volume = 1.0) Note(instrument, interval, beats, volume) end function as_dict(note::Note) Dict( "instrument_name" => note.instrument.name, "interval" => as_dict(note.interval), "beats" => note.beats, "volume" => note.volume, ) end function from_dict(::Type{Note}, dict, instruments) Note( get_instrument(instruments, dict["instrument_name"]); interval = from_dict(Interval, dict["interval"]), beats = dict["beats"], volume = dict["volume"], ) end function make_list_model(notes::Vector{Note}, instruments) list_model = ListModel(notes, false) # convert ints back and forth to floats for qml # direct access to interval fields for qml addrole( list_model, "numerator", item -> float(item.interval.numerator), (list, new_value, index) -> list[index].interval.numerator = round(Int, new_value), ) addrole( list_model, "denominator", item -> float(item.interval.denominator), (list, new_value, index) -> list[index].interval.denominator = round(Int, new_value), ) addrole( list_model, "octave", item -> float(item.interval.octave), (list, new_value, index) -> list[index].interval.octave = round(Int, new_value), ) addrole( list_model, "beats", item -> float(item.beats), (list, new_value, index) -> list[index].beats = round(Int, new_value), ) # add and subtract 1 for zero-based indexing addrole( list_model, "instrument_number", let instruments = instruments item -> get_instrument_number(instruments, item.instrument) - 1 end, let instruments = instruments (list, new_value, index) -> list[index].instrument = instruments[round(Int, new_value) + 1] end, ) addrole( list_model, "volume", item -> item.volume, (list, new_value, index) -> list[index].volume = new_value, ) setconstructor(list_model, let instrument = instruments[1] () -> Note(instrument) end) list_model end
Justly
https://github.com/bramtayl/Justly.jl.git
[ "MIT" ]
0.3.0
5a68b010397628a31464a42666493d2035871e22
code
4742
struct Song instruments::Vector{Instrument} chords::Vector{Chord} # use observables so changes in qml will propagate back volume_observable::Observable{Float64} frequency_observable::Observable{Float64} tempo_observable::Observable{Float64} precompiling_observable::Observable{Bool} end function Song( instruments; chords = Chord[], volume = 0.2, frequency = 200.0, tempo = 200.0, precompiling = false, ) Song( instruments, chords, Observable(volume), Observable(frequency), Observable(tempo), Observable(precompiling), ) end function as_dict(song::Song) Dict( "volume" => song.volume_observable[], "frequency" => song.frequency_observable[], "tempo" => song.tempo_observable[], "chords" => map(as_dict, song.chords), ) end function from_dict(::Type{Song}, dict, instruments) Song( instruments; volume = dict["volume"], frequency = dict["frequency"], tempo = dict["tempo"], chords = map(dict["chords"]) do dict from_dict(Chord, dict, instruments) end, ) end """ read_justly(file, instruments = DEFAULT_INSTRUMENTS) Create a `Song` from a song file. `instruments` are a vector of [`Instrument`](@ref)s, with the default [`DEFAULT_INSTRUMENTS`](@ref). ```jldoctest read_justly julia> using Justly julia> song = read_justly(joinpath(pkgdir(Justly), "examples", "simple.yml")); ``` You can add a song to an `AudioSchedule` at a start time. You can use this to overlap multiple songs at differnt times. ```jldoctest read_justly julia> using AudioSchedules: AudioSchedule, Hz, s julia> audio_schedule = AudioSchedule(sample_rate = 44100Hz) 0.0 s 44100.0 Hz AudioSchedule julia> push!(audio_schedule, song, 0.0s) julia> push!(audio_schedule, song, 1.0s) julia> audio_schedule 2.27 s 44100.0 Hz AudioSchedule ``` """ function read_justly(file, instruments = DEFAULT_INSTRUMENTS) from_dict(Song, load_file(file), instruments) end precompile(read_justly, (String, Vector{Instrument})) function write_justly(file, song) write_file(file, as_dict(song)) end export read_justly mutable struct PlayState volume::Float64 frequency::typeof(0.0Hz) beat_duration::typeof(0.0s) time::typeof(0.0s) end function PlayState(song::Song, time) PlayState( song.volume_observable[], (song.frequency_observable[])Hz, (60 / song.tempo_observable[])s, time, ) end function update_play_state!(play_state, chord) play_state.frequency = play_state.frequency * Rational(chord.modulation.interval) play_state.volume = play_state.volume * chord.modulation.volume nothing end function add_notes!(audio_schedule, play_state, notes) for note in notes note.instrument.note_function!( audio_schedule, play_state.time, note.beats * play_state.beat_duration, play_state.volume * note.volume, play_state.frequency * Rational(note.interval), ) end nothing end function add_chord!(audio_schedule, play_state, chord) add_notes!(audio_schedule, play_state, chord.notes) play_state.time = play_state.time + chord.modulation.beats * play_state.beat_duration nothing end function push!(audio_schedule::AudioSchedule, song::Song, start_time = 0.0s) play_state = PlayState(song, start_time) for chord in song.chords update_play_state!(play_state, chord) add_chord!(audio_schedule, play_state, chord) end nothing end precompile(push!, (AudioSchedule, Song, typeof(0.0s))) @noinline function add_notes!( audio_schedule, song, chord_index, first_note_index, last_note_index, ) chords = song.chords play_state = PlayState(song, 0.0s) for chord in chords[1:(chord_index - 1)] update_play_state!(play_state, chord) end chord = chords[chord_index] update_play_state!(play_state, chord) add_notes!(audio_schedule, play_state, chord.notes[first_note_index:last_note_index]) nothing end precompile(add_notes!, (AudioSchedule, Song, Int, Int, Int)) @noinline function add_chords!( audio_schedule, song, first_chord_index, last_chord_index = length(song.chords), ) play_state = PlayState(song, 0.0s) chords = song.chords for chord in chords[1:(first_chord_index - 1)] update_play_state!(play_state, chord) end for chord in chords[first_chord_index:last_chord_index] update_play_state!(play_state, chord) add_chord!(audio_schedule, play_state, chord) end nothing end precompile(add_chords!, (AudioSchedule, Song, Int, Int))
Justly
https://github.com/bramtayl/Justly.jl.git
[ "MIT" ]
0.3.0
5a68b010397628a31464a42666493d2035871e22
code
1233
using Justly using Justly: add_press!, DEFAULT_INSTRUMENTS, get_instrument, sustain!, pulse! using Documenter: doctest using Test: @test, @test_throws, @testset using AudioSchedules: AudioSchedule, duration, Hz, s using Unitful: s audio_schedule = AudioSchedule() song = cd(joinpath(pkgdir(Justly))) do @test_throws ArgumentError("Folder doesn't exist!") edit_justly("not_a_folder/simple.yml") edit_justly("examples/simple.yml"; test = true) song = read_justly("examples/simple.yml") end @test length(song.chords[1].notes) == 3 push!(audio_schedule, song, 0.0s) push!(audio_schedule, song, 1.0s) @test duration(audio_schedule) ≈ 2.27s empty!(audio_schedule) @test_throws ArgumentError("Instrument \"not an instrument\" not found!") get_instrument( DEFAULT_INSTRUMENTS, "not an instrument", ) pulse!(audio_schedule, 0s, 0.01s, 1, 440Hz) @test length(collect(audio_schedule)) == 2 empty!(audio_schedule) sustain!(audio_schedule, 0s, 0.01s, 1, 440Hz) @test length(collect(audio_schedule)) == 2 empty!(audio_schedule) @test_throws ArgumentError("Press type \"not a press\" not recognized") add_press!( audio_schedule, song, "not a press", (), ) if v"1.7" <= VERSION < v"1.8" doctest(Justly) end
Justly
https://github.com/bramtayl/Justly.jl.git
[ "MIT" ]
0.3.0
5a68b010397628a31464a42666493d2035871e22
docs
3889
# Justly [![Dev](https://img.shields.io/badge/docs-dev-blue.svg)](https://bramtayl.github.io/Justly.jl/dev) [![codecov](https://codecov.io/gh/bramtayl/Justly.jl/branch/master/graph/badge.svg?token=MK1IMGK0GE)](https://codecov.io/gh/bramtayl/Justly.jl) You can use Justly to both compose and play music using any pitches you want. Using staff notation, you can only write the notes of the 12-tone scale. Some intervals in any 12-tone scale are close to harmonic, but other intervals are not. Johnston [expanded staff notation](http://marsbat.space/pdfs/EJItext.pdf), but relying on staff notation limited him. To start Justly, start Julia and run ``` using Justly edit_song("new_song.yml") ``` ## How to use Justly In Justly, you write intervals as a rational fraction (integer / integer) times a power of 2. A lowercase `o` stands for (`*2^`), similar how `E` stands for (`*10^`). You can write the same ratio in multiple ways. For example, you can write a fifth as `3/2`, or `3o-1`. You will likely only need to know 4 intervals: - Octave: `2/1` - Perfect fifth: `3/2` - Major third: `5/4` - Harmonic seventh: `7/4` You can create other intervals by multiplying and dividing these intervals. For example, a minor third is up a perfect fifth and down a major third: `(3/2) / (5/4)` = `6/5`. A major second is up two fifths and down an octave: `(3/2) * (3/2) / 2` = `9/8`. In Justly, each row stands for a chord. Each row starts with a modulation, and then, has a list of notes. You can use the modulation to change the current key and volume. All notes in the chord are in reference to the key. To interactively run the example Justly file below, run ```julia using Justly cd(pkgdir(Justly)) do edit_justly("examples/simple.yml") end ``` Here is a schematic of what you will see: ``` Frequency: 220 Hz Tempo: 200 bpm Volume: 0.2 # I 1: 1, 5/4 at 2.0 with sustain!, 3/2 # IV 2/3: 3/2, 1o1 at 2.0 with sustain!, 5/4o1 # I 3/2 for 2: 1 for 2, 5/4 for 2 at 2.0 with sustain!, 3/2 for 2 ``` You can edit the initial frequency, volume, and tempo, using the sliders on the top. - `frequency` is the starting frequency, in Hz. - `volume` is the starting volume of a single voice, between 0 and 1. To avoid peaking, lower the volume for songs with many voices. - `tempo` is the tempo of the song, in beats per minute. These beats are indivisible, so for songs which subdivide beats, you will need to multiply the tempo accordingly. This song starts with a key of frequency 220Hz, that is, a A3, at a tempo of 200 beats per minute and a volume of 0.2, that is, a fifth of maximum volume. Note that playing more than 5 notes at once could result in peaking. The key does not change in the first chord. The three voices in the first chord play the tonic (≈A3), third (≈C#4), and fifth (≈E45). All three voices play for `1` beat. The second voice plays at double volume, and uses the `sustain!` instrument. All other voices use the `pulse!` instrument. See the documentation for more information about instruments. After 1 beat, the key changes: you divide the key by `3/2`, so the key goes down by a fifth. Now the key is close to D4. The three voices play the fifth (≈A3), up one octave (≈D4), and up one octave and a third (≈F#4). The second voice plays at double volume, and uses the `sustain!` instrument. All other voices use the `pulse!` instrument. After 1 more beat, you multiply the key by `3/2`, so the key goes up by a fifth. The voices repeat the notes in the first chord, but play for `2` beats. Again, the second voice plays at double volume. You can play any note by clicking the play button underneath the note. You can play a song, starting with a certain chord, by clicking the play button underneath the chord. You can add lyrics, or performance notes, to any chord. You can set beats to 0 to overlap, or to a negative number to "travel back in time".
Justly
https://github.com/bramtayl/Justly.jl.git
[ "MIT" ]
0.3.0
5a68b010397628a31464a42666493d2035871e22
docs
61
# Justly ```@index ``` ```@autodocs Modules = [Justly] ```
Justly
https://github.com/bramtayl/Justly.jl.git
[ "MIT" ]
0.3.31
a944797808499cb63982b14c42c7cb198d0deb20
code
2047
const CONFIG_DIR = occursin("cache", first(Base.DEPOT_PATH)) ? abspath(Base.DEPOT_PATH[2], "config", "RemoteHPC") : abspath(Base.DEPOT_PATH[1], "config", "RemoteHPC") config_path(path...) = joinpath(CONFIG_DIR, gethostname(), path...) paths = ["jobs", "logs/jobs", "logs/runtimes", "storage/servers", "storage/execs", "storage/environments"] for p in paths mkpath(config_path(p)) end using UUIDs, JSON3 using Pkg """ configure_local() Runs through interactive configuration of the local [`Server`](@ref). """ function configure_local() host = gethostname() spath = config_path("storage/servers/$host.json") if !ispath(spath) scheduler = nothing if haskey(ENV, "DFC_SCHEDULER") sched = ENV["DFC_SCHEDULER"] if occursin("hq", lowercase(sched)) cmd = get(ENV, "DFC_SCHEDULER_CMD", "hq") scheduler = (type = "hq", server_command = cmd, allocs = String[]) elseif lowercase(sched) == "slurm" scheduler = (type = "slurm",) else error("Scheduler $sched not recognized please set a different DFC_SCHEDULER environment var.") end end for t in ("hq", "sbatch") if Sys.which(t) !== nothing scheduler = t == "hq" ? (type = "hq", server_command = "hq", allocs = String[]) : (type = "slurm",) end end scheduler = scheduler === nothing ? (type = "bash",) : scheduler user = get(ENV, "USER", "noname") JSON3.write(spath, (name = host, username = user, domain = "localhost", julia_exec = joinpath(Sys.BINDIR, "julia"), scheduler = scheduler, jobdir = homedir(), max_concurrent_jobs = 100, uuid = string(uuid4()))) end end configure_local() Pkg.activate(CONFIG_DIR) Pkg.add("RemoteHPC")
RemoteHPC
https://github.com/louisponet/RemoteHPC.jl.git
[ "MIT" ]
0.3.31
a944797808499cb63982b14c42c7cb198d0deb20
code
353
using Documenter using RemoteHPC makedocs(; sitename = "RemoteHPC", format = Documenter.HTML(), modules = [RemoteHPC]) # Documenter can also automatically deploy documentation to gh-pages. # See "Hosting Documentation" and deploydocs() in the Documenter manual # for more information. #=deploydocs( repo = "<repository url>" )=#
RemoteHPC
https://github.com/louisponet/RemoteHPC.jl.git
[ "MIT" ]
0.3.31
a944797808499cb63982b14c42c7cb198d0deb20
code
1915
module RemoteHPC using LoggingExtras using Logging using Dates using ThreadPools using HTTP using HTTP.URIs: URI using StructTypes using Sockets using JSON3 using UUIDs using Dates using ProgressMeter using SnoopPrecompile using Base: @kwdef using Pkg using InteractiveUtils using BinaryTraits using DataStructures using Oxygen const CONFIG_DIR = occursin("cache", first(Base.DEPOT_PATH)) ? abspath(Base.DEPOT_PATH[2], "config", "RemoteHPC") : abspath(Base.DEPOT_PATH[1], "config", "RemoteHPC") config_path(path...) = joinpath(CONFIG_DIR, gethostname(), path...) function getfirst(f, itr) id = findfirst(f, itr) id === nothing && return nothing return itr[id] end const DEFAULT_PRIORITY = 5 include("utils.jl") include("logging.jl") include("database.jl") include("types.jl") include("schedulers.jl") include("servers.jl") const LOCAL_SERVER = Ref{Server}() include("runtime.jl") include("api.jl") include("client.jl") include("io.jl") @precompile_all_calls begin s = local_server() isalive(local_server()) t = "asdfe" t2 = "edfasdf" e = Exec(; name = t2, path = "srun") e1 = Environment(t, Dict("-N" => 3, "partition" => "default", "time" => "00:01:01"), Dict("OMP_NUM_THREADS" => 1), "", "", e) save(e1) save(e) e1 = load(e1) e = load(e) calcs = [Calculation(e, "< scf.in > scf.out", true)] rm(e1) rm(e) end export Server, start, restart, local_server, isalive, load, save, submit, abort, state, configure, priority!, check_connections export Calculation, Environment, Exec, HQ, Slurm, Bash export exec function __init__() LOCAL_SERVER[] = local_server() init_traits(@__MODULE__) end using TOML const PACKAGE_VERSION = let project = TOML.parsefile(joinpath(pkgdir(@__MODULE__), "Project.toml")) VersionNumber(project["version"]) end end# module RemoteHPC
RemoteHPC
https://github.com/louisponet/RemoteHPC.jl.git
[ "MIT" ]
0.3.31
a944797808499cb63982b14c42c7cb198d0deb20
code
8073
function execute_function(req::HTTP.Request) funcstr = Meta.parse(queryparams(req)["path"]) func = eval(funcstr) args = [] for (t, a) in JSON3.read(req.body, Vector) typ = Symbol(t) eval(:(arg = JSON3.read($a, $typ))) push!(args, arg) end return func(args...) end function get_version() return PACKAGE_VERSION end function server_config!(req, s::ServerData) splt = splitpath(req.target) if splt[4] == "sleep_time" return s.sleep_time = parse(Float64, splt[5]) end field = Symbol(splt[4]) server = s.server setfield!(server, field, parse(fieldtype(server, field), splt[5])) save(server) return server end function server_config(req, s::ServerData) server = s.server splt = splitpath(req.target) if length(splt) == 3 return server else return getfield(server, Symbol(splt[4])) end end function setup_core_api!(s::ServerData) @put "/server/kill" req -> (s.stop = true) @get "/info/version" req -> get_version() @get "/isalive/" req -> true @get "/isalive/*" req -> (n = splitpath(req.target)[end]; haskey(s.connections, n) && s.connections[n]) @get "/api/**" execute_function @get "/ispath/" req -> (p = queryparams(req)["path"]; ispath(p)) @get "/read/" req -> (p = queryparams(req)["path"]; read(p)) @post "/write/" req -> (p = queryparams(req)["path"]; write(p, req.body)) @post "/rm/" req -> (p = queryparams(req)["path"]; rm(p; recursive = true)) @get "/readdir/" req -> (p = queryparams(req)["path"]; readdir(p)) @get "/mtime/" req -> (p = queryparams(req)["path"]; mtime(p)) @get "/filesize/" req -> (p = queryparams(req)["path"]; filesize(p)) @get "/realpath/" req -> (p = queryparams(req)["path"]; realpath(p)) @post "/mkpath/" req -> (p = queryparams(req)["path"]; mkpath(p)) @post "/symlink/" req -> symlink(JSON3.read(req.body, Vector{String})...) @post "/cp/" req -> cp(JSON3.read(req.body, Tuple{String, String})...; force=true) @post "/server/config/*" req -> server_config!(req, s) @get "/server/config/**" req -> server_config(req, s) @get "/server/config" req -> local_server() @put "/server/check_connections" req -> check_connections!(s, get(queryparams(req), "verify_tunnels", false)) @put "/server/check_connections/*" req -> check_connections!(s, get(queryparams(req), "verify_tunnels", true); names=[splitpath(req.target)[end]]) end function submit_job(req, queue::Queue, channel) p = queryparams(req) jdir = p["path"] lock(queue) do q if !haskey(q.full_queue, jdir) error("No Job is present at $jdir.") else q.full_queue[jdir].state = Submitted end end priority = haskey(p, "priority") ? parse(Int, p["priority"]) : DEFAULT_PRIORITY put!(channel, jdir => (priority, -time())) end function get_job(req::HTTP.Request, queue::Queue) p = queryparams(req) job_dir = p["path"] info = get(queue.info.current_queue, job_dir, nothing) if info === nothing info = get(queue.info.full_queue, job_dir, nothing) end info = info === nothing ? Job(-1, Unknown) : info tquery = HTTP.queryparams(URI(req.target)) if isempty(tquery) || !haskey(tquery, "data") return [info, JSON3.read(read(joinpath(job_dir, ".remotehpc_info")), Tuple{String,Environment,Vector{Calculation}})...] else dat = tquery["data"] isa Vector ? tquery["data"] : [tquery["data"]] out = [] jinfo = any(x -> x in ("name", "environment", "calculations"), dat) ? JSON3.read(read(joinpath(job_dir, ".remotehpc_info")), Tuple{String,Environment,Vector{Calculation}}) : nothing for d in dat if d == "id" push!(out, info.id) elseif d == "state" push!(out, info.state) elseif d == "name" if jinfo !== nothing push!(out, jinfo[1]) end elseif d == "environment" if jinfo !== nothing push!(out, jinfo[2]) end elseif d == "calculations" if jinfo !== nothing push!(out, jinfo[3]) end end end return out end end function get_jobs(state::JobState, queue::Queue) jobs = String[] for q in (queue.info.full_queue, queue.info.current_queue) for (d, j) in q if j.state == state push!(jobs, d) end end end return jobs end function get_jobs(dirfuzzy::AbstractString, queue::Queue) jobs = String[] for q in (queue.info.full_queue, queue.info.current_queue) for (d, j) in q if occursin(dirfuzzy, d) push!(jobs, d) end end end return jobs end function save_job(req::HTTP.Request, args...) return save_job(queryparams(req)["path"], JSON3.read(req.body, Tuple{String,Environment,Vector{Calculation}}), args...) end function save_job(dir::AbstractString, job_info::Tuple, queue::Queue, sched::Scheduler) # Needs to be done so the inputs `dir` also changes. mkpath(dir) open(joinpath(dir, "job.sh"), "w") do f return write(f, job_info, sched) end JSON3.write(joinpath(dir, ".remotehpc_info"), job_info) lock(queue) do q return q.full_queue[dir] = Job(-1, Saved) end end function abort(req::HTTP.Request, queue::Queue, sched::Scheduler) jdir = queryparams(req)["path"] j = get(queue.info.current_queue, jdir, nothing) if j === nothing if haskey(queue.info.submit_queue, jdir) lock(queue) do q delete!(q.submit_queue, jdir) q.full_queue[jdir].state = Cancelled end return 0 else error("No Job is running or submitted at $jdir.") end else abort(sched, j.id) lock(queue) do q j = pop!(q.current_queue, jdir) j.state = Cancelled q.full_queue[jdir] = j end return j.id end end function priority!(req::HTTP.Request, queue::Queue) p = queryparams(req) jdir = p["path"] if haskey(queue.info.submit_queue, jdir) priority = haskey(p, "priority") ? parse(Int, p["priority"]) : DEFAULT_PRIORITY lock(queue) do q q.submit_queue[jdir] = (priority, q.submit_queue[jdir][2]) end return priority else error("Job at $jdir not in submission queue.") end end function setup_job_api!(s::ServerData) @post "/job/" req -> save_job(req, s.queue, s.server.scheduler) @put "/job/" req -> submit_job(req, s.queue, s.submit_channel) @put "/job/priority" req -> priority!(req, s.queue) @get "/job/" req -> get_job(req, s.queue) @get "/jobs/state" req -> get_jobs(JSON3.read(req.body, JobState), s.queue) @get "/jobs/fuzzy" req -> get_jobs(JSON3.read(req.body, String), s.queue) @post "/abort/" req -> abort(req, s.queue, s.server.scheduler) end function load(req::HTTP.Request) p = config_path("storage", queryparams(req)["path"]) if isdir(p) return map(x -> splitext(x)[1], readdir(p)) else p *= ".json" if ispath(p) return read(p, String) end end end function save(req::HTTP.Request) p = config_path("storage", queryparams(req)["path"]) mkpath(splitdir(p)[1]) write(p * ".json", req.body) end function database_rm(req) p = config_path("storage", queryparams(req)["path"]) * ".json" ispath(p) return rm(p) end function setup_database_api!() @get "/storage/" req -> load(req) @post "/storage/" req -> save(req) @put "/storage/" req -> database_rm(req) end
RemoteHPC
https://github.com/louisponet/RemoteHPC.jl.git
[ "MIT" ]
0.3.31
a944797808499cb63982b14c42c7cb198d0deb20
code
14363
""" start(s::Server) Launches the daemon process on the host [`Server`](@ref) `s`. """ function start(s::Server; verbosity=0) title = "Starting Server($(s.name))" steps = ["Verifying that local server is running", "Verifying that the server isn't already alive", "Starting server", "Waiting for server connection"] StepSpinner(title, steps) do spinner if !islocal(s) && !isalive(LOCAL_SERVER[]) push!(spinner, "Starting local server.") start(LOCAL_SERVER[]) if !isalive(LOCAL_SERVER[]) finish!(spinner, ErrorException("Couldn't start local server.")) end end push!(spinner, "local server running") next!(spinner) alive = isalive(s) || (!islocal(s) && get(JSON3.read(check_connections(names=[s.name]).body), Symbol(s.name), false)) if alive push!(spinner, "Server is already up and running.") finish!(spinner) return end next!(spinner) hostname = gethostname(s) conf_path = config_path(s) t = server_command(s, "ls $(conf_path)") if t.exitcode != 0 finish!(spinner, ErrorException("RemoteHPC not installed on server. Install it using `RemoteHPC.install(Server(\"$(s.name)\"))`")) end if islocal(s) self_destructed = ispath(config_path("self_destruct")) else cmd = "cat $(conf_path)/$hostname/self_destruct" self_destructed = server_command(s, cmd).exitcode == 0 end if self_destructed finish!(spinner, ErrorException("""Self destruction was previously triggered, signalling issues on the Server. Please investigate and if safe, remove $(conf_path)/self_destruct""")) end if !islocal(s) t = deepcopy(s) t.domain = "localhost" t.name = hostname tf = tempname() JSON3.write(tf, t) push(tf, s, "$(conf_path)/$hostname/storage/servers/$hostname.json") end # Here we check what the modify time of the server-side localhost file is. # The server will rewrite the file with the correct port, which we use to see # whether the server started succesfully. function checktime() curtime = 0 if islocal(s) return mtime(config_path("storage", "servers", "$(hostname).json")) else cmd = "stat -c %Z $(conf_path)/$hostname/storage/servers/$(hostname).json" return parse(Int, server_command(s.username, s.domain, cmd)[1]) end return curtime end firstime = checktime() p = "$(conf_path)/$hostname/logs/errors.log" scrpt = "using RemoteHPC; RemoteHPC.julia_main(verbose=$(verbosity))" if s.domain != "localhost" julia_cmd = replace("""$(s.julia_exec) --project=$(conf_path) --startup-file=no -t 10 -e "using RemoteHPC; RemoteHPC.julia_main(verbose=$(verbosity))" &> $p""", "'" => "") if Sys.which("ssh") === nothing OpenSSH_jll.ssh() do ssh_exec run(Cmd(`$ssh_exec -f $(ssh_string(s)) $julia_cmd`; detach = true)) end else run(Cmd(`ssh -f $(ssh_string(s)) $julia_cmd`; detach = true)) end else e = s.julia_exec * " --project=$(conf_path)" julia_cmd = Cmd([string.(split(e))..., "--startup-file=no", "-t", "auto", "-e", scrpt, "&>", p, "&"]) run(Cmd(julia_cmd; detach = true); wait = false) end retries = 0 push!(spinner, "Waiting for server bootup") while checktime() <= firstime && retries < 60 retries += 1 sleep(1) end if retries == 60 finish!(spinner, ErrorException("Something went wrong starting the server.")) end next!(spinner) cfg = load_config(s) s.port = cfg.port s.uuid = cfg.uuid save(s) retries = 0 if islocal(s) while !isalive(s) && retries < 60 sleep(0.1) retries += 1 end LOCAL_SERVER[] = local_server() else check_connections(; names=[s.name]) while !isalive(s) && retries < 60 sleep(0.1) end end if retries == 60 finish!(spinner, ErrorException("""Couldn't set up server connection. This can be because the daemon crashed or because the local server can't setup a ssh tunnel to it""")) end return s end end """ kill(s::Server) Kills the daemon process on [`Server`](@ref) `s`. """ function Base.kill(s::Server) HTTP.put(s, URI(path="/server/kill")) destroy_tunnel(s) if !islocal(s) check_connections(names=[s.name]) end while isalive(s) sleep(0.1) end end function restart(s::Server) kill(s) return start(s) end function update_config(s::Server) alive = isalive(s) if alive @debug "Server is alive, killing" kill(s) end save(s) return start(s) end """ isalive(s::Server) Will try to fetch some data from `s`. If the server is not running this will fail and the return is `false`. """ function isalive(s::Server) if islocal(s) try return suppress() do HTTP.get(s, URI(path="/isalive/"); connect_timeout = 2, retries = 2) !== nothing end catch return false end else if !isalive(LOCAL_SERVER[]) error("Local server not running. Use `start(local_server())` first.") end return JSON3.read(HTTP.get(LOCAL_SERVER[], URI(path="/isalive/$(s.name)"); connect_timeout = 2, retries = 2).body, Bool) end end function check_connections(; names=[]) if isempty(names) return HTTP.put(LOCAL_SERVER[], URI(path="/server/check_connections"), timeout = 60) else for n in names return HTTP.put(LOCAL_SERVER[], URI(path="/server/check_connections/$n"), timeout = 60) end end end function save(s::Server, dir::AbstractString, e::Environment, calcs::Vector{Calculation}; name = "RemoteHPC_job") adir = abspath(s, dir) HTTP.post(s, URI(path="/job/", query = Dict("path" => adir)), (name, e, calcs)) return adir end function load(s::Server, dir::AbstractString) adir = abspath(s, dir) if !ispath(s, joinpath(adir, ".remotehpc_info")) resp = HTTP.get(s, URI(path="/jobs/fuzzy/"), dir) return JSON3.read(resp.body, Vector{String}) else resp = HTTP.get(s, URI(path="/job/", query=Dict("path" => adir))) info, name, environment, calculations = JSON3.read(resp.body, Tuple{Job,String,Environment, Vector{Calculation}}) return (; info, name, environment, calculations) end end function load(s::Server, state::JobState) resp = HTTP.get(s, URI(path="/jobs/state/"), state) return JSON3.read(resp.body, Vector{String}) end function submit(s::Server, dir::AbstractString, priority=DEFAULT_PRIORITY) adir = abspath(s, dir) return HTTP.put(s, URI(path="/job/", query = Dict("path" => adir, "priority" => priority))) end function submit(s::Server, dir::AbstractString, e::Environment, calcs::Vector{Calculation}, priority=DEFAULT_PRIORITY; kwargs...) adir = save(s, dir, e, calcs; kwargs...) submit(s, adir, priority) return adir end function abort(s::Server, dir::AbstractString) adir = abspath(s, dir) resp = HTTP.post(s, URI(path="/abort/", query=Dict("path" => adir))) if resp.status == 200 id = JSON3.read(resp.body, Int) @debug "Aborted job with id $id." else return resp end end function state(s::Server, dir::AbstractString) adir = abspath(s, dir) url = URI(path = "/job/", query = Dict("path" => adir, "data" => ["state"])) resp = HTTP.get(s, url) return JSON3.read(resp.body, Tuple{JobState})[1] end function priority!(s::Server, dir::AbstractString, priority::Int) adir = abspath(s, dir) url = URI(path = "/job/priority", query = Dict("path" => adir, "priority" => priority)) resp = HTTP.put(s, url) return JSON3.read(resp.body, Int) end ask_name(::Type{S}) where {S} = ask_input(String, "Please specify a name for the new $S") function configure() if !isalive(local_server()) @info "Local server needs to be running, starting it..." start(local_server()) end @debug "Configuring (start with Servers)..." done = false while !done storables = subtypes(Storable) type = request("Which kind would you like to configure?", RadioMenu(string.(storables))) type == -1 && return storable_T = storables[type] @info "Configuring a $storable_T. Please read carefully the documentation first:" println() println() display(Docs.doc(storable_T)) println() println() name = ask_name(storable_T) if storable_T == Server server = local_server() else servers = load(local_server(), Server("")) server_id = request("Where would you like to save the $storable_T?", RadioMenu(servers)) server_id == -1 && return server = Server(servers[server_id]) end if !isalive(server) @info "Server(\"$(server.name)\") is not alive, starting it first..." start(server) end storable = storable_T(name=name) if isalive(server) && exists(server, storable) id = request("A $storable_T with name $name already exists on $(server.name). Overwrite?", RadioMenu(["no", "yes"])) id < 2 && return storable = load(server, storable) end try if storable_T == Server storable = configure!(storable) else storable = configure!(storable, server) end yn_id = request("Proceed saving $storable_T with name \"$name\" to Server(\"$(server.name)\")?", RadioMenu(["yes", "no"])) if yn_id == 1 save(server, storable) end yn_id = request("Configure more Storables?", RadioMenu(["yes", "no"])) done = yn_id == 2 catch err @error "Try again" exception=err end end end function ask_input(::Type{T}, message, default = nothing) where {T} message *= " [$T]" if default === nothing t = "" print(message * ": ") while isempty(t) t = readline() end else if !(T == String && isempty(default)) message *= " (default: $default)" end print(message * ": ") t = readline() if isempty(t) return default end end if T in (Int, Float64, Float32) return parse(T, t) elseif T == String return String(strip(t)) else out = T(eval(Meta.parse(t))) if out isa T return out else error("Can't parse $t as $T") end end end function configure!(storable::T, s::Server) where {T<:Storable} tdir = tempname() mkpath(tdir) tf = joinpath(tdir, "storable.md") open(tf, "w") do f write(f, "Storable configuration. Replace default fields inside the ```julia``` block as desired after reading the documentation below.\nSave and close editor when finished.\n```julia\n") for field in configurable_fieldnames(T) value = getfield(storable, field) ft = typeof(value) write(f, "$field::$ft = $(repr(value))\n") end write(f, "```\n\n\n") write(f, "########## DOCUMENTATION #########\n") write(f, string(Docs.doc(T))) write(f, "\n") write(f, "########## DOCUMENTATION END #####\n\n\n") end parsing_error = true while parsing_error parsing_error = false @info "Opening editor, press any key to continue..." readline() InteractiveUtils.edit(tf) tstr = filter(!isempty, readlines(tf)) i = findfirst(x -> x == "```julia", tstr) for (ii, f) in enumerate(configurable_fieldnames(T)) field = getfield(storable, f) ft = typeof(field) line = tstr[i+ii] sline = split(line, "=") try if length(sline) > 2 v = Main.eval(Meta.parse(join(sline[2:end], "="))) else v = Main.eval(Meta.parse(sline[end])) end setfield!(storable, f, v) catch e @warn "Failed parsing $(split(tstr[i+ii], "=")[end]) as $ft." showerror(stdout, e, stacktrace(catch_backtrace())) parsing_error = true end end end return storable end function version(s::Server) if isalive(s) try return JSON3.read(HTTP.get(s, URI(path="/info/version")).body, VersionNumber) catch nothing end end p = config_path(s, "Manifest.toml") t = server_command(s, "cat $p") if t.exitcode != 0 return error("Manifest.toml not found on Server $(s.name).") else tmp = tempname() write(tmp, t.stdout) man = Pkg.Types.read_manifest(tmp) deps = Pkg.Operations.load_manifest_deps(man) remid = findfirst(x->x.name == "RemoteHPC", deps) return deps[remid].version end end
RemoteHPC
https://github.com/louisponet/RemoteHPC.jl.git
[ "MIT" ]
0.3.31
a944797808499cb63982b14c42c7cb198d0deb20
code
4236
# Storable interface @trait Storable prefix Is, IsNot @implement Is{Storable} by storage_directory(_) StructTypes.StructType(::Type{<:Storable}) = StructTypes.DictType() # Constructors (::Type{S})(d::Dict) where {S<:Storable} = S(; d...) (::Type{S})(str::AbstractString; kwargs...) where {S<:Storable} = S(;name=str, kwargs...) (::Type{S})(s::S) where {S<:Storable} = s # Directory structure function storage_name(s::S) where {S<:Storable} return hasfield(S, :name) ? s.name : error("Please define a name function for type $S.") end function storage_path(s::S) where {S<:Storable} return joinpath(storage_directory(s), storage_name(s)) end storage_uri(s::Storable) = URI(path="/storage/", query = Dict("path" => storage_path(s))) # Verification before storing verify(s::Storable) = nothing # used in configure() configurable_fieldnames(::Type{S}) where {S<:Storable} = fieldnames(S) # Base extensions Base.:(==)(s1::S, s2::S) where {S<:Storable} = s1.name == s2.name Base.keys(::S) where {S<:Storable} = fieldnames(S) Base.getindex(e::S, i::Symbol) where {S<:Storable} = getproperty(e, i) Base.setindex!(e::S, i::Symbol, v) where {S<:Storable} = setproperty!(e, i) function Base.iterate(s::S, state=1) where {S<:Storable} fn = fieldnames(S) @inbounds if state > length(fn) return nothing else return s[fn[state]], state+1 end end function Base.convert(::Type{S}, d::Dict{String, Any}) where {S<:Storable} td = Dict{Symbol, Any}() for (k, v) in d td[Symbol(k)] = v end return S(td) end # These are the standard functions where things are saved as simple jsons in the # config_path. """ save([server::Server], e::Environment) save([server::Server], e::Exec) save([server::Server], s::Server) Saves an item to the database of `server`. If `server` is not specified the item will be stored in the local database. """ function save(s::Storable) p = config_path("storage", storage_path(s)) * ".json" mkpath(splitdir(p)[1]) if ispath(p) @warn "Overwriting previously existing item at $p." end verify(s) return JSON3.write(p, s) end function save(server, s::Storable) uri = storage_uri(s) return HTTP.post(server, uri, s) end """ load([server::Server], e::Environment) load([server::Server], e::Exec) load([server::Server], s::Server) Loads a previously stored item from the `server`. If `server` is not specified the local item is loaded. """ function load(s::S) where {S<:Storable} p = config_path("storage", storage_path(s)) * ".json" if !ispath(p) return map(x->splitext(x)[1], readdir(splitdir(p)[1])) end return JSON3.read(read(p, String), S) end function load(server, s::S) where {S<:Storable} uri = storage_uri(s) if exists(server, s) # asking for a stored item return JSON3.read(JSON3.read(HTTP.get(server, uri).body, String), S) else res = HTTP.get(server, URI(path="/storage/", query= Dict("path"=> splitdir(HTTP.queryparams(uri)["path"])[1]))) if !isempty(res.body) return JSON3.read(res.body, Vector{String}) else return String[] end end end exists(s::Storable) = ispath(config_path("storage", storage_path(s)) * ".json") function exists(server, s::Storable) uri = storage_uri(s) try res = HTTP.get(server, URI(path="/storage/", query= Dict("path"=> splitdir(HTTP.queryparams(uri)["path"])[1]))) if !isempty(res.body) possibilities = JSON3.read(res.body, Vector{String}) return storage_name(s) ∈ possibilities else return false end catch return false end end """ Base.rm([server::Server], e::Environment) Base.rm([server::Server], e::Exec) Base.rm([server::Server], s::Server) Removes an item from the database of `server`. If `server` is not specified the item will removed from the local database. """ function Base.rm(s::Storable) p = config_path("storage", storage_path(s)) * ".json" if !ispath(p) error("No item found at $p.") end return rm(p) end function Base.rm(server, s::Storable) uri = storage_uri(s) return HTTP.put(server, uri) end
RemoteHPC
https://github.com/louisponet/RemoteHPC.jl.git
[ "MIT" ]
0.3.31
a944797808499cb63982b14c42c7cb198d0deb20
code
2287
function flagstring(f, v) out = "" eq_sign = false if f[1] != '-' if length(f) == 1 out *= "-$f " else out *= "--$f" eq_sign = true end else if f[1:2] == "--" out *= "$f" eq_sign = true else out *= "$f " end end if v !== nothing && !isempty(v) if eq_sign out *= "=" end if !(v isa AbstractString) && length(v) > 1 for v_ in v out *= "$v_ " end else out *= "$v " end end return out end function Base.write(io::IO, e::Exec) write(io, "$(e.path) ") for (f, v) in e.flags write(io, flagstring(f, v)) end write(io, " ") end function Base.write(io::IO, c::Calculation) write(io, c.exec) return write(io, "$(c.args)") end function write_exports_string(io::IO, e::Environment) for (f, v) in e.exports write(io, "export $f=$v\n") end end function write_preamble_string(io::IO, e::Environment, sched::Scheduler) for (f, v) in e.directives write(io, "$(directive_prefix(sched)) $(flagstring(f, v))\n") end return write(io, "$(e.preamble)\n") end write_postamble_string(io::IO, e::Environment) = write(io, "$(e.postamble)\n") function Base.write(io::IO, job_info::Tuple, sched::Scheduler) name, e, calcs = job_info write(io, "#!/bin/bash\n") write(io, "# Generated by RemoteHPC\n") write(io, "$(name_directive(sched)) $name\n") write_preamble_string(io, e, sched) write_exports_string(io, e) modules = String[] for c in calcs for m in c.exec.modules if !(m ∈ modules) push!(modules, m) end end end if !isempty(modules) write(io, "module load $(join(modules, " "))\n") end for c in calcs #TODO: Put all of this in write(io, c) write(io, c.run ? "" : "#") if c.exec.parallel write(io, e.parallel_exec) names = "$(e.parallel_exec.name) $(c.exec.name)" else names = c.exec.name end write(io, c) write(io, "\n") end return write_postamble_string(io, e) end
RemoteHPC
https://github.com/louisponet/RemoteHPC.jl.git
[ "MIT" ]
0.3.31
a944797808499cb63982b14c42c7cb198d0deb20
code
3497
@enum LogType RESTLog RuntimeLog const LOGGING_DATE_FORMAT = "yyyy-mm-dd HH:MM:SS" # Logs an error with nice stacktrace function log_error(e; kwargs...) s = IOBuffer() showerror(s, e, catch_backtrace(); backtrace=true) errormsg = String(resize!(s.data, s.size)) @error errormsg kwargs... return errormsg end # Different simple Loggers LevelLogger(logger, level) = EarlyFilteredLogger(logger) do log log.level == level end function TimestampLogger(logger) TransformerLogger(logger) do log if haskey(log.kwargs, :exception) s = IOBuffer() showerror(s, log.kwargs[:exception]...; backtrace=true) msg = String(resize!(s.data, s.size)) else msg = log.message end merge(log, (;message="[$(Dates.format(now(), LOGGING_DATE_FORMAT))] {tid: $(Threads.threadid())} - $msg")) end end mutable struct TimeBufferedFileLogger <: AbstractLogger path::String buffer::IOBuffer lock::ReentrantLock interval::Float64 last_write::Float64 end TimeBufferedFileLogger(p::String; interval = 10.0) = TimeBufferedFileLogger(p, IOBuffer(), ReentrantLock(), interval, 0.0) function Logging.handle_message(logger::TimeBufferedFileLogger, level::LogLevel, message, _module, group, id, filepath, line; kwargs...) @nospecialize msglines = split(chomp(convert(String, string(message))::String), '\n') msg1, rest = Iterators.peel(msglines) curt = time() dt = curt - logger.last_write lock(logger.lock) iob = IOContext(logger.buffer, :compact => true) println(iob, msg1) for msg in rest println(iob, " ", msg) end if dt > logger.interval fsize = filesize(logger.path) open(logger.path, append = fsize < 100e6, truncate = fsize >= 100e6) do f write(f, view(logger.buffer.data, 1:logger.buffer.size)) logger.buffer.size = 0 logger.buffer.ptr = 1 end logger.last_write = curt end unlock(logger.lock) end LoggingExtras.min_enabled_level(::TimeBufferedFileLogger) = LoggingExtras.BelowMinLevel LoggingExtras.shouldlog(::TimeBufferedFileLogger, args...) = true LoggingExtras.catch_exceptions(filelogger::TimeBufferedFileLogger) = false function RESTLogger(; kwargs...) test(log) = get(log.kwargs, :logtype, nothing) == RESTLog tlogger = TransformerLogger(TimeBufferedFileLogger(config_path("logs/restapi.log"); kwargs...)) do log return merge(log, (;kwargs=())) end return ActiveFilteredLogger(test, tlogger) end function RuntimeLogger(;kwargs...) test(log) = get(log.kwargs, :logtype, nothing) == RuntimeLog tlogger = TransformerLogger(TimeBufferedFileLogger(config_path("logs/runtime.log"); kwargs...)) do log return merge(log, (;kwargs=())) end return ActiveFilteredLogger(test, tlogger) end function GenericLogger(; kwargs...) return ActiveFilteredLogger(TimeBufferedFileLogger(config_path("logs/errors.log"); kwargs...)) do log return get(log.kwargs, :logtype, nothing) === nothing end end function HTTPLogger(logger = TimeBufferedFileLogger(config_path("logs/HTTP.log"))) return EarlyFilteredLogger(logger) do log return log._module === HTTP || parentmodule(log._module) === HTTP end end function NotHTTPLogger(logger) return EarlyFilteredLogger(logger) do log return log._module !== HTTP && parentmodule(log._module) !== HTTP end end
RemoteHPC
https://github.com/louisponet/RemoteHPC.jl.git
[ "MIT" ]
0.3.31
a944797808499cb63982b14c42c7cb198d0deb20
code
14495
mutable struct Job id::Int state::JobState end Base.@kwdef mutable struct QueueInfo full_queue::Dict{String,Job} = Dict{String,Job}() current_queue::Dict{String,Job} = Dict{String,Job}() submit_queue::PriorityQueue{String, Tuple{Int, Float64}} = PriorityQueue{String, Tuple{Int, Float64}}(Base.Order.Reverse) end StructTypes.StructType(::Type{QueueInfo}) = StructTypes.Mutable() struct Queue lock::ReentrantLock info::QueueInfo end Queue() = Queue(ReentrantLock(), QueueInfo()) function Base.lock(f::Function, q::Queue) lock(q.lock) try f(q.info) catch e log_error(e, logtype=RuntimeLog) finally unlock(q.lock) end end function Base.fill!(qu::Queue, s::Scheduler, init) qfile = config_path("jobs", "queue.json") if init if ispath(qfile) t = read(qfile) if !isempty(t) # TODO: should be deprecated tq = JSON3.read(t) lock(qu) do q q.full_queue = StructTypes.constructfrom(Dict{String,Job}, tq[:full_queue]) q.current_queue = StructTypes.constructfrom(Dict{String, Job}, tq[:current_queue]) if tq[:submit_queue] isa AbstractArray for jdir in tq[:submit_queue] q.submit_queue[jdir] = DEFAULT_PRIORITY q.full_queue[jdir].state = Submitted end else for (jdir, priority) in tq[:submit_queue] if length(priority) > 1 q.submit_queue[string(jdir)] = (priority...,) else q.submit_queue[string(jdir)] = (priority, -time()) end end end end end end end lock(qu) do q for q_ in (q.full_queue, q.current_queue) for (dir, info) in q_ if !ispath(joinpath(dir, "job.sh")) delete!(q_, dir) end end end end # Here we check whether the scheduler died while the server was running and try to restart and resubmit if maybe_scheduler_restart(s) lock(qu) do q for (d, i) in q.current_queue if ispath(joinpath(d, "job.sh")) q.full_queue[d] = Job(-1, Saved) q.submit_queue[d] = (DEFAULT_PRIORITY, -time()) end pop!(q.current_queue, d) end end else squeue = queue(s) lock(qu) do q for (d, i) in q.current_queue if haskey(squeue, d) state = pop!(squeue, d)[2] else state = jobstate(s, i.id) end if in_queue(state) delete!(q.full_queue, d) q.current_queue[d] = Job(i.id, state) else delete!(q.current_queue, d) q.full_queue[d] = Job(i.id, state) end end for (k, v) in squeue q.current_queue[k] = Job(v...) end end end return qu end Base.@kwdef mutable struct ServerData server::Server total_requests::Int = 0 current_requests::Int = 0 t::Float64 = time() requests_per_second::Float64 = 0.0 total_job_submissions::Int = 0 submit_channel::Channel{Pair{String, Tuple{Int, Float64}}} = Channel{Pair{String, Tuple{Int, Float64}}}(Inf) queue::Queue = Queue() sleep_time::Float64 = 5.0 connections::Dict{String, Bool} = Dict{String, Bool}() stop::Bool = false lock::ReentrantLock = ReentrantLock() end const SLEEP_TIME = Ref(5.0) function main_loop(s::ServerData) fill!(s.queue, s.server.scheduler, true) # Used to identify if multiple servers are running in order to selfdestruct # log_mtimes = mtime.(joinpath.((config_path("logs/runtimes/"),), readdir(config_path("logs/runtimes/")))) t = Threads.@spawn while !s.stop try fill!(s.queue, s.server.scheduler, false) JSON3.write(config_path("jobs", "queue.json"), s.queue.info) catch e log_error(e, logtype = RuntimeLog) end sleep(s.sleep_time) end Threads.@spawn while !s.stop try handle_job_submission!(s) catch e log_error(e, logtype = RuntimeLog) end sleep(s.sleep_time) end while !s.stop # monitor_issues(log_mtimes) try log_info(s) catch e log_error(e, logtype = RuntimeLog) end if ispath(config_path("self_destruct")) @debug "self_destruct found, self destructing..." exit() end sleep(s.sleep_time) end fetch(t) return JSON3.write(config_path("jobs", "queue.json"), s.queue.info) end function log_info(s::ServerData) dt = time() - s.t lock(s.lock) curreq = s.current_requests s.current_requests = 0 s.t = time() unlock(s.lock) s.requests_per_second = curreq / dt s.total_requests += curreq @debugv 0 "current_queue: $(length(s.queue.info.current_queue)) - submit_queue: $(length(s.queue.info.submit_queue))" logtype=RuntimeLog @debugv 0 "total requests: $(s.total_requests) - r/s: $(s.requests_per_second)" logtype=RESTLog end function monitor_issues(log_mtimes) # new_mtimes = mtime.(joinpath.((config_path("logs/runtimes"),), # readdir(config_path("logs/runtimes")))) # if length(new_mtimes) != length(log_mtimes) # @error "More Server logs got created signalling a server was started while a previous was running." logtype=RuntimeLog # touch(config_path("self_destruct")) # end # ndiff = length(filter(x -> log_mtimes[x] != new_mtimes[x], 1:length(log_mtimes))) # if ndiff > 1 # @error "More Server logs modification times differed than 1." logtype=RuntimeLog # touch(config_path("self_destruct")) # end end function handle_job_submission!(s::ServerData) @debugv 2 "Submitting jobs" logtype=RuntimeLog to_submit = s.queue.info.submit_queue njobs = length(s.queue.info.current_queue) while !isempty(s.submit_channel) jobdir,priority = take!(s.submit_channel) to_submit[jobdir] = priority end n_submit = min(s.server.max_concurrent_jobs - njobs, length(to_submit)) submitted = 0 for i in 1:n_submit job_dir, priority = dequeue_pair!(to_submit) if ispath(job_dir) curtries = 0 while -1 < curtries < 3 try id = submit(s.server.scheduler, job_dir) @debugv 2 "Submitting Job: $(id)@$(job_dir)" logtype=RuntimeLog lock(s.queue) do q return q.current_queue[job_dir] = Job(id, Pending) end curtries = -1 submitted += 1 catch e curtries += 1 sleep(s.sleep_time) lock(s.queue) do q q.full_queue[job_dir] = Job(-1, SubmissionError) end with_logger(FileLogger(joinpath(job_dir, "submission.err"), append=true)) do log_error(e) end end end if curtries != -1 to_submit[job_dir] = (priority[1] - 1, priority[2]) end else @warnv 2 "Submission job at dir: $job_dir is not a directory." logtype=RuntimeLog end end @debugv 2 "Submitted $submitted jobs" logtype=RuntimeLog end function requestHandler(handler, s::ServerData) return function f(req) start = Dates.now() @debugv 2 "BEGIN - $(req.method) - $(req.target)" logtype=RESTLog resp = HTTP.Response(404) try obj = handler(req) if obj === nothing resp = HTTP.Response(204) elseif obj isa HTTP.Response return obj elseif obj isa Exception resp = HTTP.Response(500, log_error(obj)) else resp = HTTP.Response(200, JSON3.write(obj)) end catch e resp = HTTP.Response(500, log_error(e)) end stop = Dates.now() @debugv 2 "END - $(req.method) - $(req.target) - $(resp.status) - $(Dates.value(stop - start)) - $(length(resp.body))" logtype=RESTLog lock(s.lock) s.current_requests += 1 unlock(s.lock) return resp end end function AuthHandler(handler, user_uuid::UUID) return function f(req) if HTTP.hasheader(req, "USER-UUID") uuid = HTTP.header(req, "USER-UUID") if UUID(uuid) == user_uuid t = ThreadPools.spawnbg() do return handler(req) end while !istaskdone(t) yield() end return fetch(t) end end return HTTP.Response(401, "unauthorized") end end function check_connections!(connections, verify_tunnels; names=keys(connections)) @debug "Checking connections..." logtype=RuntimeLog for n in names if !exists(Server(name=n)) pop!(connections, n) continue end s = load(Server(n)) s.domain == "localhost" && continue try connections[n] = @timeout 30 begin return HTTP.get(s, URI(path="/isalive")) !== nothing end false catch connections[n] = false end end if verify_tunnels @debugv 1 "Verifying tunnels" logtype=RuntimeLog for n in names connections[n] && continue s = load(Server(n)) s.domain == "localhost" && continue @debugv 0 "Connection to $n: $(connections[n])" logtype=RuntimeLog connections[n] = @timeout 30 begin destroy_tunnel(s) try remote_server = load_config(s.username, s.domain, config_path(s)) remote_server === nothing && return false s.port = construct_tunnel(s, remote_server.port) sleep(5) s.uuid = remote_server.uuid try HTTP.get(s, URI(path="/isalive")) !== nothing save(s) @debugv 1 "Connected to $n" logtype=RuntimeLog return true catch destroy_tunnel(s) return false end catch err log_error(err, logtype=RuntimeLog) destroy_tunnel(s) return false end end false end end return connections end function check_connections!(server_data::ServerData, args...; kwargs...) all_servers = load(Server("")) for k in filter(x-> !(x in all_servers), keys(server_data.connections)) delete!(server_data.connections, k) end for n in all_servers n == server_data.server.name && continue server_data.connections[n] = get(server_data.connections, n, false) end conn = check_connections!(server_data.connections, args...; kwargs...) @debugv 1 "Connections: $(server_data.connections)" logtype=RuntimeLog return conn end function julia_main(;verbose=0, kwargs...)::Cint logger = TimestampLogger(TeeLogger(HTTPLogger(), NotHTTPLogger(TeeLogger(RESTLogger(), RuntimeLogger(), GenericLogger())))) with_logger(logger) do LoggingExtras.withlevel(LoggingExtras.Debug; verbosity=verbose) do try s = local_server() port, server = listenany(ip"0.0.0.0", 8080) s.port = port server_data = ServerData(server=s; kwargs...) @debug "Setting up Router" logtype=RuntimeLog setup_core_api!(server_data) setup_job_api!(server_data) setup_database_api!() connection_task = Threads.@spawn @stoppable server_data.stop begin @debug "Checking Connections" logtype=RuntimeLog try check_connections!(server_data, false) while true t = time() check_connections!(server_data, false) sleep_t = 5 - (time() - t) if sleep_t > 0 sleep(sleep_t) end end catch e log_error(e) end end @debug "Starting main loop" logtype=RuntimeLog t = Threads.@spawn try main_loop(server_data) catch e log_error(e, logtype=RuntimeLog) end @debug "Starting RESTAPI - HOST $(gethostname()) - USER $(get(ENV, "USER", "unknown_user"))" logtype=RuntimeLog save(s) @async serve(middleware = [x -> requestHandler(x, server_data), x -> AuthHandler(x, UUID(s.uuid))], host="0.0.0.0", port=Int(port), server = server, access_log=nothing, serialize=false) while !server_data.stop sleep(1) end @debug "Shutting down server" terminate() fetch(t) fetch(connection_task) return 0 catch e log_error(e) rethrow(e) end end end end
RemoteHPC
https://github.com/louisponet/RemoteHPC.jl.git
[ "MIT" ]
0.3.31
a944797808499cb63982b14c42c7cb198d0deb20
code
9167
abstract type Scheduler end @kwdef struct Bash <: Scheduler type::String = "bash" end @kwdef struct Slurm <: Scheduler type::String = "slurm" end @kwdef struct HQ <: Scheduler type::String = "hq" server_command::String = "hq" allocs::Vector{String} = String[] end StructTypes.StructType(::Type{Cmd}) = StructTypes.Struct() StructTypes.StructType(::Type{Scheduler}) = StructTypes.AbstractType() StructTypes.subtypes(::Type{Scheduler}) = (bash = Bash, slurm = Slurm, hq = HQ) StructTypes.StructType(::Type{Bash}) = StructTypes.Struct() StructTypes.StructType(::Type{Slurm}) = StructTypes.Struct() StructTypes.StructType(::Type{HQ}) = StructTypes.Struct() StructTypes.subtypekey(::Type{Scheduler}) = :type function Scheduler(d::Dict{String,Any}) t = d["type"] if t == "bash" return Bash(t) elseif t == "slurm" return Slurm(t) else return HQ(t, d["server_command"], string.(d["allocs"])) end end Base.convert(::Type{Scheduler}, d::Dict) = Scheduler(d) function submit(::S, ::AbstractString) where {S<:Scheduler} return error("No submit method defined for $S.") end abort(::S, ::Int) where {S<:Scheduler} = error("No abort method defined for $S.") jobstate(::S, ::Any) where {S<:Scheduler} = error("No jobstate method defined for $S.") submit_cmd(s::S) where {S<:Scheduler} = error("No submit_cmd method defined for $S.") submit_cmd(s::Slurm) = "sbatch" submit_cmd(s::Bash) = "bash" submit_cmd(s::HQ) = "hq" function is_reachable(server_command::String) t = run(string2cmd("which $server_command"); wait = false) while !process_exited(t) sleep(0.005) end return t.exitcode == 0 end is_reachable(s::HQ) = is_reachable(s.server_command) is_reachable(::Slurm) = is_reachable("sbatch") is_reachable(::Bash) = true directive_prefix(::Slurm) = "#SBATCH" directive_prefix(::Bash) = "#" directive_prefix(::HQ) = "#HQ" name_directive(::Slurm) = "#SBATCH --job-name" name_directive(::Bash) = "# job-name" name_directive(::HQ) = "#HQ --name" function parse_params(sched::Scheduler, preamble::String) m = match(r"$(directive_prefix(sched)) (.+)\n", preamble) params = Dict() last = 0 while m !== nothing s = split(replace(replace(m.captures[1], "-" => ""), "=" => " ")) tp = Meta.parse(s[2]) t = tp isa Symbol || tp isa Expr ? s[2] : tp params[s[1]] = t last = m.offset + length(m.match) m = match(r"$(directive_prefix(sched)) (.+)\n", preamble, last) end return params, preamble[last:end] end maybe_scheduler_restart(::Bash) = false queue(::Bash) = Dict() function jobstate(::Bash, id::Int) out = Pipe() err = Pipe() p = run(pipeline(ignorestatus(`ps -p $id`); stderr = err, stdout = out)) close(out.in) close(err.in) return p.exitcode == 1 ? Completed : Running end function submit(::Bash, j::AbstractString) return Int(getpid(run(Cmd(`bash job.sh`; detach = true, dir = j); wait = false))) end function abort(::Bash, id::Int) pids = [parse(Int, split(s)[1]) for s in readlines(`ps -s $id`)[2:end]] for p in pids run(ignorestatus(`kill $p`)) end end function in_queue(s::JobState) return s in (Submitted, Pending, Running, Configuring, Completing, Suspended) end ## SLURM ## function maybe_scheduler_restart(::Slurm) if occursin("error", read(`squeue -u $(ENV["USER"])`, String)) if occursin("(null)", read(`slurmd`, String)) error("Can not start slurmctld automatically...") else return true end else return false end end function queue(sc::Slurm) qlines = readlines(`squeue -u $(ENV["USER"]) --format="%Z %i %T"`)[2:end] return Dict([(s = split(x); s[1] => (parse(Int, s[2]), jobstate(sc, s[3]))) for x in qlines]) end function jobstate(s::Slurm, id::Int) cmd = `sacct -u $(ENV["USER"]) --format=State -j $id -P` st = Unknown try lines = readlines(cmd) if length(lines) > 1 st = jobstate(s, lines[2]) end catch nothing end st != Unknown && return st cmd = `scontrol show job $id` try lines = read(cmd, String) reg = r"JobState=(\w+)\b" m = match(reg, lines) return jobstate(s, m[1]) catch return Unknown end end function jobstate(::Slurm, state::AbstractString) if state == "PENDING" return Pending elseif state == "RUNNING" return Running elseif state == "COMPLETED" return Completed elseif state == "CONFIGURING" return Configuring elseif state == "COMPLETING" return Completing elseif state == "CANCELLED" return Cancelled elseif state == "BOOT_FAIL" return BootFail elseif state == "DEADLINE" return Deadline elseif state == "FAILED" return Failed elseif state == "NODE_FAIL" return NodeFail elseif state == "OUT_OF_MEMORY" return OutOfMemory elseif state == "PREEMTED" return Preempted elseif state == "REQUEUED" return Requeued elseif state == "RESIZING" return Resizing elseif state == "REVOKED" return Revoked elseif state == "SUSPENDED" return Suspended elseif state == "TIMEOUT" return Timeout end return Unknown end function submit(::Slurm, j::AbstractString) return parse(Int, split(read(Cmd(`sbatch job.sh`; dir = j), String))[end]) end abort(::Slurm, id::Int) = run(`scancel $id`) #### HQ function maybe_scheduler_restart(sc::HQ) function readinfo() out = Pipe() err = Pipe() run(pipeline(Cmd(Cmd(string.([split(sc.server_command)..., "server", "info"])); ignorestatus = true); stdout = out, stderr = err)) close(out.in) close(err.in) return read(err, String) end if occursin("No online", readinfo()) run(Cmd(Cmd(string.([split(sc.server_command)..., "server", "start"])); detach = true); wait = false) sleep(0.01) tries = 0 while occursin("No online", readinfo()) && tries < 10 sleep(0.01) tries += 1 end if tries == 10 error("HQ server not reachable") end maybe_restart_allocs(sc) return true else maybe_restart_allocs(sc) return false end end function maybe_restart_allocs(sc::HQ) alloc_lines = readlines(Cmd(Cmd(string.([split(sc.server_command)..., "alloc", "list"])))) if length(alloc_lines) == 3 # no allocs -> add all allocs_to_add = sc.allocs else alloc_args = map(a -> replace(strip(split(a, "|")[end-1]), "," => " "), alloc_lines[4:end-1]) allocs_to_add = filter(a -> !any(x -> x == strip(split(a, "-- ")[end]), alloc_args), sc.allocs) end for ac in allocs_to_add try run(Cmd(string.([split(sc.server_command)..., "alloc", "add", split(ac)...]))) catch e log_error(e) end end end function queue(sc::HQ) all_lines = readlines(Cmd(string.([split(sc.server_command)..., "job", "list"]))) start_id = findnext(x -> x[1] == '+', all_lines, 2) endid = findnext(x -> x[1] == '+', all_lines, start_id + 1) if endid === nothing return Dict() end qlines = all_lines[start_id+1:endid-1] jobinfos = [(s = split(x); (parse(Int, s[2]), jobstate(sc, s[6]))) for x in qlines] workdir_line_id = findfirst(x -> occursin("Working directory", x), readlines(Cmd(string.([split(sc.server_command)..., "job", "info", "$(jobinfos[1][1])"])))) function workdir(id) return split(readlines(Cmd(string.([split(sc.server_command)..., "job", "info", "$id"])))[workdir_line_id])[end-1] end return Dict([workdir(x[1]) => x for x in jobinfos]) end function jobstate(s::HQ, id::Int) lines = readlines(Cmd(string.([split(s.server_command)..., "job", "info", "$id"]))) if length(lines) <= 1 return Unknown end return jobstate(s, split(lines[findfirst(x -> occursin("State", x), lines)])[4]) end function jobstate(::HQ, state::AbstractString) if state == "WAITING" return Pending elseif state == "RUNNING" return Running elseif state == "FINISHED" return Completed elseif state == "CANCELED" return Cancelled elseif state == "FAILED" return Failed end return Unknown end function submit(h::HQ, j::AbstractString) chmod(joinpath(j, "job.sh"), 0o777) out = read(Cmd(Cmd(string.([split(h.server_command)..., "submit", "./job.sh"])); dir = j), String) if !occursin("successfully", out) error("Submission error for job in dir $j.") end return parse(Int, split(out)[end]) end function abort(h::HQ, id::Int) return run(Cmd(string.([split(h.server_command)..., "job", "cancel", "$id"]))) end
RemoteHPC
https://github.com/louisponet/RemoteHPC.jl.git
[ "MIT" ]
0.3.31
a944797808499cb63982b14c42c7cb198d0deb20
code
23415
using REPL.TerminalMenus using OpenSSH_jll const SERVER_DIR = config_path("storage/servers") """ Server(name ::String, username ::String, domain ::String, scheduler ::Scheduler, julia_exec ::String, jobdir ::String, max_concurrent_jobs ::Int) Server(name::String) A [`Server`](@ref) represents a daemon running either locally or on some remote cluster. It facilitates all remote operations that are required to save, submit, monitor and retrieve HPC jobs. As with any [`Storable`](@ref), `name` is used simply as a label. `username` and `domain` should be those that allow for `ssh` connections between your local machine and the remote host. Make sure that passwords are not required to execute `ssh` commands, i.e. by having copied your `ssh` keys using `ssh-copy-id`. `julia_exec` should be the path on the remote host where to find the `julia` executable. `scheduler` will be automatically deduced but can be overridden if needed. """ @kwdef mutable struct Server <: Storable name::String = "" username::String = "" domain::String = "" scheduler::Scheduler = Bash() julia_exec::String = "julia" jobdir::String = "" port::Int = 8080 max_concurrent_jobs::Int = 100 uuid::String = "" end storage_directory(::Server) = "servers" function configure_scheduler(s::Server; interactive = true) scheduler = nothing if haskey(ENV, "REMOTEHPC_SCHEDULER") sched = ENV["REMOTEHPC_SCHEDULER"] if occursin("hq", lowercase(sched)) cmd = get(ENV, "REMOTEHPC_SCHEDULER_CMD", "hq") return HQ(; server_command = cmd) elseif lowercase(sched) == "slurm" return Slurm() else error("Scheduler $sched not recognized please set a different REMOTEHPC_SCHEDULER environment var.") end end for t in (HQ(), Slurm()) scmd = submit_cmd(t) if server_command(s, "which $scmd").exitcode == 0 scheduler = t break end end if scheduler !== nothing return scheduler end if interactive && scheduler === nothing choice = request("Couldn't identify the scheduler select one: ", RadioMenu(["SLURM", "HQ", "BASH"])) if choice == 1 scheduler = Slurm() elseif choice == 2 scheduler = HQ(; server_command = ask_input(String, "HQ command", "hq")) elseif choice == 3 scheduler = Bash() else return end return scheduler else return Bash() end end function configure!(s::Server; interactive = true) if s.domain == "localhost" s.julia_exec = joinpath(Sys.BINDIR, "julia") else if interactive username = ask_input(String, "Username") domain = ask_input(String, "Domain") if server_command(username, domain, "ls").exitcode != 0 error("$username@$domain not reachable") end s = Server(name=s.name, username=username, domain=domain) @debug "Trying to pull existing configuration from $username@$domain..." try server = load_config(username, domain, config_path(s)) catch server = nothing end if server !== nothing server.name = s.name server.domain = s.domain change_config = request("Found remote server configuration:\n$server\nIs this correct?", RadioMenu(["yes", "no"])) change_config == -1 && return if change_config == 1 save(server) return server else s = server end else @debug "Couldn't pull server configuration, creating new..." server = Server(; name = s.name, domain = domain, username = username) end julia = ask_input(String, "Julia executable path", s.julia_exec) if server_command(s.username, s.domain, "which $julia").exitcode != 0 yn_id = request("$julia, no such file or directory. Install julia?", RadioMenu(["yes", "no"])) yn_id == -1 && return if yn_id == 1 s.julia_exec = install_julia(s) install(s) else @debug """ You will need to install julia, e.g. by using `RemoteHPC.install_julia` or manually on the cluster. Afterwards don't forget to update server.julia_exec to the correct one before starting the server. """ end else s.julia_exec = julia end else s.julia_exec = "julia" end end # Try auto configuring the scheduler scheduler = configure_scheduler(s; interactive = interactive) if scheduler === nothing return end s.scheduler = scheduler hdir = server_command(s, "pwd").stdout[1:end-1] if interactive dir = ask_input(String, "Default Jobs directory", hdir) if dir != hdir while server_command(s, "ls $dir").exitcode != 0 # @warn "$dir, no such file or directory." local_choice = request("No such directory, creating one?", RadioMenu(["yes", "no"])) if local_choice == 1 result = server_command(s, "mkdir -p $dir") if result.exitcode != 0 @warn "Couldn't create $dir, try a different one." end else dir = ask_input(String, "Default jobs directory") end end end s.jobdir = dir s.max_concurrent_jobs = ask_input(Int, "Max Concurrent Jobs", s.max_concurrent_jobs) else s.jobdir = hdir end conf_path = config_path(s) t = server_command(s, "ls $(conf_path)") if t.exitcode != 0 install(s) end s.uuid = string(uuid4()) return s end """ configure_local() Runs through interactive configuration of the local [`Server`](@ref). """ function configure_local(; interactive = true) host = gethostname() @assert !exists(Server(; name = host)) "Local server already configured." user = get(ENV, "USER", "nouser") s = Server(; name = host, username = user, domain = "localhost") configure!(s; interactive = interactive) @debug "saving server configuration...", s save(s) if interactive start_server = request("Start server?", RadioMenu(["yes", "no"])) start_server == -1 && return if start_server == 1 start(s) end end return s end function Server(s::AbstractString; overwrite=false) t = Server(; name = s) return isempty(s) ? t : load(t) end islocal(s::Server) = s.domain == "localhost" function local_server() s = Server(name=gethostname()) if !exists(s) error("Local Server wasn't configured. Try running `using Pkg; Pkg.build(\"RemoteHPC\")`") end return load(s) end # TODO use versions.json from main julia site function install_julia(s::Server) julia_tar = "julia-1.8.5-linux-x86_64.tar.gz" title = "Installing julia on Server $(s.name) ($(s.username)@$(s.domain))..." steps = ["downloading locally", "pushing to remote", "unpacking on remote"] StepSpinner(title, steps) do spinner t = tempname() mkdir(t) download("https://julialang-s3.julialang.org/bin/linux/x64/1.8/julia-1.8.5-linux-x86_64.tar.gz", joinpath(t, "julia.tar.gz")) next!(spinner) push(joinpath(t, "julia.tar.gz"), s, julia_tar) rm(t; recursive = true) next!(spinner) res = server_command(s, "tar -xf $julia_tar") if res.exitcode != 0 finish!(spinner, ErrorException("Issue unpacking julia executable on cluster, please install julia manually")) end server_command(s, "rm $julia_tar") s.julia_exec = "~/julia-1.8.5/bin/julia" save(s) return s.julia_exec end end function install(s::Server, julia_exec = s.julia_exec) # We install the latest version of julia in the homedir title = "Installing RemoteHPC on remote" steps = ["installing julia", "installing RemoteHPC"] StepSpinner(title, steps) do spinner res = server_command(s, "which $julia_exec") if res.exitcode != 0 julia_exec = install_julia(s) else julia_exec = res.stdout[1:end-1] end next!(spinner) s.julia_exec = julia_exec res = julia_cmd(s, "using Pkg; Pkg.activate(joinpath(Pkg.depots()[1], \"config/RemoteHPC\")); Pkg.add(\"RemoteHPC\");Pkg.build(\"RemoteHPC\")") if res.exitcode != 0 finish!(spinner, ErrorException("Something went wrong installing RemoteHPC on server, please install manually")) end save(s) end @info "RemoteHPC installed on remote cluster, try starting the server with `start(server)`." end mutable struct StepSpinner steps::Vector{String} step_msgs::Vector{Vector{String}} curstep::Int dt::Float64 spinner::String finished::Bool prog::ProgressUnknown t::Union{Task, Nothing} showvalues::Vector{NTuple{2, String}} end function StepSpinner(title::String, steps::Vector{String}; dt=0.1, spinner = "⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏") step_msgs = [String[] for i = 1:length(steps)] prog = ProgressUnknown(title, spinner=true, dt=0.0) out = StepSpinner(steps, step_msgs, 1, dt, spinner, false, prog, nothing, NTuple{2,String}[]) out.showvalues = showvalues(out) return out end Base.length(s::StepSpinner) = length(s.steps) function ProgressMeter.next!(s::StepSpinner) s.curstep += 1 s.showvalues = showvalues(s) end function ProgressMeter.finish!(s::StepSpinner, msg=nothing) s.finished = true if s.t !== nothing && !istaskdone(s.t) fetch(s.t) end if msg isa AbstractString finish!(s.prog; showvalues = ("SUCCESS", msg)) elseif msg === nothing finish!(s.prog) else finish!(s.prog; spinner = '✗') throw(msg) end end function showvalues(s::StepSpinner) nsteps = length(s) out = NTuple{2, String}[] for i = 1:s.curstep t = [("Step [$i/$nsteps]", s.steps[i])] for (im, msg) in enumerate(s.step_msgs[i]) push!(t, ("$im", msg)) end append!(out, t) end return out end function Base.push!(s::StepSpinner, msg::String) curlen = length(s.step_msgs[s.curstep]) push!(s.step_msgs[s.curstep], msg) push!(s.showvalues, ("$(curlen+1)", msg)) end function StepSpinner(f::Function, args...; kwargs...) s = StepSpinner(args...; kwargs...) s.t = Threads.@spawn begin while !s.finished next!(s.prog, showvalues = s.showvalues, spinner=s.spinner) sleep(s.dt) end end try return f(s) finally finish!(s) end end function update(s::Server) title = "Updating RemoteHPC on Server $(s.name) ($(s.username)@$(s.domain))..." steps = ["Checking server status", "Updating RemoteHPC", "Restarting Server if needed"] StepSpinner(title, steps, spinner= "⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏", dt=0.1) do spinner v = nothing try v = version(s) push!(spinner, "Current version $v") catch push!(spinner, "Current version could not be determined") end alive = isalive(s) if alive push!(spinner, "Server was alive, killing") kill(s) end next!(spinner) if islocal(s) curproj = Pkg.project().path Pkg.activate(joinpath(depot_path(s), "config/RemoteHPC")) push!(spinner, "Executing local update command") Pkg.update() Pkg.activate(curproj) else push!(spinner, "Executing remote update command") res = julia_cmd(s, "using Pkg; Pkg.activate(joinpath(Pkg.depots()[1], \"config/RemoteHPC\")); Pkg.update(\"RemoteHPC\")") if res.exitcode != 0 finish!(spinner, ErrorException("Error while updating Server $(s.name):\nstdout: $(res.stdout) stderr: $(res.stderr) exitcode: $(res.exitcode)")) end end next!(spinner) if alive push!(spinner, "Restarting server...") start(s) end finish!(spinner) if v !== nothing newver = version(s) if v == newver @warn "Version did not update, is RemoteHPC installed from a fixed path on the Server?" else @info "Version $v -> $newver" end else @info "New version $(version(s))" end end end Base.joinpath(s::Server, p...) = joinpath(s.jobdir, p...) function Base.ispath(s::Server, p...) return islocal(s) ? ispath(p...) : JSON3.read(HTTP.get(s, URI(path="/ispath/", query=Dict("path"=> joinpath(p...)))).body, Bool) end function Base.symlink(s::Server, p, p2) if islocal(s) symlink(p, p2) else HTTP.post(s, URI(path="/symlink/"), [p, p2]) return nothing end end function Base.rm(s::Server, p::String) if islocal(s) isdir(p) ? rm(p; recursive = true) : rm(p) else HTTP.post(s, URI(path="/rm/", query=Dict("path" => p))) return nothing end end function Base.read(s::Server, path::String, type = nothing) if islocal(s) return type === nothing ? read(path) : read(path, type) else resp = HTTP.get(s, URI(path="/read/", query = Dict("path" =>path))) t = JSON3.read(resp.body, Vector{UInt8}) return type === nothing ? t : type(t) end end function Base.write(s::Server, path::String, v) if islocal(s) write(path, v) else resp = HTTP.post(s, URI(path="/write/", query = Dict("path" => path)), Vector{UInt8}(v)) return JSON3.read(resp.body, Int) end end function Base.mkpath(s::Server, dir) HTTP.post(s, URI(path="/mkpath/", query=Dict("path" => dir))) return dir end function Base.cp(s::Server, src, dst) HTTP.post(s, URI(path="/cp/"), (src, dst)) return dst end parse_config(config) = JSON3.read(config, Server) read_config(config_file) = parse_config(read(config_file, String)) config_path(s::Server, p...) = joinpath(depot_path(s), "config", "RemoteHPC", p...) function load_config(username, domain, conf_path) hostname = gethostname(username, domain) if domain == "localhost" return parse_config(read(config_path("storage", "servers", "$hostname.json"), String)) else t = server_command(username, domain, "cat $(conf_path)/$hostname/storage/servers/$hostname.json") if t.exitcode != 0 return nothing else return parse_config(t.stdout) end end end function load_config(s::Server) if isalive(s) return JSON3.read(HTTP.get(s, URI(path="/server/config/")).body, Server) else return load_config(s.username, s.domain, config_path(s)) end end function Base.gethostname(username::AbstractString, domain::AbstractString) t = server_command(username, domain, "hostname") if !isempty(t.stderr) error(t.stderr) end return split(t.stdout)[1] end Base.gethostname(s::Server) = gethostname(s.username, s.domain) function depot_path(s::Server) if islocal(s) occursin("cache", Pkg.depots()[1]) ? Pkg.depots()[2] : Pkg.depots()[1] else t = julia_cmd(s, "print(realpath(Base.DEPOT_PATH[1]))") if t.exitcode != 0 error("Server $(s.name) can't be reached:\n$(t.stderr)") end if occursin("cache", t.stdout) return julia_cmd(s, "print(realpath(Base.DEPOT_PATH[2]))").stdout else return t.stdout end end end function julia_cmd(s::Server, cmd::String) return server_command(s, "$(s.julia_exec) --startup-file=no -e ' $cmd '") end ssh_string(s::Server) = s.username * "@" * s.domain function http_uri(s::Server, uri::URI = URI()) return URI(uri, scheme="http", port=s.port, host = "localhost") end function http_uri(s::Server, uri::AbstractString) return URI(URI(uri), scheme="http", port=s.port, host = "localhost") end function Base.rm(s::Server) return ispath(joinpath(SERVER_DIR, s.name * ".json")) && rm(joinpath(SERVER_DIR, s.name * ".json")) end function find_tunnel(s) if haskey(ENV, "USER") lines = readlines(`ps -o pid,command -u $(ENV["USER"])`) else lines = readlines(`ps -eo pid,command`) end t = getfirst(x -> occursin("-N -L", x) && occursin(ssh_string(s), x), lines) if t !== nothing return parse(Int, split(t)[1]) end end function destroy_tunnel(s) t = find_tunnel(s) if t !== nothing try run(`kill $t`) catch nothing end end end function construct_tunnel(s, remote_port) if Sys.which("ssh") === nothing OpenSSH_jll.ssh() do ssh_exec port, serv = listenany(Sockets.localhost, 0) close(serv) run(Cmd(`$ssh_exec -o ExitOnForwardFailure=yes -o ServerAliveInterval=60 -N -L $port:localhost:$remote_port $(ssh_string(s))`); wait=false) return port end else port, serv = listenany(Sockets.localhost, 0) close(serv) cmd = Cmd(`ssh -o ExitOnForwardFailure=yes -o ServerAliveInterval=60 -N -L $port:localhost:$remote_port $(ssh_string(s))`) run(cmd; wait=false) return port end end """ pull(server::Server, remote::String, loc::String) Pulls `remote` from the server to `loc`. """ function pull(server::Server, remote::String, loc::String) if !ispath(server, remote) error("No such file or directory $remote.") end path = isdir(loc) ? joinpath(loc, splitpath(remote)[end]) : loc if islocal(server) cp(remote, path; force = true) else if filesize(server, remote) > 100e6 || isdir(server, remote) out = Pipe() err = Pipe() # OpenSSH_jll.scp() do scp_exec run(pipeline(`scp -r $(ssh_string(server) * ":" * remote) $path`; stdout = out, stderr = err)) # end close(out.in) close(err.in) stderr = read(err, String) if !isempty(stderr) error("$stderr") end else write(loc, read(server, remote)) end end return path end """ push(local_file::String, server::Server, server_file::String) Pushes the `local_file` to the `server_file` on the server. """ function push(filename::String, server::Server, server_file::String) if islocal(server) cp(filename, server_file; force = true) else out = Pipe() err = Pipe() # OpenSSH_jll.scp() do scp_exec run(pipeline(`scp $filename $(ssh_string(server) * ":" * server_file)`; stdout = out, stderr=err)) # end close(out.in) close(err.in) end end "Executes a command through `ssh`." function server_command(username, domain, cmd::String) out = Pipe() err = Pipe() if domain == "localhost" e = ignorestatus(Cmd(string.(split(cmd)))) process = run(pipeline(e; stdout = out, stderr = err)) else if Sys.which("ssh") === nothing OpenSSH_jll.ssh() do ssh_exec process = run(pipeline(ignorestatus(Cmd(["$ssh_exec", "$(username * "@" * domain)", string.(split(cmd))...])); stdout = out, stderr = err)) end else process = run(pipeline(ignorestatus(Cmd(["ssh", "$(username * "@" * domain)", string.(split(cmd))...])); stdout = out, stderr = err)) end end close(out.in) close(err.in) stdout = read(out, String) stderr = read(err, String) return (stdout = stdout, stderr = stderr, exitcode = process.exitcode) end server_command(s::Server, cmd) = server_command(s.username, s.domain, cmd) function has_modules(s::Server) try server_command(s, "module avail").code == 0 catch false end end function available_modules(s::Server) if has_modules(s) return server_command(s, "module avail") else return String[] end end function HTTP.request(method::String, s::Server, url, body; kwargs...) header = ["USER-UUID" => s.uuid] return HTTP.request(method, http_uri(s, url), header, JSON3.write(body); kwargs...) end function HTTP.request(method::String, s::Server, url, body::Vector{UInt8}; kwargs...) header = ["USER-UUID" => s.uuid] return HTTP.request(method, http_uri(s, url), header, body; kwargs...) end function HTTP.request(method::String, s::Server, url; connect_timeout = 1, retries = 2, kwargs...) header = ["USER-UUID" => s.uuid] return HTTP.request(method, http_uri(s, url), header; connect_timeout = connect_timeout, retries = retries, kwargs...) end for f in (:get, :put, :post, :head, :patch) str = uppercase(string(f)) @eval function HTTP.$(f)(s::Server, url::AbstractString, args...; kwargs...) return HTTP.request("$($str)", s, url, args...; kwargs...) end end function Base.readdir(s::Server, dir::AbstractString) resp = HTTP.get(s, URI(path="/readdir/", query=Dict("path" => abspath(s, dir)))) return JSON3.read(resp.body, Vector{String}) end Base.abspath(s::Server, p) = isabspath(p) ? p : joinpath(s, p) function Base.mtime(s::Server, p) if islocal(s) return mtime(p) else resp = HTTP.get(s, URI(path="/mtime/", query=Dict("path" => p))) return JSON3.read(resp.body, Float64) end end function Base.filesize(s::Server, p) if islocal(s) return filesize(p) else resp = HTTP.get(s, URI(path="/filesize/", query = Dict("path" => p))) return JSON3.read(resp.body, Float64) end end function Base.realpath(s::Server, p) if islocal(s) return realpath(p) else resp = HTTP.get(s, URI(path="/realpath/", query=Dict("path" => p))) return JSON3.read(resp.body, String) end end
RemoteHPC
https://github.com/louisponet/RemoteHPC.jl.git
[ "MIT" ]
0.3.31
a944797808499cb63982b14c42c7cb198d0deb20
code
6915
@enum JobState BootFail Pending Running Completed Cancelled Deadline Failed NodeFail OutOfMemory Preempted Requeued Resizing Revoked Suspended Timeout Submitted Unknown PostProcessing Saved Configuring Completing SubmissionError """ Exec(;name::String = "", path::String = "", flags::Dict = Dict(), modules::Vector{String} = String[], parallel::Bool = true) Representation of an executable. As with any [`Storable`](@ref), `name` is used simply as a label to be able to [`load`](@ref) it from the [`Server`](@ref) where it is stored. In a job script this will be translated as `<path> <flags>`. # `configure()` Example ```julia name::String = "exec_label" path::String = "/path/to/exec" flags::Dict{Any, Any} = Dict{Any, Any}("l" => 1, "-np" => 4, "trialname" => "testtrial") modules::Vector{String} = String["intel","intel-mkl"] parallel::Bool = false ``` # Example: ```julia Exec(; path="ls", flags=Dict("l" => "")) ``` translates into `ls -l` in the jobscript. # Flags The `flags` `Dict` is expanded into the jobscript as follows: ```julia Exec(path="foo", flags = Dict("N" => 1, "-nk" => 10, "np" => "\$NPOOLS", "--t" => "", "--t2" => 24) # translates into: foo -N1 -nk 10 --np=\$NPOOLS --t --t2=24 ``` # Modules The `modules` vector gets expanded into `module load` commands: `modules = ["gcc", "QuantumESPRESSO"]` will lead to `module load gcc, QuantumESPRESSO` in the jobscript. # Parallel `parallel` communicates whether the executable should be ran with the parallel executable defined in the [`Environment`](@ref) that represents the execution environment. For example: ```julia # If the Environment of the job is defined as: Environment(parallel_exec=Exec(path="srun")) # then the follow Exec: Exec(path="foo", parallel=true) # wille be translated into: srun foo ``` """ @kwdef mutable struct Exec <: Storable name::String = "" path::String = "" flags::Dict = Dict() modules::Vector{String} = String[] parallel::Bool = true end function Exec(d::Dict) if haskey(d, :dir) Base.depwarn("Constructor with separate `dir` and `exec` will be deprecated. Use one `path` instead.", :Exec) return Exec(d[:name], joinpath(d[:dir], d[:exec]), d[:flags], d[:modules], d[:parallel]) else return Exec(d[:name], d[:path], d[:flags], d[:modules], d[:parallel]) end end function Exec(a,b,c,d,e,f) Base.depwarn("Constructor with separate `dir` and `exec` will be deprecated. Use one `path` instead.", :Exec) return Exec(a, joinpath(b, c), d, e, f) end exec(e::Exec) = splitdir(e.path)[end] Base.dirname(e::Exec) = splitdir(e.path)[1] # Backwards compatibility function Base.getproperty(e::Exec, name::Symbol) if name == :dir Base.depwarn("`e.dir` will be deprecated. Use `dirname(e)` instead.", :Exec) return dirname(e.path) elseif name == :exec Base.depwarn("`e.exec` will be deprecated. Use `exec(e)` instead.", :Exec) return exec(e) else return getfield(e, name) end end function Base.setproperty!(e::Exec, name::Symbol, v) if name == :dir Base.depwarn("`e.dir` will be deprecated in favor of `e.path`.", :Exec) return setfield!(e, :path, joinpath(v, exec(e))) elseif name == :exec Base.depwarn("`e.exec` will be deprecated in favor of `e.path`.", :Exec) return setfield!(e, :path, joinpath(dirname(e), v)) else return setfield!(e, name, v) end end function isrunnable(e::Exec) # To find the path to then ldd on fullpath = Sys.which(e.path) if fullpath !== nothing && ispath(fullpath) out = Pipe() err = Pipe() #by definition by submitting something with modules this means the server has them if !isempty(e.modules) cmd = `echo "source /etc/profile && module load $(join(e.modules, " ")) && ldd $fullpath"` else cmd = `echo "source /etc/profile && ldd $fullpath"` end run(pipeline(pipeline(cmd; stdout = ignorestatus(`bash`)); stdout = out, stderr = err)) close(out.in) close(err.in) stderr = String(read(err)) stdout = String(read(out)) # This basically means that the executable would run return !occursin("not found", stdout) && !occursin("not found", stderr) else return false end end # Database interface @assign Exec with Is{Storable} storage_directory(::Exec) = "execs" @kwdef struct Calculation exec::Exec args::String = "" run::Bool = true end """ Environment(;name::String, directives::Dict, exports::Dict, preamble::String, postamble::String, parallel_exec::Exec) Represents and execution environment, i.e. a job script for `SLURM`, `HQ`, etc. This forms the skeleton of the scripts with the scheduler directives, exports, pre and postambles, and which executable to use for parallel execution (think `mpirun`, `srun`, etc). As with any [`Storable`](@ref), `name` is used simply as a label to be able to [`load`](@ref) it from the [`Server`](@ref) where it is stored. # `configure()` Example ```julia name::String = "default", directives::Dict{Any, Any} = Dict{Any, Any}("time" => "24:00:00", "partition" => "standard", "account" => "s1073", "N" => 4, "ntasks-per-node" => 36, "cpus-per-task" => 1) exports::Dict{Any, Any} = Dict{Any, Any}("OMP_NUM_THREADS" => 1) preamble::String = "echo hello" postamble::String = "echo goodbye" parallel_exec::Exec = Exec(name="srun", path="srun", flags=Dict("n" => 36)) ``` # Example ```julia Environment( name = "default", directives = Dict("time" => "24:00:00", "partition" => "standard", "account" => "s1073", "N" => 4, "ntasks-per-node" => 36, "cpus-per-task" => 1) exports = Dict("OMP_NUM_THREADS" => 1) preamble = "echo hello" postamble = "echo goodbye" parallel_exec = Exec(name="srun", path="srun", flags=Dict("n" => 36)) ) ``` Will be translated into ```bash #!/bin/bash # Generated by RemoteHPC #SBATCH --job-name <will be filled in upon submission> #SBATCH --time=24:00:00 #SBATCH --partition=standard #SBATCH --account=s1073 #SBATCH -N 4 #SBATCH --ntasks-per-node=36 #SBATCH --cpus-per-task=1 export OMP_NUM_THREADS=1 <module load commands specified by Execs will go here> echo hello srun -n 36 <parallel Exec 1> srun -n 36 <parallel Exec 2> <serial Exec> echo goodbye ``` """ @kwdef mutable struct Environment <: Storable name::String = "" directives::Dict = Dict() exports::Dict = Dict() preamble::String = "" postamble::String = "" parallel_exec::Exec = Exec() end @assign Environment with Is{Storable} storage_directory(::Environment) = "environments"
RemoteHPC
https://github.com/louisponet/RemoteHPC.jl.git
[ "MIT" ]
0.3.31
a944797808499cb63982b14c42c7cb198d0deb20
code
1905
function suppress(f::Function) with_logger(FileLogger("/dev/null")) do return f() end end struct StallException <: Exception e end function Base.showerror(io::IO, err::StallException, args...) print(io, "StallException:") showerror(io, err.e, args...) end macro timeout(seconds, expr, err_expr=:(nothing)) tsk = gensym("tsk") start_time = gensym("start_time") curt = gensym("curt") timer = gensym("timer") err = gensym("err") esc(quote $tsk = @task $expr schedule($tsk) $start_time = time() $curt = time() Base.Timer(0.001, interval=0.001) do $timer if $tsk === nothing || istaskdone($tsk) close($timer) else $curt = time() if $curt - $start_time > $seconds Base.throwto($tsk, InterruptException()) end end end try fetch($tsk) catch $err if $err.task.exception isa InterruptException RemoteHPC.log_error(RemoteHPC.StallException($err)) $err_expr else rethrow($err) end end end) end macro stoppable(stop, expr) tsk = gensym("tsk") timer = gensym("timer") err = gensym("err") esc(quote $tsk = @task $expr schedule($tsk) Base.Timer(0.001, interval=0.001) do $timer if $tsk === nothing || istaskdone($tsk) close($timer) elseif $stop Base.throwto($tsk, InterruptException()) end end try fetch($tsk) catch $err if !($err.task.exception isa InterruptException) rethrow($err) end end end) end
RemoteHPC
https://github.com/louisponet/RemoteHPC.jl.git
[ "MIT" ]
0.3.31
a944797808499cb63982b14c42c7cb198d0deb20
code
5676
using Test using RemoteHPC using RemoteHPC.BinaryTraits @testset "Storable interface" begin @test @check(Exec).result @test @check(Server).result @test @check(Environment).result end tconfdir = tempname() # tconfdir = "/tmp/remotehpc" if ispath(tconfdir) rm(tconfdir; recursive = true) end import RemoteHPC: config_path config_path(p...) = joinpath(tconfdir, p...) paths = ["jobs", "logs/jobs", "storage/servers", "storage/execs", "storage/environments"] for p in paths mkpath(config_path(p)) end redirect_stdin(devnull) do redirect_stderr(devnull) do redirect_stdout(devnull) do RemoteHPC.configure_local(; interactive = false) t = @async RemoteHPC.julia_main(verbose=2) end end end while !isalive(local_server()) sleep(0.1) end const s = local_server() t_jobdir = tempname() if s.scheduler isa HQ scheds = [s.scheduler, Slurm(), Bash()] elseif s.scheduler isa Slurm scheds = [s.scheduler, Bash()] else scheds = [Bash()] end for sched in scheds @testset "$sched" begin @testset "updating config" begin kill(s) s.scheduler = sched save(s) t = @async RemoteHPC.julia_main(verbose=2) while !isalive(local_server()) sleep(0.1) end st = RemoteHPC.load_config(s) @test st.scheduler == sched end @testset "database" begin exec = RemoteHPC.Exec("test", "cat", Dict("f" => 3, "test" => [1, 2, 3], "test2" => "stringtest", "-nk" => 10), ["intel", "intel-mkl"], true) save(s, exec) te = load(s, exec) for f in fieldnames(Exec) @test getfield(te, f) == getfield(exec, f) end exec = RemoteHPC.Exec("test", "cat", Dict(), [], false) redirect_stderr(devnull) do return save(s, exec) end e = Environment("test", Dict("N" => 1, "time" => "00:01:01"), Dict("OMP_NUM_THREADS" => 1), "", "", RemoteHPC.Exec(; name = "srun", path = "srun")) partition = get(ENV, "SLURM_PARTITION", nothing) account = get(ENV, "SLURM_ACCOUNT", nothing) if partition !== nothing e.directives["partition"] = partition end if account !== nothing e.directives["account"] = account end save(s, e) te = load(s, e) for f in fieldnames(Environment) @test getfield(te, f) == getfield(e, f) end es = load(s, Exec("ca")) @test length(es) == 1 es = load(s, Exec(; path = "")) @test length(es) == 1 end @testset "job" begin @testset "creation and save" begin exec = load(s, Exec("test")) c = [Calculation(exec, "< scf.in > scf.out", true), Calculation(exec, "< nscf.in > nscf.out", true)] e = load(s, Environment("test")) save(s, t_jobdir, e, c; name = "testjob") @test state(s, t_jobdir) == RemoteHPC.Saved td = load(s, t_jobdir) @test td.name == "testjob" for (c1, c2) in zip(c, td.calculations) for f in fieldnames(Calculation) @test getfield(c1, f) == getfield(c2, f) end end @test td.environment == e end @testset "submission and running" begin write(s, joinpath(t_jobdir, "scf.in"), "test input") write(s, joinpath(t_jobdir, "nscf.in"), "test input2") submit(s, t_jobdir) while state(s, t_jobdir) != RemoteHPC.Completed sleep(0.1) end @test read(joinpath(t_jobdir, "scf.out"), String) == "test input" @test read(joinpath(t_jobdir, "nscf.out"), String) == "test input2" exec = load(s, Exec("test")) sleep_e = Exec(; name = "sleep", path = "sleep", parallel = false) c = [Calculation(exec, "< scf.in > scf.out", true), Calculation(exec, "< nscf.in > nscf.out", true), Calculation(sleep_e, "10", true)] e = load(s, Environment("test")) submit(s, t_jobdir, e, c; name = "testjob") while state(s, t_jobdir) != RemoteHPC.Running sleep(0.1) end abort(s, t_jobdir) @test state(s, t_jobdir) == RemoteHPC.Cancelled rm(s, t_jobdir) @test !ispath(s, t_jobdir) end end end end @testset "files api" begin @test length(readdir(s, config_path())) == 3 @test filesize(s, config_path("logs/restapi.log")) > 0 @test mtime(s, config_path("logs/restapi.log")) > 0 tname = tempname() write(s, tname, "test") tname2 = tempname() symlink(s, tname, tname2) @test read(s, tname2, String) == "test" rm(s, tname2) rm(s, tname) @test !ispath(s, tname) @test !ispath(s, tname2) end @testset "spinner" begin title = "test" steps = ["test1", "test2"] RemoteHPC.StepSpinner(title, steps,dt=0.1) do s RemoteHPC.push!(s, "blabla") RemoteHPC.next!(s) RemoteHPC.push!(s, "test") end end
RemoteHPC
https://github.com/louisponet/RemoteHPC.jl.git
[ "MIT" ]
0.3.31
a944797808499cb63982b14c42c7cb198d0deb20
docs
1767
# RemoteHPC.jl [![Build Status](https://github.com/louisponet/RemoteHPC.jl/workflows/CI/badge.svg)](https://github.com/louisponet/RemoteHPC.jl/actions?query=workflow%3ACI) [![codecov](https://codecov.io/gh/louisponet/RemoteHPC.jl/branch/master/graph/badge.svg?token=PAFMYMVJUT)](https://codecov.io/gh/louisponet/RemoteHPC.jl) [![Package Downloads](https://shields.io/endpoint?url=https://pkgs.genieframework.com/api/v1/badge/RemoteHPC)](https://pkgs.genieframework.com?packages=RemoteHPC) RemoteHPC attempts to wrap all the usual interactions one might have with a remote HPC cluster in a restAPI webserver that runs on the frontend of the cluster. ## Features - Store locally connection information to remote servers using `Server` - Remotely store information for available executables and execution environments using `save(server, Exec(...))` and `save(server, Environment(...))`. - Load remotely stored info using `load(server, Exec("<label>"))` and `load(server, Environment("<label>"))`. - Represent a line in a jobscript using `Calculation(exec::Exec, infile::String, outfile::String, run::Bool, parallel::Bool)`. - Save and submit a job with `save(server, jobdir, jobname, environment, calculations)` and `submit(server, jobdir)` or combine both steps with `submit(server, jobdir, jobname, environment, calculations)`. - The state of a job can be retrieved by `state(server, jobdir)`. - A job can be aborted using `abort(server, jobdir)`. - Support for running jobs with `SLURM`, `HyperQueue`, or `Bash`. - remote file operations: `read`,`write`, `rm`, `mtime`, `link`, etc. - Starting a remote server with `start(server)` and automatic creation of ssh tunnels by specifying `server.local_tunnel`, useful when the frontend of a cluster is behind a proxy.
RemoteHPC
https://github.com/louisponet/RemoteHPC.jl.git
[ "MIT" ]
0.3.31
a944797808499cb63982b14c42c7cb198d0deb20
docs
47
# RemoteHPC.jl Documentation for RemoteHPC.jl
RemoteHPC
https://github.com/louisponet/RemoteHPC.jl.git
[ "MIT" ]
1.6.0
c08db012b41bedc58adf33ca52a3004b55ad5eaa
code
41470
module RNGTest using Random import Base: convert, getindex, pointer import Distributed: pmap import TestU01_jll: libtestu01, libtestu01extractors swrite = Ref{Ptr{Ptr{Bool}}}() function __init__() swrite[] = cglobal(("swrite_Basic", libtestu01), Ptr{Bool}) unsafe_store!(swrite[], 0, 1) end # WrappedRNG # TestU01 expects a standard function as input (created via # cfunction here). When one wants to test the random stream of # an AbstractRNG, a little more work has to be done before # passing it to TestU01. The type WrappedRNG wraps an # AbstractRNG into an object which knows which type of random # numbers to produce, and also whether the scalar or array API # should be used (this is useful when different algorithms are # used for each case, which results in different streams which # should be tested separately). Such an object can then be # passed to the Unif01 constructor. const TestableNumbers = Union{Int8, UInt8, Int16, UInt16, Int32, UInt32, Int64, UInt64, Int128, UInt128, Float16, Float32, Float64} mutable struct WrappedRNG{T<:TestableNumbers, RNG<:AbstractRNG} rng::RNG cache::Vector{T} fillarray::Bool vals::Vector{UInt32} idx::Int end function WrappedRNG(rng::RNG, ::Type{T}, fillarray = true, cache_size = 3*2^11 ÷ sizeof(T)) where {RNG, T} if T <: Integer && cache_size*sizeof(T) % sizeof(UInt32) != 0 error("cache_size must be a multiple of $(Int(4/sizeof(T))) (for type $T)") elseif T === Float16 && cache_size % 6 != 0 || T === Float32 && cache_size % 3 != 0 error("cache_size must be a multiple of 3 (resp. 6) for Float32 (resp. Float16)") end cache = Vector{T}(undef, cache_size) fillcache(WrappedRNG{T, RNG}(rng, cache, fillarray, unsafe_wrap(Array, convert(Ptr{UInt32}, pointer(cache)), sizeof(cache)÷sizeof(UInt32)), 0)) # 0 is a dummy value, which will be set correctly by fillcache end # The ability to play with the cache size and the fillarray option is for advanced uses, # when one wants to test different code path of the particular RNG implementations, like # MersenneTwister from Base. # For now let's document only the type parameter in the wrap function: wrap(rng::AbstractRNG, ::Type{T}) where {T<:TestableNumbers} = WrappedRNG(rng, T) function fillcache(g::WrappedRNG{T}) where T if g.fillarray rand!(g.rng, g.cache) else for i = 1:length(g.cache) @inbounds g.cache[i] = rand(g.rng, T) end end g.idx = 0 return g end function (g::WrappedRNG{T})() where T<:Integer g.idx+1 > length(g.vals) && fillcache(g) @inbounds return g.vals[g.idx+=1] end function (g::WrappedRNG{Float64})() g.idx+1 > length(g.cache) && fillcache(g) @inbounds return g.cache[g.idx+=1] end function (g::WrappedRNG{Float32})() g.idx+3 > length(g.cache) && fillcache(g) @inbounds begin f = Float64(g.cache[g.idx+1]) # a Float32 has 24 bits of precision, but only 23 bit of entropy f += Float64(g.cache[g.idx+2])/exp2(23) f += Float64(g.cache[g.idx+=3])/exp2(46) return f % 1.0 end end function (g::WrappedRNG{Float16})() g.idx+6 > length(g.cache) && fillcache(g) @inbounds begin f = Float64(g.cache[g.idx+1]) # a Float16 has 10 bits of entropy f += Float64(g.cache[g.idx+2])/exp2(10) f += Float64(g.cache[g.idx+3])/exp2(20) f += Float64(g.cache[g.idx+4])/exp2(30) f += Float64(g.cache[g.idx+5])/exp2(40) f += Float64(g.cache[g.idx+=6])/exp2(50) return f % 1.0 end end # RNGGenerator struct mutable struct Unif01 ptr::Ptr{Cvoid} gentype::Type name::String function Unif01(f::Function, genname) for i in 1:100 tmp = f() if typeof(tmp) != Float64 error("Function must return Float64") end if tmp < 0 || tmp > 1 error("Function must return values on [0,1]") end end cf = @cfunction($f, Float64, ()) # TestU01 crashed if two unif01 object are generated. The only safe thing is to explicitly delete the object when used instead of using finalizers return new(ccall((:unif01_CreateExternGen01, libtestu01), Ptr{Cvoid}, (Ptr{UInt8}, Ptr{Cvoid}), genname, cf), Float64, genname) end function Unif01(g::WrappedRNG{T}, genname) where {T<:AbstractFloat} # we assume that g being created out of an AbstractRNG, it produces Floats in the interval [0,1) cf = @cfunction($g, Float64, ()) return new(ccall((:unif01_CreateExternGen01, libtestu01), Ptr{Cvoid}, (Ptr{UInt8}, Ptr{Cvoid}), genname, cf), Float64, genname) end function Unif01(g::WrappedRNG{T}, genname) where {T<:Integer} @assert Cuint === UInt32 cf = @cfunction($g, UInt32, ()) return new(ccall((:unif01_CreateExternGenBits, libtestu01), Ptr{Cvoid}, (Ptr{UInt8}, Ptr{Cvoid}), genname, cf), UInt32, genname) end end function delete(obj::Unif01) if obj.gentype === Float64 ccall((:unif01_DeleteExternGen01, libtestu01), Cvoid, (Ptr{Cvoid},), obj.ptr) else ccall((:unif01_DeleteExternGenBits, libtestu01), Cvoid, (Ptr{Cvoid},), obj.ptr) end end const RNGGenerator = Union{Function, WrappedRNG} # Result types ## gofw struct Gotw_TestArray data::Vector{Float64} Gotw_TestArray() = new(Vector{Float64}(undef, 11)) end function getindex(obj::Gotw_TestArray, i::Symbol) i == :KSP && return obj.data[1] i == :KSM && return obj.data[2] i == :KS && return obj.data[3] i == :AD && return obj.data[4] i == :CM && return obj.data[5] i == :WG && return obj.data[6] i == :WU && return obj.data[7] i == :Mean && return obj.data[8] i == :Var && return obj.data[9] i == :Cor && return obj.data[10] i == :Sum && return obj.data[11] throw(BoundsError()) end for (t, sCreate, sDelete, sPval) in ((:ResPoisson, :sres_CreatePoisson, :sres_DeletePoisson, :getPValPoisson), (:MarsaRes, :smarsa_CreateRes, :smarsa_DeleteRes, :getPValSmarsa), (:KnuthRes2, :sknuth_CreateRes2, :sknuth_DeleteRes2, :getPValRes2)) @eval begin # The types mutable struct $t ptr::Ptr{Cvoid} function $(t)() res = new(ccall(($(string(sCreate)), libtestu01), Ptr{Cvoid}, (), )) finalizer(delete, res) return res end end # Finalizers function delete(obj::$t) ccall(($(string(sDelete)), libtestu01), Cvoid, (Ptr{Cvoid},), obj.ptr) end # pvalue extractors pvalue(obj::$t) = ccall(($(string(sPval)), libtestu01extractors), Float64, (Ptr{Cvoid},), obj.ptr) end end # Sres # Basic ## Type mutable struct ResBasic ptr::Ptr{Cvoid} function ResBasic() res = new(ccall((:sres_CreateBasic, libtestu01), Ptr{Cvoid}, (), )) finalizer(delete, res) return res end end ## Finalizers function delete(obj::ResBasic) ccall((:sres_DeleteBasic, libtestu01), Cvoid, (Ptr{Cvoid},), obj.ptr) end ## pvalue extractors function pvalue(obj::ResBasic) res = Gotw_TestArray() ccall((:getPValBasic, libtestu01extractors), Cvoid, (Ptr{Cvoid}, Ptr{Float64}), obj.ptr, res.data) return res end # Chi2 ## Type mutable struct ResChi2 ptr::Ptr{Cvoid} N::Int function ResChi2(N::Integer) res = new(ccall((:sres_CreateChi2, libtestu01), Ptr{Cvoid}, (), ), N) finalizer(delete, res) return res end end ## Finalizers function delete(obj::ResChi2) ccall((:sres_DeleteChi2, libtestu01), Cvoid, (Ptr{Cvoid},), obj.ptr) end ## pvalue extractors function pvalue(obj::ResChi2) res = Gotw_TestArray() ccall((:getPValChi2, libtestu01extractors), Cvoid, (Ptr{Cvoid}, Ptr{Float64}), obj.ptr, res.data) return res[obj.N == 1 ? :Mean : :Sum] end # sknuth ## Type mutable struct KnuthRes1 ptr::Ptr{Cvoid} N::Int function KnuthRes1(N::Integer) res = new(ccall((:sknuth_CreateRes1, libtestu01), Ptr{Cvoid}, (), ), N) finalizer(delete, res) return res end end ## Finalizers function delete(obj::KnuthRes1) ccall((:sknuth_DeleteRes1, libtestu01), Cvoid, (Ptr{Cvoid},), obj.ptr) end ## pvalue extractors function pvalue(obj::KnuthRes1) chi = Gotw_TestArray() bas = Gotw_TestArray() ccall((:getPValRes1, libtestu01extractors), Cvoid, (Ptr{Cvoid}, Ptr{Float64}, Ptr{Float64}), obj.ptr, chi.data, bas.data) return chi[obj.N == 1 ? :Mean : :Sum], bas[obj.N == 1 ? :Mean : :AD] end # smarsa ## Type mutable struct MarsaRes2 ptr::Ptr{Cvoid} N::Int function MarsaRes2(N::Integer) res = new(ccall((:smarsa_CreateRes2, libtestu01), Ptr{Cvoid}, (), ), N) finalizer(delete, res) return res end end ## Finalizers function delete(obj::MarsaRes2) ccall((:smarsa_DeleteRes2, libtestu01), Cvoid, (Ptr{Cvoid},), obj.ptr) end ## pvalue extractors function pvalue(obj::MarsaRes2) res = Gotw_TestArray() ccall((:getPValSmarsa2, libtestu01extractors), Cvoid, (Ptr{Cvoid}, Ptr{Float64}), obj.ptr, res.data) return obj.N == 1 ? res[:Mean] : res[:Sum] end # Walk ## Type mutable struct WalkRes ptr::Ptr{Cvoid} N::Int function WalkRes(N::Integer) res = new(ccall((:swalk_CreateRes, libtestu01), Ptr{Cvoid}, (), ), N) finalizer(delete, res) return res end end ## Finalizers function delete(obj::WalkRes) ccall((:swalk_DeleteRes, libtestu01), Cvoid, (Ptr{Cvoid},), obj.ptr) end ## pvalue extractors function pvalue(obj::WalkRes) pH = Gotw_TestArray() pM = Gotw_TestArray() pJ = Gotw_TestArray() pR = Gotw_TestArray() pC = Gotw_TestArray() ccall((:getPVal_Walk, libtestu01extractors), Cvoid, (Ptr{Cvoid}, Ptr{Float64}, Ptr{Float64}, Ptr{Float64}, Ptr{Float64}, Ptr{Float64}), obj.ptr, pH.data, pM.data, pJ.data, pR.data, pC.data) return obj.N == 1 ? (pH[:Mean], pM[:Mean], pJ[:Mean], pR[:Mean], pC[:Mean]) : (pH[:Sum], pM[:Sum], pJ[:Sum], pR[:Sum], pC[:Sum]) end # Npairs struct Snpair_StatArray data::Vector{Float64} Snpair_StatArray() = new(Vector{Float64}(undef, 11)) end function getindex(obj::Snpair_StatArray, i::Symbol) i == :NP && return obj.data[1] i == :NPS && return obj.data[2] i == :NPPR && return obj.data[3] i == :mNP && return obj.data[4] i == :mNP1 && return obj.data[5] i == :mNP1S && return obj.data[6] i == :mNP2 && return obj.data[7] i == :mNP2S && return obj.data[8] i == :NJumps && return obj.data[9] i == :BB && return obj.data[10] i == :BM && return obj.data[11] throw(BoundsError()) end ## Type mutable struct NpairRes ptr::Ptr{Cvoid} N::Int function NpairRes(N::Integer) res = new(ccall((:snpair_CreateRes, libtestu01), Ptr{Cvoid}, (), ), N) finalizer(delete, res) return res end end ## Finalizers function delete(obj::NpairRes) ccall((:snpair_DeleteRes, libtestu01), Cvoid, (Ptr{Cvoid},), obj.ptr) end ## pvalue extractors function pvalue(obj::NpairRes) res = Snpair_StatArray() ccall((:getPVal_Npairs, libtestu01extractors), Cvoid, (Ptr{Cvoid}, Ptr{Float64}), obj.ptr, res.data) return obj.N == 1 ? (res[:NP], res[:mNP]) : (res[:NP], res[:mNP1], res[:mNP2], res[:NJumps]) end # scomp ## Type mutable struct CompRes ptr::Ptr{Cvoid} N::Int function CompRes(N::Integer) res = new(ccall((:scomp_CreateRes, libtestu01), Ptr{Cvoid}, (), ), N) finalizer(delete, res) return res end end ## Finalizers function delete(obj::CompRes) ccall((:scomp_DeleteRes, libtestu01), Cvoid, (Ptr{Cvoid},), obj.ptr) end ## pvalue extractors function pvalue(obj::CompRes) num = Gotw_TestArray() size = Gotw_TestArray() ccall((:getPValScomp, libtestu01extractors), Cvoid, (Ptr{Cvoid}, Ptr{Float64}, Ptr{Float64}), obj.ptr, num.data, size.data) return num[obj.N == 1 ? :Mean : :Sum], size[obj.N == 1 ? :Mean : :Sum] end # sspectral ## Type mutable struct SpectralRes ptr::Ptr{Cvoid} function SpectralRes() res = new(ccall((:sspectral_CreateRes, libtestu01), Ptr{Cvoid}, (), )) finalizer(delete, res) return res end end ## Finalizers function delete(obj::SpectralRes) ccall((:sspectral_DeleteRes, libtestu01), Cvoid, (Ptr{Cvoid},), obj.ptr) end ## pvalue extractors function pvalue(obj::SpectralRes) res = Gotw_TestArray() ccall((:getPValSspectral, libtestu01extractors), Cvoid, (Ptr{Cvoid}, Ptr{Float64}), obj.ptr, res.data) return res[:AD] end # sstring ## Type mutable struct StringRes ptr::Ptr{Cvoid} function StringRes() res = new(ccall((:sstring_CreateRes, libtestu01), Ptr{Cvoid}, (), )) finalizer(delete, res) return res end end ## Finalizers function delete(obj::StringRes) ccall((:sstring_DeleteRes, libtestu01), Cvoid, (Ptr{Cvoid},), obj.ptr) end ## pvalue extractors function pvalue(obj::StringRes) res = Gotw_TestArray() ccall((:getPValStringRes, libtestu01extractors), Cvoid, (Ptr{Cvoid}, Ptr{Float64}), obj.ptr, res.data) return res end ## Type mutable struct StringRes2 ptr::Ptr{Cvoid} N::Int function StringRes2(N::Integer) res = new(ccall((:sstring_CreateRes2, libtestu01), Ptr{Cvoid}, (), ), N) finalizer(delete, res) return res end end ## Finalizers function delete(obj::StringRes2) ccall((:sstring_DeleteRes2, libtestu01), Cvoid, (Ptr{Cvoid},), obj.ptr) end ## pvalue extractors function pvalue(obj::StringRes2) res = Gotw_TestArray() res2 = ccall((:getPValStringRes2, libtestu01extractors), Float64, (Ptr{Cvoid}, Ptr{Float64}), obj.ptr, res.data) return res[obj.N == 1 ? :Mean : :Sum], res2 end ## Type mutable struct StringRes3 ptr::Ptr{Cvoid} N::Int function StringRes3(N::Integer) res = new(ccall((:sstring_CreateRes3, libtestu01), Ptr{Cvoid}, (), ), N) finalizer(delete, res) return res end end ## Finalizers function delete(obj::StringRes3) ccall((:sstring_DeleteRes3, libtestu01), Cvoid, (Ptr{Cvoid},), obj.ptr) end ## pvalue extractors function pvalue(obj::StringRes3) res1 = Gotw_TestArray() res2 = Gotw_TestArray() ccall((:getPValStringRes3, libtestu01extractors), Float64, (Ptr{Cvoid}, Ptr{Float64}, Ptr{Float64}), obj.ptr, res1.data, res2.data) return res1[obj.N == 1 ? :Mean : :Sum], res2[obj.N == 1 ? :Mean : :Sum] end ######### # Tests # ######### ## smarsa function smarsa_BirthdaySpacings(gen::RNGGenerator, N::Integer, n::Integer, r::Integer, d::Integer, t::Integer, p::Integer) unif01 = Unif01(gen, "") sres = ResPoisson() try ccall((:smarsa_BirthdaySpacings, libtestu01), Cvoid, (Ptr{Cvoid}, Ptr{Cvoid}, Clong, Clong, Cint, Clong, Cint, Cint), unif01.ptr, sres.ptr, N, n, r, d, t, p) finally delete(unif01) end return pvalue(sres) end function smarsa_GCD(gen::RNGGenerator, N::Integer, n::Integer, r::Integer, s::Integer) unif01 = Unif01(gen, "") sres = MarsaRes2(N) try ccall((:smarsa_GCD, libtestu01), Cvoid, (Ptr{Cvoid}, Ptr{Cvoid}, Clong, Clong, Cint, Cint), unif01.ptr, sres.ptr, N, n, r, s) finally delete(unif01) end return pvalue(sres) end function smarsa_CollisionOver(gen::RNGGenerator, N::Integer, n::Integer, r::Integer, d::Integer, t::Integer) unif01 = Unif01(gen, "") sres = MarsaRes() try ccall((:smarsa_CollisionOver, libtestu01), Cvoid, (Ptr{Cvoid}, Ptr{Cvoid}, Clong, Clong, Cint, Clong, Cint), unif01.ptr, sres.ptr, N, n, r, d, t) finally delete(unif01) end return pvalue(sres) end function smarsa_Savir2(gen::RNGGenerator, N::Integer, n::Integer, r::Integer, m::Integer, t::Integer) unif01 = Unif01(gen, "") sres = ResChi2(N) try ccall((:smarsa_Savir2, libtestu01), Cvoid, (Ptr{Cvoid}, Ptr{Cvoid}, Clong, Clong, Cint, Clong, Cint), unif01.ptr, sres.ptr, N, n, r, m, t) finally delete(unif01) end return pvalue(sres) end function smarsa_SerialOver(gen::RNGGenerator, N::Integer, n::Integer, r::Integer, d::Integer, t::Integer) unif01 = Unif01(gen, "") sres = ResBasic() try ccall((:smarsa_SerialOver, libtestu01), Cvoid, (Ptr{Cvoid}, Ptr{Cvoid}, Clong, Clong, Cint, Clong, Cint), unif01.ptr, sres.ptr, N, n, r, d, t) finally delete(unif01) end return pvalue(sres) end function smarsa_MatrixRank(gen::RNGGenerator, N::Integer, n::Integer, r::Integer, s::Integer, L::Integer, k::Integer) unif01 = Unif01(gen, "") sres = ResChi2(N) try ccall((:smarsa_MatrixRank, libtestu01), Cvoid, (Ptr{Cvoid}, Ptr{Cvoid}, Clong, Clong, Cint, Cint, Cint, Cint), unif01.ptr, sres.ptr, N, n, r, s, L, k) finally delete(unif01) end return pvalue(sres) end ## sknuth function sknuth_Collision(gen::RNGGenerator, N::Integer, n::Integer, r::Integer, d::Integer, t::Integer) unif01 = Unif01(gen, "") sres = KnuthRes2() try ccall((:sknuth_Collision, libtestu01), Cvoid, (Ptr{Cvoid}, Ptr{Cvoid}, Clong, Clong, Cint, Clong, Cint), unif01.ptr, sres.ptr, N, n, r, d, t) finally delete(unif01) end return pvalue(sres) end function sknuth_CollisionPermut(gen::RNGGenerator, N::Integer, n::Integer, r::Integer, t::Integer) unif01 = Unif01(gen, "") sres = KnuthRes2() try ccall((:sknuth_CollisionPermut, libtestu01), Cvoid, (Ptr{Cvoid}, Ptr{Cvoid}, Clong, Clong, Cint, Cint), unif01.ptr, sres.ptr, N, n, r, t) finally delete(unif01) end return pvalue(sres) end function sknuth_CouponCollector(gen::RNGGenerator, N::Integer, n::Integer, r::Integer, d::Integer) unif01 = Unif01(gen, "") sres = ResChi2(N) try ccall((:sknuth_CouponCollector, libtestu01), Cvoid, (Ptr{Cvoid}, Ptr{Cvoid}, Clong, Clong, Cint, Cint), unif01.ptr, sres.ptr, N, n, r, d) finally delete(unif01) end return pvalue(sres) end function sknuth_Gap(gen::RNGGenerator, N::Integer, n::Integer, r::Integer, Alpha::Real, Beta::Real) unif01 = Unif01(gen, "") sres = ResChi2(N) try ccall((:sknuth_Gap, libtestu01), Cvoid, (Ptr{Cvoid}, Ptr{Cvoid}, Clong, Clong, Cint, Float64, Float64), unif01.ptr, sres.ptr, N, n, r, Alpha, Beta) finally delete(unif01) end return pvalue(sres) end function sknuth_MaxOft(gen::RNGGenerator, N::Integer, n::Integer, r::Integer, d::Integer, t::Integer) unif01 = Unif01(gen, "") sres = KnuthRes1(N) try ccall((:sknuth_MaxOft, libtestu01), Cvoid, (Ptr{Cvoid}, Ptr{Cvoid}, Clong, Clong, Cint, Cint, Cint), unif01.ptr, sres.ptr, N, n, r, d, t) finally delete(unif01) end return pvalue(sres) end function sknuth_Permutation(gen::RNGGenerator, N::Integer, n::Integer, r::Integer, t::Integer) unif01 = Unif01(gen, "") sres = ResChi2(N) try ccall((:sknuth_Permutation, libtestu01), Cvoid, (Ptr{Cvoid}, Ptr{Cvoid}, Clong, Clong, Cint, Cint), unif01.ptr, sres.ptr, N, n, r, t) finally delete(unif01) end return pvalue(sres) end function sknuth_Run(gen::RNGGenerator, N::Integer, n::Integer, r::Integer, up::Integer) unif01 = Unif01(gen, "") sres = ResChi2(N) try ccall((:sknuth_Run, libtestu01), Cvoid, (Ptr{Cvoid}, Ptr{Cvoid}, Clong, Clong, Cint, Cint), unif01.ptr, sres.ptr, N, n, r, up) finally delete(unif01) end return pvalue(sres) end function sknuth_SimpPoker(gen::RNGGenerator, N::Integer, n::Integer, r::Integer, d::Integer, k::Integer) unif01 = Unif01(gen, "") sres = ResChi2(N) try ccall((:sknuth_SimpPoker, libtestu01), Cvoid, (Ptr{Cvoid}, Ptr{Cvoid}, Clong, Clong, Cint, Cint, Cint), unif01.ptr, sres.ptr, N, n, r, d, k) finally delete(unif01) end return pvalue(sres) end ## svaria function svaria_AppearanceSpacings(gen::RNGGenerator, N::Integer, Q::Integer, K::Integer, r::Integer, s::Integer, L::Integer) unif01 = Unif01(gen, "") sres = ResBasic() try ccall((:svaria_AppearanceSpacings, libtestu01), Cvoid, (Ptr{Cvoid}, Ptr{Cvoid}, Clong, Clong, Clong, Cint, Cint, Cint), unif01.ptr, sres.ptr, N, Q, K, r, s, L) finally delete(unif01) end return pvalue(sres) end function svaria_SampleProd(gen::RNGGenerator, N::Integer, n::Integer, r::Integer, t::Integer) unif01 = Unif01(gen, "") sres = ResBasic() try ccall((:svaria_SampleProd, libtestu01), Cvoid, (Ptr{Cvoid}, Ptr{Cvoid}, Clong, Clong, Cint, Cint), unif01.ptr, sres.ptr, N, n, r, t) finally delete(unif01) end return pvalue(sres) end function svaria_SampleMean(gen::RNGGenerator, N::Integer, n::Integer, r::Integer) unif01 = Unif01(gen, "") sres = ResBasic() try ccall((:svaria_SampleMean, libtestu01), Cvoid, (Ptr{Cvoid}, Ptr{Cvoid}, Clong, Clong, Cint), unif01.ptr, sres.ptr, N, n, r) finally delete(unif01) end return pvalue(sres) end function svaria_SampleCorr(gen::RNGGenerator, N::Integer, n::Integer, r::Integer, k::Integer) unif01 = Unif01(gen, "") sres = ResBasic() try ccall((:svaria_SampleCorr, libtestu01), Cvoid, (Ptr{Cvoid}, Ptr{Cvoid}, Clong, Clong, Cint, Cint), unif01.ptr, sres.ptr, N, n, r, k) finally delete(unif01) end return pvalue(sres) end function svaria_SumCollector(gen::RNGGenerator, N::Integer, n::Integer, r::Integer, g::Float64) unif01 = Unif01(gen, "") sres = ResChi2(N) try ccall((:svaria_SumCollector, libtestu01), Cvoid, (Ptr{Cvoid}, Ptr{Cvoid}, Clong, Clong, Cint, Cdouble), unif01.ptr, sres.ptr, N, n, r, g) finally delete(unif01) end return pvalue(sres) end function svaria_WeightDistrib(gen::RNGGenerator, N::Integer, n::Integer, r::Integer, k::Integer, alpha::Real, beta::Real) unif01 = Unif01(gen, "") sres = ResChi2(N) try ccall((:svaria_WeightDistrib, libtestu01), Cvoid, (Ptr{Cvoid}, Ptr{Cvoid}, Clong, Clong, Cint, Clong, Float64, Float64), unif01.ptr, sres.ptr, N, n, r, k, alpha, beta) finally delete(unif01) end return pvalue(sres) end ## sstring function sstring_AutoCor(gen::RNGGenerator, N::Integer, n::Integer, r::Integer, s::Integer, d::Integer) unif01 = Unif01(gen, "") sres = ResBasic() try ccall((:sstring_AutoCor, libtestu01), Cvoid, (Ptr{Cvoid}, Ptr{Cvoid}, Clong, Clong, Cint, Cint, Cint), unif01.ptr, sres.ptr, N, n, r, s, d) finally delete(unif01) end return pvalue(sres) end function sstring_HammingCorr(gen::RNGGenerator, N::Integer, n::Integer, r::Integer, s::Integer, L::Integer) unif01 = Unif01(gen, "") sres = StringRes() try ccall((:sstring_HammingCorr, libtestu01), Cvoid, (Ptr{Cvoid}, Ptr{Cvoid}, Clong, Clong, Cint, Cint, Cint), unif01.ptr, sres.ptr, N, n, r, s, L) finally delete(unif01) end return pvalue(sres) end function sstring_HammingIndep(gen::RNGGenerator, N::Integer, n::Integer, r::Integer, s::Integer, L::Integer, d::Integer) unif01 = Unif01(gen, "") sres = StringRes() try ccall((:sstring_HammingIndep, libtestu01), Cvoid, (Ptr{Cvoid}, Ptr{Cvoid}, Clong, Clong, Cint, Cint, Cint, Cint), unif01.ptr, sres.ptr, N, n, r, s, L, d) finally delete(unif01) end return pvalue(sres) end function sstring_HammingWeight2(gen::RNGGenerator, N::Integer, n::Integer, r::Integer, s::Integer, L::Integer) unif01 = Unif01(gen, "") sres = ResBasic() try ccall((:sstring_HammingWeight2, libtestu01), Cvoid, (Ptr{Cvoid}, Ptr{Cvoid}, Clong, Clong, Cint, Cint, Clong), unif01.ptr, sres.ptr, N, n, r, s, L) finally delete(unif01) end return pvalue(sres) end function sstring_LongestHeadRun(gen::RNGGenerator, N::Integer, n::Integer, r::Integer, s::Integer, L::Integer) if L ÷ s * s < 1000 throw(ArgumentError("argument L is too small. `L ÷ s * s` must be at least 1000 but was $(L ÷ s * s)")) end unif01 = Unif01(gen, "") sres = StringRes2(N) try ccall((:sstring_LongestHeadRun, libtestu01), Cvoid, (Ptr{Cvoid}, Ptr{Cvoid}, Clong, Clong, Cint, Cint, Clong), unif01.ptr, sres.ptr, N, n, r, s, L) finally delete(unif01) end return pvalue(sres) end function sstring_PeriodsInStrings(gen::RNGGenerator, N::Integer, n::Integer, r::Integer, s::Integer) unif01 = Unif01(gen, "") sres = ResChi2(N) try ccall((:sstring_PeriodsInStrings, libtestu01), Cvoid, (Ptr{Cvoid}, Ptr{Cvoid}, Clong, Clong, Cint, Cint), unif01.ptr, sres.ptr, N, n, r, s) finally delete(unif01) end return pvalue(sres) end function sstring_Run(gen::RNGGenerator, N::Integer, n::Integer, r::Integer, s::Integer) unif01 = Unif01(gen, "") sres = StringRes3(N) try ccall((:sstring_Run, libtestu01), Cvoid, (Ptr{Cvoid}, Ptr{Cvoid}, Clong, Clong, Cint, Cint), unif01.ptr, sres.ptr, N, n, r, s) finally delete(unif01) end return pvalue(sres) end ## swalk function swalk_RandomWalk1(gen::RNGGenerator, N::Integer, n::Integer, r::Integer, s::Integer, L0::Integer, L1::Integer) unif01 = Unif01(gen, "") sres = WalkRes(N) try ccall((:swalk_RandomWalk1, libtestu01), Cvoid, (Ptr{Cvoid}, Ptr{Cvoid}, Clong, Clong, Cint, Cint, Clong, Clong), unif01.ptr, sres.ptr, N, n, r, s, L0, L1) finally delete(unif01) end return pvalue(sres) end ## snpair function snpair_ClosePairs(gen::RNGGenerator, N::Integer, n::Integer, r::Integer, t::Integer, p::Integer, m::Integer) unif01 = Unif01(gen, "") sres = NpairRes(N) try ccall((:snpair_ClosePairs, libtestu01), Cvoid, (Ptr{Cvoid}, Ptr{Cvoid}, Clong, Clong, Cint, Cint, Cint, Cint), unif01.ptr, sres.ptr, N, n, r, t, p, m) finally delete(unif01) end return pvalue(sres) end ## scomp function scomp_LempelZiv(gen::RNGGenerator, N::Integer, k::Integer, r::Integer, s::Integer) unif01 = Unif01(gen, "") sres = ResBasic() try ccall((:scomp_LempelZiv, libtestu01), Cvoid, (Ptr{Cvoid}, Ptr{Cvoid}, Clong, Cint, Cint, Cint), unif01.ptr, sres.ptr, N, k, r, s) finally delete(unif01) end return pvalue(sres) end function scomp_LinearComp(gen::RNGGenerator, N::Integer, n::Integer, r::Integer, s::Integer) unif01 = Unif01(gen, "") sres = CompRes(N) try ccall((:scomp_LinearComp, libtestu01), Cvoid, (Ptr{Cvoid}, Ptr{Cvoid}, Clong, Clong, Cint, Cint), unif01.ptr, sres.ptr, N, n, r, s) finally delete(unif01) end return pvalue(sres) end # sspectral function sspectral_Fourier3(gen::RNGGenerator, N::Integer, k::Integer, r::Integer, s::Integer) unif01 = Unif01(gen, "") sres = SpectralRes() try ccall((:sspectral_Fourier3, libtestu01), Cvoid, (Ptr{Cvoid}, Ptr{Cvoid}, Clong, Cint, Cint, Cint), unif01.ptr, sres.ptr, N, k, r, s) finally delete(unif01) end return pvalue(sres) end ################## # Test Batteries # ################## for (snm, fnm) in ((:SmallCrush, :smallcrushTestU01), (:Crush, :crushTestU01), (:BigCrush, :bigcrushTestU01), (:pseudoDIEHARD, :diehardTestU01), (:FIPS_140_2, :fips_140_2TestU01)) @eval begin function $(fnm)(f::RNGGenerator, fname::String) unif01 = Unif01(f, fname) try ccall(($(string("bbattery_", snm)), libtestu01), Cvoid, (Ptr{Cvoid},), unif01.ptr) finally delete(unif01) end end $(fnm)(f::RNGGenerator) = $(fnm)(f::RNGGenerator, "") end end function smallcrushJulia(f::RNGGenerator) # @everywhere f = ()->g() testnames = [g->smarsa_BirthdaySpacings(g, 1, 5000000, 0, 1073741824, 2, 1), g->sknuth_Collision(g, 1, 5000000, 0, 65536, 2), g->sknuth_Gap(g, 1, 200000, 22, 0.0, .00390625), g->sknuth_SimpPoker(g, 1, 400000, 24, 64, 64), g->sknuth_CouponCollector(g, 1, 500000, 26, 16), g->sknuth_MaxOft(g, 1, 2000000, 0, 100000, 6), g->svaria_WeightDistrib(g, 1, 200000, 27, 256, 0.0, 0.125), g->smarsa_MatrixRank(g, 1, 20000, 20, 10, 60, 60), g->sstring_HammingIndep(g, 1, 500000, 20, 10, 300, 0)[:Mean], g->swalk_RandomWalk1(g, 1, 1000000, 0, 30, 150, 150)] return pmap(t->t(f), testnames) end function bigcrushJulia(f::RNGGenerator) testnames = [g->smarsa_SerialOver(g, 1, 10^9, 0, 2^8, 3)[:Mean], g->smarsa_SerialOver(g, 1, 10^9, 22, 2^8, 3)[:Mean], g->smarsa_CollisionOver(g, 30, 2*10^7, 0, 2^21, 2), g->smarsa_CollisionOver(g, 30, 2*10^7, 9, 2^21, 2), g->smarsa_CollisionOver(g, 30, 2*10^7, 0, 2^14, 3), g->smarsa_CollisionOver(g, 30, 2*10^7, 16, 2^14, 3), g->smarsa_CollisionOver(g, 30, 2*10^7, 0, 64, 7), g->smarsa_CollisionOver(g, 30, 2*10^7, 24, 64, 7), g->smarsa_CollisionOver(g, 30, 2*10^7, 0, 8, 14), g->smarsa_CollisionOver(g, 30, 2*10^7, 27, 8, 14), g->smarsa_CollisionOver(g, 30, 2*10^7, 0, 4, 21), g->smarsa_CollisionOver(g, 30, 2*10^7, 28, 4, 21), g->smarsa_BirthdaySpacings(g, 100, 10^7, 0, 2^31, 2, 1), g->smarsa_BirthdaySpacings(g, 20, 2*10^7, 0, 2^21, 3, 1), g->smarsa_BirthdaySpacings(g, 20, 3*10^7, 14, 2^16, 4, 1), g->smarsa_BirthdaySpacings(g, 20, 2*10^7, 0, 2^9, 7, 1), g->smarsa_BirthdaySpacings(g, 20, 2*10^7, 7, 2^9, 7, 1), g->smarsa_BirthdaySpacings(g, 20, 3*10^7, 14, 2^8, 8, 1), g->smarsa_BirthdaySpacings(g, 20, 3*10^7, 22, 2^8, 8, 1), g->smarsa_BirthdaySpacings(g, 20, 3*10^7, 0, 2^4, 16, 1), g->smarsa_BirthdaySpacings(g, 20, 3*10^7, 26, 2^4, 16, 1), g->snpair_ClosePairs(g, 30, 6*10^6, 0, 3, 0, 30), g->snpair_ClosePairs(g, 20, 4*10^6, 0, 5, 0, 30), g->snpair_ClosePairs(g, 10, 3*10^6, 0, 9, 0, 30), g->snpair_ClosePairs(g, 5, 2*10^6, 0, 16, 0, 30), g->sknuth_SimpPoker(g, 1, 4*10^8, 0, 8, 8), g->sknuth_SimpPoker(g, 1, 4*10^8, 27, 8, 8), g->sknuth_SimpPoker(g, 1, 10^8, 0, 32, 32), g->sknuth_SimpPoker(g, 1, 10^8, 25, 32, 32), g->sknuth_CouponCollector(g, 1, 2*10^8, 0, 8), g->sknuth_CouponCollector(g, 1, 2*10^8, 10, 8), g->sknuth_CouponCollector(g, 1, 2*10^8, 20, 8), g->sknuth_CouponCollector(g, 1, 2*10^8, 27, 8), g->sknuth_Gap(g, 1, 5*10^8, 0, 0.0, 1/16), g->sknuth_Gap(g, 1, 3*10^8, 25, 0.0, 1/32), g->sknuth_Gap(g, 1, 10^8, 0, 0.0, 1/128), g->sknuth_Gap(g, 1, 10^7, 20, 0.0, 1/1024), g->sknuth_Run(g, 5, 10^9, 0, 0), g->sknuth_Run(g, 5, 10^9, 15, 1), g->sknuth_Permutation(g, 1, 10^9, 0, 3), g->sknuth_Permutation(g, 1, 10^9, 0, 5), g->sknuth_Permutation(g, 1, 5*10^8, 0, 7), g->sknuth_Permutation(g, 1, 5*10^8, 10, 10), g->sknuth_CollisionPermut(g, 20, 2*10^7, 0, 14), g->sknuth_CollisionPermut(g, 20, 2*10^7, 10, 14), g->sknuth_MaxOft(g, 40, 10^7, 0, 10^5, 8), g->sknuth_MaxOft(g, 30, 10^7, 0, 10^5, 16), g->sknuth_MaxOft(g, 20, 10^7, 0, 10^5, 24), g->sknuth_MaxOft(g, 20, 10^7, 0, 10^5, 32), g->svaria_SampleProd(g, 40, 10^7, 0, 8)[:AD], g->svaria_SampleProd(g, 20, 10^7, 0, 16)[:AD], g->svaria_SampleProd(g, 20, 10^7, 0, 24)[:AD], g->svaria_SampleMean(g, 2*10^7, 30, 0)[:AD], g->svaria_SampleMean(g, 2*10^7, 30, 10)[:AD], g->svaria_SampleCorr(g, 1, 2*10^9, 0, 1)[:Mean], g->svaria_SampleCorr(g, 1, 2*10^9, 0, 2)[:Mean], g->svaria_AppearanceSpacings(g, 1, 10^7, 10^9, 0, 3, 15)[:Mean], g->svaria_AppearanceSpacings(g, 1, 10^7, 10^9, 27, 3, 15)[:Mean], g->svaria_WeightDistrib(g, 1, 2*10^7, 0, 256, 0.0, 1/4), g->svaria_WeightDistrib(g, 1, 2*10^7, 20, 256, 0.0, 1/4), g->svaria_WeightDistrib(g, 1, 2*10^7, 28, 256, 0.0, 1/4), g->svaria_WeightDistrib(g, 1, 2*10^7, 0, 256, 0.0, 1/16), g->svaria_WeightDistrib(g, 1, 2*10^7, 10, 256, 0.0, 1/16), g->svaria_WeightDistrib(g, 1, 2*10^7, 26, 256, 0.0, 1/16), g->svaria_SumCollector(g, 1, 5*10^8, 0, 10.0), g->smarsa_MatrixRank(g, 10, 10^6, 0, 5, 30, 30), g->smarsa_MatrixRank(g, 10, 10^6, 25, 5, 30, 30), g->smarsa_MatrixRank(g, 1, 5000, 0, 4, 1000, 1000), g->smarsa_MatrixRank(g, 1, 5000, 26, 4, 1000, 1000), g->smarsa_MatrixRank(g, 1, 80, 15, 15, 5000, 5000), g->smarsa_MatrixRank(g, 1, 80, 0, 30, 5000, 5000), g->smarsa_Savir2(g, 10, 10^7, 10, 2^30, 30), g->smarsa_GCD(g, 10, 5*10^7, 0, 30), g->swalk_RandomWalk1(g, 1, 10^8, 0, 5, 50, 50), g->swalk_RandomWalk1(g, 1, 10^8, 25, 5, 50, 50), g->swalk_RandomWalk1(g, 1, 10^7, 0, 10, 1000, 1000), g->swalk_RandomWalk1(g, 1, 10^7, 20, 10, 1000, 1000), g->swalk_RandomWalk1(g, 1, 10^6, 0, 15, 1000, 1000), g->swalk_RandomWalk1(g, 1, 10^6, 15, 15, 10000, 10000), g->scomp_LinearComp(g, 1, 400000, 0, 1), g->scomp_LinearComp(g, 1, 400000, 29, 1), g->scomp_LempelZiv(g, 10, 27, 0, 30)[:Sum], g->scomp_LempelZiv(g, 10, 27, 15, 15)[:Sum], g->sspectral_Fourier3(g, 100000, 14, 0, 3), g->sspectral_Fourier3(g, 100000, 14, 27, 3), g->sstring_LongestHeadRun(g, 1, 1000, 0, 3, 10^7), g->sstring_LongestHeadRun(g, 1, 1000, 27, 3, 10^7), g->sstring_PeriodsInStrings(g, 10, 5*10^8, 0, 10), g->sstring_PeriodsInStrings(g, 10, 5*10^8, 20, 10), g->sstring_HammingWeight2(g, 10, 10^9, 0, 3, 10^6)[:Sum], g->sstring_HammingWeight2(g, 10, 10^9, 27, 3, 10^6)[:Sum], g->sstring_HammingCorr(g, 1, 10^9, 10, 10, 30)[:Mean], g->sstring_HammingCorr(g, 1, 10^8, 10, 10, 300)[:Mean], g->sstring_HammingCorr(g, 1, 10^8, 10, 10, 1200)[:Mean], g->sstring_HammingIndep(g, 10, 3*10^7, 0, 3, 30, 0)[:Sum], g->sstring_HammingIndep(g, 10, 3*10^7, 27, 3, 30, 0)[:Sum], g->sstring_HammingIndep(g, 1, 3*10^7, 0, 4, 300, 0)[:Mean], g->sstring_HammingIndep(g, 1, 3*10^7, 26, 4, 300, 0)[:Mean], g->sstring_HammingIndep(g, 1, 10^7, 0, 5, 1200, 0)[:Mean], g->sstring_HammingIndep(g, 1, 10^7, 25, 5, 1200, 0)[:Mean], g->sstring_Run(g, 1, 2*10^9, 0, 3), g->sstring_Run(g, 1, 2*10^9, 27, 3), g->sstring_AutoCor(g, 10, 10^9, 0, 3, 1)[:Sum], g->sstring_AutoCor(g, 10, 10^9, 0, 3, 3)[:Sum], g->sstring_AutoCor(g, 10, 10^9, 27, 3, 1)[:Sum], g->sstring_AutoCor(g, 10, 10^9, 27, 3, 3)[:Sum]] return pmap(t->t(f), testnames) end end
RNGTest
https://github.com/JuliaRandom/RNGTest.jl.git
[ "MIT" ]
1.6.0
c08db012b41bedc58adf33ca52a3004b55ad5eaa
code
4565
using Test using RNGTest using Random f = rand pval = 0.001 @testset "smarsa" begin @testset "BirthdaySpacings" begin @test RNGTest.smarsa_BirthdaySpacings(f, 1, 5000000, 0, 1073741824, 2, 1) > pval end @testset "MatrixRank" begin @test RNGTest.smarsa_MatrixRank(f, 1, 20000, 20, 10, 60, 60) > pval end @testset "SerialOver" begin res = RNGTest.smarsa_SerialOver(f, 1, 10, 0, 2^3, 3) @test res[:Mean] > pval @test res[:Var] == -1.0 @test res[:Cor] == -1.0 @test res[:Sum] == -1.0 @test_throws BoundsError res[:Nothing] end @testset "GCD" begin @test RNGTest.smarsa_GCD(f, 10, 5*10^2, 0, 30) > pval end @testset "CollisionOver" begin @test RNGTest.smarsa_CollisionOver(f, 30, 2*10^3, 0, 2^11, 2) > pval end @testset "Savir2" begin @test RNGTest.smarsa_Savir2(f, 10, 10^4, 10, 2^10, 10) > pval end end @testset "sknuth" begin @testset "Collision" begin @test RNGTest.sknuth_Collision(f, 1, 5000000, 0, 65536, 2) > pval end @testset "Gap" begin @test RNGTest.sknuth_Gap(f, 1, 200000, 22, 0.0, .00390625) > pval end @testset "SimpPoker" begin @test RNGTest.sknuth_SimpPoker(f, 1, 400000, 24, 64, 64) > pval end @testset "CouponCollector" begin @test RNGTest.sknuth_CouponCollector(f, 1, 500000, 26, 16) > pval end @testset "MaxOft" begin @test all(hcat(RNGTest.sknuth_MaxOft(f, 1, 2000000, 0, 100000, 6)...) .> pval) end @testset "CollisionPermut" begin @test RNGTest.sknuth_CollisionPermut(f, 20, 2*10^3, 0, 14) > pval end @testset "Permutation" begin @test RNGTest.sknuth_Permutation(f, 1, 10^4, 0, 3) > pval end @testset "Run" begin @test RNGTest.sknuth_Run(f, 5, 10^4, 0, 0) > pval end end @testset "svaria" begin @testset "WeightDistrib" begin @test RNGTest.svaria_WeightDistrib(f, 1, 200000, 27, 256, 0.0, 0.125) > pval end @testset "AppearanceSpacings" begin @test RNGTest.svaria_AppearanceSpacings(f, 1, 10^3, 10^5, 0, 3, 5)[:Mean] > pval end @testset "SampleProd" begin @test RNGTest.svaria_SampleProd(f, 40, 10^4, 0, 8)[:AD] > pval end @testset "SampleMean" begin @test RNGTest.svaria_SampleMean(f, 2*10^3, 30, 0)[:AD] > pval end @testset "SampleCorr" begin @test RNGTest.svaria_SampleCorr(f, 1, 2*10^5, 0, 1)[:Mean] > pval end @testset "SumCollector" begin @test RNGTest.svaria_SumCollector(f, 1, 5*10^4, 0, 10.0) > pval end end @testset "sstring" begin @testset "HammingIndep" begin @test RNGTest.sstring_HammingIndep(f, 1, 500000, 20, 10, 300, 0)[:Mean] > pval end @testset "LongestHeadRun" begin @test_throws ArgumentError("argument L is too small. `L ÷ s * s` must be at least 1000 but was 999") RNGTest.sstring_LongestHeadRun(f, 1, 10, 0, 3, 1000) @test all(t -> t > pval, RNGTest.sstring_LongestHeadRun(f, 1, 100, 0, 3, 10000)) end @testset "PeriodsInStrings" begin @test RNGTest.sstring_PeriodsInStrings(f, 10, 5*10^2, 0, 10) > pval end @testset "Run" begin @test all(t -> t > pval, RNGTest.sstring_Run(f, 1, 2*10^4, 0, 3)) end @testset "AutoCor" begin @test RNGTest.sstring_AutoCor(f, 10, 10^4, 0, 3, 1)[:Sum] > pval end @testset "HammingCorr" begin @test RNGTest.sstring_HammingCorr(f, 1, 10^4, 10, 10, 30)[:Mean] > pval end @testset "" begin @test RNGTest.sstring_HammingWeight2(f, 10, 10^4, 0, 3, 10^3)[:Sum] > pval end end @testset "swalk" begin @testset "RandomWalk" begin @test all(hcat(RNGTest.swalk_RandomWalk1(f, 1, 1000000, 0, 30, 150, 150)...) .> pval) end end @testset "snpair" begin @testset "ClonsePairs" begin @test all(t -> t > pval, RNGTest.snpair_ClosePairs(f, 30, 6*10^2, 0, 3, 0, 30)) end end @testset "scomp" begin @testset "LinearComp" begin @test all(t -> t > pval, RNGTest.scomp_LinearComp(f, 1, 400, 0, 1)) end @testset "LempelZiv" begin @test RNGTest.scomp_LempelZiv(f, 5, 7, 0, 10)[:Sum] > pval end end @testset "sspectral" begin @testset "Fourier3" begin @test RNGTest.sspectral_Fourier3(f, 100, 14, 0, 3) > pval end end @testset "smallcrush" begin rng = RNGTest.wrap(MersenneTwister(0), UInt32) RNGTest.smallcrushTestU01(rng) @test all(t -> t > pval, mapreduce(s -> [s...], vcat, RNGTest.smallcrushJulia(rng))) end
RNGTest
https://github.com/JuliaRandom/RNGTest.jl.git
[ "MIT" ]
1.6.0
c08db012b41bedc58adf33ca52a3004b55ad5eaa
docs
1480
# The Crush test suite of l'Ecuyer for Julia [![CI](https://github.com/JuliaRandom/RNGTest.jl/actions/workflows/CI.yml/badge.svg)](https://github.com/JuliaRandom/RNGTest.jl/actions/workflows/CI.yml) [![codecov](https://codecov.io/gh/JuliaRandom/RNGTest.jl/branch/master/graph/badge.svg?token=6FFGnqkZzu)](https://codecov.io/gh/JuliaRandom/RNGTest.jl) The package is a Julia interface to the test suite TestU01 of Pierre l'Ecuyer. All the tests included in the SmallCrush and BigCrush test batteries can be called as Julia functions. The first argument to the test function must be either * a function without arguments, which must return a `Float64` between zero and one, or * a wrapped `AbstractRNG` obtained via the function `wrap(rng, T)` where `T` is the type of the variates produced by `rng` that one wants tested (currently `T` must be one of the standard finite-precision Julia `Integer` or `FloatingPoint` types). The output from the test is a p-value. The package also includes the Small- and the BigCrush batteries. Some examples: ```julia julia> using RNGTest julia> RNGTest.smallcrushJulia(rand) julia> using Distribtions julia> gf() = cdf(Gamma(), rand(Gamma())); julia> RNGTest.bigcrushJulia(gf) julia> rng = RNGTest.wrap(MersenneTwister(), UInt32) julia> RNGTest.bigcrushTestU01(rng) ``` Note that the BigCrush test battery takes about twelve hours on a normal computer. ## Homepage of the test suite http://simul.iro.umontreal.ca/testu01/tu01.html
RNGTest
https://github.com/JuliaRandom/RNGTest.jl.git
[ "MIT" ]
0.3.0
b625976c74a2611182324d76061247fe69f922e6
code
469
module POMDPXFiles using POMDPs using POMDPTools using ProgressMeter import POMDPs: action, value # import o avoid naming conflict in POMDPs.jl (value is overloaded in LightXML) import LightXML: parse_file, root, get_elements_by_tagname, attribute, content export AbstractPOMDPXFile, POMDPXFile, MOMDPXFile, Alphas, POMDPAlphas, read_pomdp, action, value include("writer.jl") include("policy.jl") include("read.jl") end # module
POMDPXFiles
https://github.com/JuliaPOMDP/POMDPXFiles.jl.git
[ "MIT" ]
0.3.0
b625976c74a2611182324d76061247fe69f922e6
code
888
# this is taken from Louis Dressel's POMDPs.jl. Thanks Louis! # Abstract Type representing alpha vectors abstract type Alphas end mutable struct POMDPAlphas <: Alphas alpha_vectors::Matrix{Float64} alpha_actions::Vector{Int64} POMDPAlphas(av::Matrix{Float64}, aa::Vector{Int64}) = new(av, aa) # Constructor if no action list is given # Here, we 0-index actions, to match sarsop output function POMDPAlphas(av::Matrix{Float64}) numActions = size(av, 1) alist = [0:(numActions-1)] return new(av, alist) end # Constructor reading policy from file function POMDPAlphas(filename::AbstractString) alpha_vectors, alpha_actions = read_pomdp(filename) return new(alpha_vectors, alpha_actions) end # Default constructor function POMDPAlphas() return new(zeros(0,0), zeros(Int64,0)) end end
POMDPXFiles
https://github.com/JuliaPOMDP/POMDPXFiles.jl.git
[ "MIT" ]
0.3.0
b625976c74a2611182324d76061247fe69f922e6
code
4796
# Parses policy xml file and returns alpha vectors and alpha actions # Should handle any policy in the .policy format # Should handle policies written by POMDPs.jl or APPL # # alpha_vectors is a matrix containing the alpha vectors # Each row corresponds to a different alpha vector # # alpha_actions is a vector containing the list of action indices # Each index corresponds to action associated with the alpha vector of this row # These are 0-indexed... 0 means it is the first action # # TODO: Check that the input file exists and handle the case that it doesn't # TODO: Handle sparse vectors # function read_momdp(filename::String) # Parse the xml file # TODO: Check that the file exists and handle the case that it doesn't xdoc = parse_file(filename) # Get the root of the document (the Policy tag in this case) policy_tag = root(xdoc) #println(name(policy_tag)) # print the name of this tag # Determine expected number of vectors and their length alphavector_tag = get_elements_by_tagname(policy_tag, "AlphaVector")[1] #length of 1 anyway num_vectors = int(attribute(alphavector_tag, "numVectors")) vector_length = int(attribute(alphavector_tag, "vectorLength")) num_full_obs_states = int(attribute(alphavector_tag, "numObsValue")) # For debugging purposes... #println("AlphaVector tag: # vectors, vector length: $(num_vectors), $(vector_length)") # Arrays with vector and sparse vector tags vector_tags = get_elements_by_tagname(alphavector_tag, "Vector") sparsevector_tags = get_elements_by_tagname(alphavector_tag, "SparseVector") num_vectors_check = length(vector_tags) + length(sparsevector_tags) # should be same as num_vectors # Initialize the gamma matrix. This is basically a matrix with the alpha # vectors as rows. #alpha_vectors = Array(Float64, num_vectors, vector_length) alpha_vectors = Array{Float64}(vector_length, num_vectors) alpha_actions = Array{String}(num_vectors) observable_states = Array{String}(num_vectors) gammarow = 1 # Fill in gamma for vector in vector_tags alpha = float(split(content(vector))) #alpha_vectors[gammarow, :] = alpha alpha_vectors[:,gammarow] = alpha alpha_actions[gammarow] = attribute(vector, "action") observable_states[gammarow] = attribute(vector, "obsValue") gammarow += 1 end # TODO: Handle sparse vectors for vector in sparsevector_tags # Turn these into vectors as well end # Return alpha vectors and indices of actions return alpha_vectors, int(alpha_actions), int(observable_states) end function read_pomdp(filename::String) # Parse the xml file # TODO: Check that the file exists and handle the case that it doesn't xdoc = parse_file(filename) # Get the root of the document (the Policy tag in this case) policy_tag = root(xdoc) #println(name(policy_tag)) # print the name of this tag # Determine expected number of vectors and their length alphavector_tag = get_elements_by_tagname(policy_tag, "AlphaVector")[1] #length of 1 anyway num_vectors = parse(Int64, attribute(alphavector_tag, "numVectors")) vector_length = parse(Int64, attribute(alphavector_tag, "vectorLength")) num_full_obs_states = parse(Int64, attribute(alphavector_tag, "numObsValue")) # For debugging purposes... #println("AlphaVector tag: # vectors, vector length: $(num_vectors), $(vector_length)") # Arrays with vector and sparse vector tags vector_tags = get_elements_by_tagname(alphavector_tag, "Vector") sparsevector_tags = get_elements_by_tagname(alphavector_tag, "SparseVector") num_vectors_check = length(vector_tags) + length(sparsevector_tags) # should be same as num_vectors # Initialize the gamma matrix. This is basically a matrix with the alpha # vectors as columns. #alpha_vectors = Array(Float64, num_vectors, vector_length) alpha_vectors = Array{Float64}(undef, vector_length, num_vectors) alpha_actions = Array{String}(undef, num_vectors) observable_states = Array{String}(undef, num_vectors) gammarow = 1 # Fill in gamma for vector in vector_tags alpha = parse.(Float64, split(content(vector))) #alpha_vectors[gammarow, :] = alpha alpha_vectors[:,gammarow] = alpha alpha_actions[gammarow] = attribute(vector, "action") observable_states[gammarow] = attribute(vector, "obsValue") gammarow += 1 end # TODO: Handle sparse vectors for vector in sparsevector_tags # Turn these into vectors as well end # Return alpha vectors and indices of actions return alpha_vectors, [parse(Int64,s) for s in alpha_actions] end
POMDPXFiles
https://github.com/JuliaPOMDP/POMDPXFiles.jl.git
[ "MIT" ]
0.3.0
b625976c74a2611182324d76061247fe69f922e6
code
14502
################################################################# # This file implements a .pomdpx file generator using the # POMDPs.jl interface. ################################################################# abstract type AbstractPOMDPXFile end mutable struct POMDPXFile <: AbstractPOMDPXFile file_name::AbstractString description::AbstractString state_name::AbstractString action_name::AbstractString reward_name::AbstractString obs_name::AbstractString initial_belief::Vector{Float64} #initial_belief::Vector{Float64} # belief over partially observed vars function POMDPXFile(file_name::AbstractString; description::AbstractString="", initial_belief::Vector{Float64}=Float64[]) if isempty(description) description = "This is a pomdpx file for a partially observable MDP" end self = new() self.file_name = file_name self.description = description self.state_name = "state" self.action_name = "action" self.reward_name = "reward" self.obs_name = "observation" self.initial_belief = initial_belief return self end end function Base.write(pomdp::POMDP, pomdpx::AbstractPOMDPXFile) file_name = pomdpx.file_name description = pomdpx.description discount_factor = discount(pomdp) # Open file to write to out_file = open("$file_name", "w") pomdp_states = ordered_states(pomdp) pomdp_pstates = ordered_states(pomdp) acts = ordered_actions(pomdp) obs = ordered_observations(pomdp) # x = Number of next statement to track Progress # Added approximately after every four lines written to file, 14 next statements outside loops x = 14 + length(pomdp_states) + length(pomdp_states)*length(acts)*length(obs) + length(pomdp_states)*length(acts) + length(acts)*length(pomdp_pstates) p1 = Progress(x, dt=0.01) # Header stuff for xml write(out_file, "<?xml version='1.0' encoding='ISO-8859-1'?>\n\n\n") write(out_file, "<pomdpx version='0.1' id='test' ") write(out_file, "xmlns:='http://www.w3.org/2001/XMLSchema-instance' ") write(out_file, "xsi:noNamespaceSchemaLocation='pomdpx.xsd'>\n\n\n") sleep(0.01) next!(p1) ############################################################################ # DESCRIPTION ############################################################################ write(out_file, "\t<Description> $(description)</Description>\n\n\n") ############################################################################ # DISCOUNT ############################################################################ write(out_file, "\t<Discount>$(discount_factor)</Discount>\n\n\n") ############################################################################ # VARIABLES ############################################################################ write(out_file, "\t<Variable>\n") next!(p1) # State Variables str = state_xml(pomdp, pomdpx) write(out_file, str) next!(p1) # Action Variables str = action_xml(pomdp, pomdpx) write(out_file, str) next!(p1) # Observation Variables str = obs_var_xml(pomdp, pomdpx) write(out_file, str) next!(p1) # Reward Variable str = reward_var_xml(pomdp, pomdpx) write(out_file, str) write(out_file, "\t</Variable>\n\n\n") next!(p1) ############################################################################ # INITIAL STATE BELIEF ############################################################################ belief_xml(pomdp, pomdpx, out_file, p1) ############################################################################ # STATE TRANSITION FUNCTION ############################################################################ trans_xml(pomdp, pomdpx, out_file, p1) ############################################################################ # OBS FUNCTION ############################################################################ obs_xml(pomdp, pomdpx, out_file, p1) ############################################################################ # REWARD FUNCTION ############################################################################ reward_xml(pomdp, pomdpx, out_file, p1) # CLOSE POMDPX TAG AND FILE write(out_file, "</pomdpx>") close(out_file) end ############################################################################ # function: state_xml # input: pomdp model, pomdpx type # output: string in xml format the defines the state varaibles ############################################################################ function state_xml(pomdp::POMDP, pomdpx::POMDPXFile) # defines state vars for a POMDP n_s = length(states(pomdp)) sname = pomdpx.state_name str = "\t\t<StateVar vnamePrev=\"$(sname)0\" vnameCurr=\"$(sname)1\" fullyObs=\"false\">\n" str = "$(str)\t\t\t<NumValues>$(n_s)</NumValues>\n" str = "$(str)\t\t</StateVar>\n\n" return str end ############################################################################ ############################################################################ # function: obs_var_xml # input: pomdp model, pomdpx type # output: string in xml format the defines the observation varaibles ############################################################################ function obs_var_xml(pomdp::POMDP, pomdpx::AbstractPOMDPXFile) # defines observation vars for POMDP and MOMDP n_o = length(observations(pomdp)) oname = pomdpx.obs_name str = "\t\t<ObsVar vname=\"$(oname)\">\n" str = "$(str)\t\t\t<NumValues>$(n_o)</NumValues>\n" str = "$(str)\t\t</ObsVar>\n\n" return str end ############################################################################ ############################################################################ # function: action_xml # input: pomdp model, pomdpx type # output: string in xml format the defines the action varaibles ############################################################################ function action_xml(pomdp::POMDP, pomdpx::AbstractPOMDPXFile) # defines action vars for MDP, POMDP and MOMDP n_a = length(actions(pomdp)) aname = pomdpx.action_name str = "\t\t<ActionVar vname=\"$(aname)\">\n" str = "$(str)\t\t\t<NumValues>$(n_a)</NumValues>\n" str = "$(str)\t\t</ActionVar>\n\n" return str end ############################################################################ ############################################################################ # function: reward_var_xml # input: pomdp model, pomdpx type # output: string in xml format the defines the reward varaible ############################################################################ function reward_var_xml(pomdp::POMDP, pomdpx::AbstractPOMDPXFile) # defines reward var for MDP, POMDP and MOMDP rname = pomdpx.reward_name str = "\t\t<RewardVar vname=\"$(rname)\"/>\n\n" return str end ############################################################################ ############################################################################ # function: belief_xml # input: pomdp model, pomdpx type, output file # output: None, writes the initial belief to the output file ############################################################################ function belief_xml(pomdp::POMDP, pomdpx::POMDPXFile, out_file::IOStream, p1) belief = pomdpx.initial_belief var = pomdpx.state_name write(out_file, "\t<InitialStateBelief>\n") str = "\t\t<CondProb>\n" str = "$(str)\t\t\t<Var>$(var)0</Var>\n" str = "$(str)\t\t\t<Parent>null</Parent>\n" str = "$(str)\t\t\t<Parameter type = \"TBL\">\n" next!(p1) d = initialstate(pomdp) for (i, s) in enumerate(ordered_states(pomdp)) p = pdf(d, s) str = "$(str)\t\t\t\t<Entry>\n" str = "$(str)\t\t\t\t\t<Instance>s$(i-1)</Instance>\n" str = "$(str)\t\t\t\t\t<ProbTable>$(p)</ProbTable>\n" str = "$(str)\t\t\t\t</Entry>\n" next!(p1) end str = "$(str)\t\t\t</Parameter>\n" str = "$(str)\t\t</CondProb>\n" write(out_file, str) write(out_file, "\t</InitialStateBelief>\n\n\n") next!(p1) end ############################################################################ ############################################################################ # function: trans_xml # input: pomdp model, pomdpx type, output file # output: None, writes the transition probability table to the output file ############################################################################ function trans_xml(pomdp::POMDP, pomdpx::POMDPXFile, out_file::IOStream, p1) pomdp_states = ordered_states(pomdp) pomdp_pstates = ordered_states(pomdp) acts = ordered_actions(pomdp) aname = pomdpx.action_name var = pomdpx.state_name write(out_file, "\t<StateTransitionFunction>\n") str = "\t\t<CondProb>\n" str = "$(str)\t\t\t<Var>$(var)1</Var>\n" str = "$(str)\t\t\t<Parent>$(aname) $(var)0</Parent>\n" str = "$(str)\t\t\t<Parameter>\n" write(out_file, str) next!(p1) for (i, s) in enumerate(pomdp_states) if isterminal(pomdp, s) # if terminal, just remain in the same state str = "\t\t\t\t<Entry>\n" str = "$(str)\t\t\t\t\t<Instance>* s$(i-1) s$(i-1)</Instance>\n" str = "$(str)\t\t\t\t\t<ProbTable>1.0</ProbTable>\n" str = "$(str)\t\t\t\t</Entry>\n" write(out_file, str) for i = 1:length(acts)*length(pomdp_pstates) next!(p1) end else for (ai, a) in enumerate(acts) d = transition(pomdp, s, a) for (j, sp) in enumerate(pomdp_pstates) p = pdf(d, sp) if p > 0.0 str = "\t\t\t\t<Entry>\n" str = "$(str)\t\t\t\t\t<Instance>a$(ai-1) s$(i-1) s$(j-1)</Instance>\n" str = "$(str)\t\t\t\t\t<ProbTable>$(p)</ProbTable>\n" str = "$(str)\t\t\t\t</Entry>\n" write(out_file, str) end next!(p1) end end end end str = "\t\t\t</Parameter>\n" str = "$(str)\t\t</CondProb>\n" write(out_file, str) write(out_file, "\t</StateTransitionFunction>\n\n\n") next!(p1) return nothing end ############################################################################ ############################################################################ # function: obs_xml # input: pomdp model, pomdpx type, output file # output: None, writes the observation probability table to the output file ############################################################################ function obs_xml(pomdp::POMDP, pomdpx::POMDPXFile, out_file::IOStream, p1) pomdp_states = ordered_states(pomdp) acts = ordered_actions(pomdp) obs = ordered_observations(pomdp) aname = pomdpx.action_name oname = pomdpx.obs_name var = pomdpx.state_name write(out_file, "\t<ObsFunction>\n") str = "\t\t<CondProb>\n" str = "$(str)\t\t\t<Var>$(oname)</Var>\n" str = "$(str)\t\t\t<Parent>$(aname) $(var)1</Parent>\n" str = "$(str)\t\t\t<Parameter>\n" write(out_file, str) next!(p1) try observation(pomdp, first(acts), first(pomdp_states)) catch ex if ex isa MethodError @warn("""POMDPXFiles only supports observation distributions conditioned on a and sp. Check that there is an `observation(::M, ::A, ::S)` method available (or an (::A, ::S) method of the observation function for a QuickPOMDP). This warning is designed to give a helpful hint to fix errors, but may not always be relevant. """, M=typeof(pomdp), S=typeof(first(pomdp_states)), A=typeof(first(acts))) end rethrow(ex) end for (i, s) in enumerate(pomdp_states) for (ai, a) in enumerate(acts) d = observation(pomdp, a, s) for (oi, o) in enumerate(obs) p = pdf(d, o) if p > 0.0 str = "\t\t\t\t<Entry>\n" str = "$(str)\t\t\t\t\t<Instance>a$(ai-1) s$(i-1) o$(oi-1)</Instance>\n" str = "$(str)\t\t\t\t\t<ProbTable>$(p)</ProbTable>\n" str = "$(str)\t\t\t\t</Entry>\n" write(out_file, str) end next!(p1) end end end write(out_file, "\t\t\t</Parameter>\n") write(out_file, "\t\t</CondProb>\n") write(out_file, "\t</ObsFunction>\n") next!(p1) end ############################################################################ ############################################################################ # function: reward_xml # input: pomdp model, pomdpx type, output file # output: None, writes the reward function to the output file ############################################################################ function reward_xml(pomdp::POMDP, pomdpx::POMDPXFile, out_file::IOStream, p1) pomdp_states = ordered_states(pomdp) acts = ordered_actions(pomdp) rew = StateActionReward(pomdp) aname = pomdpx.action_name var = pomdpx.state_name rname = pomdpx.reward_name write(out_file, "\t<RewardFunction>\n") str = "\t\t<Func>\n" str = "$(str)\t\t\t<Var>$(rname)</Var>\n" str = "$(str)\t\t\t<Parent>$(aname) $(var)0</Parent>\n" str = "$(str)\t\t\t<Parameter>\n" write(out_file, str) next!(p1) for (i, s) in enumerate(pomdp_states) if !isterminal(pomdp, s) for (ai, a) in enumerate(acts) r = rew(s, a) str = "\t\t\t\t<Entry>\n" str = "$(str)\t\t\t\t\t<Instance>a$(ai-1) s$(i-1)</Instance>\n" str = "$(str)\t\t\t\t\t<ValueTable>$(r)</ValueTable>\n" str = "$(str)\t\t\t\t</Entry>\n" write(out_file, str) next!(p1) end else for i = 1:length(acts) next!(p1) end end end write(out_file, "\t\t\t</Parameter>\n\t\t</Func>\n") write(out_file, "\t</RewardFunction>\n\n") next!(p1) end ############################################################################
POMDPXFiles
https://github.com/JuliaPOMDP/POMDPXFiles.jl.git
[ "MIT" ]
0.3.0
b625976c74a2611182324d76061247fe69f922e6
code
1335
using POMDPs using POMDPTools using POMDPXFiles using POMDPModels using Test @testset "basic" begin file_name = "tiger_test.pomdpx" pomdp = TigerPOMDP() pomdpx = POMDPXFile(file_name) write(pomdp, pomdpx) av, aa = read_pomdp("mypolicy.policy") @test av ≈ [-81.5975 3.01448 24.6954 28.4025 19.3711; 28.4025 24.6954 3.01452 -81.5975 19.3711] @test aa == [1,0,0,2,0] end @testset "a, sp observation warning" begin struct BadObsPOMDP <: POMDP{Int,Int,Int} end POMDPs.states(m::BadObsPOMDP) = 1:2 POMDPs.actions(m::BadObsPOMDP) = 1:2 POMDPs.observations(m::BadObsPOMDP) = 1:2 POMDPs.transition(m::BadObsPOMDP, s, a) = Deterministic(clamp(s+a, 1, 2)) POMDPs.reward(m::BadObsPOMDP, s, a, o) = s POMDPs.observation(m::BadObsPOMDP, s, a, sp) = Deterministic(sp) POMDPs.discount(m::BadObsPOMDP) = 0.99 POMDPs.initialstate(m::BadObsPOMDP) = Deterministic(1) POMDPs.stateindex(m::BadObsPOMDP, s) = s POMDPs.actionindex(m::BadObsPOMDP, s) = s POMDPs.obsindex(m::BadObsPOMDP, s) = s @test_throws MethodError cd(mktempdir()) do write(BadObsPOMDP(), POMDPXFile("bad_obs_test.pomdpx")) end POMDPs.observation(m::BadObsPOMDP, a, sp) = Deterministic(1) cd(mktempdir()) do write(BadObsPOMDP(), POMDPXFile("bad_obs_test.pomdpx")) end end
POMDPXFiles
https://github.com/JuliaPOMDP/POMDPXFiles.jl.git
[ "MIT" ]
0.3.0
b625976c74a2611182324d76061247fe69f922e6
docs
1343
# POMDPXFiles [![Build Status](https://github.com/JuliaPOMDP/POMDPXFiles.jl/actions/workflows/CI.yml/badge.svg)](https://github.com/JuliaPOMDP/POMDPXFiles.jl/actions/workflows/CI.yml/) [![codecov](https://codecov.io/gh/JuliaPOMDP/POMDPXFiles.jl/branch/master/graph/badge.svg?token=14YwrQvwbp)](https://codecov.io/gh/JuliaPOMDP/POMDPXFiles.jl) This module provides an interface for generating .pomdpx files that can be used with the [SARSOP.jl](https://github.com/JuliaPOMDP/SARSOP.jl). This module leverages the API defined in [POMDPs.jl](https://github.com/JuliaPOMDP/POMDPs.jl). ## Installation ```julia Pkg.add("POMDPXFiles") ``` The module provides an interface for generating files for both POMDPs and MOMDPs. ## Module Types - `AbstractPOMDPXFile` - `POMDPXFile` - `MOMDPXFile` ## Usage Make sure that your model is defined according to the API in POMDPs.jl. ```julia pomdp = YourPOMDP() # intialize your pomdp pomdpx = POMDPX("my_pomdp.pomdpx") # for pomdp pomdpx = MOMDPX("my_pomdp.pomdpx") # for momdp write(pomdp, pomdpx) # creates a pomdpx file called my_pomdp.pomdpx ``` ## MOMDPs (Deprecated) While MOMDPs are no longer officially supported, you can look at how they were handled in an older version of POMDPs.jl in [this branch](https://github.com/altiscope/prototype/blob/develop/scenarios/memos/2/analysis.json)
POMDPXFiles
https://github.com/JuliaPOMDP/POMDPXFiles.jl.git
[ "MIT" ]
0.6.4
b87cd13d6d99575da6c0e6ff6727c2fe643d327d
code
4204
# Retrieve name of example and output directory if length(ARGS) != 1 error("please specify the name of the output directory") end const RELOUTDIR = ARGS[1] const EXAMPLEDIR = dirname(Base.active_project()) const EXAMPLE = basename(EXAMPLEDIR) const OUTDIR = joinpath(@__DIR__, "src", RELOUTDIR, EXAMPLE) mkpath(OUTDIR) # Load non-example specific packages using Literate: Literate # from stacked environment using InteractiveUtils: InteractiveUtils using Pkg: Pkg # Save Manifest.toml cp( Pkg.Types.manifestfile_path(EXAMPLEDIR; strict=true), joinpath(OUTDIR, "Manifest.toml"); force=true, ) # Strip build version from a tag (cf. JuliaDocs/Documenter.jl#1298, Literate.jl#162) function version_tag_strip_build(tag) m = match(Base.VERSION_REGEX, tag) m === nothing && return tag s0 = startswith(tag, 'v') ? "v" : "" s1 = m[1] # major s2 = m[2] === nothing ? "" : ".$(m[2])" # minor s3 = m[3] === nothing ? "" : ".$(m[3])" # patch s4 = m[5] === nothing ? "" : m[5] # pre-release (starting with -) # m[7] is the build, which we want to discard return "$s0$s1$s2$s3$s4" end # Obtain name of deploy folder function deployfolder(; devurl="dev") github_ref = get(ENV, "GITHUB_REF", "") if get(ENV, "GITHUB_EVENT_NAME", nothing) == "push" if (m = match(r"^refs\/tags\/(.*)$", github_ref)) !== nothing # new tags: correspond to a new version return version_tag_strip_build(String(m.captures[1])) end elseif (m = match(r"refs\/pull\/(\d+)\/merge", github_ref)) !== nothing # pull request: build preview "previews/PR$(m.captures[1])" end # fallback: development branch return devurl end # Add link to nbviewer below the first heading of level 1 and add footer const RELEXAMPLEDIR = relpath(EXAMPLEDIR, joinpath(@__DIR__, "..")) const DEPLOYFOLDER = deployfolder() function preprocess(content) io = IOBuffer() # Print initial lines, up to and including the first heading of level 1 lines = eachline(IOBuffer(content)) for line in lines println(io, line) startswith(line, "# # ") && break end # Add header print( io, """ # #md # [![](https://img.shields.io/badge/show-nbviewer-579ACA.svg)](@__NBVIEWER_ROOT_URL__/$RELOUTDIR/$EXAMPLE/notebook.ipynb) #md # # *You are seeing the #md # HTML output generated by [Documenter.jl](https://github.com/JuliaDocs/Documenter.jl) and #nb # notebook output generated by # [Literate.jl](https://github.com/fredrikekre/Literate.jl) from the # [Julia source file](@__REPO_ROOT_URL__/$RELEXAMPLEDIR/script.jl). # The corresponding #md # notebook can be viewed in [nbviewer](@__NBVIEWER_ROOT_URL__/$RELOUTDIR/$EXAMPLE/notebook.ipynb).* #nb # HTML output can be viewed [here](https://devmotion.github.io/CalibrationErrors.jl/$DEPLOYFOLDER/$RELOUTDIR/$EXAMPLE/).* # """, ) # Print remaining lines for line in lines println(io, line) end # Add footer println(io, "# ### Package and system information") ## Add package status iopkg = IOBuffer() Pkg.status(; io=iopkg) seekstart(iopkg) println(io, "# #### Package version\n# ```julia") for l in eachline(iopkg) println(io, "# ", l) end println(io, "# ```") ## Add computer info ioversion = IOBuffer() InteractiveUtils.versioninfo(ioversion) seekstart(ioversion) println(io, "# #### Computer information\n# ```") for l in eachline(ioversion) println(io, "# ", l) end println(io, "# ```") ## Add link to Manifest file print( io, """ # #### Manifest # To reproduce the project environment of this example you can [download the full Manifest.toml](./Manifest.toml). """, ) return String(take!(io)) end # Convert to markdown and notebook const SCRIPTJL = joinpath(EXAMPLEDIR, "script.jl") Literate.markdown(SCRIPTJL, OUTDIR; name="index", execute=true, preprocess=preprocess) Literate.notebook(SCRIPTJL, OUTDIR; name="notebook", execute=true, preprocess=preprocess)
CalibrationErrors
https://github.com/devmotion/CalibrationErrors.jl.git
[ "MIT" ]
0.6.4
b87cd13d6d99575da6c0e6ff6727c2fe643d327d
code
4839
using CalibrationErrors using Documenter ### Process examples # Always rerun examples const EXAMPLES_OUT = joinpath(@__DIR__, "src", "examples") ispath(EXAMPLES_OUT) && rm(EXAMPLES_OUT; recursive=true) mkpath(EXAMPLES_OUT) # The following function returns a script for instantiating the package # environment of an example # It ensures that the version of the package in which module `mod` is defined # (here `mod` will be ApproximateGPs loaded above) is added to the environment. # Thus the docs and the examples will use the same version of this package. # There are two special cases: # - If the script is executed by a GH action triggered by a new tag (i.e., release) # in the package repo, then this version of the package will be downloaded and installed # instead of checking out the local path # - If the script is executed by a GH action triggered by a new commit in the `devbranch` # (by default `master`) in the package repo, then this revision of the package will be # downloaded and installed instead of checking out the local path # This ensures that in these two cases the resulting Manifest.toml files do not fix the # local path of any package, and hence can be used to reproduce the package environment in # a clean and reproducible way. function instantiate_script(mod; org, name=string(nameof(mod)), devbranch="main") github_repo = get(ENV, "GITHUB_REPOSITORY", "") github_event_name = get(ENV, "GITHUB_EVENT_NAME", "") repo = org * "/" * name * ".jl" if github_repo == repo && github_event_name == "push" github_ref = get(ENV, "GITHUB_REF", "") match_tag = match(r"^refs\/tags\/(.*)$", github_ref) if match_tag !== nothing # tagged release tag_nobuild = Documenter.version_tag_strip_build(match_tag.captures[1]) if tag_nobuild !== nothing @info "Run examples with $name version $tag_nobuild" return """ using Pkg Pkg.add(PackageSpec(; name="$name", version="$tag_nobuild")) Pkg.instantiate() """ end else # no release tag match_branch = match(r"^refs\/heads\/(.*)$", github_ref) if match_branch !== nothing && string(match_branch.captures[1]) == devbranch sha = get(ENV, "GITHUB_SHA", nothing) if sha !== nothing @info "Run examples with $name commit $sha" return """ using Pkg Pkg.add(PackageSpec(; name="$name", rev="$sha")) Pkg.instantiate() """ end end end end # Default: Use local path of provided module pkgdir_mod = pkgdir(mod) @info "Run examples with $name, local path $pkgdir_mod" return """ using Pkg Pkg.develop(PackageSpec(; path="$pkgdir_mod")) Pkg.instantiate() """ end let # Install and precompile all packages # Workaround for https://github.com/JuliaLang/Pkg.jl/issues/2219 examples = filter!(isdir, readdir(joinpath(@__DIR__, "..", "examples"); join=true)) script = instantiate_script(CalibrationErrors; org="devmotion") for example in examples run(`$(Base.julia_cmd()) --project=$example -e $script`) end # Run examples asynchronously literatejl = joinpath(@__DIR__, "literate.jl") # Add current directory to LOAD_PATH: by stacking environments we can load Literate # without adding it to each example cmd = addenv( Base.julia_cmd(), "JULIA_LOAD_PATH" => (Sys.iswindows() ? ";" : ":") * @__DIR__ ) processes = map(examples) do example return run( pipeline( `$cmd --project=$example $literatejl examples`; stdin=devnull, stdout=devnull, stderr=stderr, ); wait=false, )::Base.Process end # Check that all examples were run successfully isempty(processes) || success(processes) || error("some examples were not run successfully") end # Build documentation makedocs(; modules=[CalibrationErrors], authors="David Widmann <[email protected]>", repo="https://github.com/devmotion/CalibrationErrors.jl/blob/{commit}{path}#L{line}", sitename="CalibrationErrors.jl", format=Documenter.HTML(; prettyurls=true, canonical="https://devmotion.github.io/CalibrationErrors.jl", assets=String[], ), pages=[ "index.md", "introduction.md", "ece.md", "kce.md", "others.md", "Examples" => map(filter!(isdir, readdir(EXAMPLES_OUT; join=true))) do x return joinpath("examples", basename(x), "index.md") end, ], strict=true, checkdocs=:exports, ) deploydocs(; repo="github.com/devmotion/CalibrationErrors.jl.git", push_preview=true, devbranch="main", )
CalibrationErrors
https://github.com/devmotion/CalibrationErrors.jl.git
[ "MIT" ]
0.6.4
b87cd13d6d99575da6c0e6ff6727c2fe643d327d
code
9412
# # Classification of penguin species # # ## Packages using AlgebraOfGraphics using CairoMakie using CalibrationErrors using DataFrames using Distributions using MLJ using MLJNaiveBayesInterface using PalmerPenguins using Random ## Plotting settings set_aog_theme!() CairoMakie.activate!(; type="svg") # ## Data # # In this example we study the calibration of different models that classify three penguin # species based on measurements of their bill and flipper lengths. # # We use the [Palmer penguins dataset](https://allisonhorst.github.io/palmerpenguins/) to # to train and validate the models. penguins = dropmissing(DataFrame(PalmerPenguins.load())) penguins_mapping = data(penguins) * mapping( :bill_length_mm => "bill length (mm)", :flipper_length_mm => "flipper length (mm)" ) draw(penguins_mapping * mapping(; color=:species) * visual(; alpha=0.7)) # We split the data randomly into a training and validation dataset. The training dataset # contains around 60% of the samples. Random.seed!(1234) n = nrow(penguins) k = floor(Int, 0.7 * n) Random.seed!(100) penguins.train = shuffle!(vcat(trues(k), falses(n - k))) ## Plot the training and validation data dataset = :train => renamer(true => "training", false => "validation") => "Dataset" plt = penguins_mapping * mapping(; color=:species, col=dataset) * visual(; alpha=0.7) draw(plt; axis=(height=300,)) # ## Fitting normal distributions # # For each species, we fit independent normal distributions to the observations of the bill # and flipper length in the training data, using maximum likelihood estimation. y, X = unpack( penguins, ==(:species), x -> x === :bill_length_mm || x === :flipper_length_mm; :species => Multiclass, :bill_length_mm => MLJ.Continuous, :flipper_length_mm => MLJ.Continuous, ) model = fit!(machine(GaussianNBClassifier(), X, y); rows=penguins.train); # We plot the estimated normal distributions. ## plot datasets fg = draw(plt; axis=(height=300,)) ## plot Gaussian distributions xgrid = range(extrema(penguins.bill_length_mm)...; length=100) ygrid = range(extrema(penguins.flipper_length_mm)...; length=100) let f = (x, y, dist) -> pdf(dist, [x, y]) for (class, color) in zip(classes(y), Makie.wong_colors()) pdfs = f.(xgrid, ygrid', Ref(model.fitresult.gaussians[class])) contour!(fg.figure[1, 1], xgrid, ygrid, pdfs; color=color) contour!(fg.figure[1, 2], xgrid, ygrid, pdfs; color=color) end end fg # ## Naive Bayes classifier # # Let us assume that the bill and flipper length are conditionally independent given the # penguin species. Then Bayes' theorem implies that # ```math # \begin{aligned} # \mathbb{P}(\mathrm{species} \,|\, \mathrm{bill}, \mathrm{flipper}) # &= \frac{\mathbb{P}(\mathrm{species}) \mathbb{P}(\mathrm{bill}, \mathrm{flipper} \,|\, \mathrm{species})}{\mathbb{P}(\mathrm{bill}, \mathrm{flipper})} \\ # &= \frac{\mathbb{P}(\mathrm{species}) \mathbb{P}(\mathrm{bill} \,|\, \mathrm{species}) \mathbb{P}(\mathrm{flipper} \,|\, \mathrm{species})}{\mathbb{P}(\mathrm{bill}, \mathrm{flipper})}. # \end{aligned} # ``` # This predictive model is known as # [naive Bayes classifier](https://en.wikipedia.org/wiki/Naive_Bayes_classifier). # # In the section above, we estimated $\mathbb{P}(\mathrm{species})$, # $\mathbb{P}(\mathrm{bill} \,|\, \mathrm{species})$, and # $\mathbb{P}(\mathrm{flipper} \,|\, \mathrm{species})$ for each penguin species from # the training data. For the conditional distributions we used a Gaussian approximation. predictions = MLJ.predict(model) train_predict = predictions[penguins.train] val_predict = predictions[.!penguins.train] ## Plot datasets fg = draw(plt; axis=(height=300,)) ## Plot predictions predictions_grid = reshape( MLJ.predict(model, reduce(hcat, vcat.(xgrid, ygrid'))'), length(xgrid), length(ygrid) ) for (class, color) in zip(classes(y), Makie.wong_colors()) p = pdf.(predictions_grid, class) contour!(fg.figure[1, 1], xgrid, ygrid, p; color=color) contour!(fg.figure[1, 2], xgrid, ygrid, p; color=color) end fg # ## Evaluation # # We evaluate the probabilistic predictions of the naive Bayes classifier that we just # trained. # # ### Log-likelihood # # We compute the average log-likelihood of the validation data. It is equivalent to the # negative cross-entropy. val_y = y[.!penguins.train] -mean(cross_entropy(val_predict, val_y)) # ### Brier score # # The average log-likelihood is also equivalent to the # [logarithmic score](https://sites.stat.washington.edu/raftery/Research/PDF/Gneiting2007jasa.pdf). # The Brier score is another strictly proper scoring rule that can be used for evaluating # probabilistic predictions. mean(brier_score(val_predict, val_y)) # ### Expected calibration error # # As all proper scoring rules, the logarithmic and the Brier score can be [decomposed in # three terms that quantify the sharpness and calibration of the predictive model and the # irreducible uncertainty of the targets that is inherent to the prediction # problem](https://doi.org/10.1002/qj.456). The calibration term in this decomposition is # the expected calibration error (ECE) # ```math # \mathbb{E} d\big(P_X, \mathrm{law}(Y \,|\, P_X)\big) # ``` # with respect to the score divergence $d$. # # Scoring rules, however, include also the sharpness and the uncertainty term. Thus models # can trade off calibration for sharpness and therefore scoring rules are not suitable for # specifically evaluating calibration of predictive models. # # The score divergence to the logarithmic and the Brier score are the Kullback-Leibler (KL) # divergence # ```math # d\big(P_X, \mathrm{law}(Y \,|\, P_X)\big) = \sum_{y} \mathbb{P}(Y = y \,|\, P_X) # \log\big(\mathbb{P}(Y = y \,|\, P_X) / P_X(\{y\})\big) # ``` # and the squared Euclidean distance # ```math # d\big(P_X, \mathrm{law}(Y \,|\, P_X)\big) = \sum_{y} \big(P_X - \mathrm{law}(Y \,|\, P_X)\big)^2(\{y\}), # ``` # respectively. The KL divergence is defined only if $\mathrm{law}(Y \,|\, P_X)$ is # absolutely continuous with respect to $P_X$, i.e., if $P_X(\{y\}) = 0$ implies # $\mathbb{P}(Y = y \,|\, P_X) = 0$. # We estimate the ECE by binning the probability simplex of predictions $P_X$ and computing # the weighted average of the distances between the mean prediction and the distribution of # targets in each bin. # # One approach is to use bins of uniform size. ece = ECE(UniformBinning(10), (μ, y) -> kl_divergence(y, μ)); # We have to work with a numerical encoding of the true penguin species and a # corresponding vector of predictions. We use [`RowVecs`](https://juliagaussianprocesses.github.io/KernelFunctions.jl/stable/api/#KernelFunctions.RowVecs) # to indicate that the rows in the matrix of probabilities returned by `pdf` # are the predictions. If we would provide predictions as columns of a matrix, we would have # to use [`ColVecs`](https://juliagaussianprocesses.github.io/KernelFunctions.jl/stable/api/#KernelFunctions.ColVecs). val_yint = map(MLJ.levelcode, val_y) val_probs = RowVecs(pdf(val_predict, MLJ.classes(y))); # We compute the estimate on the validation data: ece(val_probs, val_yint) # For the squared Euclidean distance we obtain: ece = ECE(UniformBinning(10), SqEuclidean()) ece(val_probs, val_yint) # Alternatively, one can use a data-dependent binning scheme that tries to split the # predictions in a way that minimizes the variance in each bin. # # With the KL divergence we get: ece = ECE(MedianVarianceBinning(5), (μ, y) -> kl_divergence(y, μ)) ece(val_probs, val_yint) # For the squared Euclidean distance we obtain: ece = ECE(MedianVarianceBinning(5), SqEuclidean()) ece(val_probs, val_yint) # We see that the estimates (of the same theoretical quantity!) are highly dependent on the # chosen binning scheme. # ### Kernel calibration error # # As an alternative to the ECE, we estimate the kernel calibration error (KCE). We keep it # simple here, and use the tensor product kernel # ```math # k\big((\mu, y), (\mu', y')\big) = \delta_{y,y'} \exp{\bigg(-\frac{{\|\mu - \mu'\|}_2^2}{2\nu^2} \bigg)} # ``` # with length scale $\nu > 0$ for predictions $\mu,\mu'$ and corresponding targets $y, y'$. # For simplicity, we estimate length scale $\nu$ with the median heuristic. distances = pairwise(SqEuclidean(), RowVecs(pdf(train_predict, MLJ.classes(y)))) ν = sqrt(median(distances[i] for i in CartesianIndices(distances) if i[1] < i[2])) kernel = with_lengthscale(GaussianKernel(), ν) ⊗ WhiteKernel(); # We obtain the following biased estimate of the squared KCE (SKCE): skce = SKCE(kernel; unbiased=false) skce(val_probs, val_yint) # Similar to the biased estimates of the ECE, the biased estimates of the SKCE are always # non-negative. The unbiased estimates can be negative as well, in particular if the model # is (close to being) calibrated: skce = SKCE(kernel) skce(val_probs, val_yint) # When the datasets are large, the quadratic sample complexity of the standard biased and # unbiased estimators of the SKCE can become prohibitive. In these cases, one can resort to # an estimator that averages estimates of non-overlapping blocks of samples. This estimator # allows to trade off computational cost for increased variance. # # Here we consider the extreme case of blocks with two samples, which yields an estimator # with linear sample complexity: skce = SKCE(kernel; blocksize=2) skce(val_probs, val_yint)
CalibrationErrors
https://github.com/devmotion/CalibrationErrors.jl.git
[ "MIT" ]
0.6.4
b87cd13d6d99575da6c0e6ff6727c2fe643d327d
code
8314
# # Distribution of calibration error estimates # # ## Packages using CairoMakie using CalibrationErrors using Distributions using StatsBase using LinearAlgebra using Random using Statistics CairoMakie.activate!(; type="svg") # ## Introduction # # This example is taken from the publication # ["Calibration tests in multi-class classification: A unifying framework"](https://proceedings.neurips.cc/paper/2019/hash/1c336b8080f82bcc2cd2499b4c57261d-Abstract.html) # by Widmann, Lindsten, and Zachariah (2019). # # We estimate calibration errors of the model # ```math # \begin{aligned} # g(X) &\sim \mathrm{Dir}(\alpha),\\ # Z &\sim \mathrm{Ber}(\pi),\\ # Y \,|\, g(X) = \gamma, Z = 1 &\sim \mathrm{Categorical}(\beta),\\ # Y \,|\, g(X) = \gamma, Z = 0 &\sim \mathrm{Categorical}(\gamma), # \end{aligned} # ``` # where $\alpha \in \mathbb{R}_{>0}^m$ determines the distribution of # predictions $g(X)$, $\pi > 0$ determines the degree of miscalibration, and # $\beta$ defines a fixed categorical distribution. # # Here we consider only the choices $\alpha = (0.1, \ldots, 0.1)$, mimicking a # distribution after training that is pushed towards the edges of the # probability simplex, and $\beta = (1, 0, \ldots, 0)$. # # In our experiments we sample 250 predictions from the Dirichlet distribution # $\textrm{Dir}(\alpha)$, and then we generate corresponding labels according to # the model stated above, for different choices of $\pi$ and number of classes $m$. # # We evaluate the standard estimators of expected calibration error (ECE) based on a # uniform binning scheme and a data-dependent binning scheme, and the biased estimator of # the squared kernel calibration error (SKCE), the quadratic unbiased estimator of # the SKCE, and the linear unbiased estimator of the SKCE for a specific choice of # matrix-valued kernels. # # The sampling procedure and the evaluation are repeated 100 times, to obtain a sample # of 100 estimates for each considered setting of $\pi$ and $m$. # # For our choice of $\alpha$ and $\beta$, the analytical ECE with respect to the # total variation distance $\|.\|_{\mathrm{TV}}$ is # ```math # \mathrm{ECE}_{\mathrm{TV}} = \frac{\pi(m-1)}{m}. # ``` # # ## Estimates # function estimates(estimator, π::Real, m::Int) ## cache array for predictions, modified predictions, and labels predictions = [Vector{Float64}(undef, m) for _ in 1:250] targets = Vector{Int}(undef, 250) data = (predictions, targets) ## define sampler of predictions sampler_predictions = sampler(Dirichlet(m, 0.1)) ## initialize estimates estimates = Vector{Float64}(undef, 100) ## for each run @inbounds for i in eachindex(estimates) ## sample predictions rand!.((sampler_predictions,), predictions) ## sample targets for (j, p) in enumerate(predictions) if rand() < π targets[j] = 1 else targets[j] = rand(Categorical(p)) end end ## evaluate estimator estimates[i] = estimator(data)(predictions, targets) end return estimates end; # We use a helper function to run the experiment for all desired parameter settings. struct EstimatesSet m::Vector{Int} π::Vector{Float64} estimates::Matrix{Vector{Float64}} end function estimates(estimator) ## for all combinations of m and π mvec = [2, 10, 100] πvec = [0.0, 0.5, 1.0] estimatesmat = estimates.((estimator,), πvec', mvec) return EstimatesSet(mvec, πvec, estimatesmat) end; # As mentioned above, we can calculate the analytic expected calibration error. For the squared # kernel calibration error, we take the mean of the estimates of the unbiased quadratic # estimator as approximation of the true value. # We provide simple histogram plots of our results. The mean value of the # estimates is indicated by a solid vertical line and the analytic calibration error for the ECE # is visualized as a dashed line. function plot_estimates(set::EstimatesSet; ece=false) ## create figure f = Figure(; resolution=(1080, 960)) ## add subplots nrows, ncols = size(set.estimates) for (j, π) in enumerate(set.π), (i, m) in enumerate(set.m) ## obtain data estimates = set.estimates[i, j] ## create new axis ax = Axis(f[i, j]; xticks=LinearTicks(4)) i < nrows && hidexdecorations!(ax; grid=false) j > 1 && hideydecorations!(ax; grid=false) ## plot histogram of estimates h = fit(Histogram, estimates) barplot!(ax, h; strokecolor=:black, strokewidth=0.5) ## indicate mean of estimates vlines!(ax, [mean(estimates)]; linewidth=2) ## indicate analytic calibration error for ECE if ece vlines!(ax, [π * (m - 1) / m]; linewidth=2, linestyle=:dash) end end ## add labels and link axes for (j, π) in enumerate(set.π) Box(f[1, j, Top()]; color=:gray90) Label(f[1, j, Top()], "π = $π"; padding=(0, 0, 5, 5)) linkxaxes!(contents(f[:, j])...) end for (i, m) in enumerate(set.m) Box(f[i, ncols, Right()]; color=:gray90) Label(f[i, ncols, Right()], "$m classes"; rotation=-π / 2, padding=(5, 5, 0, 0)) linkyaxes!(contents(f[i, :])...) end Label(f[nrows, 1:ncols, Bottom()], "calibration error estimate"; padding=(0, 0, 0, 75)) Label(f[1:nrows, 1, Left()], "# runs"; rotation=π / 2, padding=(0, 75, 0, 0)) return f end; # ## Kernel choice # We use a tensor product kernel consisting of an exponential kernel # $k(\mu, \mu') = \exp{(- \gamma \|p - p'\|)}$ on the space of predicted categorical # distributions and a white kernel $k(y, y') = \delta(y - y')$ on the space of targets # $\{1,\ldots,m\}$. The total variation distance is chosen as the norm on the space of # predictions, and the inverse lengthscale $\gamma$ is set according to the median # heuristic. struct MedianHeuristicKernel distances::Matrix{Float64} cache::Vector{Float64} end function MedianHeuristicKernel(n::Int) return MedianHeuristicKernel( Matrix{Float64}(undef, n, n), Vector{Float64}(undef, (n * (n - 1)) ÷ 2) ) end function (f::MedianHeuristicKernel)((predictions, targets)) distances = f.distances cache = f.cache ## compute lengthscale with median heuristic pairwise!(distances, TotalVariation(), predictions) k = 0 @inbounds for j in axes(distances, 2), i in 1:(j - 1) cache[k += 1] = distances[i, j] end λ = median!(cache) ## create tensor product kernel kernel_predictions = with_lengthscale(ExponentialKernel(; metric=TotalVariation()), λ) kernel_targets = WhiteKernel() return kernel_predictions ⊗ kernel_targets end #md nothing #hide # ## Expected calibration error # # ### Uniform binning # # We start by analyzing the expected calibration error (ECE). # For our estimation we use 10 bins of uniform width in each dimension. Random.seed!(1234) data = estimates(_ -> ECE(UniformBinning(10), TotalVariation())) plot_estimates(data; ece=true) # ### Non-uniform binning # # We repeat our experiments with a different data-dependent binning scheme. This # time the bins will be computed dynamically by splitting the predictions at the # median of the classes with the highest variance, as long as the number of bins # does not exceed a given threshold and the number of samples per bin is above # a certain lower bound. In our experiments we do not impose any restriction on # the number of bins but only stop splitting if the number of samples is less # than 10. Random.seed!(1234) data = estimates(_ -> ECE(MedianVarianceBinning(10), TotalVariation())) plot_estimates(data; ece=true) # ## Unbiased estimators of the squared kernel calibration error # Random.seed!(1234) data = estimates(SKCE ∘ MedianHeuristicKernel(250)) plot_estimates(data) Random.seed!(1234) data = estimates() do predictions_targets return SKCE(MedianHeuristicKernel(250)(predictions_targets); blocksize=2) end plot_estimates(data) # ## Biased estimator of the squared kernel calibration error # Random.seed!(1234) data = estimates() do predictions_targets return SKCE(MedianHeuristicKernel(250)(predictions_targets); unbiased=false) end plot_estimates(data)
CalibrationErrors
https://github.com/devmotion/CalibrationErrors.jl.git
[ "MIT" ]
0.6.4
b87cd13d6d99575da6c0e6ff6727c2fe643d327d
code
983
module CalibrationErrors using Reexport using DataStructures @reexport using Distances @reexport using Distributions using ExactOptimalTransport: ExactOptimalTransport @reexport using KernelFunctions using PDMats: PDMats using SimpleUnPack: @unpack using StatsBase: StatsBase using Tulip: Tulip using LinearAlgebra using Statistics const OT = ExactOptimalTransport # estimators export ECE, SKCE, UCME # binning algorithms export UniformBinning, MedianVarianceBinning # Wasserstein distances export Wasserstein, SqWasserstein, MixtureWasserstein, SqMixtureWasserstein include("distances/types.jl") include("distances/wasserstein.jl") include("generic.jl") include("binning/generic.jl") include("binning/uniform.jl") include("binning/medianvariance.jl") include("ece.jl") include("skce.jl") include("ucme.jl") include("distributions/normal.jl") include("distributions/laplace.jl") include("distributions/mvnormal.jl") include("distributions/mixturemodel.jl") end # module
CalibrationErrors
https://github.com/devmotion/CalibrationErrors.jl.git
[ "MIT" ]
0.6.4
b87cd13d6d99575da6c0e6ff6727c2fe643d327d
code
2441
struct ECE{B<:AbstractBinningAlgorithm,D} <: CalibrationErrorEstimator """Binning algorithm.""" binning::B """Distance function.""" distance::D end """ ECE(binning[, distance = TotalVariation()]) Estimator of the expected calibration error (ECE) for a classification model with respect to the given `distance` function using the `binning` algorithm. For classification models, the predictions ``P_{X_i}`` and targets ``Y_i`` are identified with vectors in the probability simplex. The estimator of the ECE is defined as ```math \\frac{1}{B} \\sum_{i=1}^B d\\big(\\overline{P}_i, \\overline{Y}_i\\big), ``` where ``B`` is the number of non-empty bins, ``d`` is the distance function, and ``\\overline{P}_i`` and ``\\overline{Y}_i`` are the average vector of the predictions and the average vector of targets in the ``i``th bin. By default, the total variation distance is used. The `distance` has to be a function of the form ```julia distance(pbar::Vector{<:Real}, ybar::Vector{<:Real}). ``` In particular, distance measures of the package [Distances.jl](https://github.com/JuliaStats/Distances.jl) are supported. """ ECE(binning::AbstractBinningAlgorithm) = ECE(binning, TotalVariation()) # estimate ECE function (ece::ECE)(predictions::AbstractVector, targets::AbstractVector) @unpack binning, distance = ece # check number of samples check_nsamples(predictions, targets) # bin predictions and labels bins = perform(binning, predictions, targets) nbins = length(bins) nbins > 0 || error("there must exist at least one bin") # compute the weighted mean of the distances in each bin # use West's algorithm for numerical stability # evaluate the distance in the first bin @inbounds begin bin, state = iterate(bins) # there is always at least one bin x = distance(bin.mean_predictions, bin.proportions_targets) # initialize the estimate estimate = x / 1 # for all other bins n = bin.nsamples while true bin_state = iterate(bins, state) bin_state === nothing && break # evaluate the distance bin, state = bin_state x = distance(bin.mean_predictions, bin.proportions_targets) # update the estimate m = bin.nsamples n += m estimate += (m / n) * (x - estimate) end end return estimate end
CalibrationErrors
https://github.com/devmotion/CalibrationErrors.jl.git