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
|
---|---|---|---|---|---|---|---|---|
[
"MPL-2.0"
] | 0.3.0 | f49af35a8dd097d4dccabf94bd2053afbfdab3a4 | code | 614 | using Documenter, KrylovPreconditioners
makedocs(
modules = [KrylovPreconditioners],
doctest = true,
linkcheck = true,
format = Documenter.HTML(assets = ["assets/style.css"],
ansicolor = true,
prettyurls = get(ENV, "CI", nothing) == "true",
collapselevel = 1),
sitename = "KrylovPreconditioners.jl",
pages = ["Home" => "index.md",
"Reference" => "reference.md"
]
)
deploydocs(
repo = "github.com/JuliaSmoothOptimizers/KrylovPreconditioners.jl.git",
push_preview = true,
devbranch = "main",
)
| KrylovPreconditioners | https://github.com/JuliaSmoothOptimizers/KrylovPreconditioners.jl.git |
|
[
"MPL-2.0"
] | 0.3.0 | f49af35a8dd097d4dccabf94bd2053afbfdab3a4 | code | 528 | module KrylovPreconditionersAMDGPUExt
using LinearAlgebra
using SparseArrays
using AMDGPU
using AMDGPU.rocSPARSE, AMDGPU.rocSOLVER
using LinearAlgebra: checksquare, BlasReal, BlasFloat
import LinearAlgebra: ldiv!, mul!
import Base: size, eltype, unsafe_convert
using KrylovPreconditioners
const KP = KrylovPreconditioners
using KernelAbstractions
const KA = KernelAbstractions
include("AMDGPU/ic0.jl")
include("AMDGPU/ilu0.jl")
include("AMDGPU/blockjacobi.jl")
include("AMDGPU/operators.jl")
include("AMDGPU/scaling.jl")
end
| KrylovPreconditioners | https://github.com/JuliaSmoothOptimizers/KrylovPreconditioners.jl.git |
|
[
"MPL-2.0"
] | 0.3.0 | f49af35a8dd097d4dccabf94bd2053afbfdab3a4 | code | 506 | module KrylovPreconditionersCUDAExt
using LinearAlgebra
using SparseArrays
using CUDA
using CUDA.CUSPARSE, CUDA.CUBLAS
using LinearAlgebra: checksquare, BlasReal, BlasFloat
import LinearAlgebra: ldiv!, mul!
import Base: size, eltype, unsafe_convert
using KrylovPreconditioners
const KP = KrylovPreconditioners
using KernelAbstractions
const KA = KernelAbstractions
include("CUDA/ic0.jl")
include("CUDA/ilu0.jl")
include("CUDA/blockjacobi.jl")
include("CUDA/operators.jl")
include("CUDA/scaling.jl")
end
| KrylovPreconditioners | https://github.com/JuliaSmoothOptimizers/KrylovPreconditioners.jl.git |
|
[
"MPL-2.0"
] | 0.3.0 | f49af35a8dd097d4dccabf94bd2053afbfdab3a4 | code | 483 | module KrylovPreconditionersoneAPIExt
using LinearAlgebra
using SparseArrays
using oneAPI
using oneAPI: global_queue, sycl_queue, context, device
using oneAPI.oneMKL
using LinearAlgebra: checksquare, BlasReal, BlasFloat
import LinearAlgebra: ldiv!, mul!
import Base: size, eltype, unsafe_convert
using KrylovPreconditioners
const KP = KrylovPreconditioners
using KernelAbstractions
const KA = KernelAbstractions
include("oneAPI/blockjacobi.jl")
include("oneAPI/operators.jl")
end
| KrylovPreconditioners | https://github.com/JuliaSmoothOptimizers/KrylovPreconditioners.jl.git |
|
[
"MPL-2.0"
] | 0.3.0 | f49af35a8dd097d4dccabf94bd2053afbfdab3a4 | code | 1672 | KP.BlockJacobiPreconditioner(J::rocSPARSE.ROCSparseMatrixCSR; options...) = BlockJacobiPreconditioner(SparseMatrixCSC(J); options...)
function KP.create_blocklist(cublocks::ROCArray, npart)
blocklist = Array{ROCMatrix{Float64}}(undef, npart)
for b in 1:npart
blocklist[b] = ROCMatrix{Float64}(undef, size(cublocks,1), size(cublocks,2))
end
return blocklist
end
function _update_gpu(p, j_rowptr, j_colval, j_nzval, device::ROCBackend)
nblocks = p.nblocks
blocksize = p.blocksize
fillblock_gpu_kernel! = KP._fillblock_gpu!(device)
# Fill Block Jacobi" begin
fillblock_gpu_kernel!(
p.cublocks, size(p.id,1),
p.cupartitions, p.cumap,
j_rowptr, j_colval, j_nzval,
p.cupart, p.culpartitions, p.id,
ndrange=(nblocks, blocksize),
)
KA.synchronize(device)
# Invert blocks begin
for b in 1:nblocks
p.blocklist[b] .= p.cublocks[:,:,b]
end
AMDGPU.@sync pivot, info = rocSOLVER.getrf_batched!(p.blocklist)
AMDGPU.@sync pivot, info, p.blocklist = rocSOLVER.getri_batched!(p.blocklist, pivot)
for b in 1:nblocks
p.cublocks[:,:,b] .= p.blocklist[b]
end
return
end
"""
function update!(J::ROCSparseMatrixCSR, p)
Update the preconditioner `p` from the sparse Jacobian `J` in CSR format for ROCm
1) The dense blocks `cuJs` are filled from the sparse Jacobian `J`
2) To a batch inversion of the dense blocks using CUBLAS
3) Extract the preconditioner matrix `p.P` from the dense blocks `cuJs`
"""
function KP.update!(p::BlockJacobiPreconditioner, J::rocSPARSE.ROCSparseMatrixCSR)
_update_gpu(p, J.rowPtr, J.colVal, J.nzVal, p.device)
end
| KrylovPreconditioners | https://github.com/JuliaSmoothOptimizers/KrylovPreconditioners.jl.git |
|
[
"MPL-2.0"
] | 0.3.0 | f49af35a8dd097d4dccabf94bd2053afbfdab3a4 | code | 4395 | mutable struct AMD_IC0{SM} <: AbstractKrylovPreconditioner
n::Int
desc::rocSPARSE.ROCMatrixDescriptor
buffer::ROCVector{UInt8}
info::rocSPARSE.MatInfo
timer_update::Float64
P::SM
end
for (bname, aname, sname, T) in ((:rocsparse_scsric0_buffer_size, :rocsparse_scsric0_analysis, :rocsparse_scsric0, :Float32),
(:rocsparse_dcsric0_buffer_size, :rocsparse_dcsric0_analysis, :rocsparse_dcsric0, :Float64),
(:rocsparse_ccsric0_buffer_size, :rocsparse_ccsric0_analysis, :rocsparse_ccsric0, :ComplexF32),
(:rocsparse_zcsric0_buffer_size, :rocsparse_zcsric0_analysis, :rocsparse_zcsric0, :ComplexF64))
@eval begin
function KP.kp_ic0(A::ROCSparseMatrixCSR{$T,Cint})
P = copy(A)
n = checksquare(P)
desc = rocSPARSE.ROCMatrixDescriptor('G', 'L', 'N', 'O')
info = rocSPARSE.MatInfo()
buffer_size = Ref{Csize_t}()
rocSPARSE.$bname(rocSPARSE.handle(), n, nnz(P), desc, P.nzVal, P.rowPtr, P.colVal, info, buffer_size)
buffer = ROCVector{UInt8}(undef, buffer_size[])
rocSPARSE.$aname(rocSPARSE.handle(), n, nnz(P), desc, P.nzVal, P.rowPtr, P.colVal, info,
rocSPARSE.rocsparse_analysis_policy_force, rocSPARSE.rocsparse_solve_policy_auto, buffer)
posit = Ref{Cint}(1)
rocSPARSE.rocsparse_csric0_zero_pivot(rocSPARSE.handle(), info, posit)
(posit[] ≥ 0) && error("Structural/numerical zero in A at ($(posit[]),$(posit[])))")
rocSPARSE.$sname(rocSPARSE.handle(), n, nnz(P), desc, P.nzVal, P.rowPtr, P.colVal, info, rocSPARSE.rocsparse_solve_policy_auto, buffer)
return AMD_IC0(n, desc, buffer, info, 0.0, P)
end
function KP.update!(p::AMD_IC0{ROCSparseMatrixCSR{$T,Cint}}, A::ROCSparseMatrixCSR{$T,Cint})
copyto!(p.P.nzVal, A.nzVal)
rocSPARSE.$sname(rocSPARSE.handle(), p.n, nnz(p.P), p.desc, p.P.nzVal, p.P.rowPtr, p.P.colVal, p.info, rocSPARSE.rocsparse_solve_policy_auto, p.buffer)
return p
end
function KP.kp_ic0(A::ROCSparseMatrixCSC{$T,Cint})
P = copy(A)
n = checksquare(P)
desc = rocSPARSE.ROCMatrixDescriptor('G', 'L', 'N', 'O')
info = rocSPARSE.MatInfo()
buffer_size = Ref{Csize_t}()
rocSPARSE.$bname(rocSPARSE.handle(), n, nnz(P), desc, P.nzVal, P.colPtr, P.rowVal, info, buffer_size)
buffer = ROCVector{UInt8}(undef, buffer_size[])
rocSPARSE.$aname(rocSPARSE.handle(), n, nnz(P), desc, P.nzVal, P.colPtr, P.rowVal, info,
rocSPARSE.rocsparse_analysis_policy_force, rocSPARSE.rocsparse_solve_policy_auto, buffer)
posit = Ref{Cint}(1)
rocSPARSE.rocsparse_csric0_zero_pivot(rocSPARSE.handle(), info, posit)
(posit[] ≥ 0) && error("Structural/numerical zero in A at ($(posit[]),$(posit[])))")
rocSPARSE.$sname(rocSPARSE.handle(), n, nnz(P), desc, P.nzVal, P.colPtr, P.rowVal, info, rocSPARSE.rocsparse_solve_policy_auto, buffer)
return AMD_IC0(n, desc, buffer, info, 0.0, P)
end
function KP.update!(p::AMD_IC0{ROCSparseMatrixCSC{$T,Cint}}, A::ROCSparseMatrixCSC{$T,Cint})
copyto!(p.P.nzVal, A.nzVal)
rocSPARSE.$sname(rocSPARSE.handle(), p.n, nnz(p.P), p.desc, p.P.nzVal, p.P.colPtr, p.P.rowVal, p.info, rocSPARSE.rocsparse_solve_policy_auto, p.buffer)
return p
end
end
end
for ArrayType in (:(ROCVector{T}), :(ROCMatrix{T}))
@eval begin
function ldiv!(ic::AMD_IC0{ROCSparseMatrixCSR{T,Cint}}, x::$ArrayType) where T <: BlasFloat
ldiv!(LowerTriangular(ic.P), x) # Forward substitution with L
ldiv!(LowerTriangular(ic.P)', x) # Backward substitution with Lᴴ
return x
end
function ldiv!(y::$ArrayType, ic::AMD_IC0{ROCSparseMatrixCSR{T,Cint}}, x::$ArrayType) where T <: BlasFloat
ic.timer_update += @elapsed begin
copyto!(y, x)
ldiv!(ic, y)
end
return y
end
function ldiv!(ic::AMD_IC0{ROCSparseMatrixCSC{T,Cint}}, x::$ArrayType) where T <: BlasReal
ldiv!(UpperTriangular(ic.P)', x) # Forward substitution with L
ldiv!(UpperTriangular(ic.P), x) # Backward substitution with Lᴴ
return x
end
function ldiv!(y::$ArrayType, ic::AMD_IC0{ROCSparseMatrixCSC{T,Cint}}, x::$ArrayType) where T <: BlasReal
ic.timer_update += @elapsed begin
copyto!(y, x)
ldiv!(ic, y)
end
return y
end
end
end
| KrylovPreconditioners | https://github.com/JuliaSmoothOptimizers/KrylovPreconditioners.jl.git |
|
[
"MPL-2.0"
] | 0.3.0 | f49af35a8dd097d4dccabf94bd2053afbfdab3a4 | code | 4396 | mutable struct AMD_ILU0{SM} <: AbstractKrylovPreconditioner
n::Int
desc::rocSPARSE.ROCMatrixDescriptor
buffer::ROCVector{UInt8}
info::rocSPARSE.MatInfo
timer_update::Float64
P::SM
end
for (bname, aname, sname, T) in ((:rocsparse_scsrilu0_buffer_size, :rocsparse_scsrilu0_analysis, :rocsparse_scsrilu0, :Float32),
(:rocsparse_dcsrilu0_buffer_size, :rocsparse_dcsrilu0_analysis, :rocsparse_dcsrilu0, :Float64),
(:rocsparse_ccsrilu0_buffer_size, :rocsparse_ccsrilu0_analysis, :rocsparse_ccsrilu0, :ComplexF32),
(:rocsparse_zcsrilu0_buffer_size, :rocsparse_zcsrilu0_analysis, :rocsparse_zcsrilu0, :ComplexF64))
@eval begin
function KP.kp_ilu0(A::ROCSparseMatrixCSR{$T,Cint})
P = copy(A)
n = checksquare(P)
desc = rocSPARSE.ROCMatrixDescriptor('G', 'L', 'N', 'O')
info = rocSPARSE.MatInfo()
buffer_size = Ref{Csize_t}()
rocSPARSE.$bname(rocSPARSE.handle(), n, nnz(P), desc, P.nzVal, P.rowPtr, P.colVal, info, buffer_size)
buffer = ROCVector{UInt8}(undef, buffer_size[])
rocSPARSE.$aname(rocSPARSE.handle(), n, nnz(P), desc, P.nzVal, P.rowPtr, P.colVal, info, rocSPARSE.rocsparse_analysis_policy_force, rocSPARSE.rocsparse_solve_policy_auto, buffer)
posit = Ref{Cint}(1)
rocSPARSE.rocsparse_csrilu0_zero_pivot(rocSPARSE.handle(), info, posit)
(posit[] ≥ 0) && error("Structural/numerical zero in A at ($(posit[]),$(posit[])))")
rocSPARSE.$sname(rocSPARSE.handle(), n, nnz(P), desc, P.nzVal, P.rowPtr, P.colVal, info, rocSPARSE.rocsparse_solve_policy_auto, buffer)
return AMD_ILU0(n, desc, buffer, info, 0.0, P)
end
function KP.update!(p::AMD_ILU0{ROCSparseMatrixCSR{$T,Cint}}, A::ROCSparseMatrixCSR{$T,Cint})
copyto!(p.P.nzVal, A.nzVal)
rocSPARSE.$sname(rocSPARSE.handle(), p.n, nnz(p.P), p.desc, p.P.nzVal, p.P.rowPtr, p.P.colVal, p.info, rocSPARSE.rocsparse_solve_policy_auto, p.buffer)
return p
end
function KP.kp_ilu0(A::ROCSparseMatrixCSC{$T,Cint})
P = copy(A)
n = checksquare(P)
desc = rocSPARSE.ROCMatrixDescriptor('G', 'L', 'N', 'O')
info = rocSPARSE.MatInfo()
buffer_size = Ref{Csize_t}()
rocSPARSE.$bname(rocSPARSE.handle(), n, nnz(P), desc, P.nzVal, P.colPtr, P.rowVal, info, buffer_size)
buffer = ROCVector{UInt8}(undef, buffer_size[])
rocSPARSE.$aname(rocSPARSE.handle(), n, nnz(P), desc, P.nzVal, P.colPtr, P.rowVal, info, rocSPARSE.rocsparse_analysis_policy_force, rocSPARSE.rocsparse_solve_policy_auto, buffer)
posit = Ref{Cint}(1)
rocSPARSE.rocsparse_csrilu0_zero_pivot(rocSPARSE.handle(), info, posit)
(posit[] ≥ 0) && error("Structural/numerical zero in A at ($(posit[]),$(posit[])))")
rocSPARSE.$sname(rocSPARSE.handle(), n, nnz(P), desc, P.nzVal, P.colPtr, P.rowVal, info, rocSPARSE.rocsparse_solve_policy_auto, buffer)
return AMD_ILU0(n, desc, buffer, info, 0.0, P)
end
function KP.update!(p::AMD_ILU0{ROCSparseMatrixCSC{$T,Cint}}, A::ROCSparseMatrixCSC{$T,Cint})
copyto!(p.P.nzVal, A.nzVal)
rocSPARSE.$sname(rocSPARSE.handle(), p.n, nnz(p.P), p.desc, p.P.nzVal, p.P.colPtr, p.P.rowVal, p.info, rocSPARSE.rocsparse_solve_policy_auto, p.buffer)
return p
end
end
end
for ArrayType in (:(ROCVector{T}), :(ROCMatrix{T}))
@eval begin
function ldiv!(ilu::AMD_ILU0{ROCSparseMatrixCSR{T,Cint}}, x::$ArrayType) where T <: BlasFloat
ldiv!(UnitLowerTriangular(ilu.P), x) # Forward substitution with L
ldiv!(UpperTriangular(ilu.P), x) # Backward substitution with U
return x
end
function ldiv!(y::$ArrayType, ilu::AMD_ILU0{ROCSparseMatrixCSR{T,Cint}}, x::$ArrayType) where T <: BlasFloat
copyto!(y, x)
ilu.timer_update += @elapsed begin
ldiv!(ilu, y)
end
return y
end
function ldiv!(ilu::AMD_ILU0{ROCSparseMatrixCSC{T,Cint}}, x::$ArrayType) where T <: BlasReal
ldiv!(LowerTriangular(ilu.P), x) # Forward substitution with L
ldiv!(UnitUpperTriangular(ilu.P), x) # Backward substitution with U
return x
end
function ldiv!(y::$ArrayType, ilu::AMD_ILU0{ROCSparseMatrixCSC{T,Cint}}, x::$ArrayType) where T <: BlasReal
copyto!(y, x)
ilu.timer_update += @elapsed begin
ldiv!(ilu, y)
end
return y
end
end
end
| KrylovPreconditioners | https://github.com/JuliaSmoothOptimizers/KrylovPreconditioners.jl.git |
|
[
"MPL-2.0"
] | 0.3.0 | f49af35a8dd097d4dccabf94bd2053afbfdab3a4 | code | 9830 | using AMDGPU.HIP
mutable struct AMD_KrylovOperator{T} <: AbstractKrylovOperator{T}
type::Type{T}
m::Int
n::Int
nrhs::Int
transa::Char
descA::rocSPARSE.ROCSparseMatrixDescriptor
buffer_size::Ref{Csize_t}
buffer::ROCVector{UInt8}
end
eltype(A::AMD_KrylovOperator{T}) where T = T
size(A::AMD_KrylovOperator) = (A.m, A.n)
for (SparseMatrixType, BlasType) in ((:(ROCSparseMatrixCSR{T}), :BlasFloat),
(:(ROCSparseMatrixCSC{T}), :BlasFloat),
(:(ROCSparseMatrixCOO{T}), :BlasFloat))
@eval begin
function KP.KrylovOperator(A::$SparseMatrixType; nrhs::Int=1, transa::Char='N') where T <: $BlasType
m,n = size(A)
alpha = Ref{T}(one(T))
beta = Ref{T}(zero(T))
descA = rocSPARSE.ROCSparseMatrixDescriptor(A, 'O')
if nrhs == 1
descX = rocSPARSE.ROCDenseVectorDescriptor(T, n)
descY = rocSPARSE.ROCDenseVectorDescriptor(T, m)
algo = rocSPARSE.rocSPARSE.rocsparse_spmv_alg_default
buffer_size = Ref{Csize_t}()
if HIP.runtime_version() ≥ v"6-"
rocSPARSE.rocsparse_spmv(rocSPARSE.handle(), transa, alpha, descA, descX,
beta, descY, T, algo, rocSPARSE.rocsparse_spmv_stage_buffer_size,
buffer_size, C_NULL)
else
rocSPARSE.rocsparse_spmv(rocSPARSE.handle(), transa, alpha, descA, descX,
beta, descY, T, algo, buffer_size, C_NULL)
end
buffer = ROCVector{UInt8}(undef, buffer_size[])
if HIP.runtime_version() ≥ v"6-"
rocSPARSE.rocsparse_spmv(rocSPARSE.handle(), transa, alpha, descA, descX,
beta, descY, T, algo, rocSPARSE.rocsparse_spmv_stage_preprocess,
buffer_size, buffer)
end
return AMD_KrylovOperator{T}(T, m, n, nrhs, transa, descA, buffer_size, buffer)
else
descX = rocSPARSE.ROCDenseMatrixDescriptor(T, n, nrhs)
descY = rocSPARSE.ROCDenseMatrixDescriptor(T, m, nrhs)
algo = rocSPARSE.rocsparse_spmm_alg_default
buffer_size = Ref{Csize_t}()
transb = 'N'
rocSPARSE.rocsparse_spmm(rocSPARSE.handle(), transa, 'N', alpha, descA, descX, beta, descY, T,
algo, rocSPARSE.rocsparse_spmm_stage_buffer_size, buffer_size, C_NULL)
buffer = ROCVector{UInt8}(undef, buffer_size[])
rocSPARSE.rocsparse_spmm(rocSPARSE.handle(), transa, 'N', alpha, descA, descX, beta, descY, T,
algo, rocSPARSE.rocsparse_spmm_stage_preprocess, buffer_size, buffer)
return AMD_KrylovOperator{T}(T, m, n, nrhs, transa, descA, buffer_size, buffer)
end
end
function KP.update!(A::AMD_KrylovOperator{T}, B::$SparseMatrixType) where T <: $BlasFloat
descB = rocSPARSE.ROCSparseMatrixDescriptor(B, 'O')
A.descA = descB
return A
end
end
end
function LinearAlgebra.mul!(y::ROCVector{T}, A::AMD_KrylovOperator{T}, x::ROCVector{T}) where T <: BlasFloat
(length(y) != A.m) && throw(DimensionMismatch("length(y) != A.m"))
(length(x) != A.n) && throw(DimensionMismatch("length(x) != A.n"))
(A.nrhs == 1) || throw(DimensionMismatch("A.nrhs != 1"))
descY = rocSPARSE.ROCDenseVectorDescriptor(y)
descX = rocSPARSE.ROCDenseVectorDescriptor(x)
algo = rocSPARSE.rocsparse_spmv_alg_default
alpha = Ref{T}(one(T))
beta = Ref{T}(zero(T))
if HIP.runtime_version() ≥ v"6-"
rocSPARSE.rocsparse_spmv(rocSPARSE.handle(), A.transa, alpha, A.descA, descX,
beta, descY, T, algo, rocSPARSE.rocsparse_spmv_stage_compute,
A.buffer_size, A.buffer)
else
rocSPARSE.rocsparse_spmv(rocSPARSE.handle(), A.transa, alpha, A.descA, descX,
beta, descY, T, algo, A.buffer_size, A.buffer)
end
end
function LinearAlgebra.mul!(Y::ROCMatrix{T}, A::AMD_KrylovOperator{T}, X::ROCMatrix{T}) where T <: BlasFloat
mY, nY = size(Y)
mX, nX = size(X)
(mY != A.m) && throw(DimensionMismatch("mY != A.m"))
(mX != A.n) && throw(DimensionMismatch("mX != A.n"))
(nY == nX == A.nrhs) || throw(DimensionMismatch("nY != A.nrhs or nX != A.nrhs"))
descY = rocSPARSE.ROCDenseMatrixDescriptor(Y)
descX = rocSPARSE.ROCDenseMatrixDescriptor(X)
algo = rocSPARSE.rocsparse_spmm_alg_default
alpha = Ref{T}(one(T))
beta = Ref{T}(zero(T))
rocSPARSE.rocsparse_spmm(rocSPARSE.handle(), A.transa, 'N', alpha, A.descA, descX,
beta, descY, T, algo, rocSPARSE.rocsparse_spmm_stage_compute, A.buffer_size, A.buffer)
end
mutable struct AMD_TriangularOperator{T} <: AbstractTriangularOperator{T}
type::Type{T}
m::Int
n::Int
nrhs::Int
transa::Char
descA::rocSPARSE.ROCSparseMatrixDescriptor
buffer_size::Ref{Csize_t}
buffer::ROCVector{UInt8}
end
eltype(A::AMD_TriangularOperator{T}) where T = T
size(A::AMD_TriangularOperator) = (A.m, A.n)
for (SparseMatrixType, BlasType) in ((:(ROCSparseMatrixCSR{T}), :BlasFloat),
(:(ROCSparseMatrixCOO{T}), :BlasFloat))
@eval begin
function KP.TriangularOperator(A::$SparseMatrixType, uplo::Char, diag::Char; nrhs::Int=1, transa::Char='N') where T <: $BlasType
m,n = size(A)
alpha = Ref{T}(one(T))
descA = rocSPARSE.ROCSparseMatrixDescriptor(A, 'O')
rocsparse_uplo = Ref{rocSPARSE.rocsparse_fill_mode}(uplo)
rocsparse_diag = Ref{rocSPARSE.rocsparse_diag_type}(diag)
rocSPARSE.rocsparse_spmat_set_attribute(descA, rocSPARSE.rocsparse_spmat_fill_mode, rocsparse_uplo, Csize_t(sizeof(rocsparse_uplo)))
rocSPARSE.rocsparse_spmat_set_attribute(descA, rocSPARSE.rocsparse_spmat_diag_type, rocsparse_diag, Csize_t(sizeof(rocsparse_diag)))
if nrhs == 1
descX = rocSPARSE.ROCDenseVectorDescriptor(T, n)
descY = rocSPARSE.ROCDenseVectorDescriptor(T, m)
algo = rocSPARSE.rocsparse_spsv_alg_default
buffer_size = Ref{Csize_t}()
rocSPARSE.rocsparse_spsv(rocSPARSE.handle(), transa, alpha, descA, descX, descY, T, algo,
rocSPARSE.rocsparse_spsv_stage_buffer_size, buffer_size, C_NULL)
buffer = ROCVector{UInt8}(undef, buffer_size[])
rocSPARSE.rocsparse_spsv(rocSPARSE.handle(), transa, alpha, descA, descX, descY, T, algo,
rocSPARSE.rocsparse_spsv_stage_preprocess, buffer_size, buffer)
return AMD_TriangularOperator{T}(T, m, n, nrhs, transa, descA, buffer_size, buffer)
else
descX = rocSPARSE.ROCDenseMatrixDescriptor(T, n, nrhs)
descY = rocSPARSE.ROCDenseMatrixDescriptor(T, m, nrhs)
algo = rocSPARSE.rocsparse_spsm_alg_default
buffer_size = Ref{Csize_t}()
rocSPARSE.rocsparse_spsm(rocSPARSE.handle(), transa, 'N', alpha, descA, descX, descY, T, algo,
rocSPARSE.rocsparse_spsm_stage_buffer_size, buffer_size, C_NULL)
buffer = ROCVector{UInt8}(undef, buffer_size[])
rocSPARSE.rocsparse_spsm(rocSPARSE.handle(), transa, 'N', alpha, descA, descX, descY, T, algo,
rocSPARSE.rocsparse_spsm_stage_preprocess, buffer_size, buffer)
return AMD_TriangularOperator{T}(T, m, n, nrhs, transa, descA, buffer_size, buffer)
end
end
function KP.update!(A::AMD_TriangularOperator{T}, B::$SparseMatrixType) where T <: $BlasFloat
(B isa ROCSparseMatrixCOO) && rocSPARSE.rocsparse_coo_set_pointers(A.descA, B.rowInd, B.colInd, B.nzVal)
(B isa ROCSparseMatrixCSR) && rocSPARSE.rocsparse_csr_set_pointers(A.descA, B.rowPtr, B.colVal, B.nzVal)
return A
end
end
end
function LinearAlgebra.ldiv!(y::ROCVector{T}, A::AMD_TriangularOperator{T}, x::ROCVector{T}) where T <: BlasFloat
(length(y) != A.m) && throw(DimensionMismatch("length(y) != A.m"))
(length(x) != A.n) && throw(DimensionMismatch("length(x) != A.n"))
(A.nrhs == 1) || throw(DimensionMismatch("A.nrhs != 1"))
descY = rocSPARSE.ROCDenseVectorDescriptor(y)
descX = rocSPARSE.ROCDenseVectorDescriptor(x)
algo = rocSPARSE.rocsparse_spsv_alg_default
alpha = Ref{T}(one(T))
rocSPARSE.rocsparse_spsv(rocSPARSE.handle(), A.transa, alpha, A.descA, descX, descY, T,
algo, rocSPARSE.rocsparse_spsv_stage_compute, A.buffer_size, A.buffer)
end
function LinearAlgebra.ldiv!(Y::ROCMatrix{T}, A::AMD_TriangularOperator{T}, X::ROCMatrix{T}) where T <: BlasFloat
mY, nY = size(Y)
mX, nX = size(X)
(mY != A.m) && throw(DimensionMismatch("mY != A.m"))
(mX != A.n) && throw(DimensionMismatch("mX != A.n"))
(nY == nX == A.nrhs) || throw(DimensionMismatch("nY != A.nrhs or nX != A.nrhs"))
descY = rocSPARSE.ROCDenseMatrixDescriptor(Y)
descX = rocSPARSE.ROCDenseMatrixDescriptor(X)
algo = rocSPARSE.rocsparse_spsm_alg_default
alpha = Ref{T}(one(T))
rocSPARSE.rocsparse_spsm(rocSPARSE.handle(), A.transa, 'N', alpha, A.descA, descX, descY, T,
algo, rocSPARSE.rocsparse_spsm_stage_compute, A.buffer_size, A.buffer)
end
| KrylovPreconditioners | https://github.com/JuliaSmoothOptimizers/KrylovPreconditioners.jl.git |
|
[
"MPL-2.0"
] | 0.3.0 | f49af35a8dd097d4dccabf94bd2053afbfdab3a4 | code | 98 | KP.scaling_csr!(A::rocSPARSE.ROCSparseMatrixCSR, b::ROCVector) = scaling_csr!(A, b, ROCBackend())
| KrylovPreconditioners | https://github.com/JuliaSmoothOptimizers/KrylovPreconditioners.jl.git |
|
[
"MPL-2.0"
] | 0.3.0 | f49af35a8dd097d4dccabf94bd2053afbfdab3a4 | code | 1660 | KP.BlockJacobiPreconditioner(J::CUSPARSE.CuSparseMatrixCSR; options...) = BlockJacobiPreconditioner(SparseMatrixCSC(J); options...)
function KP.create_blocklist(cublocks::CuArray, npart)
blocklist = Array{CuMatrix{Float64}}(undef, npart)
for b in 1:npart
blocklist[b] = CuMatrix{Float64}(undef, size(cublocks,1), size(cublocks,2))
end
return blocklist
end
function _update_gpu(p, j_rowptr, j_colval, j_nzval, device::CUDABackend)
nblocks = p.nblocks
blocksize = p.blocksize
fillblock_gpu_kernel! = KP._fillblock_gpu!(device)
# Fill Block Jacobi" begin
fillblock_gpu_kernel!(
p.cublocks, size(p.id,1),
p.cupartitions, p.cumap,
j_rowptr, j_colval, j_nzval,
p.cupart, p.culpartitions, p.id,
ndrange=(nblocks, blocksize),
)
KA.synchronize(device)
# Invert blocks begin
for b in 1:nblocks
p.blocklist[b] .= p.cublocks[:,:,b]
end
CUDA.@sync pivot, info = CUBLAS.getrf_batched!(p.blocklist, true)
CUDA.@sync pivot, info, p.blocklist = CUBLAS.getri_batched(p.blocklist, pivot)
for b in 1:nblocks
p.cublocks[:,:,b] .= p.blocklist[b]
end
return
end
"""
function update!(J::CuSparseMatrixCSR, p)
Update the preconditioner `p` from the sparse Jacobian `J` in CSR format for CUDA
1) The dense blocks `cuJs` are filled from the sparse Jacobian `J`
2) To a batch inversion of the dense blocks using CUBLAS
3) Extract the preconditioner matrix `p.P` from the dense blocks `cuJs`
"""
function KP.update!(p::BlockJacobiPreconditioner, J::CUSPARSE.CuSparseMatrixCSR)
_update_gpu(p, J.rowPtr, J.colVal, J.nzVal, p.device)
end
| KrylovPreconditioners | https://github.com/JuliaSmoothOptimizers/KrylovPreconditioners.jl.git |
|
[
"MPL-2.0"
] | 0.3.0 | f49af35a8dd097d4dccabf94bd2053afbfdab3a4 | code | 4586 | mutable struct IC0Info
info::CUSPARSE.csric02Info_t
function IC0Info()
info_ref = Ref{CUSPARSE.csric02Info_t}()
CUSPARSE.cusparseCreateCsric02Info(info_ref)
obj = new(info_ref[])
finalizer(CUSPARSE.cusparseDestroyCsric02Info, obj)
obj
end
end
unsafe_convert(::Type{CUSPARSE.csric02Info_t}, info::IC0Info) = info.info
mutable struct NVIDIA_IC0{SM} <: AbstractKrylovPreconditioner
n::Int
desc::CUSPARSE.CuMatrixDescriptor
buffer::CuVector{UInt8}
info::IC0Info
timer_update::Float64
P::SM
end
for (bname, aname, sname, T) in ((:cusparseScsric02_bufferSize, :cusparseScsric02_analysis, :cusparseScsric02, :Float32),
(:cusparseDcsric02_bufferSize, :cusparseDcsric02_analysis, :cusparseDcsric02, :Float64),
(:cusparseCcsric02_bufferSize, :cusparseCcsric02_analysis, :cusparseCcsric02, :ComplexF32),
(:cusparseZcsric02_bufferSize, :cusparseZcsric02_analysis, :cusparseZcsric02, :ComplexF64))
@eval begin
function KP.kp_ic0(A::CuSparseMatrixCSR{$T,Cint})
P = copy(A)
n = checksquare(P)
desc = CUSPARSE.CuMatrixDescriptor('G', 'L', 'N', 'O')
info = IC0Info()
buffer_size = Ref{Cint}()
CUSPARSE.$bname(CUSPARSE.handle(), n, nnz(P), desc, P.nzVal, P.rowPtr, P.colVal, info, buffer_size)
buffer = CuVector{UInt8}(undef, buffer_size[])
CUSPARSE.$aname(CUSPARSE.handle(), n, nnz(P), desc, P.nzVal, P.rowPtr, P.colVal, info, CUSPARSE.CUSPARSE_SOLVE_POLICY_USE_LEVEL, buffer)
posit = Ref{Cint}(1)
CUSPARSE.cusparseXcsric02_zeroPivot(CUSPARSE.handle(), info, posit)
(posit[] ≥ 0) && error("Structural/numerical zero in A at ($(posit[]),$(posit[])))")
CUSPARSE.$sname(CUSPARSE.handle(), n, nnz(P), desc, P.nzVal, P.rowPtr, P.colVal, info, CUSPARSE.CUSPARSE_SOLVE_POLICY_USE_LEVEL, buffer)
return NVIDIA_IC0(n, desc, buffer, info, 0.0, P)
end
function KP.update!(p::NVIDIA_IC0{CuSparseMatrixCSR{$T,Cint}}, A::CuSparseMatrixCSR{$T,Cint})
copyto!(p.P.nzVal, A.nzVal)
CUSPARSE.$sname(CUSPARSE.handle(), p.n, nnz(p.P), p.desc, p.P.nzVal, p.P.rowPtr, p.P.colVal, p.info, CUSPARSE.CUSPARSE_SOLVE_POLICY_USE_LEVEL, p.buffer)
return p
end
function KP.kp_ic0(A::CuSparseMatrixCSC{$T,Cint})
P = copy(A)
n = checksquare(P)
desc = CUSPARSE.CuMatrixDescriptor('G', 'L', 'N', 'O')
info = IC0Info()
buffer_size = Ref{Cint}()
CUSPARSE.$bname(CUSPARSE.handle(), n, nnz(P), desc, P.nzVal, P.colPtr, P.rowVal, info, buffer_size)
buffer = CuVector{UInt8}(undef, buffer_size[])
CUSPARSE.$aname(CUSPARSE.handle(), n, nnz(P), desc, P.nzVal, P.colPtr, P.rowVal, info, CUSPARSE.CUSPARSE_SOLVE_POLICY_USE_LEVEL, buffer)
posit = Ref{Cint}(1)
CUSPARSE.cusparseXcsric02_zeroPivot(CUSPARSE.handle(), info, posit)
(posit[] ≥ 0) && error("Structural/numerical zero in A at ($(posit[]),$(posit[])))")
CUSPARSE.$sname(CUSPARSE.handle(), n, nnz(P), desc, P.nzVal, P.colPtr, P.rowVal, info, CUSPARSE.CUSPARSE_SOLVE_POLICY_USE_LEVEL, buffer)
return NVIDIA_IC0(n, desc, buffer, info, 0.0, P)
end
function KP.update!(p::NVIDIA_IC0{CuSparseMatrixCSC{$T,Cint}}, A::CuSparseMatrixCSC{$T,Cint})
copyto!(p.P.nzVal, A.nzVal)
CUSPARSE.$sname(CUSPARSE.handle(), p.n, nnz(p.P), p.desc, p.P.nzVal, p.P.colPtr, p.P.rowVal, p.info, CUSPARSE.CUSPARSE_SOLVE_POLICY_USE_LEVEL, p.buffer)
return p
end
end
end
for ArrayType in (:(CuVector{T}), :(CuMatrix{T}))
@eval begin
function ldiv!(ic::NVIDIA_IC0{CuSparseMatrixCSR{T,Cint}}, x::$ArrayType) where T <: BlasFloat
ldiv!(LowerTriangular(ic.P), x) # Forward substitution with L
ldiv!(LowerTriangular(ic.P)', x) # Backward substitution with Lᴴ
return x
end
function ldiv!(y::$ArrayType, ic::NVIDIA_IC0{CuSparseMatrixCSR{T,Cint}}, x::$ArrayType) where T <: BlasFloat
copyto!(y, x)
ic.timer_update += @elapsed begin
ldiv!(ic, y)
end
return y
end
function ldiv!(ic::NVIDIA_IC0{CuSparseMatrixCSC{T,Cint}}, x::$ArrayType) where T <: BlasFloat
ldiv!(UpperTriangular(ic.P)', x) # Forward substitution with L
ldiv!(UpperTriangular(ic.P), x) # Backward substitution with Lᴴ
return x
end
function ldiv!(y::$ArrayType, ic::NVIDIA_IC0{CuSparseMatrixCSC{T,Cint}}, x::$ArrayType) where T <: BlasReal
copyto!(y, x)
ic.timer_update += @elapsed begin
ldiv!(ic, y)
end
return y
end
end
end
| KrylovPreconditioners | https://github.com/JuliaSmoothOptimizers/KrylovPreconditioners.jl.git |
|
[
"MPL-2.0"
] | 0.3.0 | f49af35a8dd097d4dccabf94bd2053afbfdab3a4 | code | 4643 | mutable struct ILU0Info
info::CUSPARSE.csrilu02Info_t
function ILU0Info()
info_ref = Ref{CUSPARSE.csrilu02Info_t}()
CUSPARSE.cusparseCreateCsrilu02Info(info_ref)
obj = new(info_ref[])
finalizer(CUSPARSE.cusparseDestroyCsrilu02Info, obj)
obj
end
end
unsafe_convert(::Type{CUSPARSE.csrilu02Info_t}, info::ILU0Info) = info.info
mutable struct NVIDIA_ILU0{SM} <: AbstractKrylovPreconditioner
n::Int
desc::CUSPARSE.CuMatrixDescriptor
buffer::CuVector{UInt8}
info::ILU0Info
timer_update::Float64
P::SM
end
for (bname, aname, sname, T) in ((:cusparseScsrilu02_bufferSize, :cusparseScsrilu02_analysis, :cusparseScsrilu02, :Float32),
(:cusparseDcsrilu02_bufferSize, :cusparseDcsrilu02_analysis, :cusparseDcsrilu02, :Float64),
(:cusparseCcsrilu02_bufferSize, :cusparseCcsrilu02_analysis, :cusparseCcsrilu02, :ComplexF32),
(:cusparseZcsrilu02_bufferSize, :cusparseZcsrilu02_analysis, :cusparseZcsrilu02, :ComplexF64))
@eval begin
function KP.kp_ilu0(A::CuSparseMatrixCSR{$T,Cint})
P = copy(A)
n = checksquare(P)
desc = CUSPARSE.CuMatrixDescriptor('G', 'L', 'N', 'O')
info = ILU0Info()
buffer_size = Ref{Cint}()
CUSPARSE.$bname(CUSPARSE.handle(), n, nnz(P), desc, P.nzVal, P.rowPtr, P.colVal, info, buffer_size)
buffer = CuVector{UInt8}(undef, buffer_size[])
CUSPARSE.$aname(CUSPARSE.handle(), n, nnz(P), desc, P.nzVal, P.rowPtr, P.colVal, info, CUSPARSE.CUSPARSE_SOLVE_POLICY_USE_LEVEL, buffer)
posit = Ref{Cint}(1)
CUSPARSE.cusparseXcsrilu02_zeroPivot(CUSPARSE.handle(), info, posit)
(posit[] ≥ 0) && error("Structural/numerical zero in A at ($(posit[]),$(posit[])))")
CUSPARSE.$sname(CUSPARSE.handle(), n, nnz(P), desc, P.nzVal, P.rowPtr, P.colVal, info, CUSPARSE.CUSPARSE_SOLVE_POLICY_USE_LEVEL, buffer)
return NVIDIA_ILU0(n, desc, buffer, info, 0.0, P)
end
function KP.update!(p::NVIDIA_ILU0{CuSparseMatrixCSR{$T,Cint}}, A::CuSparseMatrixCSR{$T,Cint})
copyto!(p.P.nzVal, A.nzVal)
CUSPARSE.$sname(CUSPARSE.handle(), p.n, nnz(p.P), p.desc, p.P.nzVal, p.P.rowPtr, p.P.colVal, p.info, CUSPARSE.CUSPARSE_SOLVE_POLICY_USE_LEVEL, p.buffer)
return p
end
function KP.kp_ilu0(A::CuSparseMatrixCSC{$T,Cint})
P = copy(A)
n = checksquare(P)
desc = CUSPARSE.CuMatrixDescriptor('G', 'L', 'N', 'O')
info = ILU0Info()
buffer_size = Ref{Cint}()
CUSPARSE.$bname(CUSPARSE.handle(), n, nnz(P), desc, P.nzVal, P.colPtr, P.rowVal, info, buffer_size)
buffer = CuVector{UInt8}(undef, buffer_size[])
CUSPARSE.$aname(CUSPARSE.handle(), n, nnz(P), desc, P.nzVal, P.colPtr, P.rowVal, info, CUSPARSE.CUSPARSE_SOLVE_POLICY_USE_LEVEL, buffer)
posit = Ref{Cint}(1)
CUSPARSE.cusparseXcsrilu02_zeroPivot(CUSPARSE.handle(), info, posit)
(posit[] ≥ 0) && error("Structural/numerical zero in A at ($(posit[]),$(posit[])))")
CUSPARSE.$sname(CUSPARSE.handle(), n, nnz(P), desc, P.nzVal, P.colPtr, P.rowVal, info, CUSPARSE.CUSPARSE_SOLVE_POLICY_USE_LEVEL, buffer)
return NVIDIA_ILU0(n, desc, buffer, info, 0.0, P)
end
function KP.update!(p::NVIDIA_ILU0{CuSparseMatrixCSC{$T,Cint}}, A::CuSparseMatrixCSC{$T,Cint})
copyto!(p.P.nzVal, A.nzVal)
CUSPARSE.$sname(CUSPARSE.handle(), p.n, nnz(p.P), p.desc, p.P.nzVal, p.P.colPtr, p.P.rowVal, p.info, CUSPARSE.CUSPARSE_SOLVE_POLICY_USE_LEVEL, p.buffer)
return p
end
end
end
for ArrayType in (:(CuVector{T}), :(CuMatrix{T}))
@eval begin
function ldiv!(ilu::NVIDIA_ILU0{CuSparseMatrixCSR{T,Cint}}, x::$ArrayType) where T <: BlasFloat
ldiv!(UnitLowerTriangular(ilu.P), x) # Forward substitution with L
ldiv!(UpperTriangular(ilu.P), x) # Backward substitution with U
return x
end
function ldiv!(y::$ArrayType, ilu::NVIDIA_ILU0{CuSparseMatrixCSR{T,Cint}}, x::$ArrayType) where T <: BlasFloat
copyto!(y, x)
ilu.timer_update += @elapsed begin
ldiv!(ilu, y)
end
return y
end
function ldiv!(ilu::NVIDIA_ILU0{CuSparseMatrixCSC{T,Cint}}, x::$ArrayType) where T <: BlasReal
ldiv!(LowerTriangular(ilu.P), x) # Forward substitution with L
ldiv!(UnitUpperTriangular(ilu.P), x) # Backward substitution with U
return x
end
function ldiv!(y::$ArrayType, ilu::NVIDIA_ILU0{CuSparseMatrixCSC{T,Cint}}, x::$ArrayType) where T <: BlasReal
copyto!(y, x)
ilu.timer_update += @elapsed begin
ldiv!(ilu, y)
end
return y
end
end
end
| KrylovPreconditioners | https://github.com/JuliaSmoothOptimizers/KrylovPreconditioners.jl.git |
|
[
"MPL-2.0"
] | 0.3.0 | f49af35a8dd097d4dccabf94bd2053afbfdab3a4 | code | 8704 | mutable struct NVIDIA_KrylovOperator{T} <: AbstractKrylovOperator{T}
type::Type{T}
m::Int
n::Int
nrhs::Int
transa::Char
descA::CUSPARSE.CuSparseMatrixDescriptor
buffer::CuVector{UInt8}
end
eltype(A::NVIDIA_KrylovOperator{T}) where T = T
size(A::NVIDIA_KrylovOperator) = (A.m, A.n)
for (SparseMatrixType, BlasType) in ((:(CuSparseMatrixCSR{T}), :BlasFloat),
(:(CuSparseMatrixCSC{T}), :BlasFloat),
(:(CuSparseMatrixCOO{T}), :BlasFloat))
@eval begin
function KP.KrylovOperator(A::$SparseMatrixType; nrhs::Int=1, transa::Char='N') where T <: $BlasType
m,n = size(A)
alpha = Ref{T}(one(T))
beta = Ref{T}(zero(T))
descA = CUSPARSE.CuSparseMatrixDescriptor(A, 'O')
if nrhs == 1
descX = CUSPARSE.CuDenseVectorDescriptor(T, n)
descY = CUSPARSE.CuDenseVectorDescriptor(T, m)
algo = CUSPARSE.CUSPARSE_SPMV_ALG_DEFAULT
buffer_size = Ref{Csize_t}()
CUSPARSE.cusparseSpMV_bufferSize(CUSPARSE.handle(), transa, alpha, descA, descX, beta, descY, T, algo, buffer_size)
buffer = CuVector{UInt8}(undef, buffer_size[])
if CUSPARSE.version() ≥ v"12.3"
CUSPARSE.cusparseSpMV_preprocess(CUSPARSE.handle(), transa, alpha, descA, descX, beta, descY, T, algo, buffer)
end
return NVIDIA_KrylovOperator{T}(T, m, n, nrhs, transa, descA, buffer)
else
descX = CUSPARSE.CuDenseMatrixDescriptor(T, n, nrhs)
descY = CUSPARSE.CuDenseMatrixDescriptor(T, m, nrhs)
algo = CUSPARSE.CUSPARSE_SPMM_ALG_DEFAULT
buffer_size = Ref{Csize_t}()
CUSPARSE.cusparseSpMM_bufferSize(CUSPARSE.handle(), transa, 'N', alpha, descA, descX, beta, descY, T, algo, buffer_size)
buffer = CuVector{UInt8}(undef, buffer_size[])
if !(A isa CuSparseMatrixCOO)
CUSPARSE.cusparseSpMM_preprocess(CUSPARSE.handle(), transa, 'N', alpha, descA, descX, beta, descY, T, algo, buffer)
end
return NVIDIA_KrylovOperator{T}(T, m, n, nrhs, transa, descA, buffer)
end
end
function KP.update!(A::NVIDIA_KrylovOperator{T}, B::$SparseMatrixType) where T <: $BlasFloat
descB = CUSPARSE.CuSparseMatrixDescriptor(B, 'O')
A.descA = descB
return A
end
end
end
function LinearAlgebra.mul!(y::CuVector{T}, A::NVIDIA_KrylovOperator{T}, x::CuVector{T}) where T <: BlasFloat
(length(y) != A.m) && throw(DimensionMismatch("length(y) != A.m"))
(length(x) != A.n) && throw(DimensionMismatch("length(x) != A.n"))
(A.nrhs == 1) || throw(DimensionMismatch("A.nrhs != 1"))
descY = CUSPARSE.CuDenseVectorDescriptor(y)
descX = CUSPARSE.CuDenseVectorDescriptor(x)
algo = CUSPARSE.CUSPARSE_SPMV_ALG_DEFAULT
alpha = Ref{T}(one(T))
beta = Ref{T}(zero(T))
CUSPARSE.cusparseSpMV(CUSPARSE.handle(), A.transa, alpha, A.descA, descX, beta, descY, T, algo, A.buffer)
end
function LinearAlgebra.mul!(Y::CuMatrix{T}, A::NVIDIA_KrylovOperator{T}, X::CuMatrix{T}) where T <: BlasFloat
mY, nY = size(Y)
mX, nX = size(X)
(mY != A.m) && throw(DimensionMismatch("mY != A.m"))
(mX != A.n) && throw(DimensionMismatch("mX != A.n"))
(nY == nX == A.nrhs) || throw(DimensionMismatch("nY != A.nrhs or nX != A.nrhs"))
descY = CUSPARSE.CuDenseMatrixDescriptor(Y)
descX = CUSPARSE.CuDenseMatrixDescriptor(X)
algo = CUSPARSE.CUSPARSE_SPMM_ALG_DEFAULT
alpha = Ref{T}(one(T))
beta = Ref{T}(zero(T))
CUSPARSE.cusparseSpMM(CUSPARSE.handle(), A.transa, 'N', alpha, A.descA, descX, beta, descY, T, algo, A.buffer)
end
mutable struct NVIDIA_TriangularOperator{T,S} <: AbstractTriangularOperator{T}
type::Type{T}
m::Int
n::Int
nrhs::Int
transa::Char
descA::CUSPARSE.CuSparseMatrixDescriptor
descT::S
buffer::CuVector{UInt8}
end
eltype(A::NVIDIA_TriangularOperator{T}) where T = T
size(A::NVIDIA_TriangularOperator) = (A.m, A.n)
for (SparseMatrixType, BlasType) in ((:(CuSparseMatrixCSR{T}), :BlasFloat),
(:(CuSparseMatrixCOO{T}), :BlasFloat))
@eval begin
function KP.TriangularOperator(A::$SparseMatrixType, uplo::Char, diag::Char; nrhs::Int=1, transa::Char='N') where T <: $BlasType
m,n = size(A)
alpha = Ref{T}(one(T))
descA = CUSPARSE.CuSparseMatrixDescriptor(A, 'O')
cusparse_uplo = Ref{CUSPARSE.cusparseFillMode_t}(uplo)
cusparse_diag = Ref{CUSPARSE.cusparseDiagType_t}(diag)
CUSPARSE.cusparseSpMatSetAttribute(descA, 'F', cusparse_uplo, Csize_t(sizeof(cusparse_uplo)))
CUSPARSE.cusparseSpMatSetAttribute(descA, 'D', cusparse_diag, Csize_t(sizeof(cusparse_diag)))
if nrhs == 1
descT = CUSPARSE.CuSparseSpSVDescriptor()
descX = CUSPARSE.CuDenseVectorDescriptor(T, n)
descY = CUSPARSE.CuDenseVectorDescriptor(T, m)
algo = CUSPARSE.CUSPARSE_SPSV_ALG_DEFAULT
buffer_size = Ref{Csize_t}()
CUSPARSE.cusparseSpSV_bufferSize(CUSPARSE.handle(), transa, alpha, descA, descX, descY, T, algo, descT, buffer_size)
buffer = CuVector{UInt8}(undef, buffer_size[])
CUSPARSE.cusparseSpSV_analysis(CUSPARSE.handle(), transa, alpha, descA, descX, descY, T, algo, descT, buffer)
return NVIDIA_TriangularOperator{T,CUSPARSE.CuSparseSpSVDescriptor}(T, m, n, nrhs, transa, descA, descT, buffer)
else
descT = CUSPARSE.CuSparseSpSMDescriptor()
descX = CUSPARSE.CuDenseMatrixDescriptor(T, n, nrhs)
descY = CUSPARSE.CuDenseMatrixDescriptor(T, m, nrhs)
algo = CUSPARSE.CUSPARSE_SPSM_ALG_DEFAULT
buffer_size = Ref{Csize_t}()
CUSPARSE.cusparseSpSM_bufferSize(CUSPARSE.handle(), transa, 'N', alpha, descA, descX, descY, T, algo, descT, buffer_size)
buffer = CuVector{UInt8}(undef, buffer_size[])
CUSPARSE.cusparseSpSM_analysis(CUSPARSE.handle(), transa, 'N', alpha, descA, descX, descY, T, algo, descT, buffer)
return NVIDIA_TriangularOperator{T,CUSPARSE.CuSparseSpSMDescriptor}(T, m, n, nrhs, transa, descA, descT, buffer)
end
end
function KP.update!(A::NVIDIA_TriangularOperator{T,CUSPARSE.CuSparseSpSVDescriptor}, B::$SparseMatrixType) where T <: $BlasFloat
CUSPARSE.version() ≥ v"12.2" || error("This operation is only supported by CUDA ≥ v12.3")
descB = CUSPARSE.CuSparseMatrixDescriptor(B, 'O')
A.descA = descB
CUSPARSE.cusparseSpSV_updateMatrix(CUSPARSE.handle(), A.descT, B.nzVal, 'G')
return A
end
function KP.update!(A::NVIDIA_TriangularOperator{T,CUSPARSE.CuSparseSpSMDescriptor}, B::$SparseMatrixType) where T <: $BlasFloat
CUSPARSE.version() ≥ v"12.3" || error("This operation is only supported by CUDA ≥ v12.4")
descB = CUSPARSE.CuSparseMatrixDescriptor(B, 'O')
A.descA = descB
CUSPARSE.cusparseSpSM_updateMatrix(CUSPARSE.handle(), A.descT, B.nzVal, 'G')
return A
end
end
end
function LinearAlgebra.ldiv!(y::CuVector{T}, A::NVIDIA_TriangularOperator{T}, x::CuVector{T}) where T <: BlasFloat
(length(y) != A.m) && throw(DimensionMismatch("length(y) != A.m"))
(length(x) != A.n) && throw(DimensionMismatch("length(x) != A.n"))
(A.nrhs == 1) || throw(DimensionMismatch("A.nrhs != 1"))
descY = CUSPARSE.CuDenseVectorDescriptor(y)
descX = CUSPARSE.CuDenseVectorDescriptor(x)
algo = CUSPARSE.CUSPARSE_SPSV_ALG_DEFAULT
alpha = Ref{T}(one(T))
CUSPARSE.cusparseSpSV_solve(CUSPARSE.handle(), A.transa, alpha, A.descA, descX, descY, T, algo, A.descT)
end
function LinearAlgebra.ldiv!(Y::CuMatrix{T}, A::NVIDIA_TriangularOperator{T}, X::CuMatrix{T}) where T <: BlasFloat
mY, nY = size(Y)
mX, nX = size(X)
(mY != A.m) && throw(DimensionMismatch("mY != A.m"))
(mX != A.n) && throw(DimensionMismatch("mX != A.n"))
(nY == nX == A.nrhs) || throw(DimensionMismatch("nY != A.nrhs or nX != A.nrhs"))
descY = CUSPARSE.CuDenseMatrixDescriptor(Y)
descX = CUSPARSE.CuDenseMatrixDescriptor(X)
algo = CUSPARSE.CUSPARSE_SPSM_ALG_DEFAULT
alpha = Ref{T}(one(T))
CUSPARSE.cusparseSpSM_solve(CUSPARSE.handle(), A.transa, 'N', alpha, A.descA, descX, descY, T, algo, A.descT)
end
| KrylovPreconditioners | https://github.com/JuliaSmoothOptimizers/KrylovPreconditioners.jl.git |
|
[
"MPL-2.0"
] | 0.3.0 | f49af35a8dd097d4dccabf94bd2053afbfdab3a4 | code | 96 | KP.scaling_csr!(A::CUSPARSE.CuSparseMatrixCSR, b::CuVector) = scaling_csr!(A, b, CUDABackend())
| KrylovPreconditioners | https://github.com/JuliaSmoothOptimizers/KrylovPreconditioners.jl.git |
|
[
"MPL-2.0"
] | 0.3.0 | f49af35a8dd097d4dccabf94bd2053afbfdab3a4 | code | 1666 | KP.BlockJacobiPreconditioner(J::oneMKL.oneSparseMatrixCSR; options...) = BlockJacobiPreconditioner(SparseMatrixCSC(J); options...)
function KP.create_blocklist(cublocks::oneArray, npart)
blocklist = Array{oneMatrix{Float64}}(undef, npart)
for b in 1:npart
blocklist[b] = oneMatrix{Float64}(undef, size(cublocks,1), size(cublocks,2))
end
return blocklist
end
function _update_gpu(p, j_rowptr, j_colval, j_nzval, device::oneAPIBackend)
nblocks = p.nblocks
blocksize = p.blocksize
fillblock_gpu_kernel! = KP._fillblock_gpu!(device)
# Fill Block Jacobi" begin
fillblock_gpu_kernel!(
p.cublocks, size(p.id,1),
p.cupartitions, p.cumap,
j_rowptr, j_colval, j_nzval,
p.cupart, p.culpartitions, p.id,
ndrange=(nblocks, blocksize),
)
KA.synchronize(device)
# Invert blocks begin
for b in 1:nblocks
p.blocklist[b] .= p.cublocks[:,:,b]
end
oneAPI.@sync pivot, p.blocklist = oneMKL.getrf_batched!(p.blocklist)
oneAPI.@sync pivot, p.blocklist = oneMKL.getri_batched!(p.blocklist, pivot)
for b in 1:nblocks
p.cublocks[:,:,b] .= p.blocklist[b]
end
return
end
"""
function update!(J::oneSparseMatrixCSR, p)
Update the preconditioner `p` from the sparse Jacobian `J` in CSR format for oneAPI
1) The dense blocks `cuJs` are filled from the sparse Jacobian `J`
2) To a batch inversion of the dense blocks using oneMKL
3) Extract the preconditioner matrix `p.P` from the dense blocks `cuJs`
"""
function KP.update!(p::BlockJacobiPreconditioner, J::oneMKL.oneSparseMatrixCSR)
_update_gpu(p, J.rowPtr, J.colVal, J.nzVal, p.device)
end
| KrylovPreconditioners | https://github.com/JuliaSmoothOptimizers/KrylovPreconditioners.jl.git |
|
[
"MPL-2.0"
] | 0.3.0 | f49af35a8dd097d4dccabf94bd2053afbfdab3a4 | code | 3765 | mutable struct INTEL_KrylovOperator{T} <: AbstractKrylovOperator{T}
type::Type{T}
m::Int
n::Int
nrhs::Int
transa::Char
matrix::oneSparseMatrixCSR{T}
end
eltype(A::INTEL_KrylovOperator{T}) where T = T
size(A::INTEL_KrylovOperator) = (A.m, A.n)
for (SparseMatrixType, BlasType) in ((:(oneSparseMatrixCSR{T}), :BlasFloat),)
@eval begin
function KP.KrylovOperator(A::$SparseMatrixType; nrhs::Int=1, transa::Char='N') where T <: $BlasType
m,n = size(A)
if nrhs == 1
oneMKL.sparse_optimize_gemv!(transa, A)
end
# sparse_optimize_gemm! is only available with oneAPI > v2024.1.0
return INTEL_KrylovOperator{T}(T, m, n, nrhs, transa, A)
end
function KP.update!(A::INTEL_KrylovOperator{T}, B::$SparseMatrixType) where T <: $BlasFloat
error("The update of an INTEL_KrylovOperator is not supported.")
end
end
end
function LinearAlgebra.mul!(y::oneVector{T}, A::INTEL_KrylovOperator{T}, x::oneVector{T}) where T <: BlasFloat
(length(y) != A.m) && throw(DimensionMismatch("length(y) != A.m"))
(length(x) != A.n) && throw(DimensionMismatch("length(x) != A.n"))
(A.nrhs == 1) || throw(DimensionMismatch("A.nrhs != 1"))
alpha = one(T)
beta = zero(T)
oneMKL.sparse_gemv!(A.transa, alpha, A.matrix, x, beta, y)
end
function LinearAlgebra.mul!(Y::oneMatrix{T}, A::INTEL_KrylovOperator{T}, X::oneMatrix{T}) where T <: BlasFloat
mY, nY = size(Y)
mX, nX = size(X)
(mY != A.m) && throw(DimensionMismatch("mY != A.m"))
(mX != A.n) && throw(DimensionMismatch("mX != A.n"))
(nY == nX == A.nrhs) || throw(DimensionMismatch("nY != A.nrhs or nX != A.nrhs"))
alpha = one(T)
beta = zero(T)
oneMKL.sparse_gemm!(A.transa, 'N', alpha, A.matrix, X, beta, Y)
end
mutable struct INTEL_TriangularOperator{T} <: AbstractTriangularOperator{T}
type::Type{T}
m::Int
n::Int
nrhs::Int
uplo::Char
diag::Char
transa::Char
matrix::oneSparseMatrixCSR{T}
end
eltype(A::INTEL_TriangularOperator{T}) where T = T
size(A::INTEL_TriangularOperator) = (A.m, A.n)
for (SparseMatrixType, BlasType) in ((:(oneSparseMatrixCSR{T}), :BlasFloat),)
@eval begin
function KP.TriangularOperator(A::$SparseMatrixType, uplo::Char, diag::Char; nrhs::Int=1, transa::Char='N') where T <: $BlasType
m,n = size(A)
if nrhs == 1
oneMKL.sparse_optimize_trsv!(uplo, transa, diag, A)
else
oneMKL.sparse_optimize_trsm!(uplo, transa, diag, nrhs, A)
end
return INTEL_TriangularOperator{T}(T, m, n, nrhs, uplo, diag, transa, A)
end
function KP.update!(A::INTEL_TriangularOperator{T}, B::$SparseMatrixType) where T <: $BlasFloat
return error("The update of an INTEL_TriangularOperator is not supported.")
end
end
end
function LinearAlgebra.ldiv!(y::oneVector{T}, A::INTEL_TriangularOperator{T}, x::oneVector{T}) where T <: BlasFloat
(length(y) != A.m) && throw(DimensionMismatch("length(y) != A.m"))
(length(x) != A.n) && throw(DimensionMismatch("length(x) != A.n"))
(A.nrhs == 1) || throw(DimensionMismatch("A.nrhs != 1"))
oneMKL.sparse_trsv!(A.uplo, A.transa, A.diag, one(T), A.matrix, x, y)
end
function LinearAlgebra.ldiv!(Y::oneMatrix{T}, A::INTEL_TriangularOperator{T}, X::oneMatrix{T}) where T <: BlasFloat
mY, nY = size(Y)
mX, nX = size(X)
(mY != A.m) && throw(DimensionMismatch("mY != A.m"))
(mX != A.n) && throw(DimensionMismatch("mX != A.n"))
(nY == nX == A.nrhs) || throw(DimensionMismatch("nY != A.nrhs or nX != A.nrhs"))
oneMKL.sparse_trsm!(A.uplo, A.transa, 'N', A.diag, one(T), A.matrix, X, Y)
end
| KrylovPreconditioners | https://github.com/JuliaSmoothOptimizers/KrylovPreconditioners.jl.git |
|
[
"MPL-2.0"
] | 0.3.0 | f49af35a8dd097d4dccabf94bd2053afbfdab3a4 | code | 1444 | module KrylovPreconditioners
using LinearAlgebra, SparseArrays
using Adapt
using KernelAbstractions
const KA = KernelAbstractions
using LinearAlgebra: checksquare, BlasReal, BlasFloat
import LinearAlgebra: ldiv!
abstract type AbstractKrylovPreconditioner end
export AbstractKrylovPreconditioner
abstract type AbstractKrylovOperator{T} end
export AbstractKrylovOperator
abstract type AbstractTriangularOperator{T} end
export AbstractTriangularOperator
update!(p::AbstractKrylovPreconditioner, A::SparseMatrixCSC) = error("update!() for $(typeof(p)) is not implemented.")
update!(p::AbstractKrylovPreconditioner, A) = error("update!() for $(typeof(p)) is not implemented.")
update!(p::AbstractKrylovOperator, A::SparseMatrixCSC) = error("update!() for $(typeof(p)) is not implemented.")
update!(p::AbstractKrylovOperator, A) = error("update!() for $(typeof(p)) is not implemented.")
export update!, get_timer, reset_timer!
function get_timer(p::AbstractKrylovPreconditioner)
return p.timer_update
end
function reset_timer!(p::AbstractKrylovPreconditioner)
p.timer_update = 0.0
end
function KrylovOperator end
export KrylovOperator
function TriangularOperator end
export TriangularOperator
# Preconditioners
include("ic0.jl")
include("ilu0.jl")
include("blockjacobi.jl")
include("ilu/IncompleteLU.jl")
# Scaling
include("scaling.jl")
export scaling_csr!
# Ordering
# include(ordering.jl)
end # module KrylovPreconditioners
| KrylovPreconditioners | https://github.com/JuliaSmoothOptimizers/KrylovPreconditioners.jl.git |
|
[
"MPL-2.0"
] | 0.3.0 | f49af35a8dd097d4dccabf94bd2053afbfdab3a4 | code | 9993 | export BlockJacobiPreconditioner
using LightGraphs, Metis
"""
overlap(Graph, subset, level)
Given subset embedded within Graph, compute subset2 such that
subset2 contains subset and all of its adjacent vertices.
"""
function overlap(Graph, subset; level=1)
@assert level > 0
subset2 = [LightGraphs.neighbors(Graph, v) for v in subset]
subset2 = reduce(vcat, subset2)
subset2 = unique(vcat(subset, subset2))
level -= 1
if level == 0
return subset2
else
return overlap(Graph, subset2, level=level)
end
end
"""
BlockJacobiPreconditioner
Overlapping-Schwarz preconditioner.
### Attributes
* `nblocks::Int64`: Number of partitions or blocks.
* `blocksize::Int64`: Size of each block.
* `partitions::Vector{Vector{Int64}}``: `npart` partitions stored as lists
* `cupartitions`: `partitions` transfered to the GPU
* `lpartitions::Vector{Int64}``: Length of each partitions.
* `culpartitions::Vector{Int64}``: Length of each partitions, on the GPU.
* `blocks`: Dense blocks of the block-Jacobi
* `cublocks`: `Js` transfered to the GPU
* `map`: The partitions as a mapping to construct views
* `cumap`: `cumap` transferred to the GPU`
* `part`: Partitioning as output by Metis
* `cupart`: `part` transferred to the GPU
"""
mutable struct BlockJacobiPreconditioner{AT,GAT,VI,GVI,GMT,MI,GMI} <: AbstractKrylovPreconditioner
nblocks::Int64
blocksize::Int64
partitions::MI
cupartitions::GMI
lpartitions::VI
culpartitions::GVI
rest_size::VI
curest_size::GVI
blocks::AT
cublocks::GAT
map::VI
cumap::GVI
part::VI
cupart::GVI
id::GMT
blocklist::Vector{GMT}
timer_update::Float64
device::KA.Backend
end
function create_blocklist(blocks::Array, npart)
blocklist = Array{Array{Float64,2}}(undef, npart)
for b in 1:npart
blocklist[b] = Matrix{Float64}(undef, size(blocks,1), size(blocks,2))
end
return blocklist
end
function BlockJacobiPreconditioner(J, npart::Int64, device=CPU(), olevel=0)
if npart < 2
error("Number of partitions `npart` should be at" *
"least 2 for partitioning in Metis")
end
adj = build_adjmatrix(SparseMatrixCSC(J))
g = LightGraphs.Graph(adj)
part = Metis.partition(g, npart)
partitions = Vector{Vector{Int64}}()
for i in 1:npart
push!(partitions, [])
end
for (i,v) in enumerate(part)
push!(partitions[v], i)
end
# We keep track of the partition size pre-overlap.
# This will allow us to implement the RAS update.
rest_size = length.(partitions)
# overlap
if olevel > 0
for i in 1:npart
partitions[i] = overlap(g, partitions[i], level=olevel)
end
end
lpartitions = length.(partitions)
blocksize = maximum(length.(partitions))
blocks = zeros(Float64, blocksize, blocksize, npart)
# Get partitions into bit typed structure
bpartitions = zeros(Int64, blocksize, npart)
bpartitions .= 0.0
for i in 1:npart
bpartitions[1:length(partitions[i]),i] .= Vector{Int64}(partitions[i])
end
id = Matrix{Float64}(I, blocksize, blocksize)
for i in 1:npart
blocks[:,:,i] .= id
end
nmap = 0
for b in partitions
nmap += length(b)
end
map = zeros(Int64, nmap)
part = zeros(Int64, nmap)
for b in 1:npart
for (i,el) in enumerate(partitions[b])
map[el] = i
part[el] = b
end
end
id = adapt(device, id)
cubpartitions = adapt(device, bpartitions)
culpartitions = adapt(device, lpartitions)
curest_size = adapt(device, rest_size)
cublocks = adapt(device, blocks)
cumap = adapt(device, map)
cupart = adapt(device, part)
blocklist = create_blocklist(cublocks, npart)
return BlockJacobiPreconditioner(
npart, blocksize, bpartitions,
cubpartitions, lpartitions,
culpartitions, rest_size,
curest_size, blocks,
cublocks, map,
cumap, part,
cupart, id, blocklist, 0.0,
device
)
end
function BlockJacobiPreconditioner(J::SparseMatrixCSC; nblocks=-1, device=CPU(), noverlaps=0)
n = size(J, 1)
npartitions = if nblocks > 0
nblocks
else
div(n, 32)
end
return BlockJacobiPreconditioner(J, npartitions, device, noverlaps)
end
Base.eltype(::BlockJacobiPreconditioner) = Float64
# NOTE: Custom kernel to implement blocks - vector multiplication.
# The blocks have very unbalanced sizes, leading to imbalances
# between the different threads.
# CUBLAS.gemm_strided_batched has been tested has well, but is
# overall 3x slower than this custom kernel : due to the various sizes
# of the blocks, gemm_strided is performing too many unecessary operations,
# impairing its performance.
@kernel function mblock_b_kernel!(y, b, p_len, rp_len, part, blocks)
j, i = @index(Global, NTuple)
@inbounds len = p_len[i]
@inbounds rlen = rp_len[i]
if j <= rlen
accum = 0.0
idxA = @inbounds part[j, i]
for k=1:len
idxB = @inbounds part[k, i]
@inbounds accum = accum + blocks[j, k, i]*b[idxB]
end
@inbounds y[idxA] = accum
end
end
@kernel function mblock_B_kernel!(y, b, p_len, rp_len, part, blocks)
p = size(b, 2)
i, j = @index(Global, NTuple)
len = p_len[i]
rlen = rp_len[i]
if j <= rlen
for ℓ=1:p
accum = 0.0
idxA = @inbounds part[j, i]
for k=1:len
idxB = @inbounds part[k, i]
@inbounds accum = accum + blocks[j, k, i]*b[idxB,ℓ]
end
@inbounds y[idxA,ℓ] = accum
end
end
end
function LinearAlgebra.mul!(y, C::BlockJacobiPreconditioner, b::Vector{T}) where T
n = size(b, 1)
fill!(y, zero(T))
for i=1:C.nblocks
rlen = C.lpartitions[i]
part = C.partitions[1:rlen, i]
blck = C.blocks[1:rlen, 1:rlen, i]
for j=1:C.rest_size[i]
idx = part[j]
y[idx] += dot(blck[j, :], b[part])
end
end
end
function LinearAlgebra.mul!(Y, C::BlockJacobiPreconditioner, B::Matrix{T}) where T
n, p = size(B)
fill!(Y, zero(T))
for i=1:C.nblocks
rlen = C.lpartitions[i]
part = C.partitions[1:rlen, i]
blck = C.blocks[1:rlen, 1:rlen, i]
for rhs=1:p
for j=1:C.rest_size[i]
idx = part[j]
Y[idx,rhs] += dot(blck[j, :], B[part,rhs])
end
end
end
end
function LinearAlgebra.mul!(y, C::BlockJacobiPreconditioner, b::AbstractVector{T}) where T
device = KA.get_backend(b)
n = size(b, 1)
fill!(y, zero(T))
max_rlen = maximum(C.rest_size)
ndrange = (max_rlen, C.nblocks)
C.timer_update += @elapsed begin mblock_b_kernel!(device)(
y, b, C.culpartitions, C.curest_size,
C.cupartitions, C.cublocks,
ndrange=ndrange,
)
KA.synchronize(device)
end
end
function LinearAlgebra.mul!(Y, C::BlockJacobiPreconditioner, B::AbstractMatrix{T}) where T
device = KA.get_backend(B)
n, p = size(B)
fill!(Y, zero(T))
max_rlen = maximum(C.rest_size)
ndrange = (C.nblocks, max_rlen)
C.timer_update += @elapsed begin mblock_B_kernel!(device)(
Y, B, C.culpartitions, C.curest_size,
C.cupartitions, C.cublocks,
ndrange=ndrange,
)
KA.synchronize(device)
end
end
"""
build_adjmatrix
Build the adjacency matrix of a matrix A corresponding to the undirected graph
"""
function build_adjmatrix(A)
rows = Int64[]
cols = Int64[]
vals = Float64[]
rowsA = rowvals(A)
m, n = size(A)
for i = 1:n
for j in nzrange(A, i)
push!(rows, rowsA[j])
push!(cols, i)
push!(vals, 1.0)
push!(rows, i)
push!(cols, rowsA[j])
push!(vals, 1.0)
end
end
return sparse(rows,cols,vals,size(A,1),size(A,2))
end
"""
_fillblock_gpu
Fill the dense blocks of the preconditioner from the sparse CSR matrix arrays
"""
@kernel function _fillblock_gpu!(blocks, blocksize, partition, map, rowPtr, colVal, nzVal, part, lpartitions, id)
b,k = @index(Global, NTuple)
for i in 1:blocksize
blocks[k,i,b] = id[k,i]
end
@synchronize
@inbounds if k <= lpartitions[b]
# select row
i = partition[k, b]
# iterate matrix
for row_ptr in rowPtr[i]:(rowPtr[i + 1] - 1)
# retrieve column value
col = colVal[row_ptr]
# iterate partition list and see if pertains to it
for j in 1:lpartitions[b]
if col == partition[j, b]
@inbounds blocks[k, j, b] = nzVal[row_ptr]
end
end
end
end
end
"""
function update!(p, J::SparseMatrixCSC)
Update the preconditioner `p` from the sparse Jacobian `J` in CSC format for the CPU
Note that this implements the same algorithm as for the GPU and becomes very slow on CPU with growing number of blocks.
"""
function update!(p::BlockJacobiPreconditioner, J::SparseMatrixCSC)
# TODO: Enabling threading leads to a crash here
for b in 1:p.nblocks
p.blocks[:,:,b] = p.id[:,:]
for k in 1:p.lpartitions[b]
i = p.partitions[k,b]
for j in J.colptr[i]:J.colptr[i+1]-1
if b == p.part[J.rowval[j]]
p.blocks[p.map[J.rowval[j]], p.map[i], b] = J.nzval[j]
end
end
end
end
for b in 1:p.nblocks
# Invert blocks
p.blocks[:,:,b] .= inv(p.blocks[:,:,b])
end
end
function Base.show(precond::BlockJacobiPreconditioner)
npartitions = precond.npart
nblock = precond.nblocks
println("#partitions: $npartitions, Blocksize: n = ", nblock,
" Mbytes = ", (nblock*nblock*npartitions*8.0)/(1024.0*1024.0))
println("Block Jacobi block size: $(precond.nJs)")
end
| KrylovPreconditioners | https://github.com/JuliaSmoothOptimizers/KrylovPreconditioners.jl.git |
|
[
"MPL-2.0"
] | 0.3.0 | f49af35a8dd097d4dccabf94bd2053afbfdab3a4 | code | 79 | export kp_ic0
kp_ic0(A) = error("Not implemented for this type $(typeof(A))")
| KrylovPreconditioners | https://github.com/JuliaSmoothOptimizers/KrylovPreconditioners.jl.git |
|
[
"MPL-2.0"
] | 0.3.0 | f49af35a8dd097d4dccabf94bd2053afbfdab3a4 | code | 81 | export kp_ilu0
kp_ilu0(A) = error("Not implemented for this type $(typeof(A))")
| KrylovPreconditioners | https://github.com/JuliaSmoothOptimizers/KrylovPreconditioners.jl.git |
|
[
"MPL-2.0"
] | 0.3.0 | f49af35a8dd097d4dccabf94bd2053afbfdab3a4 | code | 605 | @kernel function scaling_csr_kernel!(rowPtr, nzVal, b)
m = @index(Global, Linear)
max = 0.0
@inbounds for i = rowPtr[m]:(rowPtr[m + 1] - 1)
absnzVal = abs(nzVal[i])
# This works somehow better in ExaPF. Was initially a bug I thought
# absnzVal = nzVal[i]
if absnzVal > max
max = absnzVal
end
end
if max < 1.0
b[m] /= max
@inbounds for i = rowPtr[m]:(rowPtr[m + 1] - 1)
nzVal[i] /= max
end
end
end
function scaling_csr!(A, b, backend::KA.Backend)
scaling_csr_kernel!(backend)(A.rowPtr, A.nzVal, b; ndrange=length(b))
synchronize(backend)
end
| KrylovPreconditioners | https://github.com/JuliaSmoothOptimizers/KrylovPreconditioners.jl.git |
|
[
"MPL-2.0"
] | 0.3.0 | f49af35a8dd097d4dccabf94bd2053afbfdab3a4 | code | 465 | using LinearAlgebra: Factorization, AdjointFactorization, LowerTriangular, UnitLowerTriangular, UpperTriangular
using SparseArrays
using Base: @propagate_inbounds
struct ILUFactorization{Tv,Ti} <: Factorization{Tv}
L::SparseMatrixCSC{Tv,Ti}
U::SparseMatrixCSC{Tv,Ti}
end
include("sorted_set.jl")
include("linked_list.jl")
include("sparse_vector_accumulator.jl")
include("insertion_sort_update_vector.jl")
include("application.jl")
include("crout_ilu.jl")
| KrylovPreconditioners | https://github.com/JuliaSmoothOptimizers/KrylovPreconditioners.jl.git |
|
[
"MPL-2.0"
] | 0.3.0 | f49af35a8dd097d4dccabf94bd2053afbfdab3a4 | code | 5853 | import SparseArrays: nnz
import LinearAlgebra: ldiv!
import Base.\
export forward_substitution!, backward_substitution!
export adjoint_forward_substitution!, adjoint_backward_substitution!
"""
Returns the number of nonzeros of the `L` and `U`
factor combined.
Excludes the unit diagonal of the `L` factor,
which is not stored.
"""
nnz(F::ILUFactorization) = nnz(F.L) + nnz(F.U)
function ldiv!(F::ILUFactorization, y::AbstractVecOrMat)
forward_substitution!(F, y)
backward_substitution!(F, y)
end
function ldiv!(F::AdjointFactorization{<:Any,<:ILUFactorization}, y::AbstractVecOrMat)
adjoint_forward_substitution!(F.parent, y)
adjoint_backward_substitution!(F.parent, y)
end
function ldiv!(y::AbstractVector, F::ILUFactorization, x::AbstractVector)
y .= x
ldiv!(F, y)
end
function ldiv!(y::AbstractVector, F::AdjointFactorization{<:Any,<:ILUFactorization}, x::AbstractVector)
y .= x
ldiv!(F, y)
end
function ldiv!(y::AbstractMatrix, F::ILUFactorization, x::AbstractMatrix)
y .= x
ldiv!(F, y)
end
function ldiv!(y::AbstractMatrix, F::AdjointFactorization{<:Any,<:ILUFactorization}, x::AbstractMatrix)
y .= x
ldiv!(F, y)
end
(\)(F::ILUFactorization, y::AbstractVecOrMat) = ldiv!(F, copy(y))
(\)(F::AdjointFactorization{<:Any,<:ILUFactorization}, y::AbstractVecOrMat) = ldiv!(F, copy(y))
"""
Applies in-place backward substitution with the U factor of F, under the assumptions:
1. U is stored transposed / row-wise
2. U has no lower-triangular elements stored
3. U has (nonzero) diagonal elements stored.
"""
function backward_substitution!(F::ILUFactorization, y::AbstractVector)
U = F.U
@inbounds for col = U.n : -1 : 1
# Substitutions
for idx = U.colptr[col + 1] - 1 : -1 : U.colptr[col] + 1
y[col] -= U.nzval[idx] * y[U.rowval[idx]]
end
# Final value for y[col]
y[col] /= U.nzval[U.colptr[col]]
end
y
end
function backward_substitution!(F::ILUFactorization, y::AbstractMatrix)
U = F.U
p = size(y, 2)
@inbounds for c = 1 : p
@inbounds for col = U.n : -1 : 1
# Substitutions
for idx = U.colptr[col + 1] - 1 : -1 : U.colptr[col] + 1
y[col,c] -= U.nzval[idx] * y[U.rowval[idx],c]
end
# Final value for y[col,c]
y[col,c] /= U.nzval[U.colptr[col]]
end
end
y
end
function backward_substitution!(v::AbstractVector, F::ILUFactorization, y::AbstractVector)
v .= y
backward_substitution!(F, v)
end
function backward_substitution!(v::AbstractMatrix, F::ILUFactorization, y::AbstractMatrix)
v .= y
backward_substitution!(F, v)
end
function adjoint_backward_substitution!(F::ILUFactorization, y::AbstractVector)
L = F.L
@inbounds for col = L.n - 1 : -1 : 1
# Substitutions
for idx = L.colptr[col + 1] - 1 : -1 : L.colptr[col]
y[col] -= L.nzval[idx] * y[L.rowval[idx]]
end
end
y
end
function adjoint_backward_substitution!(F::ILUFactorization, y::AbstractMatrix)
L = F.L
p = size(y, 2)
@inbounds for c = 1 : p
@inbounds for col = L.n - 1 : -1 : 1
# Substitutions
for idx = L.colptr[col + 1] - 1 : -1 : L.colptr[col]
y[col,c] -= L.nzval[idx] * y[L.rowval[idx],c]
end
end
end
y
end
function adjoint_backward_substitution!(v::AbstractVector, F::ILUFactorization, y::AbstractVector)
v .= y
adjoint_backward_substitution!(F, v)
end
function adjoint_backward_substitution!(v::AbstractMatrix, F::ILUFactorization, y::AbstractMatrix)
v .= y
adjoint_backward_substitution!(F, v)
end
"""
Applies in-place forward substitution with the L factor of F, under the assumptions:
1. L is stored column-wise (unlike U)
2. L has no upper triangular elements
3. L has *no* diagonal elements
"""
function forward_substitution!(F::ILUFactorization, y::AbstractVector)
L = F.L
@inbounds for col = 1 : L.n - 1
for idx = L.colptr[col] : L.colptr[col + 1] - 1
y[L.rowval[idx]] -= L.nzval[idx] * y[col]
end
end
y
end
function forward_substitution!(F::ILUFactorization, y::AbstractMatrix)
L = F.L
p = size(y, 2)
@inbounds for c = 1 : p
@inbounds for col = 1 : L.n - 1
for idx = L.colptr[col] : L.colptr[col + 1] - 1
y[L.rowval[idx],c] -= L.nzval[idx] * y[col,c]
end
end
end
y
end
function forward_substitution!(v::AbstractVector, F::ILUFactorization, y::AbstractVector)
v .= y
forward_substitution!(F, v)
end
function forward_substitution!(v::AbstractMatrix, F::ILUFactorization, y::AbstractMatrix)
v .= y
forward_substitution!(F, v)
end
function adjoint_forward_substitution!(F::ILUFactorization, y::AbstractVector)
U = F.U
@inbounds for col = 1 : U.n
# Final value for y[col]
y[col] /= U.nzval[U.colptr[col]]
for idx = U.colptr[col] + 1 : U.colptr[col + 1] - 1
y[U.rowval[idx]] -= U.nzval[idx] * y[col]
end
end
y
end
function adjoint_forward_substitution!(F::ILUFactorization, y::AbstractMatrix)
U = F.U
p = size(y, 2)
@inbounds for c = 1 : p
@inbounds for col = 1 : U.n
# Final value for y[col,c]
y[col,c] /= U.nzval[U.colptr[col]]
for idx = U.colptr[col] + 1 : U.colptr[col + 1] - 1
y[U.rowval[idx],c] -= U.nzval[idx] * y[col,c]
end
end
end
y
end
function adjoint_forward_substitution!(v::AbstractVector, F::ILUFactorization, y::AbstractVector)
v .= y
adjoint_forward_substitution!(F, v)
end
function adjoint_forward_substitution!(v::AbstractMatrix, F::ILUFactorization, y::AbstractMatrix)
v .= y
adjoint_forward_substitution!(F, v)
end
| KrylovPreconditioners | https://github.com/JuliaSmoothOptimizers/KrylovPreconditioners.jl.git |
|
[
"MPL-2.0"
] | 0.3.0 | f49af35a8dd097d4dccabf94bd2053afbfdab3a4 | code | 3193 | export ilu
function lutype(T::Type)
UT = typeof(oneunit(T) - oneunit(T) * (oneunit(T) / (oneunit(T) + zero(T))))
LT = typeof(oneunit(UT) / oneunit(UT))
S = promote_type(T, LT, UT)
end
function ilu(A::SparseMatrixCSC{ATv,Ti}; τ = 1e-3) where {ATv,Ti}
n = size(A, 1)
Tv = lutype(ATv)
L = spzeros(Tv, Ti, n, n)
U = spzeros(Tv, Ti, n, n)
U_row = SparseVectorAccumulator{Tv,Ti}(n)
L_col = SparseVectorAccumulator{Tv,Ti}(n)
A_reader = RowReader(A)
L_reader = RowReader(L, Val{false})
U_reader = RowReader(U, Val{false})
@inbounds for k = Ti(1) : Ti(n)
##
## Copy the new row into U_row and the new column into L_col
##
col::Int = first_in_row(A_reader, k)
while is_column(col)
add!(U_row, nzval(A_reader, col), col)
next_col = next_column(A_reader, col)
next_row!(A_reader, col)
# Check if the next nonzero in this column
# is still above the diagonal
if has_next_nonzero(A_reader, col) && nzrow(A_reader, col) ≤ col
enqueue_next_nonzero!(A_reader, col)
end
col = next_col
end
# Copy the remaining part of the column into L_col
axpy!(one(Tv), A, k, nzidx(A_reader, k), L_col)
##
## Combine the vectors:
##
# U_row[k:n] -= L[k,i] * U[i,k:n] for i = 1 : k - 1
col = first_in_row(L_reader, k)
while is_column(col)
axpy!(-nzval(L_reader, col), U, col, nzidx(U_reader, col), U_row)
next_col = next_column(L_reader, col)
next_row!(L_reader, col)
if has_next_nonzero(L_reader, col)
enqueue_next_nonzero!(L_reader, col)
end
col = next_col
end
# Nothing is happening here when k = n, maybe remove?
# L_col[k+1:n] -= U[i,k] * L[i,k+1:n] for i = 1 : k - 1
if k < n
col = first_in_row(U_reader, k)
while is_column(col)
axpy!(-nzval(U_reader, col), L, col, nzidx(L_reader, col), L_col)
next_col = next_column(U_reader, col)
next_row!(U_reader, col)
if has_next_nonzero(U_reader, col)
enqueue_next_nonzero!(U_reader, col)
end
col = next_col
end
end
##
## Apply a drop rule
##
U_diag_element = U_row.nzval[k]
# U_diag_element = U_row.values[k]
# Append the columns
append_col!(U, U_row, k, τ)
append_col!(L, L_col, k, τ, inv(U_diag_element))
# Add the new row and column to U_nonzero_col, L_nonzero_row, U_first, L_first
# (First index *after* the diagonal)
U_reader.next_in_column[k] = U.colptr[k] + 1
if U.colptr[k] < U.colptr[k + 1] - 1
enqueue_next_nonzero!(U_reader, k)
end
L_reader.next_in_column[k] = L.colptr[k]
if L.colptr[k] < L.colptr[k + 1]
enqueue_next_nonzero!(L_reader, k)
end
end
return ILUFactorization(L, U)
end
| KrylovPreconditioners | https://github.com/JuliaSmoothOptimizers/KrylovPreconditioners.jl.git |
|
[
"MPL-2.0"
] | 0.3.0 | f49af35a8dd097d4dccabf94bd2053afbfdab3a4 | code | 2609 | import Base: getindex, setindex!, empty!, Vector
import LinearAlgebra: axpy!
"""
`InsertableSparseVector` accumulates the sparse vector
result from SpMV. Initialization requires O(N) work,
therefore the data structure is reused. Insertion
requires O(nnz) at worst, as insertion sort is used.
"""
struct InsertableSparseVector{Tv}
values::Vector{Tv}
indices::SortedSet
InsertableSparseVector{Tv}(n::Int) where {Tv} = new(Vector{Tv}(undef, n), SortedSet(n))
end
@propagate_inbounds getindex(v::InsertableSparseVector{Tv}, idx::Int) where {Tv} = v.values[idx]
@propagate_inbounds setindex!(v::InsertableSparseVector{Tv}, value::Tv, idx::Int) where {Tv} = v.values[idx] = value
@inline indices(v::InsertableSparseVector) = Vector(v.indices)
function Vector(v::InsertableSparseVector{Tv}) where {Tv}
vals = zeros(Tv, v.indices.N - 1)
for index in v.indices
@inbounds vals[index] = v.values[index]
end
return vals
end
"""
Sets `v[idx] += a` when `idx` is occupied, or sets `v[idx] = a`.
Complexity is O(nnz). The `prev_idx` can be used to start the linear
search at `prev_idx`, useful when multiple already sorted values
are added.
"""
function add!(v::InsertableSparseVector, a, idx::Integer, prev_idx::Integer)
if push!(v.indices, idx, prev_idx)
@inbounds v[idx] = a
else
@inbounds v[idx] += a
end
v
end
"""
Add without providing a previous index.
"""
@propagate_inbounds add!(v::InsertableSparseVector, a, idx::Integer) = add!(v, a, idx, v.indices.N)
function axpy!(a, A::SparseMatrixCSC, column::Integer, start::Integer, y::InsertableSparseVector)
prev_index = y.indices.N
@inbounds for idx = start : A.colptr[column + 1] - 1
add!(y, a * A.nzval[idx], A.rowval[idx], prev_index)
prev_index = A.rowval[idx]
end
y
end
"""
Empties the InsterableSparseVector in O(1) operations.
"""
@inline empty!(v::InsertableSparseVector) = empty!(v.indices)
"""
Basically `A[:, j] = scale * drop(y)`, where drop removes
values less than `drop`.
Resets the `InsertableSparseVector`.
Note: does *not* update `A.colptr` for columns > j + 1,
as that is done during the steps.
"""
function append_col!(A::SparseMatrixCSC{Tv}, y::InsertableSparseVector{Tv}, j::Int, drop::Tv, scale::Tv = one(Tv)) where {Tv}
total = 0
@inbounds for row = y.indices
if abs(y[row]) ≥ drop || row == j
push!(A.rowval, row)
push!(A.nzval, scale * y[row])
total += 1
end
end
@inbounds A.colptr[j + 1] = A.colptr[j] + total
empty!(y)
nothing
end
| KrylovPreconditioners | https://github.com/JuliaSmoothOptimizers/KrylovPreconditioners.jl.git |
|
[
"MPL-2.0"
] | 0.3.0 | f49af35a8dd097d4dccabf94bd2053afbfdab3a4 | code | 2352 | import Base: push!
"""
The factor L is stored column-wise, but we need
all nonzeros in row `row`. We already keep track of
the first nonzero in each column (at most `n` indices).
Take `l = LinkedLists(n)`. Let `l.head[row]` be the column
of some nonzero in row `row`. Then we can store the column
of the next nonzero of row `row` in `l.next[l.head[row]]`, etc.
That "spot" is empty and there will never be a conflict
because as long as we only store the first nonzero per column:
the column is then a unique identifier.
"""
struct LinkedLists{Ti}
head::Vector{Ti}
next::Vector{Ti}
end
LinkedLists{Ti}(n::Integer) where {Ti} = LinkedLists(zeros(Ti, n), zeros(Ti, n))
"""
For the L-factor: insert in row `head` column `value`
For the U-factor: insert in column `head` row `value`
"""
@propagate_inbounds function push!(l::LinkedLists, head::Integer, value::Integer)
l.head[head], l.next[value] = value, l.head[head]
return l
end
struct RowReader{Tv,Ti}
A::SparseMatrixCSC{Tv,Ti}
next_in_column::Vector{Ti}
rows::LinkedLists{Ti}
end
function RowReader(A::SparseMatrixCSC{Tv,Ti}) where {Tv,Ti}
n = size(A, 2)
@inbounds next_in_column = [A.colptr[i] for i = 1 : n]
rows = LinkedLists{Ti}(n)
@inbounds for i = Ti(1) : Ti(n)
push!(rows, A.rowval[A.colptr[i]], i)
end
return RowReader(A, next_in_column, rows)
end
function RowReader(A::SparseMatrixCSC{Tv,Ti}, initialize::Type{Val{false}}) where {Tv,Ti}
n = size(A, 2)
return RowReader(A, zeros(Ti, n), LinkedLists{Ti}(n))
end
@propagate_inbounds nzidx(r::RowReader, column::Integer) = r.next_in_column[column]
@propagate_inbounds nzrow(r::RowReader, column::Integer) = r.A.rowval[nzidx(r, column)]
@propagate_inbounds nzval(r::RowReader, column::Integer) = r.A.nzval[nzidx(r, column)]
@propagate_inbounds has_next_nonzero(r::RowReader, column::Integer) = nzidx(r, column) < r.A.colptr[column + 1]
@propagate_inbounds enqueue_next_nonzero!(r::RowReader, column::Integer) = push!(r.rows, nzrow(r, column), column)
@propagate_inbounds next_column(r::RowReader, column::Integer) = r.rows.next[column]
@propagate_inbounds first_in_row(r::RowReader, row::Integer) = r.rows.head[row]
@propagate_inbounds is_column(column::Integer) = column != 0
@propagate_inbounds next_row!(r::RowReader, column::Integer) = r.next_in_column[column] += 1
| KrylovPreconditioners | https://github.com/JuliaSmoothOptimizers/KrylovPreconditioners.jl.git |
|
[
"MPL-2.0"
] | 0.3.0 | f49af35a8dd097d4dccabf94bd2053afbfdab3a4 | code | 1917 | import Base: iterate, push!, Vector, getindex, setindex!, show, empty!
"""
SortedSet keeps track of a sorted set of integers ≤ N
using insertion sort with a linked list structure in a pre-allocated
vector. Requires O(N + 1) memory. Insertion goes via a linear scan in O(n)
where `n` is the number of stored elements, but can be accelerated
by passing along a known value in the set (which is useful when pushing
in an already sorted list). The insertion itself requires O(1) operations
due to the linked list structure. Provides iterators:
```julia
ints = SortedSet(10)
push!(ints, 5)
push!(ints, 3)
for value in ints
println(value)
end
```
"""
struct SortedSet
next::Vector{Int}
N::Int
function SortedSet(N::Int)
next = Vector{Int}(undef, N + 1)
@inbounds next[N + 1] = N + 1
new(next, N + 1)
end
end
# Convenience wrappers for indexing
@propagate_inbounds getindex(s::SortedSet, i::Int) = s.next[i]
@propagate_inbounds setindex!(s::SortedSet, value::Int, i::Int) = s.next[i] = value
# Iterate in
@inline function iterate(s::SortedSet, p::Int = s.N)
@inbounds nxt = s[p]
return nxt == s.N ? nothing : (nxt, nxt)
end
show(io::IO, s::SortedSet) = print(io, typeof(s), " with values ", Vector(s))
"""
For debugging and testing
"""
function Vector(s::SortedSet)
v = Int[]
for index in s
push!(v, index)
end
return v
end
"""
Insert `index` after a known value `after`
"""
function push!(s::SortedSet, value::Int, after::Int)
@inbounds begin
while s[after] < value
after = s[after]
end
if s[after] == value
return false
end
s[after], s[value] = value, s[after]
return true
end
end
"""
Make the head pointer do a self-loop.
"""
@inline empty!(s::SortedSet) = s[s.N] = s.N
@inline push!(s::SortedSet, index::Int) = push!(s, index, s.N)
| KrylovPreconditioners | https://github.com/JuliaSmoothOptimizers/KrylovPreconditioners.jl.git |
|
[
"MPL-2.0"
] | 0.3.0 | f49af35a8dd097d4dccabf94bd2053afbfdab3a4 | code | 3386 | import Base: setindex!, empty!, Vector
import LinearAlgebra: axpy!
"""
`SparseVectorAccumulator` accumulates the sparse vector
resulting from SpMV. Initialization requires O(N) work,
therefore the data structure is reused. Insertion is O(1).
Note that `nzind` is unordered. Also note that there is
wasted space: `nzind` could be a growing list. Pre-allocation
seems faster though.
SparseVectorAccumulator incorporates the multiple switch technique
by Gustavson (1976), which makes resetting an O(1) operation rather
than O(nnz): the `curr` value is used to flag the occupied indices,
and `curr` is increased at each reset.
occupied = [0, 1, 0, 1, 0, 0, 0]
nzind = [2, 4, 0, 0, 0, 0]
nzval = [0., .1234, 0., .435, 0., 0., 0.]
nnz = 2
length = 7
curr = 1
"""
mutable struct SparseVectorAccumulator{Tv,Ti}
occupied::Vector{Ti}
nzind::Vector{Ti}
nzval::Vector{Tv}
nnz::Ti
length::Ti
curr::Ti
return SparseVectorAccumulator{Tv,Ti}(N::Integer) where {Tv,Ti} = new(
zeros(Ti, N),
Vector{Ti}(undef, N),
Vector{Tv}(undef, N),
0,
N,
1
)
end
function Vector(v::SparseVectorAccumulator{T}) where {T}
x = zeros(T, v.length)
@inbounds x[v.nzind[1 : v.nnz]] = v.nzval[v.nzind[1 : v.nnz]]
return x
end
"""
Add a part of a SparseMatrixCSC column to a SparseVectorAccumulator,
starting at a given index until the end.
"""
function axpy!(a, A::SparseMatrixCSC, column, start, y::SparseVectorAccumulator)
# Loop over the whole column of A
@inbounds for idx = start : A.colptr[column + 1] - 1
add!(y, a * A.nzval[idx], A.rowval[idx])
end
return y
end
"""
Sets `v[idx] += a` when `idx` is occupied, or sets `v[idx] = a`.
Complexity is O(1).
"""
function add!(v::SparseVectorAccumulator, a, idx)
@inbounds begin
if isoccupied(v, idx)
v.nzval[idx] += a
else
v.nnz += 1
v.occupied[idx] = v.curr
v.nzval[idx] = a
v.nzind[v.nnz] = idx
end
end
return nothing
end
"""
Check whether `idx` is nonzero.
"""
@propagate_inbounds isoccupied(v::SparseVectorAccumulator, idx::Integer) = v.occupied[idx] == v.curr
"""
Empty the SparseVectorAccumulator in O(1) operations.
"""
@inline function empty!(v::SparseVectorAccumulator)
v.curr += 1
v.nnz = 0
end
"""
Basically `A[:, j] = scale * drop(y)`, where drop removes
values less than `drop`. Note: sorts the `nzind`'s of `y`,
so that the column can be appended to a SparseMatrixCSC.
Resets the `SparseVectorAccumulator`.
Note: does *not* update `A.colptr` for columns > j + 1,
as that is done during the steps.
"""
function append_col!(A::SparseMatrixCSC, y::SparseVectorAccumulator, j::Integer, drop, scale = one(eltype(A)))
# Move the indices of interest up front
total = 0
@inbounds for idx = 1 : y.nnz
row = y.nzind[idx]
value = y.nzval[row]
if abs(value) ≥ drop || row == j
total += 1
y.nzind[total] = row
end
end
# Sort the retained values.
sort!(y.nzind, 1, total, Base.Sort.QuickSort, Base.Order.Forward)
@inbounds for idx = 1 : total
row = y.nzind[idx]
push!(A.rowval, row)
push!(A.nzval, scale * y.nzval[row])
end
@inbounds A.colptr[j + 1] = A.colptr[j] + total
empty!(y)
return nothing
end
| KrylovPreconditioners | https://github.com/JuliaSmoothOptimizers/KrylovPreconditioners.jl.git |
|
[
"MPL-2.0"
] | 0.3.0 | f49af35a8dd097d4dccabf94bd2053afbfdab3a4 | code | 617 | using AMDGPU
using CUDA
using oneAPI
using Test
using KrylovPreconditioners
@testset "KrylovPreconditioners" begin
if AMDGPU.functional()
@info "Testing AMDGPU backend"
@testset "Testing AMDGPU backend" begin
include("gpu/amd.jl")
end
end
if CUDA.functional()
@info "Testing CUDA backend"
@testset "Testing CUDA backend" begin
include("gpu/nvidia.jl")
end
end
if oneAPI.functional()
@info "Testing oneAPI backend"
@testset "Testing oneAPI backend" begin
include("gpu/intel.jl")
end
end
@testset "IncompleteLU.jl" begin
include("ilu/ilu.jl")
end
end
| KrylovPreconditioners | https://github.com/JuliaSmoothOptimizers/KrylovPreconditioners.jl.git |
|
[
"MPL-2.0"
] | 0.3.0 | f49af35a8dd097d4dccabf94bd2053afbfdab3a4 | code | 1926 | using AMDGPU, AMDGPU.rocSPARSE, AMDGPU.rocSOLVER
_get_type(J::ROCSparseMatrixCSR) = ROCArray{Float64, 1, AMDGPU.Mem.HIPBuffer}
_is_csr(J::ROCSparseMatrixCSR) = true
_is_csc(J::ROCSparseMatrixCSR) = false
include("gpu.jl")
@testset "AMD -- AMDGPU.jl" begin
@test AMDGPU.functional()
AMDGPU.allowscalar(false)
@testset "IC(0)" begin
@testset "ROCSparseMatrixCSC -- $FC" for FC in (Float64,)
test_ic0(FC, ROCVector{FC}, ROCSparseMatrixCSC{FC})
end
@testset "ROCSparseMatrixCSR -- $FC" for FC in (Float64, ComplexF64)
test_ic0(FC, ROCVector{FC}, ROCSparseMatrixCSR{FC})
end
end
@testset "ILU(0)" begin
@testset "ROCSparseMatrixCSC -- $FC" for FC in (Float64,)
test_ilu0(FC, ROCVector{FC}, ROCSparseMatrixCSC{FC})
end
@testset "ROCSparseMatrixCSR -- $FC" for FC in (Float64, ComplexF64)
test_ilu0(FC, ROCVector{FC}, ROCSparseMatrixCSR{FC})
end
end
@testset "KrylovOperator" begin
@testset "ROCSparseMatrixCOO -- $FC" for FC in (Float64, ComplexF64)
test_operator(FC, ROCVector{FC}, ROCMatrix{FC}, ROCSparseMatrixCOO{FC})
end
@testset "ROCSparseMatrixCSC -- $FC" for FC in (Float64, ComplexF64)
test_operator(FC, ROCVector{FC}, ROCMatrix{FC}, ROCSparseMatrixCSC{FC})
end
@testset "ROCSparseMatrixCSR -- $FC" for FC in (Float64, ComplexF64)
test_operator(FC, ROCVector{FC}, ROCMatrix{FC}, ROCSparseMatrixCSR{FC})
end
end
@testset "TriangularOperator" begin
@testset "ROCSparseMatrixCOO -- $FC" for FC in (Float64, ComplexF64)
test_triangular(FC, ROCVector{FC}, ROCMatrix{FC}, ROCSparseMatrixCOO{FC})
end
@testset "ROCSparseMatrixCSR -- $FC" for FC in (Float64, ComplexF64)
test_triangular(FC, ROCVector{FC}, ROCMatrix{FC}, ROCSparseMatrixCSR{FC})
end
end
@testset "Block Jacobi preconditioner" begin
test_block_jacobi(ROCBackend(), ROCArray, ROCSparseMatrixCSR)
end
end
| KrylovPreconditioners | https://github.com/JuliaSmoothOptimizers/KrylovPreconditioners.jl.git |
|
[
"MPL-2.0"
] | 0.3.0 | f49af35a8dd097d4dccabf94bd2053afbfdab3a4 | code | 6107 | using SparseArrays, Random, Test
using LinearAlgebra, Krylov, KrylovPreconditioners
Random.seed!(666)
function test_ic0(FC, V, M)
n = 100
R = real(FC)
A_cpu = rand(FC, n, n)
A_cpu = A_cpu * A_cpu'
A_cpu = sparse(A_cpu)
b_cpu = rand(FC, n)
A_gpu = M(A_cpu)
b_gpu = V(b_cpu)
P = kp_ic0(A_gpu)
x_gpu, stats = cg(A_gpu, b_gpu, M=P, ldiv=true)
r_gpu = b_gpu - A_gpu * x_gpu
@test stats.niter ≤ 5
if (FC <: ComplexF64) && V.body.name.name == :ROCArray
@test_broken norm(r_gpu) ≤ 1e-6
else
@test norm(r_gpu) ≤ 1e-8
end
A_gpu = M(A_cpu + 200*I)
update!(P, A_gpu)
x_gpu, stats = cg(A_gpu, b_gpu, M=P, ldiv=true)
r_gpu = b_gpu - A_gpu * x_gpu
@test stats.niter ≤ 5
if (FC <: ComplexF64) && V.body.name.name == :ROCArray
@test_broken norm(r_gpu) ≤ 1e-6
else
@test norm(r_gpu) ≤ 1e-8
end
end
function test_ilu0(FC, V, M)
n = 100
R = real(FC)
A_cpu = rand(FC, n, n)
A_cpu = sparse(A_cpu)
b_cpu = rand(FC, n)
A_gpu = M(A_cpu)
b_gpu = V(b_cpu)
P = kp_ilu0(A_gpu)
x_gpu, stats = gmres(A_gpu, b_gpu, N=P, ldiv=true)
r_gpu = b_gpu - A_gpu * x_gpu
@test stats.niter ≤ 5
@test norm(r_gpu) ≤ 1e-8
A_gpu = M(A_cpu + 200*I)
update!(P, A_gpu)
x_gpu, stats = gmres(A_gpu, b_gpu, N=P, ldiv=true)
r_gpu = b_gpu - A_gpu * x_gpu
@test stats.niter ≤ 5
@test norm(r_gpu) ≤ 1e-8
end
function test_operator(FC, V, DM, SM)
m = 200
n = 100
A_cpu = rand(FC, n, n)
A_cpu = sparse(A_cpu)
b_cpu = rand(FC, n)
A_gpu = SM(A_cpu)
b_gpu = V(b_cpu)
opA_gpu = KrylovOperator(A_gpu)
x_gpu, stats = gmres(opA_gpu, b_gpu)
r_gpu = b_gpu - A_gpu * x_gpu
@test stats.solved
@test norm(r_gpu) ≤ 1e-8
A_cpu = rand(FC, m, n)
A_cpu = sparse(A_cpu)
A_gpu = SM(A_cpu)
opA_gpu = KrylovOperator(A_gpu)
for i = 1:5
y_cpu = rand(FC, m)
x_cpu = rand(FC, n)
mul!(y_cpu, A_cpu, x_cpu)
y_gpu = V(y_cpu)
x_gpu = V(x_cpu)
mul!(y_gpu, opA_gpu, x_gpu)
@test collect(y_gpu) ≈ y_cpu
end
if V.body.name.name != :oneArray
for j = 1:5
y_cpu = rand(FC, m)
x_cpu = rand(FC, n)
A_cpu2 = A_cpu + j*I
mul!(y_cpu, A_cpu2, x_cpu)
y_gpu = V(y_cpu)
x_gpu = V(x_cpu)
A_gpu2 = SM(A_cpu2)
update!(opA_gpu, A_gpu2)
mul!(y_gpu, opA_gpu, x_gpu)
@test collect(y_gpu) ≈ y_cpu
end
end
nrhs = 3
opA_gpu = KrylovOperator(A_gpu; nrhs)
for i = 1:5
Y_cpu = rand(FC, m, nrhs)
X_cpu = rand(FC, n, nrhs)
mul!(Y_cpu, A_cpu, X_cpu)
Y_gpu = DM(Y_cpu)
X_gpu = DM(X_cpu)
mul!(Y_gpu, opA_gpu, X_gpu)
@test collect(Y_gpu) ≈ Y_cpu
end
if V.body.name.name != :oneArray
for j = 1:5
Y_cpu = rand(FC, m, nrhs)
X_cpu = rand(FC, n, nrhs)
A_cpu2 = A_cpu + j*I
mul!(Y_cpu, A_cpu2, X_cpu)
Y_gpu = DM(Y_cpu)
X_gpu = DM(X_cpu)
A_gpu2 = SM(A_cpu2)
update!(opA_gpu, A_gpu2)
mul!(Y_gpu, opA_gpu, X_gpu)
@test collect(Y_gpu) ≈ Y_cpu
end
end
end
function test_triangular(FC, V, DM, SM)
n = 100
for (uplo, diag, triangle) in [('L', 'U', UnitLowerTriangular),
('L', 'N', LowerTriangular ),
('U', 'U', UnitUpperTriangular),
('U', 'N', UpperTriangular )]
A_cpu = rand(FC, n, n)
A_cpu = uplo == 'L' ? tril(A_cpu) : triu(A_cpu)
A_cpu = diag == 'U' ? A_cpu - Diagonal(A_cpu) + I : A_cpu
A_cpu = sparse(A_cpu)
b_cpu = rand(FC, n)
A_gpu = SM(A_cpu)
b_gpu = V(b_cpu)
opA_gpu = TriangularOperator(A_gpu, uplo, diag)
for i = 1:5
y_cpu = rand(FC, n)
x_cpu = rand(FC, n)
ldiv!(y_cpu, triangle(A_cpu), x_cpu)
y_gpu = V(y_cpu)
x_gpu = V(x_cpu)
ldiv!(y_gpu, opA_gpu, x_gpu)
@test collect(y_gpu) ≈ y_cpu
end
if V.body.name.name != :oneArray
for j = 1:5
y_cpu = rand(FC, n)
x_cpu = rand(FC, n)
A_cpu2 = A_cpu + j*tril(A_cpu,-1) + j*triu(A_cpu,1)
ldiv!(y_cpu, triangle(A_cpu2), x_cpu)
y_gpu = V(y_cpu)
x_gpu = V(x_cpu)
A_gpu2 = SM(A_cpu2)
update!(opA_gpu, A_gpu2)
ldiv!(y_gpu, opA_gpu, x_gpu)
@test collect(y_gpu) ≈ y_cpu
end
end
nrhs = 3
opA_gpu = TriangularOperator(A_gpu, uplo, diag; nrhs)
for i = 1:5
Y_cpu = rand(FC, n, nrhs)
X_cpu = rand(FC, n, nrhs)
ldiv!(Y_cpu, triangle(A_cpu), X_cpu)
Y_gpu = DM(Y_cpu)
X_gpu = DM(X_cpu)
ldiv!(Y_gpu, opA_gpu, X_gpu)
@test collect(Y_gpu) ≈ Y_cpu
end
if V.body.name.name != :oneArray
for j = 1:5
Y_cpu = rand(FC, n, nrhs)
X_cpu = rand(FC, n, nrhs)
A_cpu2 = A_cpu + j*tril(A_cpu,-1) + j*triu(A_cpu,1)
ldiv!(Y_cpu, triangle(A_cpu2), X_cpu)
Y_gpu = DM(Y_cpu)
X_gpu = DM(X_cpu)
A_gpu2 = SM(A_cpu2)
update!(opA_gpu, A_gpu2)
ldiv!(Y_gpu, opA_gpu, X_gpu)
@test collect(Y_gpu) ≈ Y_cpu
end
end
end
end
_get_type(J::SparseMatrixCSC) = Vector{Float64}
function generate_random_system(n::Int, m::Int)
# Add a diagonal term for conditionning
A = randn(n, m) + 15I
x♯ = randn(m)
b = A * x♯
# Be careful: all algorithms work with sparse matrix
spA = sparse(A)
return spA, b, x♯
end
function test_block_jacobi(device, AT, SMT)
n, m = 100, 100
A, b, x♯ = generate_random_system(n, m)
# Transfer data to device
A = A |> SMT
b = b |> AT
x♯ = x♯ |> AT
x = similar(b); r = similar(b)
nblocks = 2
if _is_csr(A)
scaling_csr!(A, b, device)
end
precond = BlockJacobiPreconditioner(A, nblocks, device)
update!(precond, A)
S = _get_type(A)
linear_solver = Krylov.BicgstabSolver(n, m, S)
Krylov.bicgstab!(
linear_solver, A, b;
N=precond,
atol=1e-10,
rtol=1e-10,
verbose=0,
history=true,
)
n_iters = linear_solver.stats.niter
copyto!(x, linear_solver.x)
r = b - A * x
resid = norm(r) / norm(b)
@test(resid ≤ 1e-6)
@test x ≈ x♯
@test n_iters ≤ n
end
| KrylovPreconditioners | https://github.com/JuliaSmoothOptimizers/KrylovPreconditioners.jl.git |
|
[
"MPL-2.0"
] | 0.3.0 | f49af35a8dd097d4dccabf94bd2053afbfdab3a4 | code | 799 | using oneAPI, oneAPI.oneMKL
_get_type(J::oneSparseMatrixCSR) = oneArray{Float64, 1, oneAPI.oneL0.DeviceBuffer}
_is_csr(J::oneSparseMatrixCSR) = true
include("gpu.jl")
@testset "Intel -- oneAPI.jl" begin
@test oneAPI.functional()
oneAPI.allowscalar(false)
@testset "KrylovOperator" begin
@testset "oneSparseMatrixCSR -- $FC" for FC in (Float32,) # ComplexF32)
test_operator(FC, oneVector{FC}, oneMatrix{FC}, oneSparseMatrixCSR)
end
end
@testset "TriangularOperator" begin
@testset "oneSparseMatrixCSR -- $FC" for FC in (Float32,) # ComplexF32)
test_triangular(FC, oneVector{FC}, oneMatrix{FC}, oneSparseMatrixCSR)
end
end
# @testset "Block Jacobi preconditioner" begin
# test_block_jacobi(oneAPIBackend(), oneArray, oneSparseMatrixCSR)
# end
end
| KrylovPreconditioners | https://github.com/JuliaSmoothOptimizers/KrylovPreconditioners.jl.git |
|
[
"MPL-2.0"
] | 0.3.0 | f49af35a8dd097d4dccabf94bd2053afbfdab3a4 | code | 1879 | using CUDA, CUDA.CUSPARSE, CUDA.CUSOLVER
_get_type(J::CuSparseMatrixCSR) = CuArray{Float64, 1, CUDA.Mem.DeviceBuffer}
_is_csr(J::CuSparseMatrixCSR) = true
_is_csc(J::CuSparseMatrixCSR) = false
include("gpu.jl")
@testset "Nvidia -- CUDA.jl" begin
@test CUDA.functional()
CUDA.allowscalar(false)
@testset "IC(0)" begin
@testset "CuSparseMatrixCSC -- $FC" for FC in (Float64,)
test_ic0(FC, CuVector{FC}, CuSparseMatrixCSC{FC})
end
@testset "CuSparseMatrixCSR -- $FC" for FC in (Float64, ComplexF64)
test_ic0(FC, CuVector{FC}, CuSparseMatrixCSR{FC})
end
end
@testset "ILU(0)" begin
@testset "CuSparseMatrixCSC -- $FC" for FC in (Float64,)
test_ilu0(FC, CuVector{FC}, CuSparseMatrixCSC{FC})
end
@testset "CuSparseMatrixCSR -- $FC" for FC in (Float64, ComplexF64)
test_ilu0(FC, CuVector{FC}, CuSparseMatrixCSR{FC})
end
end
@testset "KrylovOperator" begin
@testset "CuSparseMatrixCOO -- $FC" for FC in (Float64, ComplexF64)
test_operator(FC, CuVector{FC}, CuMatrix{FC}, CuSparseMatrixCOO{FC})
end
@testset "CuSparseMatrixCSC -- $FC" for FC in (Float64, ComplexF64)
test_operator(FC, CuVector{FC}, CuMatrix{FC}, CuSparseMatrixCSC{FC})
end
@testset "CuSparseMatrixCSR -- $FC" for FC in (Float64, ComplexF64)
test_operator(FC, CuVector{FC}, CuMatrix{FC}, CuSparseMatrixCSR{FC})
end
end
@testset "TriangularOperator" begin
@testset "CuSparseMatrixCOO -- $FC" for FC in (Float64, ComplexF64)
test_triangular(FC, CuVector{FC}, CuMatrix{FC}, CuSparseMatrixCOO{FC})
end
@testset "CuSparseMatrixCSR -- $FC" for FC in (Float64, ComplexF64)
test_triangular(FC, CuVector{FC}, CuMatrix{FC}, CuSparseMatrixCSR{FC})
end
end
@testset "Block Jacobi preconditioner" begin
test_block_jacobi(CUDABackend(), CuArray, CuSparseMatrixCSR)
end
end
| KrylovPreconditioners | https://github.com/JuliaSmoothOptimizers/KrylovPreconditioners.jl.git |
|
[
"MPL-2.0"
] | 0.3.0 | f49af35a8dd097d4dccabf94bd2053afbfdab3a4 | code | 5347 | using Test
using KrylovPreconditioners: ILUFactorization, forward_substitution!, backward_substitution!
using LinearAlgebra
@testset "Forward and backward substitutions" begin
function test_fw_substitution(F::ILUFactorization)
A = F.L
n = size(A, 1)
x = rand(n)
y = copy(x)
v = zeros(n)
forward_substitution!(v, F, x)
forward_substitution!(F, x)
ldiv!(UnitLowerTriangular(A), y)
@test v ≈ y
@test x ≈ y
x = rand(n, 5)
y = copy(x)
v = zeros(n, 5)
forward_substitution!(v, F, x)
forward_substitution!(F, x)
ldiv!(UnitLowerTriangular(A), y)
@test v ≈ y
@test x ≈ y
end
function test_bw_substitution(F::ILUFactorization)
A = F.U
n = size(A, 1)
x = rand(n)
y = copy(x)
v = zeros(n)
backward_substitution!(v, F, x)
backward_substitution!(F, x)
ldiv!(UpperTriangular(A'), y)
@test v ≈ y
@test x ≈ y
x = rand(n, 5)
y = copy(x)
v = zeros(n, 5)
backward_substitution!(v, F, x)
backward_substitution!(F, x)
ldiv!(UpperTriangular(A'), y)
@test v ≈ y
@test x ≈ y
end
L = sparse(tril(rand(10, 10), -1))
U = sparse(tril(rand(10, 10)) + 10I)
F = ILUFactorization(L, U)
test_fw_substitution(F)
test_bw_substitution(F)
L = sparse(tril(tril(sprand(10, 10, .5), -1)))
U = sparse(tril(sprand(10, 10, .5) + 10I))
F = ILUFactorization(L, U)
test_fw_substitution(F)
test_bw_substitution(F)
L = spzeros(10, 10)
U = spzeros(10, 10) + 10I
F = ILUFactorization(L, U)
test_fw_substitution(F)
test_bw_substitution(F)
end
@testset "Adjoint -- Forward and backward substitutions" begin
function test_adjoint_fw_substitution(F::ILUFactorization)
A = F.U
n = size(A, 1)
x = rand(n)
y = copy(x)
v = zeros(n)
adjoint_forward_substitution!(v, F, x)
adjoint_forward_substitution!(F, x)
ldiv!(LowerTriangular(A), y)
@test v ≈ y
@test x ≈ y
x = rand(n, 5)
x2 = copy(x)
y = copy(x)
v = zeros(n, 5)
adjoint_forward_substitution!(v, F, x)
adjoint_forward_substitution!(F, x)
ldiv!(LowerTriangular(A), y)
@test v ≈ y
@test x ≈ y
end
function test_adjoint_bw_substitution(F::ILUFactorization)
A = F.L
n = size(A, 1)
x = rand(n)
y = copy(x)
v = zeros(n)
adjoint_backward_substitution!(v, F, x)
adjoint_backward_substitution!(F, x)
ldiv!(UnitLowerTriangular(A)', y)
@test v ≈ y
@test x ≈ y
x = rand(n, 5)
y = copy(x)
v = zeros(n, 5)
adjoint_backward_substitution!(v, F, x)
adjoint_backward_substitution!(F, x)
ldiv!(UnitLowerTriangular(A)', y)
@test v ≈ y
@test x ≈ y
end
L = sparse(tril(rand(10, 10), -1))
U = sparse(tril(rand(10, 10)) + 10I)
F = ILUFactorization(L, U)
test_adjoint_fw_substitution(F)
test_adjoint_bw_substitution(F)
L = sparse(tril(tril(sprand(10, 10, .5), -1)))
U = sparse(tril(sprand(10, 10, .5) + 10I))
F = ILUFactorization(L, U)
test_adjoint_fw_substitution(F)
test_adjoint_bw_substitution(F)
L = spzeros(10, 10)
U = spzeros(10, 10) + 10I
F = ILUFactorization(L, U)
test_adjoint_fw_substitution(F)
test_adjoint_bw_substitution(F)
end
@testset "ldiv!" begin
function test_ldiv!(L, U)
LU = ILUFactorization(L, U)
x = rand(size(LU.L, 1))
y = copy(x)
z = copy(x)
w = copy(x)
ldiv!(LU, x)
ldiv!(UnitLowerTriangular(LU.L), y)
ldiv!(UpperTriangular(LU.U'), y)
@test x ≈ y
@test LU \ z == x
ldiv!(w, LU, z)
@test w == x
x = rand(size(LU.L, 1), 5)
y = copy(x)
z = copy(x)
w = copy(x)
ldiv!(LU, x)
ldiv!(UnitLowerTriangular(LU.L), y)
ldiv!(UpperTriangular(LU.U'), y)
@test x ≈ y
@test LU \ z == x
ldiv!(w, LU, z)
@test w == x
end
test_ldiv!(tril(sprand(10, 10, .5), -1), tril(sprand(10, 10, .5) + 10I))
end
@testset "Adjoint -- ldiv!" begin
function test_adjoint_ldiv!(L, U)
LU = ILUFactorization(L, U)
ALU = adjoint(LU)
x = rand(size(LU.L, 1))
y = copy(x)
z = copy(x)
w = copy(x)
ldiv!(ALU, x)
ldiv!(LowerTriangular(LU.U), y)
ldiv!(UnitLowerTriangular(LU.L)', y)
@test x ≈ y
@test ALU \ z == x
ldiv!(w, ALU, z)
@test w == x
x = rand(size(LU.L, 1), 5)
y = copy(x)
z = copy(x)
w = copy(x)
ldiv!(ALU, x)
ldiv!(LowerTriangular(LU.U), y)
ldiv!(UnitLowerTriangular(LU.L)', y)
@test x ≈ y
@test ALU \ z == x
ldiv!(w, ALU, z)
@test w == x
end
test_adjoint_ldiv!(tril(sprand(10, 10, .5), -1), tril(sprand(10, 10, .5) + 10I))
end
@testset "nnz" begin
L = tril(sprand(10, 10, .5), -1)
U = tril(sprand(10, 10, .5)) + 10I
LU = ILUFactorization(L, U)
@test nnz(LU) == nnz(L) + nnz(U)
end
| KrylovPreconditioners | https://github.com/JuliaSmoothOptimizers/KrylovPreconditioners.jl.git |
|
[
"MPL-2.0"
] | 0.3.0 | f49af35a8dd097d4dccabf94bd2053afbfdab3a4 | code | 1152 | using Test
using SparseArrays
using LinearAlgebra
@testset "Crout ILU" for Tv in (Float64, Float32, ComplexF64, ComplexF32), Ti in (Int64, Int32)
let
# Test if it performs full LU if droptol is zero
A = convert(SparseMatrixCSC{Tv, Ti}, sprand(Tv, 10, 10, .5) + 10I)
ilu = KrylovPreconditioners.ilu(A, τ = 0)
flu = lu(Matrix(A), NoPivot())
@test typeof(ilu) == KrylovPreconditioners.ILUFactorization{Tv,Ti}
@test Matrix(ilu.L + I) ≈ flu.L
@test Matrix(transpose(ilu.U)) ≈ flu.U
end
let
# Test if L = I and U = diag(A) when the droptol is large.
A = convert(SparseMatrixCSC{Tv, Ti}, sprand(10, 10, .5) + 10I)
ilu = KrylovPreconditioners.ilu(A, τ = 1.0)
@test nnz(ilu.L) == 0
@test nnz(ilu.U) == 10
@test diag(ilu.U) == diag(A)
end
end
@testset "Crout ILU with integer matrix" begin
A = sparse(Int32(1):Int32(10), Int32(1):Int32(10), 1)
ilu = KrylovPreconditioners.ilu(A, τ = 0)
@test typeof(ilu) == KrylovPreconditioners.ILUFactorization{Float64,Int32}
@test nnz(ilu.L) == 0
@test diag(ilu.U) == diag(A)
end
| KrylovPreconditioners | https://github.com/JuliaSmoothOptimizers/KrylovPreconditioners.jl.git |
|
[
"MPL-2.0"
] | 0.3.0 | f49af35a8dd097d4dccabf94bd2053afbfdab3a4 | code | 184 | include("sorted_set.jl")
include("linked_list.jl")
include("sparse_vector_accumulator.jl")
include("insertion_sort_update_vector.jl")
include("application.jl")
include("crout_ilu.jl")
| KrylovPreconditioners | https://github.com/JuliaSmoothOptimizers/KrylovPreconditioners.jl.git |
|
[
"MPL-2.0"
] | 0.3.0 | f49af35a8dd097d4dccabf94bd2053afbfdab3a4 | code | 1725 | using Test
using KrylovPreconditioners: InsertableSparseVector, add!, axpy!, append_col!, indices
@testset "InsertableSparseVector" begin
@testset "Insertion sorted sparse vector" begin
v = InsertableSparseVector{Float64}(10)
add!(v, 3.0, 6, 11)
add!(v, 3.0, 3, 11)
add!(v, 3.0, 3, 11)
@test v[6] == 3.0
@test v[3] == 6.0
@test indices(v) == [3, 6]
end
@testset "Add column of SparseMatrixCSC" begin
v = InsertableSparseVector{Float64}(5)
A = sprand(5, 5, 1.0)
axpy!(2., A, 3, A.colptr[3], v)
axpy!(3., A, 4, A.colptr[4], v)
@test Vector(v) == 2 * A[:, 3] + 3 * A[:, 4]
end
@testset "Append column to SparseMatrixCSC" begin
A = spzeros(5, 5)
v = InsertableSparseVector{Float64}(5)
add!(v, 0.3, 1)
add!(v, 0.009, 3)
add!(v, 0.12, 4)
add!(v, 0.007, 5)
append_col!(A, v, 1, 0.1)
# Test whether the column is copied correctly
# and the dropping rule is applied
@test A[1, 1] == 0.3
@test A[2, 1] == 0.0 # zero
@test A[3, 1] == 0.0 # dropped
@test A[4, 1] == 0.12
@test A[5, 1] == 0.0 # dropped
# Test whether the InsertableSparseVector is reset
# when reusing it for the second column. Also do
# scaling with a factor of 10.
add!(v, 0.5, 2)
add!(v, 0.009, 3)
add!(v, 0.5, 4)
add!(v, 0.007, 5)
append_col!(A, v, 2, 0.1, 10.0)
@test A[1, 2] == 0.0 # zero
@test A[2, 2] == 5.0 # scaled
@test A[3, 2] == 0.0 # dropped
@test A[4, 2] == 5.0 # scaled
@test A[5, 2] == 0.0 # dropped
end
end
| KrylovPreconditioners | https://github.com/JuliaSmoothOptimizers/KrylovPreconditioners.jl.git |
|
[
"MPL-2.0"
] | 0.3.0 | f49af35a8dd097d4dccabf94bd2053afbfdab3a4 | code | 1180 | using Test
using KrylovPreconditioners: LinkedLists, RowReader, first_in_row, is_column, nzval, next_column,
next_row!, has_next_nonzero, enqueue_next_nonzero!
using SparseArrays
@testset "Linked List" begin
n = 5
let
lists = LinkedLists{Int}(n)
# head[2] -> 5 -> nil
# head[5] -> 4 -> 3 -> nil
push!(lists, 5, 3)
push!(lists, 5, 4)
push!(lists, 2, 5)
@test lists.head[5] == 4
@test lists.next[4] == 3
@test lists.next[3] == 0
@test lists.head[2] == 5
@test lists.next[5] == 0
end
end
@testset "Read SparseMatrixCSC row by row" begin
# Read a sparse matrix row by row.
n = 10
A = sprand(n, n, .5)
reader = RowReader(A)
for row = 1 : n
column = first_in_row(reader, row)
while is_column(column)
@test nzval(reader, column) == A[row, column]
next_col = next_column(reader, column)
next_row!(reader, column)
if has_next_nonzero(reader, column)
enqueue_next_nonzero!(reader, column)
end
column = next_col
end
end
end
| KrylovPreconditioners | https://github.com/JuliaSmoothOptimizers/KrylovPreconditioners.jl.git |
|
[
"MPL-2.0"
] | 0.3.0 | f49af35a8dd097d4dccabf94bd2053afbfdab3a4 | code | 1107 | using Test
import KrylovPreconditioners: SortedSet, push!
@testset "Sorted indices" begin
@testset "New values" begin
indices = SortedSet(10)
@test push!(indices, 5)
@test push!(indices, 7)
@test push!(indices, 4)
@test push!(indices, 6)
@test push!(indices, 8)
as_vec = Vector(indices)
@test as_vec == [4, 5, 6, 7, 8]
end
@testset "Duplicate values" begin
indices = SortedSet(10)
@test push!(indices, 3)
@test push!(indices, 3) == false
@test push!(indices, 8)
@test push!(indices, 8) == false
@test Vector(indices) == [3, 8]
end
@testset "Quick insertion with known previous index" begin
indices = SortedSet(10)
@test push!(indices, 3)
@test push!(indices, 4, 3)
@test push!(indices, 8, 4)
@test Vector(indices) == [3, 4, 8]
end
@testset "Pretty printing" begin
indices = SortedSet(10)
push!(indices, 3)
push!(indices, 2)
@test occursin("with values", sprint(show, indices))
end
end
| KrylovPreconditioners | https://github.com/JuliaSmoothOptimizers/KrylovPreconditioners.jl.git |
|
[
"MPL-2.0"
] | 0.3.0 | f49af35a8dd097d4dccabf94bd2053afbfdab3a4 | code | 2235 | using KrylovPreconditioners: SparseVectorAccumulator, add!, append_col!, isoccupied
using LinearAlgebra
@testset "SparseVectorAccumulator" for Ti in (Int32, Int64), Tv in (Float64, Float32)
@testset "Initialization" begin
v = SparseVectorAccumulator{Tv,Ti}(10)
@test iszero(v.nnz)
@test iszero(v.occupied)
end
@testset "Add to SparseVectorAccumulator" begin
v = SparseVectorAccumulator{Tv,Ti}(3)
add!(v, Tv(1.0), Ti(3))
add!(v, Tv(1.0), Ti(3))
add!(v, Tv(3.0), Ti(2))
@test v.nnz == 2
@test isoccupied(v, 1) == false
@test isoccupied(v, 2)
@test isoccupied(v, 3)
@test Vector(v) == Tv[0.; 3.0; 2.0]
end
@testset "Add column of SparseMatrixCSC" begin
# Copy all columns of a
v = SparseVectorAccumulator{Tv,Ti}(5)
A = convert(SparseMatrixCSC{Tv,Ti}, sprand(Tv, 5, 5, 1.0))
axpy!(Tv(2), A, Ti(3), A.colptr[3], v)
axpy!(Tv(3), A, Ti(4), A.colptr[4], v)
@test Vector(v) == 2 * A[:, 3] + 3 * A[:, 4]
end
@testset "Append column to SparseMatrixCSC" begin
A = spzeros(Tv, Ti, 5, 5)
v = SparseVectorAccumulator{Tv,Ti}(5)
add!(v, Tv(0.3), Ti(1))
add!(v, Tv(0.009), Ti(3))
add!(v, Tv(0.12), Ti(4))
add!(v, Tv(0.007), Ti(5))
append_col!(A, v, Ti(1), Tv(0.1))
# Test whether the column is copied correctly
# and the dropping rule is applied
@test A[1, 1] == Tv(0.3)
@test A[2, 1] == Tv(0.0) # zero
@test A[3, 1] == Tv(0.0) # dropped
@test A[4, 1] == Tv(0.12)
@test A[5, 1] == Tv(0.0) # dropped
# Test whether the InsertableSparseVector is reset
# when reusing it for the second column. Also do
# scaling with a factor of 10.
add!(v, Tv(0.5), Ti(2))
add!(v, Tv(0.009), Ti(3))
add!(v, Tv(0.5), Ti(4))
add!(v, Tv(0.007), Ti(5))
append_col!(A, v, Ti(2), Tv(0.1), Tv(10.0))
@test A[1, 2] == Tv(0.0) # zero
@test A[2, 2] == Tv(5.0) # scaled
@test A[3, 2] == Tv(0.0) # dropped
@test A[4, 2] == Tv(5.0) # scaled
@test A[5, 2] == Tv(0.0) # dropped
end
end
| KrylovPreconditioners | https://github.com/JuliaSmoothOptimizers/KrylovPreconditioners.jl.git |
|
[
"MPL-2.0"
] | 0.3.0 | f49af35a8dd097d4dccabf94bd2053afbfdab3a4 | docs | 1883 | # `KrylovPreconditioners`.jl
| **Documentation** | **CI** | **Coverage** | **Downloads** |
|:-----------------:|:------:|:------------:|:-------------:|
| [![docs-stable][docs-stable-img]][docs-stable-url] [![docs-dev][docs-dev-img]][docs-dev-url] | [![build-gh][build-gh-img]][build-gh-url] [![build-cirrus][build-cirrus-img]][build-cirrus-url] | [![codecov][codecov-img]][codecov-url] | [![downloads][downloads-img]][downloads-url] |
[docs-stable-img]: https://img.shields.io/badge/docs-stable-blue.svg
[docs-stable-url]: https://JuliaSmoothOptimizers.github.io/KrylovPreconditioners.jl/stable
[docs-dev-img]: https://img.shields.io/badge/docs-dev-purple.svg
[docs-dev-url]: https://JuliaSmoothOptimizers.github.io/KrylovPreconditioners.jl/dev
[build-gh-img]: https://github.com/JuliaSmoothOptimizers/KrylovPreconditioners.jl/workflows/CI/badge.svg?branch=main
[build-gh-url]: https://github.com/JuliaSmoothOptimizers/KrylovPreconditioners.jl/actions
[build-cirrus-img]: https://img.shields.io/cirrus/github/JuliaSmoothOptimizers/KrylovPreconditioners.jl?logo=Cirrus%20CI
[build-cirrus-url]: https://cirrus-ci.com/github/JuliaSmoothOptimizers/KrylovPreconditioners.jl
[codecov-img]: https://codecov.io/gh/JuliaSmoothOptimizers/KrylovPreconditioners.jl/branch/main/graph/badge.svg
[codecov-url]: https://app.codecov.io/gh/JuliaSmoothOptimizers/KrylovPreconditioners.jl
[downloads-img]: https://shields.io/endpoint?url=https://pkgs.genieframework.com/api/v1/badge/KrylovPreconditioners
[downloads-url]: https://pkgs.genieframework.com?packages=KrylovPreconditioners
## How to Cite
If you use KrylovPreconditioners.jl in your work, please cite using the format given in [`CITATION.cff`](https://github.com/JuliaSmoothOptimizers/KrylovPreconditioners.jl/blob/main/CITATION.cff).
The best sidekick of [Krylov.jl](https://github.com/JuliaSmoothOptimizers/Krylov.jl) └(^o^ )X( ^o^)┘
| KrylovPreconditioners | https://github.com/JuliaSmoothOptimizers/KrylovPreconditioners.jl.git |
|
[
"MPL-2.0"
] | 0.3.0 | f49af35a8dd097d4dccabf94bd2053afbfdab3a4 | docs | 1194 | # [KrylovPreconditioners.jl documentation](@id Home)
This package provides a collection of preconditioners.
## How to Cite
If you use KrylovPreconditioners.jl in your work, please cite using the format given in [`CITATION.cff`](https://github.com/JuliaSmoothOptimizers/KrylovPreconditioners.jl/blob/main/CITATION.cff).
## How to Install
KrylovPreconditioners.jl can be installed and tested through the Julia package manager:
```julia
julia> ]
pkg> add KrylovPreconditioners
pkg> test KrylovPreconditioners
```
# Bug reports and discussions
If you think you found a bug, feel free to open an [issue](https://github.com/JuliaSmoothOptimizers/KrylovPreconditioners.jl/issues).
Focused suggestions and requests can also be opened as issues. Before opening a pull request, start an issue or a discussion on the topic, please.
If you want to ask a question not suited for a bug report, feel free to start a discussion [here](https://github.com/JuliaSmoothOptimizers/Organization/discussions). This forum is for general discussion about this repository and the [JuliaSmoothOptimizers](https://github.com/JuliaSmoothOptimizers) organization, so questions about any of our packages are welcome.
| KrylovPreconditioners | https://github.com/JuliaSmoothOptimizers/KrylovPreconditioners.jl.git |
|
[
"MPL-2.0"
] | 0.3.0 | f49af35a8dd097d4dccabf94bd2053afbfdab3a4 | docs | 118 | # Reference
## Index
```@index
```
```@autodocs
Modules = [KrylovPreconditioners]
Order = [:function, :type]
```
| KrylovPreconditioners | https://github.com/JuliaSmoothOptimizers/KrylovPreconditioners.jl.git |
|
[
"MIT"
] | 3.0.0 | 6391447698371a09458574a620f02ad91afbec3a | code | 199 | cd(@__DIR__)
using Pkg
Pkg.activate(".")
Pkg.develop(path = "..")
run(`quarto render README.qmd`)
mv("README.md", "../README.md", force = true)
mv("README_files/", "../README_files/", force = true)
| SummaryTables | https://github.com/PumasAI/SummaryTables.jl.git |
|
[
"MIT"
] | 3.0.0 | 6391447698371a09458574a620f02ad91afbec3a | code | 579 | using Documenter, SummaryTables
makedocs(
sitename = "SummaryTables.jl",
pages = [
"index.md",
"output.md",
"Predefined Tables" => [
"predefined_tables/listingtable.md",
"predefined_tables/summarytable.md",
"predefined_tables/table_one.md",
],
"Custom Tables" => [
"custom_tables/table.md",
"custom_tables/cell.md",
"custom_tables/cellstyle.md",
],
]
)
deploydocs(
repo = "github.com/PumasAI/SummaryTables.jl.git",
push_preview = true,
) | SummaryTables | https://github.com/PumasAI/SummaryTables.jl.git |
|
[
"MIT"
] | 3.0.0 | 6391447698371a09458574a620f02ad91afbec3a | code | 731 | module SummaryTables
#
# Imports and exports.
#
using Tables
using CategoricalArrays
using DataFrames
using Statistics
import EnumX
import HypothesisTests
import OrderedCollections
import MultipleTesting
import StatsBase
import Printf
import NaturalSort
import WriteDocx
import SHA
export table_one
export listingtable
export summarytable
export Cell
export CellStyle
export Table
export Annotated
export Concat
export Multiline
export Pagination
export ReplaceMissing
export Replace
export Superscript
export Subscript
const DEFAULT_ROWGAP = 6.0
include("cells.jl")
include("table_one.jl")
include("table.jl")
include("helpers.jl")
include("latex.jl")
include("html.jl")
include("docx.jl")
include("typst.jl")
end # module
| SummaryTables | https://github.com/PumasAI/SummaryTables.jl.git |
|
[
"MIT"
] | 3.0.0 | 6391447698371a09458574a620f02ad91afbec3a | code | 19904 | """
CellStyle(;
bold::Bool = false,
italic::Bool = false,
underline::Bool = false,
halign::Symbol = :center,
valign::Symbol = :top,
indent_pt::Float64 = 0.0,
border_bottom::Bool = false,
merge::Bool = false,
mergegroup::UInt8 = 0,
)
Create a `CellStyle` object which determines the visual appearance of `Cell`s.
Keyword arguments:
- `bold` renders text `bold` if `true`.
- `italic` renders text `italic` if `true`.
- `underline` underlines text if `true`.
- `halign` determines the horizontal alignment within the cell, either `:left`, `:center` or `:right`.
- `valign` determines the vertical alignment within the cell, either `:top`, `:center` or `:bottom`.
- `indent_pt` adds left indentation in points to the cell text.
- `border_bottom` adds a bottom border to the cell if `true`.
- `merge` causes adjacent cells which are `==` equal to be rendered as a single merged cell.
- `mergegroup` is a number that can be used to differentiate between two otherwise equal adjacent groups of cells that should not be merged together.
"""
Base.@kwdef struct CellStyle
indent_pt::Float64 = 0.0
bold::Bool = false
italic::Bool = false
underline::Bool = false
border_bottom::Bool = false
halign::Symbol = :center
valign::Symbol = :top
merge::Bool = false
mergegroup::UInt8 = 0
end
@eval function CellStyle(c::CellStyle; kwargs...)
Base.Cartesian.@ncall $(length(fieldnames(CellStyle))) CellStyle i -> begin
name = $(fieldnames(CellStyle))[i]
get(kwargs, name, getfield(c, name))
end
end
struct SpannedCell
span::Tuple{UnitRange{Int64},UnitRange{Int64}}
value
style::CellStyle
function SpannedCell(span::Tuple{UnitRange{Int64},UnitRange{Int64}}, value, style)
rowstart = span[1].start
colstart = span[2].start
if rowstart < 1
error("SpannedCell must not begin at a row lower than 1, but begins at row $(rowstart).")
end
if colstart < 1
error("SpannedCell must not begin at a column lower than 1, but begins at column $(colstart).")
end
new(span, value, style)
end
end
SpannedCell(rows::Union{Int,UnitRange{Int}}, cols::Union{Int,UnitRange{Int}}, value, style = CellStyle()) = SpannedCell((_to_range(rows), _to_range(cols)), value, style)
_to_range(i::Int) = i:i
_to_range(ur::UnitRange{Int}) = ur
# the old type never did anything, so now we just make any old use of this a no-op basically
const CellList = Vector{SpannedCell}
"""
Cell(value, style::CellStyle)
Cell(value; [bold, italic, underline, halign, valign, border_bottom, indent_pt, merge, mergegroup])
Construct a `Cell` with value `value` and `CellStyle` `style`, which can also be created implicitly with keyword arguments.
For explanations of the styling options, refer to `CellStyle`.
A cell with value `nothing` is displayed as an empty cell (styles might still apply).
The type of `value` can be anything.
Some types with special behavior are:
- `Multiline` for content broken over multiple lines in a cell. This object may not be used nested in other values, only as the top-level value.
- `Concat` for stringing together multiple values without having to interpolate them into a `String`, which keeps their own special behaviors intact.
- `Superscript` and `Subscript`
- `Annotated` for a value with an optional superscript label and a footnote annotation.
"""
struct Cell
value
style::CellStyle
Cell(value, style::CellStyle; kwargs...) = new(value, CellStyle(style; kwargs...))
end
Base.adjoint(c::Cell) = c # simplifies making row vectors out of column vectors of Cells with '
Cell(value; kwargs...) = Cell(value, CellStyle(; kwargs...))
Cell(cell::Cell; kwargs...) = Cell(cell.value, CellStyle(cell.style; kwargs...))
Cell(cell::Cell, value; kwargs...) = Cell(value, CellStyle(cell.style; kwargs...))
Base.broadcastable(c::Cell) = Ref(c)
@inline Base.getproperty(c::Cell, s::Symbol) = hasfield(Cell, s) ? getfield(c, s) : getproperty(c.style, s)
Base.propertynames(c::Cell) = (fieldnames(Cell)..., propertynames(c.style)...)
struct Table
cells::Matrix{Cell}
header::Union{Nothing, Int}
footer::Union{Nothing, Int}
footnotes::Vector{Any}
rowgaps::Vector{Pair{Int,Float64}}
colgaps::Vector{Pair{Int,Float64}}
postprocess::Vector{Any}
round_digits::Int
round_mode::Union{Nothing,Symbol}
trailing_zeros::Bool
linebreak_footnotes::Bool
end
function Table(cells, header, footer;
round_digits = 3,
round_mode = :auto,
trailing_zeros = false,
footnotes = [],
postprocess = [],
rowgaps = Pair{Int,Float64}[],
colgaps = Pair{Int,Float64}[],
linebreak_footnotes::Bool = true,
)
Table(cells, header, footer, footnotes, rowgaps, colgaps, postprocess, round_digits, round_mode, trailing_zeros, linebreak_footnotes)
end
"""
function Table(cells;
header = nothing,
footer = nothing,
round_digits = 3,
round_mode = :auto,
trailing_zeros = false,
footnotes = [],
postprocess = [],
rowgaps = Pair{Int,Float64}[],
colgaps = Pair{Int,Float64}[],
linebreak_footnotes = true,
)
Create a `Table` which can be rendered in multiple formats, such as HTML or LaTeX.
## Arguments
- `cells::AbstractMatrix{<:Cell}`: The matrix of `Cell`s that make up the table.
## Keyword arguments
- `header`: The index of the last row of the header, `nothing` if no header is specified.
- `footer`: The index of the first row of the footer, `nothing` if no footer is specified.
- `footnotes`: A vector of objects printed as footnotes that are not derived from `Annotated`
values and therefore don't get labels with counterparts inside the table.
- `round_digits = 3`: Float values will be rounded to this precision before printing.
- `round_mode = :auto`: How the float values are rounded, options are `:auto`, `:digits` or `:sigdigits`.
If `round_mode === nothing`, no rounding will be applied and `round_digits` and `trailing_zeros`
will have no effect.
- `trailing_zeros = false`: Controls if float values keep trailing zeros, for example `4.0` vs `4`.
- `postprocess = []`: A list of post-processors which will be applied left to right to the table before displaying the table.
A post-processor can either work element-wise or on the whole table object. See the `postprocess_table` and
`postprocess_cell` functions for defining custom postprocessors.
- `rowgaps = Pair{Int,Float64}[]`: A list of pairs `index => gap_pt`. For each pair, a visual gap
the size of `gap_pt` is added between the rows `index` and `index+1`.
- `colgaps = Pair{Int,Float64}[]`: A list of pairs `index => gap_pt`. For each pair, a visual gap
the size of `gap_pt` is added between the columns `index` and `index+1`.
- `linebreak_footnotes = true`: If `true`, each footnote and annotation starts on a separate line.
## Round mode
Consider the numbers `0.006789`, `23.4567`, `456.789` or `12345.0`.
Here is how these numbers are formatted with the different available rounding modes:
- `:auto` rounds to `n` significant digits but doesn't zero out additional digits before the comma unlike `:sigdigits`.
For example, `round_digits = 3` would result in `0.00679`, `23.5`, `457.0` or `12345.0`.
Numbers at orders of magnitude >= 6 or <= -5 are displayed in exponential notation as in Julia.
- `:digits` rounds to `n` digits after the comma and shows possibly multiple trailing zeros.
For example, `round_digits = 3` would result in `0.007`, `23.457` or `456.789` or `12345.000`.
Numbers are never shown with exponential notation.
- `:sigdigits` rounds to `n` significant digits and zeros out additional digits before the comma unlike `:auto`.
For example, `round_digits = 3` would result in `0.00679`, `23.5`, `457.0` or `12300.0`.
Numbers at orders of magnitude >= 6 or <= -5 are displayed in exponential notation as in Julia.
"""
Table(cells; header = nothing, footer = nothing, kwargs...) = Table(cells, header, footer; kwargs...)
# non-public-API method to keep old code working in the meantime
function Table(cells::AbstractVector{SpannedCell}, args...; kwargs...)
sz = reduce(cells; init = (0, 0)) do sz, cell
max.(sz, (cell.span[1].stop, cell.span[2].stop))
end
m = fill(Cell(nothing), sz...)
visited = zeros(Bool, sz...)
mergegroup = 0
for cell in cells
is_spanned = length(cell.span[1]) > 1 || length(cell.span[2]) > 1
if is_spanned
mergegroup = mod(mergegroup + 1, 255)
end
for row in cell.span[1]
for col in cell.span[2]
if visited[row, col]
error("Tried to fill cell $row,$col twice. First value was $(m[row, col].value) and second $(cell.value).")
end
visited[row, col] = true
if is_spanned
m[row, col] = Cell(cell.value, CellStyle(cell.style; merge = true, mergegroup))
else
m[row, col] = Cell(cell.value, cell.style)
end
end
end
end
return Table(m, args...; kwargs...)
end
function to_spanned_cells(m::AbstractMatrix{<:Cell})
cells = Vector{SpannedCell}()
sizehint!(cells, length(m))
visited = zeros(Bool, size(m))
nrow, ncol = size(m)
for row in 1:nrow
for col in 1:ncol
visited[row, col] && continue
c = m[row, col]
lastrow = row
for _row in row+1:nrow
if !visited[_row, col] && c.merge && m[_row, col] == c
lastrow = _row
else
break
end
end
lastcol = col
for _col in col+1:ncol
if !visited[row, _col] && c.merge && m[row, _col] == c
lastcol = _col
else
break
end
end
for _row in row+1:lastrow
for _col in col+1:lastcol
_c = m[_row, _col]
if _c != c
error("Cell $c was detected to span over [$(row:lastrow),$(col:lastcol)] but at $_row,$_col the value was $_c. This is not allowed. Cells spanning multiple rows and columns must always span a full rectangle.")
end
end
end
push!(cells, SpannedCell((row:lastrow,col:lastcol), c.value, c.style))
visited[row:lastrow,col:lastcol] .= true
end
end
return cells
end
"""
Multiline(args...)
Create a `Multiline` object which renders each `arg` on a separate line.
A `Multiline` value may only be used as the top-level value of a cell, so
`Cell(Multiline(...))` is allowed but `Cell(Concat(Multiline(...), ...))` is not.
"""
struct Multiline
values::Tuple
Multiline(args...) = new(args)
end
"""
Concat(args...)
Create a `Concat` object which can be used to concatenate the representations
of multiple values in a single table cell while keeping the conversion semantics
of each `arg` in `args` intact.
## Example
```julia
Concat(
"Some text and an ",
Annotated("annotated", "Some annotation"),
" value",
)
# will be rendered as "Some text and an annotated¹ value"
```
"""
struct Concat
args::Tuple
Concat(args...) = new(args)
end
struct Annotated
value
annotation
label
end
struct AutoNumbering end
"""
Annotated(value, annotation; label = AutoNumbering())
Create an `Annotated` object which will be given a footnote annotation
in the `Table` where it is used.
If the `label` keyword is `AutoNumbering()`, annotations will be given number labels
from 1 to N in the order of their appearance. If it is `nothing`, no label will be
shown. Any other `label` will be used directly as the footnote label.
Each unique label must be paired with a unique annotation, but the same
combination can exist multiple times in a single table.
"""
Annotated(value, annotation; label = AutoNumbering()) = Annotated(value, annotation, label)
struct ResolvedAnnotation
value
label
end
# Signals that a given annotation should have no label.
# This is useful for cases where the value itself is the label
# for example when printing NA or - for a missing value.
# You would not want a superscript label for every one of those.
struct NoLabel end
function resolve_annotations(cells::AbstractVector{<:SpannedCell})
annotations = collect_annotations(cells)
k = 1
for (annotation, label) in annotations
if label === AutoNumbering()
annotations[annotation] = k
k += 1
elseif label === nothing
annotations[annotation] = NoLabel()
end
end
labels = Set()
for label in values(annotations)
label === NoLabel() && continue
label ∈ labels && error("Found the same label $(repr(label)) twice with different annotations.")
push!(labels, label)
end
# put all non-integer labels (so all manual labels) behind the auto-incremented labels
# the remaining order will be corresponding to the elements in the list
annotations = OrderedCollections.OrderedDict(sort(collect(annotations), by = x -> !(last(x) isa Int)))
cells = map(cells) do cell
SpannedCell(cell.span, resolve_annotation(cell.value, annotations), cell.style)
end
return cells, annotations
end
function collect_annotations(cells)
annotations = OrderedCollections.OrderedDict()
for cell in cells
collect_annotations!(annotations, cell.value)
end
return annotations
end
collect_annotations!(annotations, x) = nothing
function collect_annotations!(annotations, c::Concat)
for arg in c.args
collect_annotations!(annotations, arg)
end
end
function collect_annotations!(annotations, x::Annotated)
if haskey(annotations, x.annotation)
if annotations[x.annotation] != x.label
error("Found the same annotation $(repr(x.annotation)) with two different labels: $(repr(x.label)) and $(repr(annotations[x.annotation])).")
end
else
annotations[x.annotation] = x.label
end
return
end
resolve_annotation(x, annotations) = x
function resolve_annotation(a::Annotated, annotations)
ResolvedAnnotation(a.value, annotations[a.annotation])
end
function resolve_annotation(c::Concat, annotations)
new_args = map(c.args) do arg
resolve_annotation(arg, annotations)
end
Concat(new_args...)
end
function create_cell_matrix(cells)
nrows = 0
ncols = 0
for cell in cells
nrows = max(nrows, cell.span[1].stop)
ncols = max(ncols, cell.span[2].stop)
end
matrix = zeros(Int, nrows, ncols)
for (i, cell) in enumerate(cells)
enter_cell!(matrix, cell, i)
end
matrix
end
function enter_cell!(matrix, cell, i)
for row in cell.span[1], col in cell.span[2]
v = matrix[row, col]
if v == 0
matrix[row, col] = i
else
error(
"""
Can't place cell $i in [$row, $col] as cell $v is already there.
Value of cell $i: $(cell.value)
"""
)
end
end
end
"""
postprocess_table
Overload `postprocess_table(t::Table, postprocessor::YourPostProcessor)`
to enable using `YourPostProcessor` as a table postprocessor by passing
it to the `postprocess` keyword argument of `Table`.
The function must always return a `Table`.
Use `postprocess_cell` instead if you do not need to modify table attributes
during postprocessing but only individual cells.
"""
function postprocess_table end
"""
postprocess_cell
Overload `postprocess_cell(c::Cell, postprocessor::YourPostProcessor)`
to enable using `YourPostProcessor` as a cell postprocessor by passing
it to the `postprocess` keyword argument of `Table`.
The function must always return a `Cell`. It will be applied on every cell
of the table that is being postprocessed, all other table attributes will
be left unmodified.
Use `postprocess_table` instead if you need to modify table attributes
during postprocessing.
"""
function postprocess_cell end
function postprocess_cell(cell::Cell, any)
error("""
`postprocess_cell` is not implemented for postprocessor type `$(typeof(any))`.
To use this object for postprocessing, either implement `postprocess_table(::Table, ::$(typeof(any)))` or
`postprocess_cell(::Cell, ::$(typeof(any)))` for it.
""")
end
function postprocess_table(ct::Table, any)
new_cl = map(ct.cells) do cell
new_cell = postprocess_cell(cell, any)
if !(new_cell isa Cell)
error("`postprocess_cell` called with `$(any)` returned an object of type `$(typeof(new_cell))` instead of `Cell`.")
end
return new_cell
end
Table(new_cl, ct.header, ct.footer, ct.footnotes, ct.rowgaps, ct.colgaps, [], ct.round_digits, ct.round_mode, ct.trailing_zeros, ct.linebreak_footnotes)
end
function postprocess_table(ct::Table, v::AbstractVector)
for postprocessor in v
ct = postprocess_table(ct, postprocessor)
!(ct isa Table) && error("Postprocessor $postprocessor caused `postprocess_table` not to return a `Table` but a `$(typeof(ct))`")
end
return ct
end
"""
Replace(f, with)
Replace(f; with)
This postprocessor replaces all cell values for which `f(value) === true`
with the value `with`.
If `with <: Function` then the new value will be `with(value)`, instead.
## Examples
```
Replace(x -> x isa String, "A string was here")
Replace(x -> x isa String, uppercase)
Replace(x -> x isa Int && iseven(x), "An even Int was here")
```
"""
struct Replace{F,W}
f::F
with::W
end
Replace(f; with) = Replace(f, with)
"""
ReplaceMissing(; with = Annotated("-", "- No value"; label = NoLabel()))
This postprocessor replaces all `missing` cell values with the value in `with`.
"""
ReplaceMissing(; with = Annotated("-", "- No value"; label = NoLabel())) =
Replace(ismissing, with)
function postprocess_cell(cell::Cell, r::Replace)
matches = r.f(cell.value)
if !(matches isa Bool)
error("`Replace` predicate `$(r.f)` did not return a `Bool` but a value of type `$(typeof(matches))`.")
end
fn(_, with) = with
fn(x, with::Function) = with(x)
value = matches ? fn(cell.value, r.with) : cell.value
return Cell(value, cell.style)
end
struct Rounder
round_digits::Int
round_mode::Symbol
trailing_zeros::Bool
end
struct RoundedFloat
f::Float64
round_digits::Int
round_mode::Symbol
trailing_zeros::Bool
end
apply_rounder(x, r::Rounder) = x
apply_rounder(x::AbstractFloat, r::Rounder) = RoundedFloat(x, r.round_digits, r.round_mode, r.trailing_zeros)
apply_rounder(x::Concat, r::Rounder) = Concat(map(arg -> apply_rounder(arg, r), x.args)...)
apply_rounder(x::Multiline, r::Rounder) = Multiline(map(arg -> apply_rounder(arg, r), x.values)...)
apply_rounder(x::Annotated, r::Rounder) = Annotated(apply_rounder(x.value, r), x.annotation, x.label)
function postprocess_cell(cell::Cell, r::Rounder)
Cell(apply_rounder(cell.value, r), cell.style)
end
struct Superscript
super
end
struct Subscript
sub
end
apply_rounder(x::Superscript, r::Rounder) = Superscript(apply_rounder(x.super, r))
apply_rounder(x::Subscript, r::Rounder) = Subscript(apply_rounder(x.sub, r))
function postprocess(ct::Table)
# every table has float rounding / formatting applied as the very last step
pp = ct.postprocess
if ct.round_mode !== nothing
rounder = Rounder(ct.round_digits, ct.round_mode, ct.trailing_zeros)
pp = [ct.postprocess; rounder]
end
return postprocess_table(ct, pp)
end
| SummaryTables | https://github.com/PumasAI/SummaryTables.jl.git |
|
[
"MIT"
] | 3.0.0 | 6391447698371a09458574a620f02ad91afbec3a | code | 11194 | const DOCX_OUTER_RULE_SIZE = 8 * WriteDocx.eighthpt
const DOCX_INNER_RULE_SIZE = 4 * WriteDocx.eighthpt
const DOCX_ANNOTATION_FONTSIZE = 8 * WriteDocx.pt
"""
to_docx(ct::Table)
Creates a `WriteDocx.Table` node for `Table` `ct` which can be inserted into
a `WriteDocx` document.
"""
function to_docx(ct::Table)
ct = postprocess(ct)
cells = sort(to_spanned_cells(ct.cells), by = x -> (x.span[1].start, x.span[2].start))
cells, annotations = resolve_annotations(cells)
matrix = create_cell_matrix(cells)
running_index = 0
tablerows = WriteDocx.TableRow[]
function full_width_border_row(sz; header = false)
WriteDocx.TableRow(
[WriteDocx.TableCell([WriteDocx.Paragraph([])],
WriteDocx.TableCellProperties(
gridspan = size(matrix, 2),
borders = WriteDocx.TableCellBorders(
bottom = WriteDocx.TableCellBorder(
color = WriteDocx.automatic,
size = sz,
style = WriteDocx.BorderStyle.single,
),
start = WriteDocx.TableCellBorder(color = WriteDocx.automatic, size = sz, style = WriteDocx.BorderStyle.none),
stop = WriteDocx.TableCellBorder(color = WriteDocx.automatic, size = sz, style = WriteDocx.BorderStyle.none),
),
hide_mark = true,
))],
WriteDocx.TableRowProperties(; header)
)
end
push!(tablerows, full_width_border_row(DOCX_OUTER_RULE_SIZE; header = true))
validate_rowgaps(ct.rowgaps, size(matrix, 1))
validate_colgaps(ct.colgaps, size(matrix, 2))
rowgaps = Dict(ct.rowgaps)
colgaps = Dict(ct.colgaps)
for row in 1:size(matrix, 1)
rowcells = WriteDocx.TableCell[]
for col in 1:size(matrix, 2)
index = matrix[row, col]
if index == 0
push!(rowcells, WriteDocx.TableCell([
WriteDocx.Paragraph([
WriteDocx.Run([
WriteDocx.Text("")
])
])
]))
else
cell = cells[index]
is_firstcol = col == cell.span[2].start
if !is_firstcol
continue
end
push!(rowcells, docx_cell(row, col, cell, rowgaps, colgaps))
running_index = index
end
end
push!(tablerows, WriteDocx.TableRow(rowcells, WriteDocx.TableRowProperties(; header = ct.header !== nothing && row <= ct.header)))
if row == ct.header
push!(tablerows, full_width_border_row(DOCX_INNER_RULE_SIZE; header = true))
end
end
push!(tablerows, full_width_border_row(DOCX_OUTER_RULE_SIZE))
separator_element = ct.linebreak_footnotes ? WriteDocx.Break() : WriteDocx.Text(" ")
if !isempty(annotations) || !isempty(ct.footnotes)
elements = []
for (i, (annotation, label)) in enumerate(annotations)
i > 1 && push!(elements, WriteDocx.Run([separator_element]))
if label !== NoLabel()
push!(elements, WriteDocx.Run([WriteDocx.Text(docx_sprint(label)), WriteDocx.Text(" ")],
WriteDocx.RunProperties(valign = WriteDocx.VerticalAlignment.superscript)))
end
push!(elements, WriteDocx.Run([WriteDocx.Text(docx_sprint(annotation))],
WriteDocx.RunProperties(size = DOCX_ANNOTATION_FONTSIZE)))
end
for (i, footnote) in enumerate(ct.footnotes)
(!isempty(annotations) || i > 1) && push!(elements, WriteDocx.Run([separator_element]))
push!(elements, WriteDocx.Run([WriteDocx.Text(docx_sprint(footnote))],
WriteDocx.RunProperties(size = DOCX_ANNOTATION_FONTSIZE)))
end
annotation_row = WriteDocx.TableRow([WriteDocx.TableCell(
[WriteDocx.Paragraph(elements)],
WriteDocx.TableCellProperties(gridspan = size(matrix, 2))
)])
push!(tablerows, annotation_row)
end
tablenode = WriteDocx.Table(tablerows,
WriteDocx.TableProperties(
margins = WriteDocx.TableLevelCellMargins(
# Word already has relatively broadly spaced tables,
# so we keep margins to a minimum. A little bit on the left
# and right is needed to separate the columns from each other
top = WriteDocx.pt * 0,
bottom = WriteDocx.pt * 0,
start = WriteDocx.pt * 1.5,
stop = WriteDocx.pt * 1.5,
),
# this spacing allows adjacent column underlines to be ever-so-slightly spaced apart,
# which is otherwise not possible to achieve in Word (aside from adding empty spacing columns maybe)
spacing = 1 * WriteDocx.pt,
)
)
return tablenode
end
function paragraph_and_run_properties(st::CellStyle)
para = WriteDocx.ParagraphProperties(
justification = st.halign === :center ? WriteDocx.Justification.center :
st.halign === :left ? WriteDocx.Justification.start :
st.halign === :right ? WriteDocx.Justification.stop :
error("Unhandled halign $(st.halign)"),
)
run = WriteDocx.RunProperties(
bold = st.bold ? true : nothing, # TODO: fix bug in WriteDocx?
italic = st.italic ? true : nothing, # TODO: fix bug in WriteDocx?
)
return para, run
end
function hardcoded_styles(class::Nothing)
WriteDocx.ParagraphProperties(), (;)
end
function cell_properties(cell::SpannedCell, row, col, vertical_merge, gridspan, rowgaps, colgaps)
cs = cell.style
pt = WriteDocx.pt
bottom_rowgap = get(rowgaps, cell.span[1].stop, nothing)
if bottom_rowgap === nothing
if cs.border_bottom # borders need a bit of spacing to look ok
bottom_margin = 2.0 * pt
else
bottom_margin = nothing
end
else
bottom_margin = 0.5 * bottom_rowgap * pt
end
top_rowgap = get(rowgaps, cell.span[1].start-1, nothing)
top_margin = top_rowgap === nothing ? nothing : 0.5 * top_rowgap * pt
left_colgap = get(colgaps, cell.span[2].start-1, nothing)
if left_colgap === nothing
if cs.indent_pt != 0
left_margin = cs.indent_pt * pt
else
left_margin = nothing
end
else
if cs.indent_pt != 0
left_margin = (cs.indent_pt + 0.5 * left_colgap) * pt
else
left_margin = 0.5 * left_colgap * pt
end
end
right_colgap = get(colgaps, cell.span[2].stop, nothing)
right_margin = right_colgap === nothing ? nothing : 0.5 * right_colgap * pt
left_end = col == cell.span[2].start
right_end = col == cell.span[2].stop
top_end = row == cell.span[1].start
bottom_end = row == cell.span[1].stop
# spanned cells cannot have margins in the interior
if !right_end
right_margin = nothing
end
if !left_end
left_margin = nothing
end
if !top_end
top_margin = nothing
end
if !bottom_end
bottom_margin = nothing
end
WriteDocx.TableCellProperties(;
margins = WriteDocx.TableCellMargins(
start = left_margin,
bottom = bottom_margin,
top = top_margin,
stop = right_margin,
),
borders = cs.border_bottom ? WriteDocx.TableCellBorders(
bottom = WriteDocx.TableCellBorder(color = WriteDocx.automatic, size = DOCX_INNER_RULE_SIZE, style = WriteDocx.BorderStyle.single),
start = WriteDocx.TableCellBorder(color = WriteDocx.automatic, size = DOCX_INNER_RULE_SIZE, style = WriteDocx.BorderStyle.none), # the left/right none styles keep adjacent cells' bottom borders from merging together
stop = WriteDocx.TableCellBorder(color = WriteDocx.automatic, size = DOCX_INNER_RULE_SIZE, style = WriteDocx.BorderStyle.none),
) : nothing,
valign = cs.valign === :center ? WriteDocx.VerticalAlign.center :
cs.valign === :bottom ? WriteDocx.VerticalAlign.bottom :
cs.valign === :top ? WriteDocx.VerticalAlign.top :
error("Unhandled valign $(cs.valign)"),
vertical_merge,
gridspan,
)
end
function docx_cell(row, col, cell, rowgaps, colgaps)
ncols = length(cell.span[2])
is_firstrow = row == cell.span[1].start
is_firstcol = col == cell.span[2].start
vertical_merge = length(cell.span[1]) == 1 ? nothing : is_firstrow
gridspan = ncols > 1 ? ncols : nothing
paraproperties, runproperties = paragraph_and_run_properties(cell.style)
runs = if is_firstrow && is_firstcol
if cell.value === nothing
WriteDocx.Run[]
else
to_runs(cell.value, runproperties)
end
else
[WriteDocx.Run([WriteDocx.Text("")], runproperties)]
end
cellprops = cell_properties(cell, row, col, vertical_merge, gridspan, rowgaps, colgaps)
WriteDocx.TableCell([
WriteDocx.Paragraph(runs, paraproperties),
], cellprops)
end
to_runs(x, props) = [WriteDocx.Run([WriteDocx.Text(docx_sprint(x))], props)]
function to_runs(c::Concat, props)
runs = WriteDocx.Run[]
for arg in c.args
append!(runs, to_runs(arg, props))
end
return runs
end
# make a new property object where each field that's not nothing in x2 replaces the equivalent
# from x1, however, if the elements are both also property objects, merge those separately
@generated function merge_props(x1::T, x2::T) where {T<:Union{WriteDocx.TableCellProperties,WriteDocx.RunProperties,WriteDocx.ParagraphProperties,WriteDocx.TableCellBorders,WriteDocx.TableCellMargins}}
FN = fieldnames(T)
N = fieldcount(T)
quote
Base.Cartesian.@ncall $N $T i -> begin
f1 = getfield(x1, $FN[i])
f2 = getfield(x2, $FN[i])
merge_props(f1, f2)
end
end
end
merge_props(x, y) = y === nothing ? x : y
function to_runs(s::Superscript, props::WriteDocx.RunProperties)
props = merge_props(props, WriteDocx.RunProperties(valign = WriteDocx.VerticalAlignment.superscript))
return to_runs(s.super, props)
end
function to_runs(s::Subscript, props::WriteDocx.RunProperties)
props = merge_props(props, WriteDocx.RunProperties(valign = WriteDocx.VerticalAlignment.subscript))
return to_runs(s.sub, props)
end
function to_runs(m::Multiline, props)
runs = WriteDocx.Run[]
for (i, val) in enumerate(m.values)
i > 1 && push!(runs, WriteDocx.Run([WriteDocx.Break()])),
append!(runs, to_runs(val, props))
end
return runs
end
function to_runs(r::ResolvedAnnotation, props)
runs = to_runs(r.value, props)
if r.label !== NoLabel()
props = merge_props(props, WriteDocx.RunProperties(valign = WriteDocx.VerticalAlignment.superscript))
push!(runs, WriteDocx.Run([WriteDocx.Text(docx_sprint(r.label))], props))
end
return runs
end
docx_sprint(x) = sprint(x) do io, x
_showas(io, MIME"text"(), x)
end | SummaryTables | https://github.com/PumasAI/SummaryTables.jl.git |
|
[
"MIT"
] | 3.0.0 | 6391447698371a09458574a620f02ad91afbec3a | code | 4359 | function _showas(io::IO, mime::MIME, value)
fn(io::IO, ::MIME"text/html", value::AbstractString) = _str_html_escaped(io, value)
fn(io::IO, ::MIME"text/html", value) = _str_html_escaped(io, repr(value))
fn(io::IO, ::MIME"text/latex", value::AbstractString) = _str_latex_escaped(io, value)
fn(io::IO, ::MIME"text/latex", value) = _str_latex_escaped(io, repr(value))
fn(io::IO, ::MIME"text/typst", value::AbstractString) = _str_typst_escaped(io, value)
fn(io::IO, ::MIME"text/typst", value) = _str_typst_escaped(io, repr(value))
fn(io::IO, ::MIME, value) = print(io, value)
return showable(mime, value) ? show(io, mime, value) : fn(io, mime, value)
end
function _showas(io::IO, m::MIME, r::RoundedFloat)
f = r.f
mode = r.round_mode
digits = r.round_digits
s = if mode === :auto
string(auto_round(f, target_digits = digits))
elseif mode === :sigdigits
string(round(f, sigdigits = digits))
elseif mode === :digits
fmt = Printf.Format("%.$(digits)f")
Printf.format(fmt, f)
else
error("Unknown round mode $mode")
end
if !r.trailing_zeros
s = replace(s, r"^(\d+)$|^(\d+)\.0*$|^(\d+\.[1-9]*?)0*$" => s"\1\2\3")
end
_showas(io, m, s)
end
_showas(io::IO, m::MIME, c::CategoricalValue) = _showas(io, m, CategoricalArrays.DataAPI.unwrap(c))
function _showas(io::IO, m::MIME, c::Concat)
for arg in c.args
_showas(io, m, arg)
end
end
format_value(x) = x
"""
auto_round(number; target_digits)
Rounds a floating point number to a target number of digits that are not leading zeros.
For example, with 3 target digits, desirable numbers would be 123.0, 12.3, 1.23,
0.123, 0.0123 etc. Numbers larger than the number of digits are only rounded to the next integer
(compare with `round(1234, sigdigits = 3)` which rounds to `1230.0`).
Numbers are rounded to `target_digits` significant digits when the floored base 10
exponent is -5 and lower or 6 and higher, as these numbers print with `e` notation by default in Julia.
```
auto_round( 1234567, target_digits = 4) = 1.235e6
auto_round( 123456.7, target_digits = 4) = 123457.0
auto_round( 12345.67, target_digits = 4) = 12346.0
auto_round( 1234.567, target_digits = 4) = 1235.0
auto_round( 123.4567, target_digits = 4) = 123.5
auto_round( 12.34567, target_digits = 4) = 12.35
auto_round( 1.234567, target_digits = 4) = 1.235
auto_round( 0.1234567, target_digits = 4) = 0.1235
auto_round( 0.01234567, target_digits = 4) = 0.01235
auto_round( 0.001234567, target_digits = 4) = 0.001235
auto_round( 0.0001234567, target_digits = 4) = 0.0001235
auto_round( 0.00001234567, target_digits = 4) = 1.235e-5
auto_round( 0.000001234567, target_digits = 4) = 1.235e-6
auto_round(0.0000001234567, target_digits = 4) = 1.235e-7
```
"""
function auto_round(number; target_digits::Int)
!isfinite(number) && return number
target_digits < 1 && throw(ArgumentError("target_digits needs to be 1 or more"))
order_of_magnitude = number == 0 ? 0 : log10(abs(number))
oom = floor(Int, order_of_magnitude)
ndigits = max(0, -oom + target_digits - 1)
if -5 < oom < 6
round(number, digits = ndigits)
else
# this relies on Base printing e notation >= 6 and <= -5
round(number, sigdigits = target_digits)
end
end
natural_lt(x::AbstractString, y::AbstractString) = NaturalSort.natural(x, y)
natural_lt(x, y) = x < y
function validate_rowgaps(rowgaps, nrows)
nrows == 1 && !isempty(rowgaps) && error("No row gaps allowed for a table with one row.")
for (m, _) in rowgaps
if m < 1
error("A row gap index of $m is invalid, must be at least 1.")
end
if m >= nrows
error("A row gap index of $m is invalid for a table with $nrows rows. The maximum allowed is $(nrows - 1).")
end
end
end
function validate_colgaps(colgaps, ncols)
ncols == 1 && !isempty(colgaps) && error("No column gaps allowed for a table with one column.")
for (m, _) in colgaps
if m < 1
error("A column gap index of $m is invalid, must be at least 1.")
end
if m >= ncols
error("A column gap index of $m is invalid for a table with $ncols columns. The maximum allowed is $(ncols - 1).")
end
end
end | SummaryTables | https://github.com/PumasAI/SummaryTables.jl.git |
|
[
"MIT"
] | 3.0.0 | 6391447698371a09458574a620f02ad91afbec3a | code | 10224 | Base.show(io::IO, ::MIME"juliavscode/html", ct::Table) = show(io, MIME"text/html"(), ct)
function Base.show(io::IO, ::MIME"text/html", ct::Table)
ct = postprocess(ct)
cells = sort(to_spanned_cells(ct.cells), by = x -> (x.span[1].start, x.span[2].start))
cells, annotations = resolve_annotations(cells)
matrix = create_cell_matrix(cells)
_io = IOBuffer()
# The final table has a hash-based class name so that several different renderings (maybe even across
# SummaryTables.jl versions) don't conflict and influence each other.
hash_placeholder = "<<HASH>>" # should not collide because it's not valid HTML and <> are not allowed otherwise
println(_io, "<table class=\"st-$(hash_placeholder)\">")
print(_io, """
<style>
.st-$(hash_placeholder) {
border: none;
margin: 0 auto;
padding: 0.25rem;
border-collapse: separate;
border-spacing: 0.85em 0.2em;
line-height: 1.2em;
}
.st-$(hash_placeholder) tr td {
vertical-align: top;
padding: 0;
border: none;
}
.st-$(hash_placeholder) br {
line-height: 0em;
margin: 0;
}
.st-$(hash_placeholder) sub {
line-height: 0;
}
.st-$(hash_placeholder) sup {
line-height: 0;
}
</style>
""")
# border-collapse requires a separate row/cell to insert a border, it can't be put on <tfoot>
println(_io, " <tr><td colspan=\"$(size(matrix, 2))\" style=\"border-bottom: 1.5px solid black; padding: 0\"></td></tr>")
validate_rowgaps(ct.rowgaps, size(matrix, 1))
validate_colgaps(ct.colgaps, size(matrix, 2))
rowgaps = Dict(ct.rowgaps)
colgaps = Dict(ct.colgaps)
running_index = 0
for row in 1:size(matrix, 1)
if row == ct.footer
print(_io, " <tfoot>\n")
# border-collapse requires a separate row/cell to insert a border, it can't be put on <tfoot>
print(_io, " <tr><td colspan=\"$(size(matrix, 2))\" style=\"border-bottom:1px solid black;padding:0\"></td></tr>")
end
print(_io, " <tr>\n")
for col in 1:size(matrix, 2)
index = matrix[row, col]
if index > running_index
print(_io, " ")
print_html_cell(_io, cells[index], rowgaps, colgaps)
running_index = index
print(_io, "\n")
elseif index == 0
print(_io, " ")
print_empty_html_cell(_io)
print(_io, "\n")
end
end
print(_io, " </tr>\n")
if row == ct.header
# border-collapse requires a separate row/cell to insert a border, it can't be put on <thead>
print(_io, " <tr><td colspan=\"$(size(matrix, 2))\" style=\"border-bottom:1px solid black;padding:0\"></td></tr>")
end
end
# border-collapse requires a separate row/cell to insert a border, it can't be put on <tfoot>
println(_io, " <tr><td colspan=\"$(size(matrix, 2))\" style=\"border-bottom: 1.5px solid black; padding: 0\"></td></tr>")
if !isempty(annotations) || !isempty(ct.footnotes)
print(_io, " <tr><td colspan=\"$(size(matrix, 2))\" style=\"font-size: 0.8em;\">")
for (i, (annotation, label)) in enumerate(annotations)
if i > 1
if ct.linebreak_footnotes
print(_io, "<br/>")
else
print(_io, " ")
end
end
if label !== NoLabel()
print(_io, "<sup>")
_showas(_io, MIME"text/html"(), label)
print(_io, "</sup> ")
end
_showas(_io, MIME"text/html"(), annotation)
end
for (i, footnote) in enumerate(ct.footnotes)
if !isempty(annotations) || i > 1
if ct.linebreak_footnotes
print(_io, "<br/>")
else
print(_io, " ")
end
end
_showas(_io, MIME"text/html"(), footnote)
end
println(_io, "</td></tr>")
end
print(_io, "</table>")
s = String(take!(_io))
short_hash = first(bytes2hex(SHA.sha256(s)), 8)
s2 = replace(s, hash_placeholder => short_hash)
print(io, s2)
end
function _showas(io::IO, ::MIME"text/html", m::Multiline)
for (i, value) in enumerate(m.values)
i > 1 && print(io, "<br>")
_showas(io, MIME"text/html"(), value)
end
end
function _showas(io::IO, ::MIME"text/html", r::ResolvedAnnotation)
_showas(io, MIME"text/html"(), r.value)
if r.label !== NoLabel()
print(io, "<sup>")
_showas(io, MIME"text/html"(), r.label)
print(io, "</sup>")
end
end
function _showas(io::IO, ::MIME"text/html", s::Superscript)
print(io, "<sup>")
_showas(io, MIME"text/html"(), s.super)
print(io, "</sup>")
end
function _showas(io::IO, ::MIME"text/html", s::Subscript)
print(io, "<sub>")
_showas(io, MIME"text/html"(), s.sub)
print(io, "</sub>")
end
function print_html_cell(io, cell::SpannedCell, rowgaps, colgaps)
print(io, "<td")
nrows, ncols = map(length, cell.span)
if nrows > 1
print(io, " rowspan=\"$nrows\"")
end
if ncols > 1
print(io, " colspan=\"$ncols\"")
end
print(io, " style=\"")
if cell.style.bold
print(io, "font-weight:bold;")
end
if cell.style.italic
print(io, "font-style:italic;")
end
if cell.style.underline
print(io, "text-decoration:underline;")
end
padding_left = get(colgaps, cell.span[2].start-1, nothing)
if cell.style.indent_pt != 0 || padding_left !== nothing
pl = something(padding_left, 0.0) / 2 + cell.style.indent_pt
print(io, "padding-left:$(pl)pt;")
end
padding_right = get(colgaps, cell.span[2].stop, nothing)
if padding_right !== nothing
print(io, "padding-right:$(padding_right/2)pt;")
end
if cell.style.border_bottom
print(io, "border-bottom:1px solid black; ")
end
padding_bottom = get(rowgaps, cell.span[1].stop, nothing)
if padding_bottom !== nothing
print(io, "padding-bottom: $(padding_bottom/2)pt;")
elseif cell.style.border_bottom
print(io, "padding-bottom: 0.25em;") # needed to make border bottoms look less cramped
end
padding_top = get(rowgaps, cell.span[1].start-1, nothing)
if padding_top !== nothing
print(io, "padding-top: $(padding_top/2)pt;")
end
if cell.style.valign ∉ (:top, :center, :bottom)
error("Invalid valign $(repr(cell.style.valign)). Options are :top, :center, :bottom.")
end
if cell.style.valign !== :top
v = cell.style.valign === :center ? "middle" : "bottom"
print(io, "vertical-align:$v;")
end
if cell.style.halign ∉ (:left, :center, :right)
error("Invalid halign $(repr(cell.style.halign)). Options are :left, :center, :right.")
end
print(io, "text-align:$(cell.style.halign);")
print(io, "\">")
if cell.value !== nothing
_showas(io, MIME"text/html"(), cell.value)
end
print(io, "</td>")
return
end
function print_empty_html_cell(io)
print(io, "<td class=\"st-empty\"></td>")
end
function print_html_styles(io, table_styles)
println(io, "<style>")
for (key, dict) in _sorted_dict(table_styles)
println(io, key, " {")
for (subkey, value) in _sorted_dict(dict)
println(io, " ", subkey, ": ", value, ";")
end
println(io, "}")
end
println(io, "</style>")
end
function _sorted_dict(d)
ps = collect(pairs(d))
sort!(ps, by = first)
end
# Escaping functions, copied from PrettyTables, MIT licensed.
function _str_html_escaped(
io::IO,
s::AbstractString,
replace_newline::Bool = false,
escape_html_chars::Bool = true,
)
a = Iterators.Stateful(s)
for c in a
if isascii(c)
c == '\n' ? (replace_newline ? print(io, "<BR>") : print(io, "\\n")) :
c == '&' ? (escape_html_chars ? print(io, "&") : print(io, c)) :
c == '<' ? (escape_html_chars ? print(io, "<") : print(io, c)) :
c == '>' ? (escape_html_chars ? print(io, ">") : print(io, c)) :
c == '"' ? (escape_html_chars ? print(io, """) : print(io, c)) :
c == '\'' ? (escape_html_chars ? print(io, "'") : print(io, c)) :
c == '\0' ? print(io, escape_nul(peek(a))) :
c == '\e' ? print(io, "\\e") :
c == '\\' ? print(io, "\\\\") :
'\a' <= c <= '\r' ? print(io, '\\', "abtnvfr"[Int(c)-6]) :
# c == '%' ? print(io, "\\%") :
isprint(c) ? print(io, c) :
print(io, "\\x", string(UInt32(c), base = 16, pad = 2))
elseif !Base.isoverlong(c) && !Base.ismalformed(c)
isprint(c) ? print(io, c) :
c <= '\x7f' ? print(io, "\\x", string(UInt32(c), base = 16, pad = 2)) :
c <= '\uffff' ? print(io, "\\u", string(UInt32(c), base = 16, pad = Base.need_full_hex(peek(a)) ? 4 : 2)) :
print(io, "\\U", string(UInt32(c), base = 16, pad = Base.need_full_hex(peek(a)) ? 8 : 4))
else # malformed or overlong
u = bswap(reinterpret(UInt32, c))
while true
print(io, "\\x", string(u % UInt8, base = 16, pad = 2))
(u >>= 8) == 0 && break
end
end
end
end
function _str_html_escaped(
s::AbstractString,
replace_newline::Bool = false,
escape_html_chars::Bool = true
)
return sprint(
_str_html_escaped,
s,
replace_newline,
escape_html_chars;
sizehint = lastindex(s)
)
end
| SummaryTables | https://github.com/PumasAI/SummaryTables.jl.git |
|
[
"MIT"
] | 3.0.0 | 6391447698371a09458574a620f02ad91afbec3a | code | 8928 | function Base.show(io::IO, ::MIME"text/latex", ct::Table)
ct = postprocess(ct)
cells = sort(to_spanned_cells(ct.cells), by = x -> (x.span[1].start, x.span[2].start))
cells, annotations = resolve_annotations(cells)
matrix = create_cell_matrix(cells)
validate_rowgaps(ct.rowgaps, size(matrix, 1))
validate_colgaps(ct.colgaps, size(matrix, 2))
rowgaps = Dict(ct.rowgaps)
colgaps = Dict(ct.colgaps)
column_alignments = most_common_column_alignments(cells, matrix)
colspec = let
iob = IOBuffer()
for (icol, al) in enumerate(column_alignments)
char = al === :center ? 'c' :
al === :right ? 'r' :
al === :left ? 'l' : error("Invalid align $al")
print(iob, char)
if haskey(colgaps, icol)
print(iob, "@{\\hskip $(colgaps[icol])pt}")
end
end
String(take!(iob))
end
print(io, """
\\begin{table}[!ht]
\\setlength\\tabcolsep{0pt}
\\centering
\\begin{threeparttable}
\\begin{tabular}{@{\\extracolsep{2ex}}*{$(size(matrix, 2))}{$colspec}}
\\toprule
""")
running_index = 0
bottom_borders = Dict{Int, Vector{UnitRange}}()
for row in axes(matrix, 1)
for col in axes(matrix, 2)
index = matrix[row, col]
column_align = column_alignments[col]
if index == 0
col > 1 && print(io, " & ")
print_empty_latex_cell(io)
else
cell = cells[index]
if cell.style.border_bottom && col == cell.span[2].start
lastrow = cell.span[1].stop
ranges = get!(bottom_borders, lastrow) do
UnitRange[]
end
border_columns = cell.span[2]
push!(ranges, border_columns)
end
halign_char = cell.style.halign === :left ? 'l' :
cell.style.halign === :center ? 'c' :
cell.style.halign === :right ? 'r' :
error("Unknown halign $(cell.style.halign)")
valign_char = cell.style.valign === :top ? 't' :
cell.style.valign === :center ? 'c' :
cell.style.valign === :bottom ? 'b' :
error("Unknown valign $(cell.style.valign)")
nrow = length(cell.span[1])
ncol = length(cell.span[2])
use_multicolumn = ncol > 1 || cell.style.halign !== column_align
if index > running_index
# this is the top-left part of a new cell which can be a single or multicolumn/row cell
col > 1 && print(io, " & ")
if cell.value !== nothing
use_multicolumn && print(io, "\\multicolumn{$ncol}{$halign_char}{")
nrow > 1 && print(io, "\\multirow[$valign_char]{$nrow}{*}{")
print_latex_cell(io, cell)
nrow > 1 && print(io, "}")
use_multicolumn && print(io, "}")
end
running_index = index
elseif col == cell.span[2][begin]
# we need to print additional multicolumn statements in the second to last
# row of a multirow
col > 1 && print(io, " & ")
if ncol > 1
print(io, "\\multicolumn{$ncol}{$halign_char}{}")
end
end
end
end
print(io, " \\\\")
if haskey(rowgaps, row)
print(io, "[$(rowgaps[row])pt]")
end
println(io)
# draw any bottom borders that have been registered to be drawn below this row
if haskey(bottom_borders, row)
for range in bottom_borders[row]
print(io, "\\cmidrule{$(range.start)-$(range.stop)}")
end
print(io, "\n")
end
if row == ct.header
print(io, "\\midrule\n")
end
if row + 1 == ct.footer
print(io, "\\midrule\n")
end
end
print(io, "\\bottomrule\n")
print(io, raw"""
\end{tabular}
""")
if !isempty(annotations) || !isempty(ct.footnotes)
println(io, "\\begin{tablenotes}[flushleft$(ct.linebreak_footnotes ? "" : ",para")]")
println(io, raw"\footnotesize")
for (annotation, label) in annotations
if label !== NoLabel()
print(io, raw"\item[")
_showas(io, MIME"text/latex"(), label)
print(io, "]")
else
print(io, raw"\item[]")
end
_showas(io, MIME"text/latex"(), annotation)
println(io)
end
for footnote in ct.footnotes
print(io, raw"\item[]")
_showas(io, MIME"text/latex"(), footnote)
println(io)
end
println(io, raw"\end{tablenotes}")
end
print(io, raw"""
\end{threeparttable}
\end{table}
""")
# after end{tabular}:
return
end
function most_common_column_alignments(cells, matrix)
column_alignment_counts = StatsBase.countmap((cell.span[2], cell.style.halign) for cell in cells if cell.value !== nothing)
alignments = (:center, :left, :right)
return map(1:size(matrix,2)) do i_col
i_max = argmax(get(column_alignment_counts, (i_col:i_col, al), 0) for al in alignments)
return alignments[i_max]
end
end
function get_class_styles(class, table_styles)
properties = Dict{Symbol, Any}()
if haskey(table_styles, class)
merge!(properties, table_styles[class])
end
return properties
end
print_empty_latex_cell(io) = nothing
function print_latex_cell(io, cell::SpannedCell)
cell.value === nothing && return
st = cell.style
st.indent_pt > 0 && print(io, "\\hspace{$(st.indent_pt)pt}")
st.bold && print(io, "\\textbf{")
st.italic && print(io, "\\textit{")
st.underline && print(io, "\\underline{")
_showas(io, MIME"text/latex"(), cell.value)
st.underline && print(io, "}")
st.italic && print(io, "}")
st.bold && print(io, "}")
return
end
function _showas(io::IO, ::MIME"text/latex", m::Multiline)
print(io, "\\begin{tabular}{@{}c@{}}")
for (i, value) in enumerate(m.values)
i > 1 && print(io, " \\\\ ")
_showas(io, MIME"text/latex"(), value)
end
print(io, "\\end{tabular}")
end
function _showas(io::IO, m::MIME"text/latex", s::Superscript)
print(io, "\\textsuperscript{")
_showas(io, m, s.super)
print(io, "}")
end
function _showas(io::IO, m::MIME"text/latex", s::Subscript)
print(io, "\\textsubscript{")
_showas(io, m, s.sub)
print(io, "}")
end
function _showas(io::IO, ::MIME"text/latex", r::ResolvedAnnotation)
_showas(io, MIME"text/latex"(), r.value)
if r.label !== NoLabel()
print(io, "\\tnote{")
_showas(io, MIME"text/latex"(), r.label)
print(io, "}")
end
end
function _str_latex_escaped(io::IO, s::AbstractString)
escapable_special_chars = raw"&%$#_{}"
a = Iterators.Stateful(s)
for c in a
if c in escapable_special_chars
print(io, '\\', c)
elseif c === '\\'
print(io, "\\textbackslash{}")
elseif c === '~'
print(io, "\\textasciitilde{}")
elseif c === '^'
print(io, "\\textasciicircum{}")
elseif isascii(c)
c == '\0' ? print(io, Base.escape_nul(peek(a))) :
c == '\e' ? print(io, "\\e") :
# c == '\\' ? print(io, "\\\\") :
'\a' <= c <= '\r' ? print(io, '\\', "abtnvfr"[Int(c)-6]) :
c == '%' ? print(io, "\\%") :
isprint(c) ? print(io, c) :
print(io, "\\x", string(UInt32(c), base = 16, pad = 2))
elseif !Base.isoverlong(c) && !Base.ismalformed(c)
isprint(c) ? print(io, c) :
c <= '\x7f' ? print(io, "\\x", string(UInt32(c), base = 16, pad = 2)) :
c <= '\uffff' ? print(io, "\\u", string(UInt32(c), base = 16, pad = Base.need_full_hex(peek(a)) ? 4 : 2)) :
print(io, "\\U", string(UInt32(c), base = 16, pad = Base.need_full_hex(peek(a)) ? 8 : 4))
else # malformed or overlong
u = bswap(reinterpret(UInt32, c))
while true
print(io, "\\x", string(u % UInt8, base = 16, pad = 2))
(u >>= 8) == 0 && break
end
end
end
end
function _str_latex_escaped(s::AbstractString)
return sprint(_str_latex_escaped, s, sizehint=lastindex(s))
end
| SummaryTables | https://github.com/PumasAI/SummaryTables.jl.git |
|
[
"MIT"
] | 3.0.0 | 6391447698371a09458574a620f02ad91afbec3a | code | 35614 | """
Specifies one variable to group over and an associated name for display.
"""
struct Group
symbol::Symbol
name
end
Group(s::Symbol) = Group(s, string(s))
Group(p::Pair{Symbol, <:Any}) = Group(p[1], p[2])
make_groups(v::AbstractVector) = map(Group, v)
make_groups(x) = [Group(x)]
"""
Specifies one function to summarize the raw values of one group with,
and an associated name for display.
"""
struct SummaryAnalysis
func
name
end
SummaryAnalysis(p::Pair{<:Function, <:Any}) = SummaryAnalysis(p[1], p[2])
SummaryAnalysis(f::Function) = SummaryAnalysis(f, string(f))
"""
Stores the index of the grouping variable under which the summaries defined in
`analyses` should be run. An index of `0` means that one summary block is appended
after all columns or rows, an index of `1` means on summary block after each group
from the first grouping key of rows or columns, and so on.
"""
struct Summary
groupindex::Int
analyses::Vector{SummaryAnalysis}
end
function Summary(p::Pair{Symbol, <:Vector}, symbols)
sym = p[1]
summary_index = findfirst(==(sym), symbols)
if summary_index === nothing
error("Summary variable :$(sym) is not a grouping variable.")
end
Summary(summary_index, SummaryAnalysis.(p[2]))
end
function Summary(v::Vector, _)
summary_index = 0
Summary(summary_index, SummaryAnalysis.(v))
end
# The variable that is used to populate the raw-value cells.
struct Variable
symbol::Symbol
name
end
Variable(s::Symbol) = Variable(s, string(s))
Variable(p::Pair{Symbol, <:Any}) = Variable(p[1], p[2])
struct ListingTable
gdf::DataFrames.GroupedDataFrame
variable::Variable
row_keys::Vector{<:Tuple}
col_keys::Vector{<:Tuple}
rows::Vector{Group}
columns::Vector{Group}
rowsummary::Summary
gdf_rowsummary::DataFrames.GroupedDataFrame
colsummary::Summary
gdf_colsummary::DataFrames.GroupedDataFrame
end
struct Pagination{T<:NamedTuple}
options::T
end
Pagination(; kwargs...) = Pagination(NamedTuple(sort(collect(pairs(kwargs)), by = first)))
"""
Page{M}
Represents one page of a `PaginatedTable`.
It has two public fields:
- `table::Table`: A part of the full table, created according to the chosen `Pagination`.
- `metadata::M`: Information about which part of the full table this page contains. This is different for each
table function that takes a `Pagination` argument because each such function may use its own logic
for how to split pages.
"""
struct Page{M}
metadata::M
table::Table
end
function Base.show(io::IO, M::MIME"text/plain", p::Page)
indent = " " ^ get(io, :indent, 0)
i_page = get(io, :i_page, nothing)
print(io, indent, "Page")
i_page !== nothing && print(io, " $i_page")
println(io)
show(IOContext(io, :indent => get(io, :indent, 0) + 2), M, p.metadata)
end
"""
GroupKey
Holds the group column names and values for one group of a dataset.
This struct has only one field:
- `entries::Vector{Pair{Symbol,Any}}`: A vector of `column_name => group_value` pairs.
"""
struct GroupKey
entries::Vector{Pair{Symbol,Any}}
end
GroupKey(g::DataFrames.GroupKey) = GroupKey(collect(pairs(g)))
"""
ListingPageMetadata
Describes which row and column group sections of a full listing table
are included in a given page. There are two fields:
- `rows::Vector{GroupKey}`
- `cols::Vector{GroupKey}`
Each `Vector{GroupKey}` holds all group keys that were relevant for pagination
along that side of the listing table. A vector is empty if the table was not
paginated along that side.
"""
Base.@kwdef struct ListingPageMetadata
rows::Vector{GroupKey} = []
cols::Vector{GroupKey} = []
end
function Base.show(io::IO, M::MIME"text/plain", p::ListingPageMetadata)
indent = " " ^ get(io, :indent, 0)
println(io, indent, "ListingPageMetadata")
print(io, indent, " rows:")
isempty(p.rows) && print(io, " no pagination")
for r in p.rows
print(io, "\n ", indent,)
print(io, "[", join(("$key => $value" for (key, value) in r.entries), ", "), "]")
end
print(io, "\n", indent, " cols:")
isempty(p.cols) && print(io, " no pagination")
for c in p.cols
print(io, "\n ", indent)
print(io, "[", join(("$key => $value" for (key, value) in c.entries), ", "), "]")
end
end
"""
PaginatedTable{M}
The return type for all table functions that take a `Pagination` argument to split the table
into pages according to table-specific pagination rules.
This type only has one field:
- `pages::Vector{Page{M}}`: Each `Page` holds a table and metadata of type `M` which depends on the table function that creates the `PaginatedTable`.
To get the table of page 2, for a `PaginatedTable` stored in variable `p`, access `p.pages[2].table`.
"""
struct PaginatedTable{M}
pages::Vector{Page{M}}
end
function Base.show(io::IO, M::MIME"text/plain", p::PaginatedTable)
len = length(p.pages)
print(io, "PaginatedTable with $(len) page$(len == 1 ? "" : "s")")
for (i, page) in enumerate(p.pages)
print(io, "\n")
show(IOContext(io, :indent => 2, :i_page => i), M, page)
end
end
# a basic interactive display of the different pages in the PaginatedTable, which is much
# nicer than just having the textual overview that you get printed out in the REPL
function Base.show(io::IO, M::Union{MIME"text/html",MIME"juliavscode/html"}, p::PaginatedTable)
println(io, "<div>")
println(io, """
<script>
function showPaginatedPage(el, index){
const container = el.parentElement.querySelector('div');
for (var i = 0; i<container.children.length; i++){
container.children[i].style.display = i == index ? 'block' : 'none';
}
}
</script>
""")
for i in 1:length(p.pages)
println(io, """
<button onclick="showPaginatedPage(this, $(i-1))">
Page $i
</button>
""")
end
println(io, "<div>")
for (i, page) in enumerate(p.pages)
println(io, "<div style=\"display:$(i == 1 ? "block" : "none")\">")
println(io, "<h3>Page $i</h3>")
show(io, M, page.table)
println(io, "\n</div>")
end
println(io, "</div>")
println(io, "</div>")
return
end
"""
listingtable(table, variable, [pagination];
rows = [],
cols = [],
summarize_rows = [],
summarize_cols = [],
variable_header = true,
table_kwargs...
)
Create a listing table `Table` from `table` which displays raw values from column `variable`.
## Arguments
- `table`: Data source which must be convertible to a `DataFrames.DataFrame`.
- `variable`: Determines which variable's raw values are shown. Can either be a `Symbol` such as `:ColumnA`, or alternatively a `Pair` where the second element is the display name, such as `:ColumnA => "Column A"`.
- `pagination::Pagination`: If a pagination object is passed, the return type changes to `PaginatedTable`.
The `Pagination` object may be created with keywords `rows` and/or `cols`.
These must be set to `Int`s that determine how many group sections along each side are included in one page.
These group sections are determined by the summary structure, because pagination never splits a listing table
within rows or columns that are being summarized together.
If `summarize_rows` or `summarize_cols` is empty or unset, each group along that side is its own section.
If `summarize_rows` or `summarize_cols` has a group passed via the `column => ...` syntax, the group sections
along that side are determined by `column`. If no such `column` is passed (i.e., the summary
along that side applies to the all groups) there is only one section along that side, which means
that this side cannot be paginated into more than one page.
## Keyword arguments
- `rows = []`: Grouping structure along the rows. Should be a `Vector` where each element is a grouping variable, specified as a `Symbol` such as `:Column1`, or a `Pair`, where the first element is the symbol and the second a display name, such as `:Column1 => "Column 1"`. Specifying multiple grouping variables creates nested groups, with the last variable changing the fastest.
- `cols = []`: Grouping structure along the columns. Follows the same structure as `rows`.
- `summarize_rows = []`: Specifies functions to summarize `variable` with along the rows.
Should be a `Vector`, where each entry is one separate summary.
Each summary can be given as a `Function` such as `mean` or `maximum`, in which case the display name is the function's name.
Alternatively, a display name can be given using the pair syntax, such as `mean => "Average"`.
By default, one summary is computed over all groups.
You can also pass `Symbol => [...]` where `Symbol` is a grouping column, to compute one summary for each level of that group.
- `summarize_cols = []`: Specifies functions to summarize `variable` with along the columns. Follows the same structure as `summarize_rows`.
- `variable_header = true`: Controls if the cell with the name of the summarized `variable` is shown.
- `sort = true`: Sort the input table before grouping. Pre-sort as desired and set to `false` when you want to maintain a specific group order or are using non-sortable objects as group keys.
All other keywords are forwarded to the `Table` constructor, refer to its docstring for details.
## Example
```
using Statistics
tbl = [
:Apples => [1, 2, 3, 4, 5, 6, 7, 8],
:Batch => [1, 1, 1, 1, 2, 2, 2, 2],
:Checked => [true, false, true, false, true, false, true, false],
:Delivery => ['a', 'a', 'b', 'b', 'a', 'a', 'b', 'b'],
]
listingtable(
tbl,
:Apples => "Number of apples",
rows = [:Batch, :Checked => "Checked for spots"],
cols = [:Delivery],
summarize_cols = [sum => "total"],
summarize_rows = :Batch => [mean => "average", sum]
)
```
"""
function listingtable(table, variable, pagination::Union{Nothing,Pagination} = nothing; rows = [],
cols = [],
summarize_rows = [],
summarize_cols = [],
variable_header = true,
sort = true,
table_kwargs...)
df = DataFrames.DataFrame(table)
var = Variable(variable)
rowgroups = make_groups(rows)
colgroups = make_groups(cols)
rowsymbols = [r.symbol for r in rowgroups]
rowsummary = Summary(summarize_rows, rowsymbols)
colsymbols = [c.symbol for c in colgroups]
colsummary = Summary(summarize_cols, colsymbols)
if pagination === nothing
return _listingtable(df, var, rowgroups, colgroups, rowsummary, colsummary; variable_header, sort, table_kwargs...)
else
sd = setdiff(keys(pagination.options), [:rows, :cols])
if !isempty(sd)
throw(ArgumentError("`listingtable` only accepts `rows` and `cols` as pagination arguments. Found $(join(sd, ", ", " and "))"))
end
paginate_cols = get(pagination.options, :cols, nothing)
paginate_rows = get(pagination.options, :rows, nothing)
paginated_colgroupers = colsymbols[1:(isempty(colsummary.analyses) ? end : colsummary.groupindex)]
paginated_rowgroupers = rowsymbols[1:(isempty(rowsummary.analyses) ? end : rowsummary.groupindex)]
pages = Page{ListingPageMetadata}[]
rowgrouped = DataFrames.groupby(df, paginated_rowgroupers; sort)
rowgroup_indices = 1:length(rowgrouped)
for r_indices in Iterators.partition(rowgroup_indices, something(paginate_rows, length(rowgroup_indices)))
colgrouped = DataFrames.groupby(DataFrame(rowgrouped[r_indices]), paginated_colgroupers; sort)
colgroup_indices = 1:length(colgrouped)
for c_indices in Iterators.partition(colgroup_indices, something(paginate_cols, length(colgroup_indices)))
t = _listingtable(DataFrame(colgrouped[c_indices]), var, rowgroups, colgroups, rowsummary, colsummary; variable_header, sort, table_kwargs...)
push!(pages, Page(
ListingPageMetadata(
cols = paginate_cols === nothing ? GroupKey[] : GroupKey.(keys(colgrouped)[c_indices]),
rows = paginate_rows === nothing ? GroupKey[] : GroupKey.(keys(rowgrouped)[r_indices]),
),
t,
))
end
end
return PaginatedTable(pages)
end
end
struct TooManyRowsError <: Exception
msg::String
end
Base.show(io::IO, t::TooManyRowsError) = print(io, "TooManyRowsError: ", t.msg)
struct SortingError <: Exception end
function Base.showerror(io::IO, ::SortingError)
print(io, """
Sorting the input dataframe for grouping failed.
This can happen when a column contains special objects intended for table formatting which are not sortable, for example `Concat`, `Multiline`, `Subscript` or `Superscript`.
Consider pre-sorting your dataframe and retrying with `sort = false`.
Note that group keys will appear in the order they are present in the dataframe, so usually you should sort in the same order that the groups are given to the table function.
""")
end
function _listingtable(
df::DataFrames.DataFrame,
variable::Variable,
rowgroups::Vector{Group},
colgroups::Vector{Group},
rowsummary::Summary,
colsummary::Summary;
variable_header::Bool,
sort::Bool,
celltable_kws...)
rowsymbols = [r.symbol for r in rowgroups]
colsymbols = [c.symbol for c in colgroups]
groups = vcat(rowsymbols, colsymbols)
# remove unneeded columns from the dataframe
used_columns = [variable.symbol; rowsymbols; colsymbols]
if sort && !isempty(groups)
try
df = Base.sort(df, groups, lt = natural_lt)
catch e
throw(SortingError())
end
end
gdf = DataFrames.groupby(df, groups, sort = false)
for group in gdf
if size(group, 1) > 1
nonuniform_columns = filter(names(df, DataFrames.Not(used_columns))) do name
length(Set((getproperty(group, name)))) > 1
end
throw(TooManyRowsError("""
Found a group which has more than one value. This is not allowed, only one value of "$(variable.symbol)" per table cell may exist.
$(repr(DataFrames.select(group, used_columns), context = :limit => true))
Filter your dataset or use additional row or column grouping factors.
$(!isempty(nonuniform_columns) ?
"The following columns in the dataset are not uniform in this group and could potentially be used: $nonuniform_columns." :
"There are no other non-uniform columns in this dataset.")
"""))
end
end
rowsummary_groups = vcat(rowsymbols[1:rowsummary.groupindex], colsymbols)
gdf_rowsummary = DataFrames.combine(
DataFrames.groupby(df, rowsummary_groups),
[variable.symbol => a.func => "____$i" for (i, a) in enumerate(rowsummary.analyses)]...,
ungroup = false
)
colsummary_groups = vcat(rowsymbols, colsymbols[1:colsummary.groupindex])
gdf_colsummary = DataFrames.combine(
DataFrames.groupby(df, colsummary_groups),
[variable.symbol => a.func => "____$i" for (i, a) in enumerate(colsummary.analyses)]...,
ungroup = false
)
gdf_rows = DataFrames.groupby(df, rowsymbols, sort = sort ? (; lt = natural_lt) : false)
row_keys = Tuple.(keys(gdf_rows))
gdf_cols = DataFrames.groupby(df, colsymbols, sort = sort ? (; lt = natural_lt) : false)
col_keys = Tuple.(keys(gdf_cols))
lt = ListingTable(
gdf,
variable,
row_keys,
col_keys,
rowgroups,
colgroups,
rowsummary,
gdf_rowsummary,
colsummary,
gdf_colsummary,
)
cl, i_header, rowgap_indices = get_cells(lt; variable_header)
Table(cl, i_header, nothing; rowgaps = rowgap_indices .=> DEFAULT_ROWGAP, celltable_kws...)
end
function get_cells(l::ListingTable; variable_header::Bool)
cells = SpannedCell[]
row_summaryindex = l.rowsummary.groupindex
col_summaryindex = l.colsummary.groupindex
rowparts = partition(l.row_keys, by = x -> x[1:row_summaryindex])
colparts = partition(l.col_keys, by = x -> x[1:col_summaryindex])
lengths_rowparts = map(length, rowparts)
cumsum_lengths_rowparts = cumsum(lengths_rowparts)
n_row_summaries = length(l.rowsummary.analyses)
lengths_colparts = map(length, colparts)
cumsum_lengths_colparts = cumsum(lengths_colparts)
n_col_summaries = length(l.colsummary.analyses)
n_rowgroups = length(l.rows)
n_colgroups = length(l.columns)
colheader_offset = 2 * n_colgroups + (variable_header ? 1 : 0)
rowheader_offset = n_rowgroups
rowgap_indices = Int[]
# group headers for row groups
for (i_rowgroup, rowgroup) in enumerate(l.rows)
cell = SpannedCell(colheader_offset, i_rowgroup, rowgroup.name, listingtable_row_header())
push!(cells, cell)
end
for (i_colpart, colpart) in enumerate(colparts)
coloffset = rowheader_offset +
(i_colpart == 1 ? 0 : cumsum_lengths_colparts[i_colpart-1]) +
(i_colpart-1) * n_col_summaries
colrange = coloffset .+ (1:length(colpart))
# variable headers on top of each column part
if variable_header
cell = SpannedCell(colheader_offset, colrange, l.variable.name, listingtable_variable_header())
push!(cells, cell)
end
values_spans = nested_run_length_encodings(colpart)
all_spanranges = [spanranges(spans) for (values, spans) in values_spans]
# column headers on top of each column part
for i_colgroupkey in 1:n_colgroups
headerspanranges = i_colgroupkey == 1 ? [1:length(colpart)] : all_spanranges[i_colgroupkey-1]
for headerspanrange in headerspanranges
header_offset_range = headerspanrange .+ coloffset
class = length(headerspanrange) > 1 ? listingtable_column_header_spanned() : listingtable_column_header()
cell = SpannedCell(i_colgroupkey * 2 - 1, header_offset_range, l.columns[i_colgroupkey].name, class)
push!(cells, cell)
end
values, _ = values_spans[i_colgroupkey]
ranges = all_spanranges[i_colgroupkey]
for (value, range) in zip(values, ranges)
label_offset_range = range .+ coloffset
cell = SpannedCell(i_colgroupkey * 2, label_offset_range, format_value(value), listingtable_column_header_key())
push!(cells, cell)
end
end
# column analysis headers after each column part
for (i_colsumm, summ_ana) in enumerate(l.colsummary.analyses)
summ_coloffset = coloffset + length(colpart)
push!(cells, SpannedCell(
colheader_offset,
summ_coloffset + i_colsumm,
summ_ana.name,
listingtable_column_analysis_header()
))
end
end
for (i_rowpart, rowpart) in enumerate(rowparts)
rowgroupoffset = i_rowpart == 1 ? 0 : cumsum_lengths_rowparts[i_rowpart-1]
rowsummoffset = (i_rowpart - 1) * n_row_summaries
rowoffset = rowgroupoffset + rowsummoffset + colheader_offset
all_rowspans = nested_run_length_encodings(rowpart)
# row groups to the left of each row part
for i_rowgroupkey in 1:n_rowgroups
values, spans = all_rowspans[i_rowgroupkey]
ranges = spanranges(spans)
for (value, range) in zip(values, ranges)
offset_range = range .+ rowoffset
cell = SpannedCell(offset_range, i_rowgroupkey, format_value(value), listingtable_row_key())
push!(cells, cell)
end
end
summ_rowoffset = rowoffset + length(rowpart)
if !isempty(l.rowsummary.analyses)
push!(rowgap_indices, summ_rowoffset)
if i_rowpart < length(rowparts)
push!(rowgap_indices, summ_rowoffset + length(l.rowsummary.analyses))
end
end
# row analysis headers below each row part
for (i_rowsumm, summ_ana) in enumerate(l.rowsummary.analyses)
push!(cells, SpannedCell(
summ_rowoffset + i_rowsumm,
n_rowgroups,
summ_ana.name,
listingtable_row_analysis_header()
))
end
# this loop goes over each block of rowparts x colparts
for (i_colpart, colpart) in enumerate(colparts)
colgroupoffset = i_colpart == 1 ? 0 : cumsum_lengths_colparts[i_colpart-1]
colsummoffset = (i_colpart - 1) * n_col_summaries
coloffset = colgroupoffset + colsummoffset + rowheader_offset
# populate raw value cells for the current block
for (i_row, rowkey) in enumerate(rowpart)
for (i_col, colkey) in enumerate(colpart)
fullkey = (rowkey..., colkey...)
data = get(l.gdf, fullkey, nothing)
if data === nothing
value = ""
else
value = only(getproperty(data, l.variable.symbol))
end
row = rowoffset + i_row
col = coloffset + i_col
cell = SpannedCell(row, col, format_value(value), listingtable_body())
push!(cells, cell)
end
end
# populate row analysis cells for the current block
for i_rowsumm in eachindex(l.rowsummary.analyses)
summ_rowoffset = rowoffset + length(rowpart)
for (i_col, colkey) in enumerate(colpart)
partial_rowkey = first(rowpart)[1:row_summaryindex]
summkey = (partial_rowkey..., colkey...)
datacol_index = length(summkey) + i_rowsumm
data = get(l.gdf_rowsummary, summkey, nothing)
if data === nothing
value = ""
else
value = only(data[!, datacol_index])
end
cell = SpannedCell(
summ_rowoffset + i_rowsumm,
coloffset + i_col,
format_value(value),
listingtable_row_analysis_body()
)
push!(cells, cell)
end
end
# populate column analysis cells for the current block
for i_colsumm in eachindex(l.colsummary.analyses)
summ_coloffset = coloffset + length(colpart)
for (i_row, rowkey) in enumerate(rowpart)
partial_colkey = first(colpart)[1:col_summaryindex]
summkey = (rowkey..., partial_colkey...)
datacol_index = length(summkey) + i_colsumm
data = get(l.gdf_colsummary, summkey, nothing)
if data === nothing
value = ""
else
value = only(data[!, datacol_index])
end
cell = SpannedCell(
rowoffset + i_row,
summ_coloffset + i_colsumm,
format_value(value),
listingtable_column_analysis_body()
)
push!(cells, cell)
end
end
end
end
cells, colheader_offset, rowgap_indices
end
listingtable_row_header() = CellStyle(halign = :left, bold = true)
listingtable_variable_header() = CellStyle(bold = true)
listingtable_row_key() = CellStyle(halign = :left)
listingtable_body() = CellStyle()
listingtable_column_header() = CellStyle(bold = true)
listingtable_column_header_spanned() = CellStyle(border_bottom = true, bold = true)
listingtable_column_header_key() = CellStyle()
listingtable_row_analysis_header() = CellStyle(halign = :left, bold = true)
listingtable_row_analysis_body() = CellStyle()
listingtable_column_analysis_header() = CellStyle(halign = :right, bold = true)
listingtable_column_analysis_body() = CellStyle(halign = :right)
function nested_run_length_encodings(gdf_keys)
n_entries = length(gdf_keys)
n_levels = length(first(gdf_keys))
spans = Tuple{Vector{Any},Vector{Int}}[]
for level in 1:n_levels
keys = Any[]
lengths = Int[]
prev_key = first(gdf_keys)[level]
current_length = 1
starts_of_previous_level = level == 1 ? Int[] : cumsum([1; spans[level-1][2][1:end-1]])
for (i, entrykeys) in zip(2:length(gdf_keys), gdf_keys[2:end])
key = entrykeys[level]
is_previous_level_start = i in starts_of_previous_level
if !is_previous_level_start && key == prev_key
current_length += 1
else
push!(lengths, current_length)
push!(keys, prev_key)
current_length = 1
end
prev_key = key
end
push!(lengths, current_length)
push!(keys, prev_key)
push!(spans, (keys, lengths))
end
return spans
end
function spanranges(spans)
start = 1
stop = 0
map(spans) do span
stop = start + span - 1
range = start:stop
start += span
return range
end
end
# split a collection into parts where each element in a part `isequal` for `by(element)`
function partition(collection; by)
parts = Vector{eltype(collection)}[]
part = eltype(collection)[]
for element in collection
if isempty(part)
push!(part, element)
else
if isequal(by(last(part)), by(element))
push!(part, element)
else
push!(parts, part)
part = eltype(collection)[element]
end
end
end
push!(parts, part)
parts
end
struct SummaryTable
gdf::DataFrames.GroupedDataFrame
variable::Variable
row_keys::Vector{<:Tuple}
col_keys::Vector{<:Tuple}
rows::Vector{Group}
columns::Vector{Group}
summary::Summary
gdf_summary::DataFrames.GroupedDataFrame
end
"""
summarytable(table, variable;
rows = [],
cols = [],
summary = [],
variable_header = true,
celltable_kws...
)
Create a summary table `Table` from `table`, which summarizes values from column `variable`.
## Arguments
- `table`: Data source which must be convertible to a `DataFrames.DataFrame`.
- `variable`: Determines which variable from `table` is summarized. Can either be a `Symbol` such as `:ColumnA`, or alternatively a `Pair` where the second element is the display name, such as `:ColumnA => "Column A"`.
## Keyword arguments
- `rows = []`: Grouping structure along the rows. Should be a `Vector` where each element is a grouping variable, specified as a `Symbol` such as `:Column1`, or a `Pair`, where the first element is the symbol and the second a display name, such as `:Column1 => "Column 1"`. Specifying multiple grouping variables creates nested groups, with the last variable changing the fastest.
- `cols = []`: Grouping structure along the columns. Follows the same structure as `rows`.
- `summary = []`: Specifies functions to summarize `variable` with.
Should be a `Vector`, where each entry is one separate summary.
Each summary can be given as a `Function` such as `mean` or `maximum`, in which case the display name is the function's name.
Alternatively, a display name can be given using the pair syntax, such as `mean => "Average"`.
By default, one summary is computed over all groups.
You can also pass `Symbol => [...]` where `Symbol` is a grouping column, to compute one summary for each level of that group.
- `variable_header = true`: Controls if the cell with the name of the summarized `variable` is shown.
- `sort = true`: Sort the input table before grouping. Pre-sort as desired and set to `false` when you want to maintain a specific group order or are using non-sortable objects as group keys.
All other keywords are forwarded to the `Table` constructor, refer to its docstring for details.
## Example
```
using Statistics
tbl = [
:Apples => [1, 2, 3, 4, 5, 6, 7, 8],
:Batch => [1, 1, 1, 1, 2, 2, 2, 2],
:Delivery => ['a', 'a', 'b', 'b', 'a', 'a', 'b', 'b'],
]
summarytable(
tbl,
:Apples => "Number of apples",
rows = [:Batch],
cols = [:Delivery],
summary = [length => "N", mean => "average", sum]
)
```
"""
function summarytable(
table, variable;
rows = [],
cols = [],
summary = [],
variable_header = true,
celltable_kws...
)
df = DataFrames.DataFrame(table)
var = Variable(variable)
rowgroups = make_groups(rows)
colgroups = make_groups(cols)
rowsymbols = [r.symbol for r in rowgroups]
_summary = Summary(summary, rowsymbols)
if isempty(_summary.analyses)
throw(ArgumentError("No summary analyses defined."))
end
_summarytable(df, var, rowgroups, colgroups, _summary; variable_header, celltable_kws...)
end
function _summarytable(
df::DataFrames.DataFrame,
variable::Variable,
rowgroups::Vector{Group},
colgroups::Vector{Group},
summary::Summary;
variable_header::Bool,
sort = true,
celltable_kws...)
rowsymbols = [r.symbol for r in rowgroups]
colsymbols = [c.symbol for c in colgroups]
groups = vcat(rowsymbols, colsymbols)
# remove unneeded columns from the dataframe
used_columns = [variable.symbol; rowsymbols; colsymbols]
_df = DataFrames.select(df, used_columns)
if !isempty(groups) && sort
try
Base.sort!(_df, groups, lt = natural_lt)
catch e
throw(SortingError())
end
end
gdf = DataFrames.groupby(_df, groups, sort = false)
gdf_summary = DataFrames.combine(
DataFrames.groupby(_df, groups),
[variable.symbol => a.func => "____$i" for (i, a) in enumerate(summary.analyses)]...,
ungroup = false
)
gdf_rows = DataFrames.groupby(_df, rowsymbols; sort = sort ? (; lt = natural_lt) : false)
row_keys = Tuple.(keys(gdf_rows))
gdf_cols = DataFrames.groupby(_df, colsymbols; sort = sort ? (; lt = natural_lt) : false)
col_keys = Tuple.(keys(gdf_cols))
st = SummaryTable(
gdf,
variable,
row_keys,
col_keys,
rowgroups,
colgroups,
summary,
gdf_summary,
)
cl, i_header = get_cells(st; variable_header)
Table(cl, i_header, nothing; celltable_kws...)
end
function get_cells(l::SummaryTable; variable_header::Bool)
cells = SpannedCell[]
n_row_summaries = length(l.summary.analyses)
n_rowgroups = length(l.rows)
n_colgroups = length(l.columns)
colheader_offset = if n_colgroups == 0 && n_rowgroups > 0
1
else
2 * n_colgroups + (variable_header ? 1 : 0)
end
rowheader_offset = n_rowgroups + 1
# group headers for row groups
for (i_rowgroup, rowgroup) in enumerate(l.rows)
cell = SpannedCell(colheader_offset, i_rowgroup, rowgroup.name, summarytable_row_header())
push!(cells, cell)
end
# variable headers on top of each column part
if variable_header
colrange = rowheader_offset .+ (1:length(l.col_keys))
cell = SpannedCell(colheader_offset, colrange, l.variable.name, summarytable_column_header())
push!(cells, cell)
end
values_spans_cols = nested_run_length_encodings(l.col_keys)
all_spanranges_cols = [spanranges(spans) for (values, spans) in values_spans_cols]
# column headers on top of each column part
for i_colgroupkey in 1:n_colgroups
headerspanranges = i_colgroupkey == 1 ? [1:length(l.col_keys)] : all_spanranges_cols[i_colgroupkey-1]
for headerspanrange in headerspanranges
header_offset_range = headerspanrange .+ rowheader_offset
class = length(headerspanrange) > 1 ? summarytable_column_header_spanned() : summarytable_column_header()
cell = SpannedCell(i_colgroupkey * 2 - 1, header_offset_range, l.columns[i_colgroupkey].name, class)
push!(cells, cell)
end
values, _ = values_spans_cols[i_colgroupkey]
ranges = all_spanranges_cols[i_colgroupkey]
for (value, range) in zip(values, ranges)
label_offset_range = range .+ rowheader_offset
cell = SpannedCell(i_colgroupkey * 2, label_offset_range, format_value(value), summarytable_body())
push!(cells, cell)
end
end
values_spans_rows = nested_run_length_encodings(l.row_keys)
all_spanranges_rows = [spanranges(spans) for (values, spans) in values_spans_rows]
for (i_rowkey, rowkey) in enumerate(l.row_keys)
rowgroupoffset = (i_rowkey - 1) * n_row_summaries
rowoffset = rowgroupoffset + colheader_offset
# row group keys to the left
for i_rowgroupkey in 1:n_rowgroups
# show key only once per span
spanranges = all_spanranges_rows[i_rowgroupkey]
ith_span = findfirst(spanrange -> first(spanrange) == i_rowkey, spanranges)
if ith_span === nothing
continue
end
spanrange = spanranges[ith_span]
range = 1:n_row_summaries * length(spanrange)
offset_range = range .+ rowoffset
key = rowkey[i_rowgroupkey]
cell = SpannedCell(offset_range, i_rowgroupkey, format_value(key), summarytable_row_key())
push!(cells, cell)
end
# row analysis headers to the right of each row key
for (i_rowsumm, summ_ana) in enumerate(l.summary.analyses)
summ_rowoffset = rowoffset + 1
push!(cells, SpannedCell(
summ_rowoffset + i_rowsumm - 1,
n_rowgroups + 1,
summ_ana.name,
summarytable_analysis_header()
))
end
# populate row analysis cells
for i_rowsumm in eachindex(l.summary.analyses)
summ_rowoffset = rowoffset
for (i_col, colkey) in enumerate(l.col_keys)
summkey = (rowkey..., colkey...)
datacol_index = length(summkey) + i_rowsumm
data = get(l.gdf_summary, summkey, nothing)
if data === nothing
value = ""
else
value = only(data[!, datacol_index])
end
cell = SpannedCell(
summ_rowoffset + i_rowsumm,
rowheader_offset + i_col,
format_value(value),
summarytable_body()
)
push!(cells, cell)
end
end
end
cells, colheader_offset
end
summarytable_column_header() = CellStyle(halign = :center, bold = true)
summarytable_column_header_spanned() = CellStyle(halign = :center, bold = true, border_bottom = true)
summarytable_analysis_header() = CellStyle(halign = :left, bold = true)
summarytable_body() = CellStyle()
summarytable_row_header() = CellStyle(halign = :left, bold = true)
summarytable_row_key() = CellStyle(halign = :left)
| SummaryTables | https://github.com/PumasAI/SummaryTables.jl.git |
|
[
"MIT"
] | 3.0.0 | 6391447698371a09458574a620f02ad91afbec3a | code | 19369 | default_tests() = (
categorical = HypothesisTests.ChisqTest,
nonnormal = HypothesisTests.KruskalWallisTest,
minmax = HypothesisTests.UnequalVarianceTTest,
normal = HypothesisTests.UnequalVarianceTTest,
)
hformatter(num::Real) = num < 0.001 ? "<0.001" : string(round(num; digits = 3))
hformatter((a, b)::Tuple{<:Real,<:Real}; digits = 3) = "($(round(a; digits)), $(round(b; digits)))"
hformatter(::Tuple{Nothing,Nothing}) = ""
hformatter(::Vector) = "" # TODO
hformatter(other) = ""
## Categorical:
function htester(data::Matrix, test, combine)
data = identity.(data)
try
if size(data) == (2, 2)
a, c, b, d = data
test = HypothesisTests.FisherExactTest
return test, test(a, b, c, d)
else
return test, test(data)
end
catch _
return nothing, nothing
end
end
## Continuous:
function htester(data::Vector, test::Type{HypothesisTests.KruskalWallisTest}, combine)
try
return test, test(data...)
catch _
return nothing, nothing
end
end
function htester(data::Vector, test, combine)
try
if length(data) > 2
# test each unique pair of vectors from data
results = [test(a, b) for (i, a) in pairs(data) for b in data[i+1:end]]
pvalues = HypothesisTests.pvalue.(results)
return test, MultipleTesting.combine(pvalues, combine)
else
return test, test(data...)
end
catch _
return nothing, nothing
end
end
## P-Values:
get_pvalue(n::Real) = n
get_pvalue(::Nothing) = nothing
get_pvalue(result) = HypothesisTests.pvalue(result)
## CI:
function get_confint(result)
try
return HypothesisTests.confint(result)
catch _
return nothing, nothing
end
end
get_confint(::Real) = (nothing, nothing)
get_confint(::Nothing) = (nothing, nothing)
## Test name:
get_testname(test) = string(nameof(test))
get_testname(::Nothing) = ""
##
struct Analysis
variable::Symbol
func::Function
name
end
function Analysis(s::Symbol, df::DataFrames.DataFrame)
Analysis(s, default_analysis(df[!, s]), string(s))
end
function Analysis(p::Pair{Symbol, <:Any}, df::DataFrames.DataFrame)
sym, rest = p
Analysis(sym, rest, df)
end
function Analysis(sym::Symbol, name, df::DataFrames.DataFrame)
Analysis(sym, default_analysis(df[!, sym]), name)
end
function Analysis(sym::Symbol, funcvec::AbstractVector, df::DataFrames.DataFrame)
Analysis(sym, to_func(funcvec), df)
end
function Analysis(sym::Symbol, f::Function, df::DataFrames.DataFrame)
Analysis(sym, f, string(sym))
end
function Analysis(s::Symbol, f::Function, name, df::DataFrames.DataFrame)
Analysis(s, f, name)
end
function Analysis(sym::Symbol, p::Pair, df::DataFrames.DataFrame)
funcs, name = p
Analysis(sym, funcs, name, df)
end
make_analyses(v::AbstractVector, df::DataFrame) = map(x -> Analysis(x, df), v)
make_analyses(x, df::DataFrame) = [Analysis(x, df)]
to_func(f::Function) = f
function to_func(v::AbstractVector)
return function(col)
result_name_pairs = map(v) do el
f, name = func_and_name(el)
f(col) => name
end
Tuple(result_name_pairs)
end
end
func_and_name(p::Pair{<:Function, <:Any}) = p
func_and_name(f::Function) = f => string(f)
not_computable_annotation() = Annotated("NC", "NC - Not computable", label = nothing)
function guard_statistic(stat)
function (vec)
sm = skipmissing(vec)
if isempty(sm)
missing
else
stat(sm)
end
end
end
function default_analysis(v::AbstractVector{<:Union{Missing, <:Real}})
anymissing = any(ismissing, v)
function (col)
allmissing = isempty(skipmissing(col))
_mean = guard_statistic(mean)(col)
_sd = guard_statistic(std)(col)
mean_sd = if allmissing
not_computable_annotation()
else
Concat(_mean, " (", _sd, ")")
end
_median = guard_statistic(median)(col)
_min = guard_statistic(minimum)(col)
_max = guard_statistic(maximum)(col)
med_min_max = if allmissing
not_computable_annotation()
else
Concat(_median, " [", _min, ", ", _max, "]")
end
if anymissing
nm = count(ismissing, col)
_mis = Concat(nm, " (", nm / length(col) * 100, "%)")
end
(
mean_sd => "Mean (SD)",
med_min_max => "Median [Min, Max]",
(anymissing ? (_mis => "Missing",) : ())...
)
end
end
default_analysis(c::CategoricalArray) = level_analyses(c)
default_analysis(v::AbstractVector{<:Union{Missing, Bool}}) = level_analyses(v)
# by default we just count levels for all datatypes that are not known
default_analysis(v) = level_analyses(v)
function level_analyses(c)
has_missing = any(ismissing, c) # if there's any missing, we report them for every col in c
function (col)
_levels = levels(c) # levels are computed for the whole column, not per group, so they are always exhaustive
lvls = tuple(_levels...)
cm = StatsBase.countmap(col)
n = length(col)
_entry(n_lvl) = Concat(n_lvl, " (", n_lvl / n * 100, "%)")
entries = map(lvls) do lvl
n_lvl = get(cm, lvl, 0)
s = _entry(n_lvl)
s => lvl
end
if has_missing
n_missing = count(ismissing, col)
entries = (entries..., _entry(n_missing) => "Missing")
end
return entries
end
end
"""
table_one(table, analyses; keywords...)
Construct a "Table 1" which summarises the patient baseline
characteristics from the provided `table` dataset. This table is commonly used
in biomedical research papers.
It can handle both continuous and categorical columns in `table` and summary
statistics and hypothesis testing are able to be customised by the user. Tables
can be stratified by one, or more, variables using the `groupby` keyword.
## Keywords
- `groupby`: Which columns to stratify the dataset with, as a `Vector{Symbol}`.
- `nonnormal`: A vector of column names where hypothesis tests for the `:nonnormal` type are chosen.
- `minmax`: A vector of column names where hypothesis tests for the `:minmax` type are chosen.
- `tests`: A `NamedTuple` of hypothesis test types to use for `categorical`, `nonnormal`, `minmax`, and `normal` variables.
- `combine`: An object from `MultipleTesting` to use when combining p-values.
- `show_total`: Display the total column summary. Default is `true`.
- `group_totals`: A group `Symbol` or vector of symbols specifying for which group levels totals should be added. Any group levels but the topmost can be chosen (the topmost being already handled by the `show_total` option). Default is `Symbol[]`.
- `total_name`: The name for all total columns. Default is `"Total"`.
- `show_n`: Display the number of rows for each group key next to its label.
- `show_pvalues`: Display the `P-Value` column. Default is `false`.
- `show_testnames`: Display the `Test` column. Default is `false`.
- `show_confints`: Display the `CI` column. Default is `false`.
- `sort`: Sort the input table before grouping. Default is `true`. Pre-sort as desired and set to `false` when you want to maintain a specific group order or are using non-sortable objects as group keys.
## Deprecated keywords
- `show_overall`: Use `show_total` instead
All other keywords are forwarded to the `Table` constructor, refer to its docstring for details.
"""
function table_one(
table,
analyses;
groupby = [],
show_total = true,
show_overall = nothing, # deprecated in version 3
group_totals = Symbol[],
total_name = "Total",
show_pvalues = false,
show_tests = true,
show_confints = false,
show_n = false,
compare_groups::Vector = [],
nonnormal = [],
minmax = [],
tests = default_tests(),
combine = MultipleTesting.Fisher(),
sort = true,
celltable_kws...
)
df = DataFrames.DataFrame(table)
groups = make_groups(groupby)
n_groups = length(groups)
if show_overall !== nothing
@warn """`show_overall` has been deprecated, use `show_total` instead. You can change the identifier back from "Total" to "Overall" using the `total_name` keyword argument"""
show_total = show_overall
end
show_total || n_groups > 0 || error("`show_total` can't be false if there are no groups.")
_analyses = make_analyses(analyses, df)
typedict = Dict(map(_analyses) do analysis
type = if getproperty(df, analysis.variable) isa CategoricalVector
:categorical
elseif analysis.variable in nonnormal
:nonnormal
elseif analysis.variable in minmax
:minmax
else
:normal
end
analysis.variable => type
end)
columns = Vector{Cell}[]
groupsymbols = [g.symbol for g in groups]
_group_totals(a::AbstractVector{Symbol}) = collect(a)
_group_totals(s::Symbol) = [s]
group_totals = _group_totals(group_totals)
if !isempty(groupsymbols) && first(groupsymbols) in group_totals
throw(ArgumentError("Cannot show totals for topmost group $(repr(first(groupsymbols))) as it would be equivalent to the `show_total` option. Grouping is $groupsymbols"))
end
other_syms = setdiff(group_totals, groupsymbols)
if !isempty(other_syms)
throw(ArgumentError("Invalid group symbols in `group_totals`: $other_syms. Grouping is $groupsymbols"))
end
if sort && !isempty(groupsymbols)
try
Base.sort!(df, groupsymbols, lt = natural_lt)
catch e
throw(SortingError())
end
end
gdf = DataFrames.groupby(df, groupsymbols, sort = false)
calculate_comparisons = length(gdf) >= 2 && show_pvalues
if calculate_comparisons
compare_groups = [make_testfunction(show_pvalues, show_tests, show_confints, typedict, merge(default_tests(), tests), combine); compare_groups]
end
rows_per_groups = map(1:n_groups) do k
_gdf = DataFrames.groupby(df, groupsymbols[1:k], sort = false)
DataFrames.combine(_gdf, nrow, ungroup = false)
end
funcvector = [a.variable => a.func for a in _analyses]
df_analyses = DataFrames.combine(gdf, funcvector; ungroup = false)
if show_total
df_total = DataFrames.combine(df, funcvector)
end
group_total_indices = Base.sort(map(sym -> findfirst(==(sym), groupsymbols), group_totals))
dfs_group_total = map(group_total_indices) do i
DataFrames.groupby(df, groupsymbols[1:i-1], sort = false)
end
gdfs_group_total = map(dfs_group_total) do _gdf
return DataFrames.combine(_gdf, funcvector, ungroup = false)
end
analysis_labels = map(n_groups+1:n_groups+length(_analyses)) do i_col
col = df_analyses[1][!, i_col]
x = only(col)
if x isa Tuple
map(last, x)
else
error("Expected a tuple")
end
end
n_values_per_analysis = map(length, analysis_labels)
header_offset = n_groups == 0 ? 2 : n_groups * 2 + 1
ana_title_col = Cell[]
for _ in 1:max(1, 2 * n_groups)
push!(ana_title_col, Cell(nothing))
end
for (analysis, labels) in zip(_analyses, analysis_labels)
push!(ana_title_col, Cell(analysis.name, tableone_variable_header()))
for label in labels
push!(ana_title_col, Cell(label, tableone_analysis_name()))
end
end
push!(columns, ana_title_col)
if show_total
total_col = Cell[]
for _ in 1:max(0, 2 * n_groups - 1)
push!(total_col, Cell(nothing))
end
title = if show_n
Multiline(total_name, "(n=$(nrow(df)))")
else
total_name
end
push!(total_col, Cell(title, tableone_column_header()))
for col in eachcol(df_total)
push!(total_col, Cell(nothing))
for result in only(col)
push!(total_col, Cell(result[1]))
end
end
push!(columns, total_col)
end
# value => index dictionaries for each grouping level
mergegroups = map(1:n_groups) do i
Dict(reverse(t) for t in enumerate(unique(key[i] for key in keys(gdf))))
end
if n_groups > 0
for (ikey, (key, ggdf)) in enumerate(pairs(df_analyses))
function group_key_title(igroup)
groupkey = ggdf[1, igroup]
title = if show_n
nrows_gdf = rows_per_groups[igroup]
reduced_key = Tuple(key)[1:igroup]
nrows = only(nrows_gdf[reduced_key].nrow)
Multiline(groupkey, "(n=$nrows)")
else
groupkey
end
end
data_col = Cell[]
if n_groups == 0
push!(data_col, Cell(nothing))
end
for i in 1:n_groups
# we assign merge groups according to the value in the parent group,
# this way cells can never merge across their parent groups
mergegroup = i == 1 ? 0 : mergegroups[i-1][key[i-1]]
push!(data_col, Cell(groups[i].name, tableone_column_header_spanned(); merge = true, mergegroup))
push!(data_col, Cell(group_key_title(i), tableone_column_header_key(); merge = true, mergegroup))
end
for icol in (n_groups+1):ncol(ggdf)
push!(data_col, Cell(nothing))
for result in ggdf[1, icol]
push!(data_col, Cell(result[1]))
end
end
push!(columns, data_col)
# go from smallest to largest group if there are multiple at this border
for ii in length(group_total_indices):-1:1
i_total_group = group_total_indices[ii]
i_parent_group = i_total_group - 1
next_key = length(df_analyses) == ikey ? nothing : keys(df_analyses)[ikey+1]
if next_key === nothing || key[i_parent_group] != next_key[i_parent_group] || ikey == length(df_analyses)
group_total_col = Cell[]
for i in 1:i_total_group
# we assign merge groups according to the value in the parent group,
# this way cells can never merge across their parent groups
mergegroup = i == 1 ? 0 : mergegroups[i-1][key[i-1]]
push!(group_total_col, Cell(groups[i].name, tableone_column_header_spanned(); merge = true, mergegroup))
i < i_total_group && push!(group_total_col, Cell(group_key_title(i), tableone_column_header_key(); merge = true, mergegroup))
end
agg_key = Tuple(key)[1:i_total_group-1]
title = if show_n
Multiline(total_name, "(n=$(nrow(dfs_group_total[ii][agg_key])))")
else
total_name
end
push!(group_total_col, Cell(title))
for _ in 1:(2 * (n_groups-i_total_group))
push!(group_total_col, Cell(nothing))
end
gdf_group_total = gdfs_group_total[ii]
_gdf = gdf_group_total[agg_key]
for icol in i_total_group:ncol(_gdf)
push!(group_total_col, Cell(nothing))
for result in _gdf[1, icol]
push!(group_total_col, Cell(result[1]))
end
end
push!(columns, group_total_col)
end
end
end
end
for comp in compare_groups
# the logic here is much less clean than it could be because of the way
# column names have to be passed via pairs, and it cannot be guaranteed from typing
# that all are compatible, so it has to be runtime checked
values = map(_analyses) do analysis
val = comp(analysis.variable, [getproperty(g, analysis.variable) for g in gdf])
@assert val isa Tuple && all(x -> x isa Pair, val) "A comparison function has to return a tuple of value => name pairs. Function $comp returned $val"
val
end
nvalues = length(first(values))
@assert all(==(nvalues), map(length, values)) "All comparison tuples must have the same length. Found\n$values"
colnames = [map(last, v) for v in values]
unique_colnames = unique(colnames)
@assert length(unique_colnames) == 1 "All column names must be the same, found $colnames"
unique_colnames = only(unique_colnames)
for i_comp in 1:length(unique_colnames)
comp_col = Cell[]
for _ in 1:(2 * n_groups - 1)
push!(comp_col, Cell(nothing))
end
name = unique_colnames[i_comp]
push!(comp_col, Cell(name, tableone_column_header()))
for (j, val) in enumerate(values)
value, _ = val[i_comp]
push!(comp_col, Cell(value, tableone_body()))
for _ in 1:n_values_per_analysis[j]
push!(comp_col, Cell(nothing))
end
end
push!(columns, comp_col)
end
end
cells = reduce(hcat, columns)
Table(cells, header_offset-1, nothing; celltable_kws...)
end
tableone_column_header() = CellStyle(halign = :center, bold = true)
tableone_column_header_spanned() = CellStyle(halign = :center, bold = true, border_bottom = true)
tableone_column_header_key() = CellStyle(; halign = :center)
tableone_variable_header() = CellStyle(bold = true, halign = :left)
tableone_body() = CellStyle()
tableone_analysis_name() = CellStyle(indent_pt = 12, halign = :left)
formatted(f::Function, s::String) = formatted((f), s)
function formatted(fs::Tuple, s::String)
function (col)
values = map(fs) do f
f(col)
end
Printf.format(Printf.Format(s), values...)
end
end
function make_testfunction(show_pvalues::Bool, show_tests::Bool, show_confint::Bool, typedict, testdict, combine)
function testfunction(variable, cols)
cols_nomissing = map(collect ∘ skipmissing, cols)
variabletype = typedict[variable]
test = testdict[variabletype]
if variabletype === :categorical
# concatenate the level counts into a matrix which Chi Square Test needs
matrix = hcat([map(l -> count(==(l), col), levels(col)) for col in cols_nomissing]...)
used_test, result = htester(matrix, test, combine)
else
used_test, result = htester(cols_nomissing, test, combine)
end
testname = get_testname(used_test)
pvalue = hformatter(get_pvalue(result))
confint = hformatter(get_confint(result))
(
(show_pvalues ? (pvalue => "P-Value",) : ())...,
(show_tests ? (testname => "Test",) : ())...,
(show_confint ? (confint => "CI",) : ())...,
)
end
end
| SummaryTables | https://github.com/PumasAI/SummaryTables.jl.git |
|
[
"MIT"
] | 3.0.0 | 6391447698371a09458574a620f02ad91afbec3a | code | 5991 | function Base.show(io::IO, M::MIME"text/typst", ct::Table)
ct = postprocess(ct)
cells = sort(to_spanned_cells(ct.cells), by = x -> (x.span[1].start, x.span[2].start))
cells, annotations = resolve_annotations(cells)
matrix = create_cell_matrix(cells)
column_alignments = most_common_column_alignments(cells, matrix)
validate_rowgaps(ct.rowgaps, size(matrix, 1))
validate_colgaps(ct.colgaps, size(matrix, 2))
rowgaps = Dict(ct.rowgaps)
colgaps = Dict(ct.colgaps)
print(io, """
#table(
rows: $(size(matrix, 1)),
columns: $(size(matrix, 2)),
column-gutter: 0.25em,
align: ($(join(column_alignments, ", "))),
stroke: none,
""")
println(io, " table.hline(y: 0, stroke: 1pt),")
_colspan(n) = n == 1 ? "" : "colspan: $n"
_rowspan(n) = n == 1 ? "" : "rowspan: $n"
function _align(style, icol)
halign = style.halign === column_alignments[icol] ? nothing : typst_halign(style.halign)
valign = style.valign === :top ? nothing : typst_valign(style.valign)
if halign === nothing && valign === nothing
""
elseif halign === nothing
"align: $valign"
elseif valign === nothing
"align: $halign"
else
"align: $halign + $valign"
end
end
running_index = 0
for row in 1:size(matrix, 1)
if row == ct.footer
println(io, " table.hline(y: $(row-1), stroke: 0.75pt),")
end
for col in 1:size(matrix, 2)
index = matrix[row, col]
if index > running_index
cell = cells[index]
if cell.value === nothing
println(io, " [],")
else
options = join(filter(!isempty, [
_rowspan(length(cell.span[1])),
_colspan(length(cell.span[2])),
_align(cell.style, col)
]), ", ")
if isempty(options)
print(io, " [")
else
print(io, " table.cell(", options, ")[")
end
cell.style.bold && print(io, "*")
cell.style.italic && print(io, "_")
cell.style.underline && print(io, "#underline[")
cell.style.indent_pt > 0 && print(io, "#h($(cell.style.indent_pt)pt)")
_showas(io, M, cell.value)
cell.style.underline && print(io, "]")
cell.style.italic && print(io, "_")
cell.style.bold && print(io, "*")
print(io, "],\n")
end
if cell.style.border_bottom
println(io, " table.hline(y: $(row), start: $(cell.span[2].start-1), end: $(cell.span[2].stop), stroke: 0.75pt),")
end
running_index = index
end
end
if row == ct.header
println(io, " table.hline(y: $(row), stroke: 0.75pt),")
end
end
println(io, " table.hline(y: $(size(matrix, 1)), stroke: 1pt),")
if !isempty(annotations) || !isempty(ct.footnotes)
align = _align(CellStyle(halign = :left), 1)
colspan = "colspan: $(size(matrix, 2))"
options = join(filter(!isempty, [align, colspan]), ", ")
print(io, " table.cell($options)[#text(size: 0.8em)[")
if (!isempty(annotations) || !isempty(ct.footnotes)) && ct.linebreak_footnotes
print(io, "\n ")
end
for (i, (annotation, label)) in enumerate(annotations)
i > 1 && print(io, ct.linebreak_footnotes ? "\\\n " : "#h(1.5em, weak: true)")
if label !== NoLabel()
print(io, "#super[")
_showas(io, MIME"text/typst"(), label)
print(io, "]")
end
_showas(io, MIME"text/typst"(), annotation)
end
for (i, footnote) in enumerate(ct.footnotes)
(!isempty(annotations) || i > 1) && print(io, ct.linebreak_footnotes ? "\\\n " : "#h(1.5em, weak: true)")
_showas(io, MIME"text/typst"(), footnote)
end
if (!isempty(annotations) || !isempty(ct.footnotes)) && ct.linebreak_footnotes
print(io, "\n ")
end
println(io, "]],") # table.cell()[#text(..)[
end
println(io, ")") # table()
return
end
function _showas(io::IO, M::MIME"text/typst", m::Multiline)
for (i, v) in enumerate(m.values)
i > 1 && print(io, " #linebreak() ")
_showas(io, M, v)
end
end
function typst_halign(halign)
halign === :left ? "left" : halign === :right ? "right" : halign === :center ? "center" : error("Invalid halign $(halign)")
end
function typst_valign(valign)
valign === :top ? "top" : valign === :bottom ? "bottom" : valign === :center ? "horizon" : error("Invalid valign $(s.valign)")
end
function _showas(io::IO, ::MIME"text/typst", r::ResolvedAnnotation)
_showas(io, MIME"text/typst"(), r.value)
if r.label !== NoLabel()
print(io, "#super[")
_showas(io, MIME"text/typst"(), r.label)
print(io, "]")
end
end
function _showas(io::IO, ::MIME"text/typst", s::Superscript)
print(io, "#super[")
_showas(io, MIME"text/typst"(), s.super)
print(io, "]")
end
function _showas(io::IO, ::MIME"text/typst", s::Subscript)
print(io, "#sub[")
_showas(io, MIME"text/typst"(), s.sub)
print(io, "]")
end
function _str_typst_escaped(io::IO, s::AbstractString)
escapable_special_chars = raw"\$#*_"
a = Iterators.Stateful(s)
for c in a
if c in escapable_special_chars
print(io, '\\', c)
else
print(io, c)
end
end
end
function _str_typst_escaped(s::AbstractString)
return sprint(_str_typst_escaped, s, sizehint=lastindex(s))
end
| SummaryTables | https://github.com/PumasAI/SummaryTables.jl.git |
|
[
"MIT"
] | 3.0.0 | 6391447698371a09458574a620f02ad91afbec3a | code | 29790 | using SummaryTables
using SummaryTables: Table, SpannedCell, to_docx, CellStyle
using SummaryTables: WriteDocx
using SummaryTables: SortingError
const W = WriteDocx
using Test
using DataFrames
using Statistics
using ReferenceTests
using tectonic_jll
using Typst_jll
using ZipFile
# Wrapper type to dispatch to the right `show` implementations.
struct AsMIME{M}
object
end
Base.show(io::IO, m::AsMIME{M}) where M = show(io, M(), m.object)
function Base.show(io::IO, m::AsMIME{M}) where M <: MIME"text/latex"
print(io, raw"""
\documentclass{article}
\usepackage{threeparttable}
\usepackage{multirow}
\usepackage{booktabs}
\begin{document}
"""
)
show(io, M(), m.object)
print(io, raw"\end{document}")
end
as_html(object) = AsMIME{MIME"text/html"}(object)
as_latex(object) = AsMIME{MIME"text/latex"}(object)
as_docx(object) = nothing
as_typst(object) = AsMIME{MIME"text/typst"}(object)
function run_reftest(table, path, func)
path_full = joinpath(@__DIR__, path * extension(func))
if func === as_docx
@test_nowarn mktempdir() do dir
tablenode = to_docx(table)
doc = W.Document(
W.Body([
W.Section([tablenode])
]),
W.Styles([])
)
docfile = joinpath(dir, "test.docx")
W.save(docfile, doc)
buf = IOBuffer()
r = ZipFile.Reader(docfile)
for f in r.files
println(buf, "#"^30, " ", f.name, " ", "#"^30)
write(buf, read(f, String))
end
close(r)
s = String(take!(buf))
@test_reference path_full s
end
else
@test_reference path_full func(table)
if func === as_latex
latex_render_test(path_full)
end
if func === as_typst
typst_render_test(path_full)
end
end
end
function latex_render_test(filepath)
mktempdir() do path
texpath = joinpath(path, "input.tex")
pdfpath = joinpath(path, "input.pdf")
cp(filepath, texpath)
tectonic_jll.tectonic() do bin
run(`$bin $texpath`)
end
@test isfile(pdfpath)
end
end
function typst_render_test(filepath)
mktempdir() do path
typ_path = joinpath(path, "input.typ")
pdfpath = joinpath(path, "input.pdf")
cp(filepath, typ_path)
Typst_jll.typst() do bin
run(`$bin compile $typ_path`)
end
@test isfile(pdfpath)
end
end
extension(f::typeof(as_html)) = ".txt"
extension(f::typeof(as_latex)) = ".latex.txt"
extension(f::typeof(as_docx)) = ".docx.txt"
extension(f::typeof(as_typst)) = ".typ.txt"
# This can be removed for `@test_throws` once CI only uses Julia 1.8 and up
macro test_throws_message(message::String, exp)
quote
threw_exception = false
try
$(esc(exp))
catch e
threw_exception = true
@test occursin($message, e.msg) # Currently only works for ErrorException
end
@test threw_exception
end
end
@testset "SummaryTables" begin
df = DataFrame(
value1 = 1:8,
value2 = ["a", "b", "c", "a", "b", "c", "a", "b"],
group1 = repeat(["a", "b"], inner = 4),
group3 = repeat(repeat(["c", "d"], inner = 2), 2),
group2 = repeat(["e", "f"], 4),
)
df2 = DataFrame(
dose = repeat(["1 mg", "50 mg", "5 mg", "10 mg"], 3),
id = repeat(["5", "50", "8", "10", "1", "80"], inner = 2),
value = [1, 2, 3, 4, 2, 3, 4, 5, 5, 2, 1, 4],
)
unsortable_df = let
parameters = repeat([
Concat("T", Subscript("max")),
Concat("C", Superscript("max")),
Multiline("One Line", "Another Line")
], inner = 4)
_df = DataFrame(;
parameters,
value = eachindex(parameters),
group = repeat(1:4, 3),
group2 = repeat(1:2, 6),
)
sort!(_df, [:group2, :group])
end
df_missing_groups = DataFrame(
value = 1:6,
A = ['c', 'c', 'c', 'b', 'b', 'a'],
B = [4, 2, 8, 2, 4, 4]
)
@testset for func in [as_html, as_latex, as_docx, as_typst]
reftest(t, path) = @testset "$path" run_reftest(t, path, func)
@testset "table_one" begin
@test_throws MethodError table_one(df)
t = table_one(df, [:value1])
reftest(t, "references/table_one/one_row")
t = table_one(df, [:value1 => "Value 1"])
reftest(t, "references/table_one/one_row_renamed")
t = table_one(df, [:value1, :value2])
reftest(t, "references/table_one/two_rows")
t = table_one(df, [:value1, :value2], groupby = [:group1])
reftest(t, "references/table_one/two_rows_one_group")
t = table_one(df, [:value1, :value2], groupby = [:group1], show_overall = false) # deprecated
reftest(t, "references/table_one/two_rows_one_group_show_overall_false")
t = table_one(df, [:value1, :value2], groupby = [:group1], show_total = false)
reftest(t, "references/table_one/two_rows_one_group_show_total_false")
t = table_one(df, [:value1, :value2], groupby = [:group1, :group2])
reftest(t, "references/table_one/two_rows_two_groups")
t = table_one(df, [:value1], groupby = [:group1, :group2], show_pvalues = true)
reftest(t, "references/table_one/one_row_two_groups_pvalues")
t = table_one(df, [:value1], groupby = [:group1], show_pvalues = true, show_tests = true, show_confints = true)
reftest(t, "references/table_one/one_row_one_group_pvalues_tests_confints")
t = table_one(df, [:value1, :value2], groupby = [:group1, :group2], group_totals = [:group2])
reftest(t, "references/table_one/group_totals_two_groups_one_total")
t = table_one(df, [:value1, :value2], groupby = [:group1, :group2, :group3], group_totals = [:group3], show_n = true)
reftest(t, "references/table_one/group_totals_three_groups_one_total_level_three")
t = table_one(df, [:value1, :value2], groupby = [:group1, :group2, :group3], group_totals = :group2, show_n = true)
reftest(t, "references/table_one/group_totals_three_groups_one_total_level_two")
function summarizer(col)
m = mean(col)
s = std(col)
(m => "Mean", s => "SD")
end
t = table_one(df, [:value1 => [mean, std => "SD"], :value1 => summarizer])
reftest(t, "references/table_one/vector_and_function_arguments")
t = table_one(df2, :value, groupby = :dose)
reftest(t, "references/table_one/natural_sort_order")
@test_throws SortingError t = table_one(unsortable_df, [:value], groupby = :parameters)
t = table_one(unsortable_df, [:value], groupby = :parameters, sort = false)
reftest(t, "references/table_one/sort_false")
t = table_one(
(;
empty = Union{Float64,Missing}[missing, missing, missing, 1, 2, 3],
group = [1, 1, 1, 2, 2, 2]
),
[:empty],
groupby = :group
)
reftest(t, "references/table_one/all_missing_group")
data = (; x = [1, 2, 3, 4, 5, 6], y = ["A", "A", "B", "B", "B", "A"], z = ["C", "C", "C", "D", "D", "D"])
t = table_one(data, :x, groupby = [:y, :z], sort = false)
reftest(t, "references/table_one/nested_spans_bad_sort")
data = (;
category = ["a", "b", "c", "b", missing, "b", "c", "c"],
group = [1, 1, 1, 1, 2, 2, 2, 2]
)
t = table_one(data, [:category], groupby = :group)
reftest(t, "references/table_one/category_with_missing")
end
@testset "listingtable" begin
@test_throws MethodError listingtable(df)
@test_throws SummaryTables.TooManyRowsError listingtable(df, :value1)
@test_throws SummaryTables.TooManyRowsError listingtable(df, :value2)
@test_throws SummaryTables.TooManyRowsError listingtable(df, :value1, rows = [:group1])
t = listingtable(df, :value1, rows = [:group1, :group2, :group3])
reftest(t, "references/listingtable/rows_only")
t = listingtable(df, :value1, cols = [:group1, :group2, :group3])
reftest(t, "references/listingtable/cols_only")
t = listingtable(df, :value1, rows = [:group1, :group2], cols = [:group3])
reftest(t, "references/listingtable/two_rows_one_col")
t = listingtable(df, :value1, rows = [:group1], cols = [:group2, :group3])
reftest(t, "references/listingtable/one_row_two_cols")
t = listingtable(df, :value1,
rows = [:group1, :group2],
cols = [:group3],
summarize_rows = [mean]
)
reftest(t, "references/listingtable/summarize_end_rows")
t = listingtable(df, :value1,
rows = [:group1, :group2],
cols = [:group3],
summarize_rows = [mean, std]
)
reftest(t, "references/listingtable/summarize_end_rows_two_funcs")
t = listingtable(df, :value1,
rows = [:group1, :group2],
cols = [:group3],
summarize_rows = :group2 => [mean]
)
reftest(t, "references/listingtable/summarize_last_group_rows")
t = listingtable(df, :value1,
rows = [:group1, :group2],
cols = [:group3],
summarize_rows = :group1 => [mean]
)
reftest(t, "references/listingtable/summarize_first_group_rows")
t = listingtable(df, :value1,
cols = [:group1, :group2],
rows = [:group3],
summarize_cols = [mean, std]
)
reftest(t, "references/listingtable/summarize_end_cols_two_funcs")
t = listingtable(df, :value1,
cols = [:group1, :group2],
rows = [:group3],
summarize_cols = :group2 => [mean]
)
reftest(t, "references/listingtable/summarize_last_group_cols")
t = listingtable(df, :value1,
cols = [:group1, :group2],
rows = [:group3],
summarize_cols = :group1 => [mean]
)
reftest(t, "references/listingtable/summarize_first_group_cols")
t = listingtable(df, :value1 => "Value 1",
rows = [:group1 => "Group 1", :group2 => "Group 2"],
cols = [:group3 => "Group 3"],
summarize_rows = [mean => "Mean", minimum => "Minimum"]
)
reftest(t, "references/listingtable/renaming")
t = listingtable(df, :value1 => "Value 1",
rows = [:group1],
cols = [:group2, :group3],
variable_header = false,
)
reftest(t, "references/listingtable/no_variable_header")
t = listingtable(df2, :value, rows = [:id, :dose])
reftest(t, "references/listingtable/natural_sort_order")
t = listingtable(df2, :value, rows = [:id, :dose], summarize_rows = [mean, mean], summarize_cols = [mean, mean])
reftest(t, "references/listingtable/two_same_summarizers")
@test_throws SortingError t = listingtable(unsortable_df, :value, rows = :parameters, cols = [:group2, :group])
t = listingtable(unsortable_df, :value, cols = :parameters, rows = [:group2, :group], sort = false)
reftest(t, "references/listingtable/sort_false")
pt = listingtable(df, :value1, Pagination(rows = 1);
rows = [:group1, :group2], cols = :group3)
for (i, page) in enumerate(pt.pages)
reftest(page.table, "references/listingtable/pagination_rows=1_$i")
end
pt = listingtable(df, :value1, Pagination(rows = 2);
rows = [:group1, :group2], cols = :group3)
for (i, page) in enumerate(pt.pages)
reftest(page.table, "references/listingtable/pagination_rows=2_$i")
end
pt = listingtable(df, :value1, Pagination(cols = 1);
cols = [:group1, :group2], rows = :group3)
for (i, page) in enumerate(pt.pages)
reftest(page.table, "references/listingtable/pagination_cols=1_$i")
end
pt = listingtable(df, :value1, Pagination(cols = 2);
cols = [:group1, :group2], rows = :group3)
for (i, page) in enumerate(pt.pages)
reftest(page.table, "references/listingtable/pagination_cols=2_$i")
end
pt = listingtable(df, :value1, Pagination(rows = 1, cols = 2);
cols = [:group1, :group2], rows = :group3)
for (i, page) in enumerate(pt.pages)
reftest(page.table, "references/listingtable/pagination_rows=1_cols=2_$i")
end
if func === as_html
reftest(pt, "references/paginated_table_interactive")
end
pt = listingtable(df, :value1, Pagination(rows = 1);
rows = [:group1, :group2], cols = :group3, summarize_rows = [mean, std])
@test length(pt.pages) == 1
for (i, page) in enumerate(pt.pages)
reftest(page.table, "references/listingtable/pagination_rows=2_summarized_$i")
end
pt = listingtable(df, :value1, Pagination(rows = 1);
rows = [:group1, :group2], cols = :group3, summarize_rows = :group2 => [mean, std])
@test length(pt.pages) == 4
for (i, page) in enumerate(pt.pages)
reftest(page.table, "references/listingtable/pagination_rows=2_summarized_grouplevel_2_$i")
end
pt = listingtable(df, :value1, Pagination(rows = 1);
rows = [:group1, :group2], cols = :group3, summarize_rows = :group1 => [mean, std])
@test length(pt.pages) == 2
for (i, page) in enumerate(pt.pages)
reftest(t, "references/listingtable/pagination_rows=2_summarized_grouplevel_1_$i")
end
t = listingtable(df_missing_groups, :value, rows = :A, cols = :B)
reftest(t, "references/listingtable/missing_groups")
end
@testset "summarytable" begin
@test_throws ArgumentError("No summary analyses defined.") t = summarytable(df, :value1)
t = summarytable(df, :value1, summary = [mean])
reftest(t, "references/summarytable/no_group_one_summary")
t = summarytable(df, :value1, summary = [mean, std => "SD"])
reftest(t, "references/summarytable/no_group_two_summaries")
t = summarytable(df, :value1, rows = [:group1 => "Group 1"], summary = [mean])
reftest(t, "references/summarytable/one_rowgroup_one_summary")
t = summarytable(df, :value1, rows = [:group1 => "Group 1"], summary = [mean, std])
reftest(t, "references/summarytable/one_rowgroup_two_summaries")
t = summarytable(df, :value1, rows = [:group1 => "Group 1"], cols = [:group2 => "Group 2"], summary = [mean])
reftest(t, "references/summarytable/one_rowgroup_one_colgroup_one_summary")
t = summarytable(df, :value1, rows = [:group1 => "Group 1"], cols = [:group2 => "Group 2"], summary = [mean, std])
reftest(t, "references/summarytable/one_rowgroup_one_colgroup_two_summaries")
t = summarytable(df, :value1, rows = [:group1 => "Group 1", :group2], cols = [:group3 => "Group 3"], summary = [mean, std])
reftest(t, "references/summarytable/two_rowgroups_one_colgroup_two_summaries")
t = summarytable(df, :value1, rows = [:group1 => "Group 1", :group2], cols = [:group3 => "Group 3"], summary = [mean, std], variable_header = false)
reftest(t, "references/summarytable/two_rowgroups_one_colgroup_two_summaries_no_header")
t = summarytable(df, :value1, summary = [mean, mean])
reftest(t, "references/summarytable/two_same_summaries")
t = summarytable(df2, :value, rows = [:id, :dose], summary = [mean])
reftest(t, "references/summarytable/natural_sort_order")
@test_throws SortingError t = summarytable(unsortable_df, :value, rows = :parameters, cols = [:group2, :group], summary = [mean])
t = summarytable(unsortable_df, :value, cols = :parameters, rows = [:group2, :group], summary = [mean], sort = false)
reftest(t, "references/summarytable/sort_false")
t = summarytable(df_missing_groups, :value, rows = :A, cols = :B, summary = [sum])
reftest(t, "references/summarytable/missing_groups")
end
@testset "annotations" begin
t = Table(
[
SpannedCell(1, 1, Annotated("A", "Note 1")),
SpannedCell(1, 2, Annotated("B", "Note 2")),
SpannedCell(2, 1, Annotated("C", "Note 3")),
SpannedCell(2, 2, Annotated("D", "Note 1")),
],
nothing,
nothing,
)
reftest(t, "references/annotations/automatic_annotations")
t = Table(
[
SpannedCell(1, 1, Annotated("A", "Note 1", label = "X")),
SpannedCell(1, 2, Annotated("B", "Note 2", label = "Y")),
SpannedCell(2, 1, Annotated("C", "Note 3")),
SpannedCell(2, 2, Annotated("D", "Note 4")),
],
nothing,
nothing,
)
reftest(t, "references/annotations/manual_annotations")
t = Table(
[
SpannedCell(1, 1, Annotated("A", "Note 1", label = "A")),
SpannedCell(1, 2, Annotated("A", "Note 1", label = "B")),
],
nothing,
nothing,
)
if func !== as_docx # TODO needs logic rework for this backend
@test_throws_message "Found the same annotation" show(devnull, func(t))
end
t = Table(
[
SpannedCell(1, 1, Annotated("A", "Note 1", label = "A")),
SpannedCell(1, 2, Annotated("A", "Note 2", label = "A")),
],
nothing,
nothing,
)
if func !== as_docx # TODO needs logic rework for this backend
@test_throws_message "Found the same label" show(devnull, func(t))
end
t = Table(
[
SpannedCell(1, 1, Annotated(0.1235513245, "Note 1", label = "A")),
],
nothing,
nothing,
)
reftest(t, "references/annotations/annotated_float")
end
@testset "manual footnotes" begin
for linebreak_footnotes in [true, false]
t = Table(
[
SpannedCell(1, 1, "Cell 1"),
SpannedCell(1, 2, "Cell 2"),
];
footnotes = ["First footnote.", "Second footnote."],
linebreak_footnotes,
)
reftest(t, "references/manual_footnotes/footnotes_linebreaks_$linebreak_footnotes")
t = Table(
[
SpannedCell(1, 1, Annotated("Cell 1", "Note 1")),
SpannedCell(1, 2, "Cell 2"),
];
footnotes = ["First footnote.", "Second footnote."],
linebreak_footnotes,
)
reftest(t, "references/manual_footnotes/footnotes_and_annotated_linebreaks_$linebreak_footnotes")
end
end
@testset "Replace" begin
t = Table(
[
SpannedCell(1, 1, missing),
SpannedCell(1, 2, missing),
SpannedCell(2, 1, 1),
SpannedCell(2, 2, 2),
],
nothing,
nothing,
postprocess = [ReplaceMissing()]
)
reftest(t, "references/replace/replacemissing_default")
t = Table(
[
SpannedCell(1, 1, missing),
SpannedCell(1, 2, nothing),
SpannedCell(2, 1, 1),
SpannedCell(2, 2, 2),
],
nothing,
nothing,
postprocess = [ReplaceMissing(with = "???")]
)
reftest(t, "references/replace/replacemissing_custom")
t = Table(
[
SpannedCell(1, 1, missing),
SpannedCell(1, 2, nothing),
SpannedCell(2, 1, 1),
SpannedCell(2, 2, 2),
],
nothing,
nothing,
postprocess = [Replace(x -> x isa Int, "an Int was here")]
)
reftest(t, "references/replace/replace_predicate_value")
t = Table(
[
SpannedCell(1, 1, missing),
SpannedCell(1, 2, nothing),
SpannedCell(2, 1, 1),
SpannedCell(2, 2, 2),
],
nothing,
nothing,
postprocess = [Replace(x -> x isa Int, x -> x + 10)]
)
reftest(t, "references/replace/replace_predicate_function")
end
@testset "Global rounding" begin
cells = [
SpannedCell(1, 1, sqrt(2)),
SpannedCell(1, 2, 12352131.000001),
SpannedCell(2, 1, sqrt(11251231251243123)),
SpannedCell(2, 2, sqrt(0.00000123124)),
SpannedCell(3, 1, Concat(1.23456, " & ", 0.0012345)),
SpannedCell(3, 2, Multiline(1.23456, 0.0012345)),
]
t = Table(
cells,
nothing,
nothing,
)
reftest(t, "references/global_rounding/default")
t = Table(
cells,
nothing,
nothing,
round_mode = nothing,
)
reftest(t, "references/global_rounding/no_rounding")
for round_mode in [:auto, :sigdigits, :digits]
for trailing_zeros in [true, false]
for round_digits in [1, 3]
t = Table(
cells,
nothing,
nothing;
round_mode,
trailing_zeros,
round_digits
)
reftest(t, "references/global_rounding/$(round_mode)_$(trailing_zeros)_$(round_digits)")
end
end
end
end
@testset "Character escaping" begin
cells = [
SpannedCell(1, 1, "& % \$ # _ { } ~ ^ \\ < > \" ' ")
]
t = Table(
cells,
nothing,
nothing,
)
reftest(t, "references/character_escaping/problematic_characters")
end
@testset "Merged cells with special values" begin
contents = [
Multiline("A", "B"),
Superscript("Sup"),
Subscript("Sub"),
Concat("A", "B"),
Annotated("Label", "Annotation"),
]
cells = Cell.(contents, merge = true)
t = Table(hcat(cells, cells))
reftest(t, "references/merged_cells/custom_datatypes")
end
@testset "Styles" begin
cells = [
SpannedCell(1, 1, "Row 1"),
SpannedCell(2, 1, "Row 2"),
SpannedCell(3, 1, "Row 3"),
SpannedCell(1:3, 2, "top", CellStyle(valign = :top)),
SpannedCell(1:3, 3, "center", CellStyle(valign = :center)),
SpannedCell(1:3, 4, "bottom", CellStyle(valign = :bottom)),
]
t = Table(
cells,
nothing,
nothing,
)
reftest(t, "references/styles/valign")
end
@testset "Row and column gaps" begin
if func !== as_docx # TODO needs logic rework for this backend
t = Table([SpannedCell(1, 1, "Row 1")], rowgaps = [1 => 5.0])
@test_throws_message "No row gaps allowed for a table with one row" show(devnull, func(t))
t = Table([SpannedCell(1, 1, "Column 1")], colgaps = [1 => 5.0])
@test_throws_message "No column gaps allowed for a table with one column" show(devnull, func(t))
t = Table([SpannedCell(1, 1, "Row 1"), SpannedCell(2, 1, "Row 2")], rowgaps = [1 => 5.0, 2 => 5.0])
@test_throws_message "A row gap index of 2 is invalid for a table with 2 rows" show(devnull, func(t))
t = Table([SpannedCell(1, 1, "Column 1"), SpannedCell(1, 2, "Column 2")], colgaps = [1 => 5.0, 2 => 5.0])
@test_throws_message "A column gap index of 2 is invalid for a table with 2 columns" show(devnull, func(t))
t = Table([SpannedCell(1, 1, "Row 1"), SpannedCell(2, 1, "Row 2")], rowgaps = [0 => 5.0])
@test_throws_message "A row gap index of 0 is invalid, must be at least 1" show(devnull, func(t))
t = Table([SpannedCell(1, 1, "Column 1"), SpannedCell(1, 2, "Column 2")], colgaps = [0 => 5.0])
@test_throws_message "A column gap index of 0 is invalid, must be at least 1" show(devnull, func(t))
end
t = Table([SpannedCell(i, j, "$i, $j") for i in 1:4 for j in 1:4], rowgaps = [1 => 4.0, 2 => 8.0], colgaps = [2 => 4.0, 3 => 8.0])
reftest(t, "references/row_and_column_gaps/singlecell")
t = Table([SpannedCell(2:4, 1, "Spanned rows"), SpannedCell(1, 2:4, "Spanned columns")], rowgaps = [1 => 4.0], colgaps = [2 => 4.0])
reftest(t, "references/row_and_column_gaps/spanned_cells")
end
end
end
@testset "auto rounding" begin
@test SummaryTables.auto_round( 1234567, target_digits = 4) == 1.235e6
@test SummaryTables.auto_round( 123456.7, target_digits = 4) == 123457
@test SummaryTables.auto_round( 12345.67, target_digits = 4) == 12346
@test SummaryTables.auto_round( 1234.567, target_digits = 4) == 1235
@test SummaryTables.auto_round( 123.4567, target_digits = 4) == 123.5
@test SummaryTables.auto_round( 12.34567, target_digits = 4) == 12.35
@test SummaryTables.auto_round( 1.234567, target_digits = 4) == 1.235
@test SummaryTables.auto_round( 0.1234567, target_digits = 4) == 0.1235
@test SummaryTables.auto_round( 0.01234567, target_digits = 4) == 0.01235
@test SummaryTables.auto_round( 0.001234567, target_digits = 4) == 0.001235
@test SummaryTables.auto_round( 0.0001234567, target_digits = 4) == 0.0001235
@test SummaryTables.auto_round( 0.00001234567, target_digits = 4) == 1.235e-5
@test SummaryTables.auto_round( 0.000001234567, target_digits = 4) == 1.235e-6
@test SummaryTables.auto_round(0.0000001234567, target_digits = 4) == 1.235e-7
@test SummaryTables.auto_round(0.1, target_digits = 4) == 0.1
@test SummaryTables.auto_round(0.0, target_digits = 4) == 0
@test SummaryTables.auto_round(1.0, target_digits = 4) == 1
end
@testset "Formatted float strings" begin
RF = SummaryTables.RoundedFloat
str(rf) = sprint(io -> SummaryTables._showas(io, MIME"text"(), rf))
x = 0.006789
@test str(RF(x, 3, :auto, true)) == "0.00679"
@test str(RF(x, 3, :sigdigits, true)) == "0.00679"
@test str(RF(x, 3, :digits, true)) == "0.007"
@test str(RF(x, 2, :auto, true)) == "0.0068"
@test str(RF(x, 2, :sigdigits, true)) == "0.0068"
@test str(RF(x, 2, :digits, true)) == "0.01"
x = 0.120
@test str(RF(x, 3, :auto, true)) == "0.12"
@test str(RF(x, 3, :sigdigits, true)) == "0.12"
@test str(RF(x, 3, :digits, true)) == "0.120"
@test str(RF(x, 3, :auto, false)) == "0.12"
@test str(RF(x, 3, :sigdigits, false)) == "0.12"
@test str(RF(x, 3, :digits, false)) == "0.12"
x = 1.0
@test str(RF(x, 3, :auto, true)) == "1.0"
@test str(RF(x, 3, :sigdigits, true)) == "1.0"
@test str(RF(x, 3, :digits, true)) == "1.000"
@test str(RF(x, 3, :auto, false)) == "1"
@test str(RF(x, 3, :sigdigits, false)) == "1"
@test str(RF(x, 3, :digits, false)) == "1"
x = 12345678.910
@test str(RF(x, 3, :auto, true)) == "1.23e7"
@test str(RF(x, 3, :sigdigits, true)) == "1.23e7"
@test str(RF(x, 3, :digits, true)) == "12345678.910"
@test str(RF(x, 3, :auto, false)) == "1.23e7"
@test str(RF(x, 3, :sigdigits, false)) == "1.23e7"
@test str(RF(x, 3, :digits, false)) == "12345678.91"
end
| SummaryTables | https://github.com/PumasAI/SummaryTables.jl.git |
|
[
"MIT"
] | 3.0.0 | 6391447698371a09458574a620f02ad91afbec3a | docs | 1346 | # Changelog
## Unreleased
## 3.0.0 - 2024-09-23
- **Breaking** Footnotes are by default separated with linebreaks now. This can be changed by setting the new `Table` option `linebreak_footnotes = false` [#34](https://github.com/PumasAI/SummaryTables.jl/pull/34).
- **Breaking** Changed `show_overall` keyword of `table_one` to `show_total`. The name of all total columns was changed from `"Overall"` to `"Total"` as well but this can be changed using the new `total_name` keyword.
- Added ability to show "Total" statistics for subgroups in `table_one` [#30](https://github.com/PumasAI/SummaryTables.jl/pull/30).
- Fixed tagging of header rows in docx output, such that the header section is now repeated across pages as expected [#32](https://github.com/PumasAI/SummaryTables.jl/pull/32).
## 2.0.2 - 2024-09-16
- Fixed issue where cells would not merge if they stored a `Multiline` value [#29](https://github.com/PumasAI/SummaryTables.jl/pull/29).
## 2.0.1 - 2024-09-16
- Fixed incorrect order of column group keys in `summarytable` and `listingtable` when some row/col group combinations were missing [#25](https://github.com/PumasAI/SummaryTables.jl/pull/25).
## 2.0.0 - 2024-05-03
- **Breaking** Changed generated Typst code to use the native table functionality available starting with Typst v0.11. Visual output should not change.
| SummaryTables | https://github.com/PumasAI/SummaryTables.jl.git |
|
[
"MIT"
] | 3.0.0 | 6391447698371a09458574a620f02ad91afbec3a | docs | 3514 | # SummaryTables.jl
<div align="center">
<picture>
<img alt="SummaryTables.jl logo"
src="/docs/src/assets/logo.png" width="150">
</picture>
</div>
[![](https://img.shields.io/badge/Docs-Stable-lightgrey.svg)](https://pumasai.github.io/SummaryTables.jl/stable/)
[![](https://img.shields.io/badge/Docs-Dev-blue.svg)](https://pumasai.github.io/SummaryTables.jl/dev/)
SummaryTables.jl is a Julia package for creating publication-ready
tables in HTML, docx, LaTeX and Typst formats. Tables are formatted in a
minimalistic style without vertical lines.
SummaryTables offers the `table_one`, `summarytable` and `listingtable`
functions to generate pharmacological tables from Tables.jl-compatible
data structures, as well as a low-level API to construct tables of any
shape manually.
## Examples
``` julia
data = DataFrame(
sex = ["m", "m", "m", "m", "f", "f", "f", "f", "f", "f"],
age = [27, 45, 34, 85, 55, 44, 24, 29, 37, 76],
blood_type = ["A", "0", "B", "B", "B", "A", "0", "A", "A", "B"],
smoker = [true, false, false, false, true, true, true, false, false, false],
)
table_one(
data,
[:age => "Age (years)", :blood_type => "Blood type", :smoker => "Smoker"],
groupby = :sex => "Sex",
show_n = true
)
```
![](README_files/figure-commonmark/cell-3-output-1.svg)
``` julia
data = DataFrame(
concentration = [1.2, 4.5, 2.0, 1.5, 0.1, 1.8, 3.2, 1.8, 1.2, 0.2,
1.7, 4.2, 1.0, 0.9, 0.3, 1.7, 3.7, 1.2, 1.0, 0.2],
id = repeat([1, 2, 3, 4], inner = 5),
dose = repeat([100, 200], inner = 10),
time = repeat([0, 0.5, 1, 2, 3], 4)
)
listingtable(
data,
:concentration => "Concentration (ng/mL)",
rows = [:dose => "Dose (mg)", :id => "ID"],
cols = :time => "Time (hr)",
summarize_rows = :dose => [
length => "N",
mean => "Mean",
std => "SD",
]
)
```
![](README_files/figure-commonmark/cell-4-output-1.svg)
``` julia
categories = ["Deciduous", "Deciduous", "Evergreen", "Evergreen", "Evergreen"]
species = ["Beech", "Oak", "Fir", "Spruce", "Pine"]
fake_data = [
"35m" "40m" "38m" "27m" "29m"
"10k" "12k" "18k" "9k" "7k"
"500yr" "800yr" "600yr" "700yr" "400yr"
"80\$" "150\$" "40\$" "70\$" "50\$"
]
labels = ["", "", "Size", Annotated("Water consumption", "Liters per year"), "Age", "Value"]
body = [
Cell.(categories, bold = true, merge = true, border_bottom = true)';
Cell.(species)';
Cell.(fake_data)
]
Table(hcat(
Cell.(labels, italic = true, halign = :right),
body
))
```
![](README_files/figure-commonmark/cell-5-output-1.svg)
## Comparison with PrettyTables.jl
[PrettyTables.jl](https://github.com/ronisbr/PrettyTables.jl/) is a
well-known Julia package whose main function is formatting tabular data,
for example as the backend to
[DataFrames.jl](https://github.com/JuliaData/DataFrames.jl).
PrettyTables supports plain-text output because it is often used for
rendering tables to the REPL, however this also means that it does not
support merging cells vertically or horizontally in its current state,
which is difficult to realize with plain text.
In contrast, SummaryTables’s main purpose is to offer convenience
functions for creating specific scientific tables which are out-of-scope
for PrettyTables. For our desired aesthetics, we also needed low-level
control over certain output formats, for example for controlling cell
border behavior in docx, which were unlikely to be added to PrettyTables
at the time of writing this package.
| SummaryTables | https://github.com/PumasAI/SummaryTables.jl.git |
|
[
"MIT"
] | 3.0.0 | 6391447698371a09458574a620f02ad91afbec3a | docs | 4757 | ---
title: SummaryTables.jl
engine: julia
format: gfm
execute:
daemon: false
---
```{=html}
<div align="center">
<picture>
<img alt="SummaryTables.jl logo"
src="/docs/src/assets/logo.png" width="150">
</picture>
</div>
```
[![](https://img.shields.io/badge/Docs-Stable-lightgrey.svg)](https://pumasai.github.io/SummaryTables.jl/stable/)
[![](https://img.shields.io/badge/Docs-Dev-blue.svg)](https://pumasai.github.io/SummaryTables.jl/dev/)
SummaryTables.jl is a Julia package for creating publication-ready tables in HTML, docx, LaTeX and Typst formats.
Tables are formatted in a minimalistic style without vertical lines.
SummaryTables offers the `table_one`, `summarytable` and `listingtable` functions to generate pharmacological tables from Tables.jl-compatible data structures, as well as a low-level API to construct tables of any shape manually.
## Examples
```{julia}
#| output: false
#| echo: false
using SummaryTables, DataFrames, Statistics, Typst_jll
Base.delete_method(only(methods(Base.show, (IO, MIME"text/html", SummaryTables.Table))))
function Base.show(io::IO, ::MIME"image/svg+xml", tbl::SummaryTables.Table)
mktempdir() do dir
input = joinpath(dir, "input.typ")
open(input, "w") do io
println(io, """
#set page(margin: 3pt, width: auto, height: auto, fill: white)
#set text(12pt)
""")
show(io, MIME"text/typst"(), tbl)
end
output = joinpath(dir, "output.svg")
run(`$(typst()) compile $input $output`)
str = read(output, String)
ids = Dict{String,Int}()
function simple_id(s)
string(get!(ids, s) do
length(ids)
end, base = 16)
end
# typst uses ids that are not stable across runs or OSes or something,
# also they're quite long so as we don't use inlined svg we just simplify them
# to the position at which they appear first
replace(io, str,
r"(?<=xlink:href=\"#).*?(?=\")" => simple_id,
r"(?<=id=\").*?(?=\")" => simple_id,
r"(?<=url\(#).*?(?=\))" => simple_id,
)
end
end
```
```{julia}
data = DataFrame(
sex = ["m", "m", "m", "m", "f", "f", "f", "f", "f", "f"],
age = [27, 45, 34, 85, 55, 44, 24, 29, 37, 76],
blood_type = ["A", "0", "B", "B", "B", "A", "0", "A", "A", "B"],
smoker = [true, false, false, false, true, true, true, false, false, false],
)
table_one(
data,
[:age => "Age (years)", :blood_type => "Blood type", :smoker => "Smoker"],
groupby = :sex => "Sex",
show_n = true
)
```
```{julia}
data = DataFrame(
concentration = [1.2, 4.5, 2.0, 1.5, 0.1, 1.8, 3.2, 1.8, 1.2, 0.2,
1.7, 4.2, 1.0, 0.9, 0.3, 1.7, 3.7, 1.2, 1.0, 0.2],
id = repeat([1, 2, 3, 4], inner = 5),
dose = repeat([100, 200], inner = 10),
time = repeat([0, 0.5, 1, 2, 3], 4)
)
listingtable(
data,
:concentration => "Concentration (ng/mL)",
rows = [:dose => "Dose (mg)", :id => "ID"],
cols = :time => "Time (hr)",
summarize_rows = :dose => [
length => "N",
mean => "Mean",
std => "SD",
]
)
```
```{julia}
categories = ["Deciduous", "Deciduous", "Evergreen", "Evergreen", "Evergreen"]
species = ["Beech", "Oak", "Fir", "Spruce", "Pine"]
fake_data = [
"35m" "40m" "38m" "27m" "29m"
"10k" "12k" "18k" "9k" "7k"
"500yr" "800yr" "600yr" "700yr" "400yr"
"80\$" "150\$" "40\$" "70\$" "50\$"
]
labels = ["", "", "Size", Annotated("Water consumption", "Liters per year"), "Age", "Value"]
body = [
Cell.(categories, bold = true, merge = true, border_bottom = true)';
Cell.(species)';
Cell.(fake_data)
]
Table(hcat(
Cell.(labels, italic = true, halign = :right),
body
))
```
## Comparison with PrettyTables.jl
[PrettyTables.jl](https://github.com/ronisbr/PrettyTables.jl/) is a well-known Julia package whose main function is formatting tabular data, for example as the backend to [DataFrames.jl](https://github.com/JuliaData/DataFrames.jl).
PrettyTables supports plain-text output because it is often used for rendering tables to the REPL, however this also means that it does not support merging cells vertically or horizontally in its current state, which is difficult to realize with plain text.
In contrast, SummaryTables's main purpose is to offer convenience functions for creating specific scientific tables which are out-of-scope for PrettyTables.
For our desired aesthetics, we also needed low-level control over certain output formats, for example for controlling cell border behavior in docx, which were unlikely to be added to PrettyTables at the time of writing this package.
| SummaryTables | https://github.com/PumasAI/SummaryTables.jl.git |
|
[
"MIT"
] | 3.0.0 | 6391447698371a09458574a620f02ad91afbec3a | docs | 49 | # API
```@autodocs
Modules = [SummaryTables]
``` | SummaryTables | https://github.com/PumasAI/SummaryTables.jl.git |
|
[
"MIT"
] | 3.0.0 | 6391447698371a09458574a620f02ad91afbec3a | docs | 1812 | # SummaryTables
SummaryTables is focused on creating tables for publications in LaTeX, docx and HTML formats.
It offers both convenient predefined table functions that are inspired by common table formats in the pharma space, as well as an API to create completely custom tables.
It deliberately uses an opinionated, limited styling API so that styling can be as consistent as possible across the different backends.
```@example
using SummaryTables
using DataFrames
data = DataFrame(
sex = ["m", "m", "m", "m", "f", "f", "f", "f", "f", "f"],
age = [27, 45, 34, 85, 55, 44, 24, 29, 37, 76],
blood_type = ["A", "0", "B", "B", "B", "A", "0", "A", "A", "B"],
smoker = [true, false, false, false, true, true, true, false, false, false],
)
table_one(
data,
[:age => "Age (years)", :blood_type => "Blood type", :smoker => "Smoker"],
groupby = :sex => "Sex",
show_n = true
)
```
```@example
using DataFrames
using SummaryTables
using Statistics
data = DataFrame(
concentration = [1.2, 4.5, 2.0, 1.5, 0.1, 1.8, 3.2, 1.8, 1.2, 0.2],
id = repeat([1, 2], inner = 5),
time = repeat([0, 0.5, 1, 2, 3], 2)
)
listingtable(
data,
:concentration => "Concentration (ng/mL)",
rows = :id => "ID",
cols = :time => "Time (hr)",
summarize_rows = [
length => "N",
mean => "Mean",
std => "SD",
]
)
```
```@example
using DataFrames
using SummaryTables
using Statistics
data = DataFrame(
concentration = [1.2, 4.5, 2.0, 1.5, 0.1, 1.8, 3.2, 1.8, 1.2, 0.2],
id = repeat([1, 2], inner = 5),
time = repeat([0, 0.5, 1, 2, 3], 2)
)
summarytable(
data,
:concentration => "Concentration (ng/mL)",
cols = :time => "Time (hr)",
summary = [
length => "N",
mean => "Mean",
std => "SD",
]
)
``` | SummaryTables | https://github.com/PumasAI/SummaryTables.jl.git |
|
[
"MIT"
] | 3.0.0 | 6391447698371a09458574a620f02ad91afbec3a | docs | 4578 | # Output
## HTML
In IDEs that support the `MIME"text/html"` or `MIME"juliavscode/html"` types, just `display`ing a `Table` will render it in HTML for you.
All examples in this documentation are rendered this way.
Alternatively, you can print HTML to any IO object via `show(io, MIME"text/html", table)`.
## LaTeX
You can print LaTeX code to any IO via `show(io, MIME"text/latex", table)`.
Keep in mind that the `threeparttable`, `multirow` and `booktabs` packages need to separately be included in your preamble due to the way LaTeX documents are structured.
```@example
using SummaryTables
using DataFrames
using tectonic_jll
mkpath(joinpath(@__DIR__, "outputs"))
data = DataFrame(
sex = ["m", "m", "m", "m", "f", "f", "f", "f", "f", "f"],
age = [27, 45, 34, 85, 55, 44, 24, 29, 37, 76],
blood_type = ["A", "0", "B", "B", "B", "A", "0", "A", "A", "B"],
smoker = [true, false, false, false, true, true, true, false, false, false],
)
tbl = table_one(
data,
[:age => "Age (years)", :blood_type => "Blood type", :smoker => "Smoker"],
groupby = :sex => "Sex",
show_n = true
)
# render latex in a temp directory
mktempdir() do dir
texfile = joinpath(dir, "main.tex")
open(texfile, "w") do io
# add the necessary packages in the preamble
println(io, raw"""
\documentclass{article}
\usepackage{threeparttable}
\usepackage{multirow}
\usepackage{booktabs}
\begin{document}
""")
# print the table as latex code
show(io, MIME"text/latex"(), tbl)
println(io, raw"\end{document}")
end
# render the tex file to pdf
tectonic_jll.tectonic() do bin
run(`$bin $texfile`)
end
cp(joinpath(dir, "main.pdf"), joinpath(@__DIR__, "outputs", "example.pdf"))
end
nothing # hide
```
Download `example.pdf`:
```@raw html
<a href="./../outputs/example.pdf"><img src="./../assets/icon_pdf.png" width="60">
```
## docx
To get docx output, you need to use the WriteDocx.jl package because this format is not plain-text like LaTeX or HTML.
The table node you get out of the `to_docx` function can be placed into
sections on the same level as paragraphs.
```@example
using SummaryTables
using DataFrames
import WriteDocx as W
mkpath(joinpath(@__DIR__, "outputs"))
data = DataFrame(
sex = ["m", "m", "m", "m", "f", "f", "f", "f", "f", "f"],
age = [27, 45, 34, 85, 55, 44, 24, 29, 37, 76],
blood_type = ["A", "0", "B", "B", "B", "A", "0", "A", "A", "B"],
smoker = [true, false, false, false, true, true, true, false, false, false],
)
tbl = table_one(
data,
[:age => "Age (years)", :blood_type => "Blood type", :smoker => "Smoker"],
groupby = :sex => "Sex",
show_n = true
)
doc = W.Document(
W.Body([
W.Section([
SummaryTables.to_docx(tbl)
])
])
)
W.save(joinpath(@__DIR__, "outputs", "example.docx"), doc)
nothing # hide
```
Download `example.docx`:
```@raw html
<a href="./../outputs/example.docx"><img src="./../assets/icon_docx.png" width="60">
```
## Typst
You can print [Typst](https://github.com/typst/typst) table code to any IO via `show(io, MIME"text/typst", table)`.
From SummaryTables v2.0 on, the Typst backend is using the native table functionality in Typst v0.11.
Previous versions used the [tablex](https://github.com/PgBiel/typst-tablex/) package.
```@example
using SummaryTables
using DataFrames
using Typst_jll
mkpath(joinpath(@__DIR__, "outputs"))
data = DataFrame(
sex = ["m", "m", "m", "m", "f", "f", "f", "f", "f", "f"],
age = [27, 45, 34, 85, 55, 44, 24, 29, 37, 76],
blood_type = ["A", "0", "B", "B", "B", "A", "0", "A", "A", "B"],
smoker = [true, false, false, false, true, true, true, false, false, false],
)
tbl = table_one(
data,
[:age => "Age (years)", :blood_type => "Blood type", :smoker => "Smoker"],
groupby = :sex => "Sex",
show_n = true
)
# render latex in a temp directory
mktempdir() do dir
typfile = joinpath(dir, "example.typ")
open(typfile, "w") do io
# print the table as latex code
show(io, MIME"text/typst"(), tbl)
end
# render the tex file to pdf
Typst_jll.typst() do bin
run(`$bin compile $typfile`)
end
cp(joinpath(dir, "example.pdf"), joinpath(@__DIR__, "outputs", "example_typst.pdf"))
end
nothing # hide
```
Download `example_typst.pdf`:
```@raw html
<a href="./../outputs/example_typst.pdf"><img src="./../assets/icon_pdf.png" width="60">
```
| SummaryTables | https://github.com/PumasAI/SummaryTables.jl.git |
|
[
"MIT"
] | 3.0.0 | 6391447698371a09458574a620f02ad91afbec3a | docs | 3814 | # `Cell`
## Argument 1: `value`
This is the content of the `Cell`.
How it is rendered is decided by the output format and what `show` methods are defined for the type of `value` and the respective output `MIME` type.
If no output-specific `MIME` type has a `show` method, the fallback is always the generic text output.
The following are some types which receive special handling by SummaryTables.
### Special `Cell` value types
#### Floating point numbers
Most tables display floating point numbers, however, the formatting of these numbers can vary.
SummaryTables postprocesses every table in order to find unformatted floating point numbers.
These are then given the default, table-wide, formatting.
```@example
using SummaryTables
cells = [
Cell(1.23456) Cell(12.3456)
Cell(0.123456) Cell(0.0123456)
]
Table(cells)
```
```@example
using SummaryTables
cells = [
Cell(1.23456) Cell(12.3456)
Cell(0.123456) Cell(0.0123456)
]
Table(cells; round_mode = :digits, round_digits = 5, trailing_zeros = true)
```
#### `Concat`
All the arguments of `Concat` are concatenated together in the final output.
Note that this is usually preferrable to string-interpolating multiple values because you lose special handling of the value types (like floating point rounding behavior or special LaTeX formatting) if you turn them into strings.
```@example
using SummaryTables
using Statistics
some_numbers = [1, 2, 4, 7, 8, 13, 27]
mu = mean(some_numbers)
sd = std(some_numbers)
cells = [
Cell("Mean (SD) interpolated") Cell("$mu ($sd)")
Cell("Mean (SD) Concat") Cell(Concat(mu, " (", sd, ")"))
]
Table(cells)
```
#### `Multiline`
Use the `Multiline` type to force linebreaks between different values in a cell.
A `Multiline` value may not be nested inside other values in a cell, it may only be the outermost value.
All nested values retain their special behaviors, so using `Multiline` is preferred over hardcoding linebreaks in the specific output formats yourself.
```@example
using SummaryTables
cells = [
Cell(Multiline("A1 a", "A1 b")) Cell("B1")
Cell("A2") Cell("B2")
]
Table(cells)
```
#### `Annotated`
To annotate elements in a table with footnotes, use the `Annotated` type.
It takes an arbitrary `value` to annotate as well as an `annotation` which becomes a footnote in the table.
You can also pass the `label` keyword if you don't want an auto-incrementing number as the label.
You can also pass `label = nothing` if you want a footnote without label.
```@example
using SummaryTables
cells = [
Cell(Annotated("A1", "This is the first cell")) Cell("B1")
Cell(Annotated("A2", "A custom label", label = "x")) Cell("B2")
Cell(Annotated("-", "- A missing value", label = nothing)) Cell("B3")
]
Table(cells)
```
#### `Superscript`
Displays the wrapped value in superscript style.
Use this instead of hardcoding output format specific commands.
```@example
using SummaryTables
cells = [
Cell("Without superscript") Cell(Concat("With ", Superscript("superscript")));
]
Table(cells)
```
#### `Subscript`
Displays the wrapped value in subscript style.
Use this instead of hardcoding output format specific commands.
```@example
using SummaryTables
cells = [
Cell("Without subscript") Cell(Concat("With ", Subscript("subscript")));
]
Table(cells)
```
## Optional argument 2: `cellstyle`
You may pass the style settings of a `Cell` as a positional argument of type [`CellStyle`](@ref).
It is usually more convenient, however, to use the keyword arguments to `Cell` instead.
```@example
using SummaryTables
Table([
Cell("A1", CellStyle(bold = true)) Cell("B1", CellStyle(underline = true))
Cell("A2", CellStyle(italic = true)) Cell("B2", CellStyle(indent_pt = 10))
])
```
| SummaryTables | https://github.com/PumasAI/SummaryTables.jl.git |
|
[
"MIT"
] | 3.0.0 | 6391447698371a09458574a620f02ad91afbec3a | docs | 3268 | # `CellStyle`
## Keyword: `bold`
Makes the text in the cell bold.
```@example
using SummaryTables
cells = reshape([
Cell("Some text in bold", bold = true),
], :, 1)
Table(cells)
```
## Keyword: `italic`
Makes the text in the cell italic.
```@example
using SummaryTables
cells = reshape([
Cell("Some text in italic", italic = true),
], :, 1)
Table(cells)
```
## Keyword: `underline`
Underlines the text in the cell.
```@example
using SummaryTables
cells = reshape([
Cell(Multiline("Some", "text", "that is", "underlined"), underline = true),
], :, 1)
Table(cells)
```
## Keyword: `halign`
Aligns the cell content horizontally either at the `:left`, the `:center` or the `:right`.
```@example
using SummaryTables
cells = reshape([
Cell("A wide cell"),
Cell(":left", halign = :left),
Cell(":center", halign = :center),
Cell(":right", halign = :right),
], :, 1)
Table(cells)
```
## Keyword: `valign`
Aligns the cell content vertically either at the `:top`, the `:center` or the `:bottom`.
```@example
using SummaryTables
cells = reshape([
Cell(Multiline("A", "tall", "cell")),
Cell(":top", valign = :top),
Cell(":center", valign = :center),
Cell(":bottom", valign = :bottom),
], 1, :)
Table(cells)
```
## Keyword: `indent_pt`
Indents the content of the cell on the left by the given number of `pt` units.
This can be used to give hierarchical structure to adjacent rows.
```@example
using SummaryTables
C(value; kwargs...) = Cell(value; halign = :left, kwargs...)
cells = [
C("Group A") C("Group B")
C("Subgroup A", indent_pt = 6) C("Subgroup B", indent_pt = 6)
C("Subgroup A", indent_pt = 6) C("Subgroup B", indent_pt = 6)
]
Table(cells)
```
## Keyword: `border_bottom`
Adds a border at the bottom of the cell.
This option is meant for horizontally merged cells functioning as subheaders.
```@example
using SummaryTables
header_cell = Cell("header", border_bottom = true, merge = true)
cells = [
header_cell header_cell
Cell("body") Cell("body")
]
Table(cells)
```
## Keyword: `merge`
All adjacent cells that are `==` equal to each other and have `merge = true` will be rendered as one merged cell.
```@example
using SummaryTables
merged_cell = Cell("merged", valign = :center, merge = true)
cells = [
Cell("A1") Cell("B1") Cell("C1") Cell("D1")
Cell("A2") merged_cell merged_cell Cell("D2")
Cell("A3") merged_cell merged_cell Cell("D3")
Cell("A4") Cell("B4") Cell("C4") Cell("D4")
]
Table(cells)
```
## Keyword: `mergegroup`
Because adjacent cells that are `==` equal to each other are merged when `merge = true` is set, you can optionally
set the `mergegroup` keyword of adjacent cells to a different value to avoid merging them even if their values are otherwise equal.
```@example
using SummaryTables
merged_cell_1 = Cell("merged", valign = :center, merge = true, mergegroup = 1)
merged_cell_2 = Cell("merged", valign = :center, merge = true, mergegroup = 2)
cells = [
Cell("A1") Cell("B1") Cell("C1") Cell("D1")
Cell("A2") merged_cell_1 merged_cell_2 Cell("D2")
Cell("A3") merged_cell_1 merged_cell_2 Cell("D3")
Cell("A4") Cell("B4") Cell("C4") Cell("D4")
]
Table(cells)
```
| SummaryTables | https://github.com/PumasAI/SummaryTables.jl.git |
|
[
"MIT"
] | 3.0.0 | 6391447698371a09458574a620f02ad91afbec3a | docs | 2461 | # `Table`
You can build custom tables using the `Table` type.
## Argument 1: `cells`
The table's content is given as an `AbstractMatrix` of `Cell`s:
```@example
using SummaryTables
cells = [Cell("$col$row") for row in 1:5, col in 'A':'E']
Table(cells)
```
## Keyword: `header`
You can pass an `Int` to mark the last row of the header section.
A divider line is placed after this row.
```@example
using SummaryTables
cells = [Cell("$col$row") for row in 1:5, col in 'A':'E']
Table(cells; header = 1)
```
## Keyword: `footer`
You can pass an `Int` to mark the first row of the footer section.
A divider line is placed before this row.
```@example
using SummaryTables
cells = [Cell("$col$row") for row in 1:5, col in 'A':'E']
Table(cells; footer = 5)
```
## Keyword: `footnotes`
The `footnotes` keyword allows to add custom footnotes to the table which do not correspond to specific [`Annotated`](@ref) values in the table.
```@example
using SummaryTables
cells = [Cell("$col$row") for row in 1:5, col in 'A':'E']
Table(cells; footnotes = ["Custom footnote 1", "Custom footnote 2"])
```
## Keyword: `rowgaps`
It can be beneficial for the readability of larger tables to add gaps between certain rows.
These gaps can be passed as a `Vector` of `Pair`s where the first element is the index of the row gap and the second element is the gap size in `pt`.
```@example
using SummaryTables
cells = [Cell("$col$row") for row in 1:9, col in 'A':'E']
Table(cells; rowgaps = [3 => 8.0, 6 => 8.0])
```
## Keyword: `colgaps`
It can be beneficial for the readability of larger tables to add gaps between certain columns.
These gaps can be passed as a `Vector` of `Pair`s where the first element is the index of the column gap and the second element is the gap size in `pt`.
```@example
using SummaryTables
cells = [Cell("$col$row") for row in 1:5, col in 'A':'I']
Table(cells; colgaps = [3 => 8.0, 6 => 8.0])
```
## Keyword: `linebreak_footnotes`
By default, footnotes are printed on a separate line each.
They can be printed in a single paragraph by setting `linebreak_footnotes = false`.
```@example linebreak_footnotes
using SummaryTables
cells = [Cell("$col$row") for row in 1:5, col in 'A':'I']
Table(cells; footnotes = ["Footnote 1.", "Footnote 2."])
```
```@example linebreak_footnotes
Table(cells; footnotes = ["Footnote 1.", "Footnote 2."], linebreak_footnotes = false)
```
## Types of cell values
TODO: List the different options here
| SummaryTables | https://github.com/PumasAI/SummaryTables.jl.git |
|
[
"MIT"
] | 3.0.0 | 6391447698371a09458574a620f02ad91afbec3a | docs | 13711 | # `listingtable`
## Synopsis
A listing table displays the raw data from one column of a source table, with optional summary sections interleaved between.
The row and column structure of the listing table is defined by grouping columns from the source table.
Each row of data has to have its own cell in the listing table, therefore the grouping applied along rows and columns must be exhaustive, i.e., no two rows may end up in the same group together.
Here is an example of a hypothetical clinical trial with drug concentration measurements of two participants with five time points each.
```@example
using DataFrames
using SummaryTables
using Statistics
data = DataFrame(
concentration = [1.2, 4.5, 2.0, 1.5, 0.1, 1.8, 3.2, 1.8, 1.2, 0.2],
id = repeat([1, 2], inner = 5),
time = repeat([0, 0.5, 1, 2, 3], 2)
)
listingtable(
data,
:concentration => "Concentration (ng/mL)",
rows = :id => "ID",
cols = :time => "Time (hr)",
summarize_rows = [
length => "N",
mean => "Mean",
std => "SD",
]
)
```
## Argument 1: `table`
The first argument can be any object that is a table compatible with the `Tables.jl` API.
Here are some common examples:
### `DataFrame`
```@example
using DataFrames
using SummaryTables
data = DataFrame(value = 1:6, group1 = repeat(["A", "B", "C"], 2), group2 = repeat(["D", "E"], inner = 3))
listingtable(data, :value, rows = :group1, cols = :group2)
```
### `NamedTuple` of `Vector`s
```@example
using SummaryTables
data = (; value = 1:6, group1 = repeat(["A", "B", "C"], 2), group2 = repeat(["D", "E"], inner = 3))
listingtable(data, :value, rows = :group1, cols = :group2)
```
### `Vector` of `NamedTuple`s
```@example
using SummaryTables
data = [
(value = 1, group1 = "A", group2 = "D")
(value = 2, group1 = "B", group2 = "D")
(value = 3, group1 = "C", group2 = "D")
(value = 4, group1 = "A", group2 = "E")
(value = 5, group1 = "B", group2 = "E")
(value = 6, group1 = "C", group2 = "E")
]
listingtable(data, :value, rows = :group1, cols = :group2)
```
## Argument 2: `variable`
The second argument primarily selects the table column whose data should populate the cells of the listing table.
The column name is specified with a `Symbol`:
```@example
using DataFrames
using SummaryTables
data = DataFrame(
value1 = 1:6,
value2 = 7:12,
group1 = repeat(["A", "B", "C"], 2),
group2 = repeat(["D", "E"], inner = 3)
)
listingtable(data, :value1, rows = :group1, cols = :group2)
```
Here we choose to list column `:value2` instead:
```@example
using DataFrames
using SummaryTables
data = DataFrame(
value1 = 1:6,
value2 = 7:12,
group1 = repeat(["A", "B", "C"], 2),
group2 = repeat(["D", "E"], inner = 3)
)
listingtable(data, :value2, rows = :group1, cols = :group2)
```
By default, the variable name is used as the label as well.
You can pass a different label as the second element of a `Pair` using the `=>` operators.
The label can be of any type (refer to [Types of cell values](@ref) for a list).
```@example
using DataFrames
using SummaryTables
data = DataFrame(
value1 = 1:6,
value2 = 7:12,
group1 = repeat(["A", "B", "C"], 2),
group2 = repeat(["D", "E"], inner = 3)
)
listingtable(data, :value1 => "Value", rows = :group1, cols = :group2)
```
## Optional argument 3: `pagination`
A listing table can grow large, in which case it may make sense to split it into multiple pages.
You can pass a `Pagination` object with `rows` and / or `cols` keyword arguments.
The `Int` you pass to `rows` and / or `cols` determines how many "sections" of the table along that dimension are included in a single page.
If there are no summary statistics, a "section" is a single row or column.
If there are summary statistics, a "section" includes all the rows or columns that are summarized together (as it would not make sense to split summarized groups across multiple pages).
If the `pagination` argument is provided, the return type of `listingtable` changes to `PaginatedTable{ListingPageMetadata}`.
This object has an interactive HTML representation for convenience the exact form of which should not be considered stable across SummaryTables versions.
The `PaginatedTable` should be deconstructed into separate `Table`s when you want to include these in a document.
Here is an example listing table without pagination:
```@example
using DataFrames
using SummaryTables
data = DataFrame(
value = 1:30,
group1 = repeat(["A", "B", "C", "D", "E"], 6),
group2 = repeat(["F", "G", "H", "I", "J", "K"], inner = 5)
)
listingtable(data, :value, rows = :group1, cols = :group2)
```
And here is the same table paginated into groups of 3 sections along the both the rows and columns.
Note that there are only five rows in the original table, which is not divisible by 3, so two pages have only two rows.
```@example
using DataFrames
using SummaryTables
data = DataFrame(
value = 1:30,
group1 = repeat(["A", "B", "C", "D", "E"], 6),
group2 = repeat(["F", "G", "H", "I", "J", "K"], inner = 5)
)
listingtable(data, :value, Pagination(rows = 3, cols = 3), rows = :group1, cols = :group2)
```
We can also paginate only along the rows:
```@example
using DataFrames
using SummaryTables
data = DataFrame(
value = 1:30,
group1 = repeat(["A", "B", "C", "D", "E"], 6),
group2 = repeat(["F", "G", "H", "I", "J", "K"], inner = 5)
)
listingtable(data, :value, Pagination(rows = 3), rows = :group1, cols = :group2)
```
Or only along the columns:
```@example
using DataFrames
using SummaryTables
data = DataFrame(
value = 1:30,
group1 = repeat(["A", "B", "C", "D", "E"], 6),
group2 = repeat(["F", "G", "H", "I", "J", "K"], inner = 5)
)
listingtable(data, :value, Pagination(cols = 3), rows = :group1, cols = :group2)
```
## Keyword: `rows`
The `rows` keyword determines the grouping structure along the rows.
It can either be a `Symbol` specifying a grouping column, a `Pair{Symbol,Any}` where the second element overrides the group's label, or a `Vector` with multiple groups of the aforementioned format.
This example uses a single group with default label.
```@example
using DataFrames
using SummaryTables
data = DataFrame(
value = 1:5,
group = ["A", "B", "C", "D", "E"],
)
listingtable(data, :value, rows = :group)
```
The label can be overridden using the `Pair` operator.
```@example
using DataFrames
using SummaryTables
data = DataFrame(
value = 1:5,
group = ["A", "B", "C", "D", "E"],
)
listingtable(data, :value, rows = :group => "Group")
```
Multiple groups are possible as well, in that case you get a nested display where the last group changes the fastest.
```@example
using DataFrames
using SummaryTables
data = DataFrame(
value = 1:5,
group1 = ["F", "F", "G", "G", "G"],
group2 = ["A", "B", "C", "D", "E"],
)
listingtable(data, :value, rows = [:group1, :group2 => "Group 2"])
```
## Keyword: `cols`
The `cols` keyword determines the grouping structure along the columns.
It can either be a `Symbol` specifying a grouping column, a `Pair{Symbol,Any}` where the second element overrides the group's label, or a `Vector` with multiple groups of the aforementioned format.
This example uses a single group with default label.
```@example
using DataFrames
using SummaryTables
data = DataFrame(
value = 1:5,
group = ["A", "B", "C", "D", "E"],
)
listingtable(data, :value, cols = :group)
```
The label can be overridden using the `Pair` operator.
```@example
using DataFrames
using SummaryTables
data = DataFrame(
value = 1:5,
group = ["A", "B", "C", "D", "E"],
)
listingtable(data, :value, cols = :group => "Group")
```
Multiple groups are possible as well, in that case you get a nested display where the last group changes the fastest.
```@example
using DataFrames
using SummaryTables
data = DataFrame(
value = 1:5,
group1 = ["F", "F", "G", "G", "G"],
group2 = ["A", "B", "C", "D", "E"],
)
listingtable(data, :value, cols = [:group1, :group2 => "Group 2"])
```
## Keyword: `summarize_rows`
This keyword takes a list of aggregation functions which are used to summarize the listed variable along the rows.
A summary function should take a vector of values (usually that will be numbers) and output one summary value.
This value can be of any type that SummaryTables can show in a cell (refer to [Types of cell values](@ref) for a list).
```@example
using DataFrames
using SummaryTables
using Statistics: mean, std
data = DataFrame(
value = 1:24,
group1 = repeat(["A", "B", "C", "D", "E", "F"], 4),
group2 = repeat(["G", "H", "I", "J"], inner = 6),
)
mean_sd(values) = Concat(mean(values), " (", std(values), ")")
listingtable(data,
:value,
rows = :group1,
cols = :group2,
summarize_rows = [
mean,
std => "SD",
mean_sd => "Mean (SD)",
]
)
```
By default, one summary will be calculated over all rows of a given column.
You can also choose to compute one summary for each group of a row grouping column, which makes sense if there is more than one row grouping column.
In this example, one summary is computed for each level of the `group1` column.
```@example
using DataFrames
using SummaryTables
using Statistics: mean, std
data = DataFrame(
value = 1:24,
group1 = repeat(["X", "Y"], 12),
group2 = repeat(["A", "B", "C"], 8),
group3 = repeat(["G", "H", "I", "J"], inner = 6),
)
mean_sd(values) = Concat(mean(values), " (", std(values), ")")
listingtable(data,
:value,
rows = [:group1, :group2],
cols = :group3,
summarize_rows = :group1 => [
mean,
std => "SD",
mean_sd => "Mean (SD)",
]
)
```
## Keyword: `summarize_cols`
This keyword takes a list of aggregation functions which are used to summarize the listed variable along the columns.
A summary function should take a vector of values (usually that will be numbers) and output one summary value.
This value can be of any type that SummaryTables can show in a cell (refer to [Types of cell values](@ref) for a list).
```@example
using DataFrames
using SummaryTables
using Statistics: mean, std
data = DataFrame(
value = 1:24,
group1 = repeat(["A", "B", "C", "D", "E", "F"], 4),
group2 = repeat(["G", "H", "I", "J"], inner = 6),
)
mean_sd(values) = Concat(mean(values), " (", std(values), ")")
listingtable(data,
:value,
rows = :group1,
cols = :group2,
summarize_cols = [
mean,
std => "SD",
mean_sd => "Mean (SD)",
]
)
```
By default, one summary will be calculated over all columns of a given row.
You can also choose to compute one summary for each group of a column grouping column, which makes sense if there is more than one column grouping column.
In this example, one summary is computed for each level of the `group1` column.
```@example
using DataFrames
using SummaryTables
using Statistics: mean, std
data = DataFrame(
value = 1:24,
group1 = repeat(["X", "Y"], 12),
group2 = repeat(["A", "B", "C"], 8),
group3 = repeat(["G", "H", "I", "J"], inner = 6),
)
mean_sd(values) = Concat(mean(values), " (", std(values), ")")
listingtable(data,
:value,
cols = [:group1, :group2],
rows = :group3,
summarize_cols = :group1 => [
mean,
std => "SD",
mean_sd => "Mean (SD)",
]
)
```
## Keyword: `variable_header`
If you set `variable_header = false`, you can hide the header cell with the variable label, which makes the table layout a little more compact.
Here is a table with the header cell:
```@example
using DataFrames
using SummaryTables
data = DataFrame(
value = 1:6,
group1 = repeat(["A", "B", "C"], 2),
group2 = repeat(["D", "E"], inner = 3)
)
listingtable(data, :value, rows = :group1, cols = :group2, variable_header = true)
```
And here is a table without it:
```@example
using DataFrames
using SummaryTables
data = DataFrame(
value = 1:6,
group1 = repeat(["A", "B", "C"], 2),
group2 = repeat(["D", "E"], inner = 3)
)
listingtable(data, :value, rows = :group1, cols = :group2, variable_header = false)
```
## Keyword: `sort`
By default, group entries are sorted.
If you need to maintain the order of entries from your dataset, set `sort = false`.
Notice how in the following two examples, the group indices are `"dos"`, `"tres"`, `"uno"` when sorted, but `"uno"`, `"dos"`, `"tres"` when not sorted.
If we want to preserve the natural order of these groups ("uno", "dos", "tres" meaning "one", "two", "three" in Spanish but having a different alphabetical order) we need to set `sort = false`.
```@example sort
using DataFrames
using SummaryTables
data = DataFrame(
value = 1:6,
group1 = repeat(["uno", "dos", "tres"], inner = 2),
group2 = repeat(["cuatro", "cinco"], 3),
)
listingtable(data, :value, rows = :group1, cols = :group2)
```
```@example sort
listingtable(data, :value, rows = :group1, cols = :group2, sort = false)
```
!!! warning
If you have multiple groups, `sort = false` can lead to splitting of higher-level groups if they are not correctly ordered in the source data.
Compare the following two tables.
In the second one, the group "A" is split by "B" so the label appears twice.
```@example bad_sort
using SummaryTables
using DataFrames
data = DataFrame(
value = 1:4,
group1 = ["A", "B", "B", "A"],
group2 = ["C", "D", "C", "D"],
)
listingtable(data, :value, rows = [:group1, :group2])
```
```@example bad_sort
data = DataFrame(
value = 1:4,
group1 = ["A", "B", "B", "A"],
group2 = ["C", "D", "C", "D"],
)
listingtable(data, :value, rows = [:group1, :group2], sort = false)
```
| SummaryTables | https://github.com/PumasAI/SummaryTables.jl.git |
|
[
"MIT"
] | 3.0.0 | 6391447698371a09458574a620f02ad91afbec3a | docs | 8756 | # `summarytable`
## Synopsis
A summary table summarizes the raw data from one column of a source table for different groups defined by grouping columns.
It is similar to a [`listingtable`](@ref) without the raw values.
Here is an example of a hypothetical clinical trial with drug concentration measurements of two participants with five time points each.
```@example
using DataFrames
using SummaryTables
using Statistics
data = DataFrame(
concentration = [1.2, 4.5, 2.0, 1.5, 0.1, 1.8, 3.2, 1.8, 1.2, 0.2],
id = repeat([1, 2], inner = 5),
time = repeat([0, 0.5, 1, 2, 3], 2)
)
summarytable(
data,
:concentration => "Concentration (ng/mL)",
cols = :time => "Time (hr)",
summary = [
length => "N",
mean => "Mean",
std => "SD",
]
)
```
## Argument 1: `table`
The first argument can be any object that is a table compatible with the `Tables.jl` API.
Here are some common examples:
### `DataFrame`
```@example
using DataFrames
using SummaryTables
using Statistics
data = DataFrame(
value = 1:6,
group = repeat(["A", "B", "C"], 2),
)
summarytable(data, :value, cols = :group, summary = [mean, std])
```
### `NamedTuple` of `Vector`s
```@example
using SummaryTables
using Statistics
data = (; value = 1:6, group = repeat(["A", "B", "C"], 2))
summarytable(data, :value, cols = :group, summary = [mean, std])
```
### `Vector` of `NamedTuple`s
```@example
using SummaryTables
using Statistics
data = [
(value = 1, group = "A")
(value = 2, group = "B")
(value = 3, group = "C")
(value = 4, group = "A")
(value = 5, group = "B")
(value = 6, group = "C")
]
summarytable(data, :value, cols = :group, summary = [mean, std])
```
## Argument 2: `variable`
The second argument primarily selects the table column whose data should populate the cells of the summary table.
The column name is specified with a `Symbol`:
```@example
using DataFrames
using SummaryTables
using Statistics
data = DataFrame(
value1 = 1:6,
value2 = 7:12,
group = repeat(["A", "B", "C"], 2),
)
summarytable(data, :value1, cols = :group, summary = [mean, std])
```
Here we choose to list column `:value2` instead:
```@example
using DataFrames
using SummaryTables
using Statistics
data = DataFrame(
value1 = 1:6,
value2 = 7:12,
group = repeat(["A", "B", "C"], 2),
)
summarytable(data, :value2, cols = :group, summary = [mean, std])
```
By default, the variable name is used as the label as well.
You can pass a different label as the second element of a `Pair` using the `=>` operators.
The label can be of any type (refer to [Types of cell values](@ref) for a list).
```@example
using DataFrames
using SummaryTables
using Statistics
data = DataFrame(
value1 = 1:6,
value2 = 7:12,
group = repeat(["A", "B", "C"], 2),
)
summarytable(data, :value1 => "Value", cols = :group, summary = [mean, std])
```
## Keyword: `rows`
The `rows` keyword determines the grouping structure along the rows.
It can either be a `Symbol` specifying a grouping column, a `Pair{Symbol,Any}` where the second element overrides the group's label, or a `Vector` with multiple groups of the aforementioned format.
This example uses a single group with default label.
```@example
using DataFrames
using SummaryTables
using Statistics
data = DataFrame(
value = 1:6,
group = repeat(["A", "B", "C"], 2),
)
summarytable(data, :value, rows = :group, summary = [mean, std])
```
The label can be overridden using the `Pair` operator.
```@example
using DataFrames
using SummaryTables
using Statistics
data = DataFrame(
value = 1:6,
group = repeat(["A", "B", "C"], 2),
)
summarytable(data, :value, rows = :group => "Group", summary = [mean, std])
```
Multiple groups are possible as well, in that case you get a nested display where the last group changes the fastest.
```@example
using DataFrames
using SummaryTables
using Statistics
data = DataFrame(
value = 1:12,
group1 = repeat(["A", "B"], inner = 6),
group2 = repeat(["C", "D", "E"], 4),
)
summarytable(data, :value, rows = [:group1, :group2 => "Group 2"], summary = [mean, std])
```
## Keyword: `cols`
The `cols` keyword determines the grouping structure along the columns.
It can either be a `Symbol` specifying a grouping column, a `Pair{Symbol,Any}` where the second element overrides the group's label, or a `Vector` with multiple groups of the aforementioned format.
This example uses a single group with default label.
```@example
using DataFrames
using SummaryTables
using Statistics
data = DataFrame(
value = 1:6,
group = repeat(["A", "B", "C"], 2),
)
summarytable(data, :value, cols = :group, summary = [mean, std])
```
The label can be overridden using the `Pair` operator.
```@example
using DataFrames
using SummaryTables
using Statistics
data = DataFrame(
value = 1:6,
group = repeat(["A", "B", "C"], 2),
)
summarytable(data, :value, cols = :group => "Group", summary = [mean, std])
```
Multiple groups are possible as well, in that case you get a nested display where the last group changes the fastest.
```@example
using DataFrames
using SummaryTables
using Statistics
data = DataFrame(
value = 1:12,
group1 = repeat(["A", "B"], inner = 6),
group2 = repeat(["C", "D", "E"], 4),
)
summarytable(data, :value, cols = [:group1, :group2 => "Group 2"], summary = [mean, std])
```
## Keyword: `summary`
This keyword takes a list of aggregation functions which are used to summarize the chosen variable.
A summary function should take a vector of values (usually that will be numbers) and output one summary value.
This value can be of any type that SummaryTables can show in a cell (refer to [Types of cell values](@ref) for a list).
```@example
using DataFrames
using SummaryTables
using Statistics
data = DataFrame(
value = 1:24,
group1 = repeat(["A", "B", "C", "D"], 6),
group2 = repeat(["E", "F", "G"], inner = 8),
)
mean_sd(values) = Concat(mean(values), " (", std(values), ")")
summarytable(
data,
:value,
rows = :group1,
cols = :group2,
summary = [
mean,
std => "SD",
mean_sd => "Mean (SD)",
]
)
```
## Keyword: `variable_header`
If you set `variable_header = false`, you can hide the header cell with the variable label, which makes the table layout a little more compact.
Here is a table with the header cell:
```@example
using DataFrames
using SummaryTables
using Statistics
data = DataFrame(
value = 1:24,
group1 = repeat(["A", "B", "C", "D"], 6),
group2 = repeat(["E", "F", "G"], inner = 8),
)
summarytable(
data,
:value,
rows = :group1,
cols = :group2,
summary = [mean, std],
)
```
And here is a table without it:
```@example
using DataFrames
using SummaryTables
using Statistics
data = DataFrame(
value = 1:24,
group1 = repeat(["A", "B", "C", "D"], 6),
group2 = repeat(["E", "F", "G"], inner = 8),
)
summarytable(
data,
:value,
rows = :group1,
cols = :group2,
summary = [mean, std],
variable_header = false,
)
```
## Keyword: `sort`
By default, group entries are sorted.
If you need to maintain the order of entries from your dataset, set `sort = false`.
Notice how in the following two examples, the group indices are `"dos"`, `"tres"`, `"uno"` when sorted, but `"uno"`, `"dos"`, `"tres"` when not sorted.
If we want to preserve the natural order of these groups ("uno", "dos", "tres" meaning "one", "two", "three" in Spanish but having a different alphabetical order) we need to set `sort = false`.
```@example sort
using DataFrames
using SummaryTables
using Statistics
data = DataFrame(
value = 1:18,
group1 = repeat(["uno", "dos", "tres"], inner = 6),
group2 = repeat(["cuatro", "cinco"], 9),
)
summarytable(data, :value, rows = :group1, cols = :group2, summary = [mean, std])
```
```@example sort
summarytable(data, :value, rows = :group1, cols = :group2, summary = [mean, std], sort = false)
```
!!! warning
If you have multiple groups, `sort = false` can lead to splitting of higher-level groups if they are not correctly ordered in the source data.
Compare the following two tables.
In the second one, the group "A" is split by "B" so the label appears twice.
```@example bad_sort
using SummaryTables
using DataFrames
using Statistics
data = DataFrame(
value = 1:4,
group1 = ["A", "B", "B", "A"],
group2 = ["C", "D", "C", "D"],
)
summarytable(data, :value, rows = [:group1, :group2], summary = [mean])
```
```@example bad_sort
data = DataFrame(
value = 1:4,
group1 = ["A", "B", "B", "A"],
group2 = ["C", "D", "C", "D"],
)
summarytable(data, :value, rows = [:group1, :group2], summary = [mean], sort = false)
```
| SummaryTables | https://github.com/PumasAI/SummaryTables.jl.git |
|
[
"MIT"
] | 3.0.0 | 6391447698371a09458574a620f02ad91afbec3a | docs | 8399 | # `table_one`
## Synopsis
"Table 1" is a common term for the first table in a paper that summarizes demographic and other individual data of the population that is being studied.
In general terms, it is a table where different columns from the source table are summarized separately, stacked along the rows.
The types of analysis can be chosen manually, or will be selected given the column types.
Optionally, there can be grouping applied along the columns as well.
In this example, several variables of a hypothetical population are analyzed split by sex.
```@example
using SummaryTables
using DataFrames
data = DataFrame(
sex = ["m", "m", "m", "m", "f", "f", "f", "f", "f", "f"],
age = [27, 45, 34, 85, 55, 44, 24, 29, 37, 76],
blood_type = ["A", "0", "B", "B", "B", "A", "0", "A", "A", "B"],
smoker = [true, false, false, false, true, true, true, false, false, false],
)
table_one(
data,
[:age => "Age (years)", :blood_type => "Blood type", :smoker => "Smoker"],
groupby = :sex => "Sex",
show_n = true
)
```
## Argument 1: `table`
The first argument can be any object that is a table compatible with the `Tables.jl` API.
Here are some common examples:
### `DataFrame`
```@example
using DataFrames
using SummaryTables
data = DataFrame(x = [1, 2, 3], y = ["4", "5", "6"])
table_one(data, [:x, :y])
```
### `NamedTuple` of `Vector`s
```@example
using SummaryTables
data = (; x = [1, 2, 3], y = ["4", "5", "6"])
table_one(data, [:x, :y])
```
### `Vector` of `NamedTuple`s
```@example
using SummaryTables
data = [(; x = 1, y = "4"), (; x = 2, y = "5"), (; x = 3, y = "6")]
table_one(data, [:x, :y])
```
## Argument 2: `analyses`
The second argument takes a vector specifying analyses, with one entry for each "row section" of the resulting table.
If only one analysis is passed, the vector can be omitted.
Each analysis can have up to three parts: the variable, the analysis function and the label.
The variable is passed as a `Symbol`, corresponding to a column in the input data, and must always be specified.
The other two parts are optional.
If you specify only variables, the analysis functions are chosen automatically based on the columns, and the labels are equal to the variable names.
Number variables show the mean, standard deviation, median, minimum and maximum.
String variables or other non-numeric variables show counts and percentages of each element type.
```@example
using SummaryTables
data = (; x = [1, 2, 3], y = ["a", "b", "a"])
table_one(data, [:x, :y])
```
In the next example, we rename the `x` variable by passing a `String` in a `Pair`.
```@example
using SummaryTables
data = (; x = [1, 2, 3], y = ["a", "b", "a"])
table_one(data, [:x => "Variable X", :y])
```
Labels can be any type except `<:Function` (that type signals that an analysis function has been passed).
One example of a non-string label is `Concat` in conjunction with `Superscript`.
```@example
using SummaryTables
data = (; x = [1, 2, 3], y = ["a", "b", "a"])
table_one(data, [:x => Concat("X", Superscript("with superscript")), :y])
```
Any object which is a subtype of `Function` is assumed to be an analysis function.
An analysis function takes a data column as input and returns a `Tuple` where each entry corresponds to one analysis row.
Each of these rows consists of a `Pair` where the left side is the analysis result and the right side the label.
Here's an example of a custom number column analysis function.
Note the use of `Concat` to build content out of multiple parts.
This is preferred to interpolating into a string because interpolation destroys the original objects and takes away the possibility for automatic rounding or other special post-processing or display behavior.
```@example
using SummaryTables
using Statistics
data = (; x = [1, 2, 3])
function custom_analysis(column)
(
minimum(column) => "Minimum",
maximum(column) => "Maximum",
Concat(mean(column), " (", std(column), ")") => "Mean (SD)",
)
end
table_one(data, :x => custom_analysis)
```
Finally, all three parts, variable, analysis function and label can be combined as well:
```@example
using SummaryTables
using Statistics
data = (; x = [1, 2, 3])
function custom_analysis(column)
(
minimum(column) => "Minimum",
maximum(column) => "Maximum",
Concat(mean(column), " (", std(column), ")") => "Mean (SD)",
)
end
table_one(data, :x => custom_analysis => "Variable X")
```
## Keyword: `groupby`
The `groupby` keyword takes a vector of column name symbols with optional labels.
If there is only one grouping column, the vector can be omitted.
Each analysis is then computed separately for each group.
```@example
using SummaryTables
data = (; x = [1, 2, 3, 4, 5, 6], y = ["a", "a", "a", "b", "b", "b"])
table_one(data, :x, groupby = :y)
```
In this example, we rename the grouping column:
```@example
using SummaryTables
data = (; x = [1, 2, 3, 4, 5, 6], y = ["a", "a", "a", "b", "b", "b"])
table_one(data, :x, groupby = :y => "Column Y")
```
If there are multiple grouping columns, they are shown in a nested fashion, with the first group at the highest level:
```@example
using SummaryTables
data = (;
x = [1, 2, 3, 4, 5, 6],
y = ["a", "a", "b", "b", "c", "c"],
z = ["d", "e", "d", "e", "d", "e"],
)
table_one(data, :x, groupby = [:y, :z => "Column Z"])
```
## Keyword: `show_n`
When `show_n` is set to `true`, the size of each group is shown under its name.
```@example
using SummaryTables
data = (; x = [1, 2, 3, 4, 5, 6], y = ["a", "a", "a", "a", "b", "b"])
table_one(data, :x, groupby = :y, show_n = true)
```
## Keyword: `show_total`
When `show_total` is set to `false`, the column summarizing all groups together is hidden.
Use this only when `groupby` is set, otherwise the resulting table will be empty.
```@example
using SummaryTables
data = (; x = [1, 2, 3, 4, 5, 6], y = ["a", "a", "a", "a", "b", "b"])
table_one(data, :x, groupby = :y, show_total = false)
```
## Keyword: `total_name`
The object that will be used to identify total columns. Can be of any value that SummaryTables knows how to display.
```@example
using SummaryTables
data = (; x = [1, 2, 3, 4, 5, 6], y = ["a", "a", "a", "a", "b", "b"])
table_one(data, :x, groupby = :y, total_name = "Overall")
```
## Keyword: `group_totals`
A `Symbol` or `Vector{Symbol}` specifying one or multiple groups for which to add subtotals. All but the topmost group can be chosen here as the topmost group is handled by `show_total` already.
```@example
using SummaryTables
data = (; x = 1:12, y = repeat(["a", "b"], 6), z = repeat(["c", "d"], inner = 6))
table_one(data, :x, groupby = [:y, :z], group_totals = :z)
```
This example shows multiple-level group totals. In order not to make the resulting table too wide, the topmost factor `q` just has one level which would otherwise be redundant.
```@example
using SummaryTables
data = (; x = 1:12, y = repeat(["a", "b"], 6), z = repeat(["c", "d"], inner = 6), q = repeat(["e"], 12))
table_one(data, :x, groupby = [:q, :y, :z], group_totals = [:y, :z])
```
## Keyword: `sort`
By default, group entries are sorted.
If you need to maintain the order of entries from your dataset, set `sort = false`.
Notice how in the following two examples, the group indices are `"dos"`, `"tres"`, `"uno"` when sorted, but `"uno"`, `"dos"`, `"tres"` when not sorted.
If we want to preserve the natural order of these groups ("uno", "dos", "tres" meaning "one", "two", "three" in Spanish but having a different alphabetical order) we need to set `sort = false`.
```@example sort
using SummaryTables
data = (; x = [1, 2, 3, 4, 5, 6], y = ["uno", "uno", "dos", "dos", "tres", "tres"])
table_one(data, :x, groupby = :y)
```
```@example sort
table_one(data, :x, groupby = :y, sort = false)
```
!!! warning
If you have multiple groups, `sort = false` can lead to splitting of higher-level groups if they are not correctly ordered in the source data.
Compare the following two tables.
In the second one, the group "A" is split by "B" so the label appears twice.
```@example bad_sort
using SummaryTables
data = (; x = [1, 2, 3, 4, 5, 6], y = ["A", "A", "B", "B", "B", "A"], z = ["C", "C", "C", "D", "D", "D"])
table_one(data, :x, groupby = [:y, :z])
```
```@example bad_sort
table_one(data, :x, groupby = [:y, :z], sort = false)
``` | SummaryTables | https://github.com/PumasAI/SummaryTables.jl.git |
|
[
"MIT"
] | 1.6.0 | 2bb2fd8988fa976a3e057bbe6197414d77d5e29d | code | 1109 | using CANalyze
using Documenter
DocMeta.setdocmeta!(CANalyze, :DocTestSetup, :(using CANalyze); recursive=true)
makedocs(;
modules=[CANalyze],
authors="Tim Lucas Sabelmann",
repo="https://github.com/tsabelmann/CANalyze.jl/blob/{commit}{path}#{line}",
sitename="CANTools.jl",
format=Documenter.HTML(;
prettyurls=get(ENV, "CI", "false") == "true",
canonical="https://tsabelmann.github.io/CANalyze.jl",
assets=String[],
),
pages=[
"Home" => "index.md",
"Usage" => [
"Signal" => "examples/signal.md",
"Message" => "examples/message.md",
"Database" => "examples/database.md",
"Decode" => "examples/decode.md"
],
"Documentation" => [
"Frames" => "frames.md",
"Utils" => "utils.md",
"Signals" => "signals.md",
"Messages" => "messages.md",
"Decode" => "decode.md",
"Encode" => "encode.md"
]
],
)
deploydocs(;
repo="github.com/tsabelmann/CANalyze.jl",
devbranch="main",
target="build"
)
| CANalyze | https://github.com/tsabelmann/CANalyze.jl.git |
|
[
"MIT"
] | 1.6.0 | 2bb2fd8988fa976a3e057bbe6197414d77d5e29d | code | 736 | using CANalyze.Signals
using CANalyze.Messages
using CANalyze.Databases
signal1 = Signals.NamedSignal("ABC", nothing, nothing, Signals.Float32Signal(start=0, byte_order=:little_endian))
signal2 = Signals.NamedSignal("ABCD", nothing, nothing, Signals.Unsigned(start=40, length=17, factor=2, offset=20, byte_order=:big_endian))
signal3 = Signals.NamedSignal("ABCDE", nothing, nothing, Signals.Unsigned(start=32, length=8, factor=2, offset=20, byte_order=:little_endian))
m1 = Messages.Message(0x1FE, 8, "ABC", signal1; strict=true)
m2 = Messages.Message(0x1FF, 8, "ABD", signal1, signal2, signal3; strict=true)
d = Databases.Database(m1, m2)
# println(d)
m = d["ABC"]
println(m)
m = d[0x1FF]
println(m)
m = get(d, 0x1FA)
println(m)
| CANalyze | https://github.com/tsabelmann/CANalyze.jl.git |
|
[
"MIT"
] | 1.6.0 | 2bb2fd8988fa976a3e057bbe6197414d77d5e29d | code | 867 | using CANalyze.Decode
using CANalyze.Frames
using CANalyze.Signals
using CANalyze.Messages
signal1 = Signals.NamedSignal("ABC", nothing, nothing, Signals.Float32Signal(start=0, byte_order=:little_endian))
signal2 = Signals.NamedSignal("ABCD", nothing, nothing, Signals.Unsigned(start=40, length=17, factor=2, offset=20, byte_order=:big_endian))
signal3 = Signals.NamedSignal("ABCDE", nothing, nothing, Signals.Unsigned(start=32, length=8, factor=2, offset=20, byte_order=:little_endian))
bits1 = Signals.Bits(signal1)
println(sort(Int64[bits1.bits...]))
bits1 = Signals.Bits(signal2)
println(sort(Int64[bits1.bits...]))
bits1 = Signals.Bits(signal3)
println(sort(Int64[bits1.bits...]))
frame = Frames.CANFrame(20, [1, 2, 0xFD, 4, 5, 6, 7, 8])
m = Messages.Message(0x1FF, 8, "ABC", signal1, signal2, signal3; strict=true)
d = Decode.decode(m, frame)
println(d)
| CANalyze | https://github.com/tsabelmann/CANalyze.jl.git |
|
[
"MIT"
] | 1.6.0 | 2bb2fd8988fa976a3e057bbe6197414d77d5e29d | code | 1628 | using CANalyze.Decode
using CANalyze.Frames
using CANalyze.Signals
frame = Frames.CANFrame(20, [1, 2, 0xFD, 4, 5, 6, 7, 8])
sig1 = Signals.Unsigned{Float32}(0, 1)
sig2 = Signals.Unsigned{Float64}(start=0, length=8, factor=2, offset=20)
sig3 = Signals.Unsigned(0, 8, 1, 0, :little_endian)
sig4 = Signals.Unsigned(start=0, length=8, factor=1.0, offset=-1337f0, byte_order=:little_endian)
sig5 = Signals.Signed{Float32}(0, 1)
sig6 = Signals.Signed{Float64}(start=3, length=16, factor=2, offset=20, byte_order=:big_endian)
sig7 = Signals.Signed(0, 8, 1, 0, :little_endian)
sig8 = Signals.Signed(start=0, length=8, factor=1.0, offset=-1337f0, byte_order=:little_endian)
sig9 = Signals.Raw(0, 8, :big_endian)
sig10 = Signals.Raw(start=21, length=7, byte_order=:little_endian)
println(sig1)
println(sig2)
println(sig3)
println(sig4)
println(sig5)
println(sig6)
println(sig7)
println(sig8)
println(sig9)
println(sig10)
# signal = Signals.Float32Signal(start=7, factor=1.0f0, offset=0.0f0, byte_order=:big_endian)
bits = Signals.Bits(sig6)
println(bits)
# value = Decode.decode(signal,frame)
# hex = reinterpret(UInt8, [value])
# println(value)
# println(hex)
#
# signal = Signals.Float32Signal(start=0, byte_order=:little_endian)
# value = Decode.decode(signal,frame)
# hex = reinterpret(UInt8, [value])
# println(value)
# println(hex)
# println(Signals.overlap(sig1,sig5))
s = Signals.Float32Signal(start=0, byte_order=:little_endian)
signal = Signals.NamedSignal("ABC", nothing, nothing, s)
# println(signal)
# value = Decode.decode(signal,frame)
# hex = reinterpret(UInt8, [value])
# println(value)
# println(hex)
| CANalyze | https://github.com/tsabelmann/CANalyze.jl.git |
|
[
"MIT"
] | 1.6.0 | 2bb2fd8988fa976a3e057bbe6197414d77d5e29d | code | 309 | module CANalyze
include("Utils.jl")
using .Utils
include("Frames.jl")
using .Frames
include("Signals.jl")
using .Signals
include("Messages.jl")
using .Messages
include("Databases.jl")
using .Databases
include("Decode.jl")
using .Decode
include("Encode.jl")
using .Encode
include("IO.jl")
using .IO
end
| CANalyze | https://github.com/tsabelmann/CANalyze.jl.git |
|
[
"MIT"
] | 1.6.0 | 2bb2fd8988fa976a3e057bbe6197414d77d5e29d | code | 2243 | module Databases
import Base
import ..Messages
struct Database
frame_id_index::Dict{UInt32, Ref{Messages.Message}}
name_index::Dict{String, Ref{Messages.Message}}
function Database(messages::Set{Messages.Message})
v = [messages...]
e = enumerate(v)
l1 = [Messages.name(m1) == Messages.name(m2) for (i, m1) in e for (j, m2) in e if i < j]
l2 = [Messages.frame_id(m1) == Messages.frame_id(m2) for (i, m1) in e for (j, m2) in e if i < j]
a1 = any(l1)
a2 = any(l2)
if a1
throw(DomainError(a1, "messages with the same name"))
end
if a2
throw(DomainError(a2, "messages with the same frame_id"))
end
frame_id_index = Dict{UInt32, Ref{Messages.Message}}()
name_index = Dict{String, Ref{Messages.Message}}()
for message in messages
m = Ref(message)
frame_id_index[Messages.frame_id(message)] = m
name_index[Messages.name(message)] = m
end
new(frame_id_index, name_index)
end
end
function Database(messages::Messages.Message...)
s = Set(messages)
return Database(s)
end
function Base.getindex(db::Database, index::String)
m_ref = db.name_index[index]
return m_ref[]
end
function Base.getindex(db::Database, index::UInt32)
m_ref = db.frame_id_index[index]
return m_ref[]
end
function Base.getindex(db::Database, index::Integer)
index = convert(UInt32, index)
return db[index]
end
function Base.get(db::Database, key::String, default=nothing)
try
value = db[key]
return value
catch
return default
end
end
function Base.get(db::Database, key::UInt32, default=nothing)
try
value = db[key]
return value
catch
return default
end
end
function Base.get(db::Database, key::Integer, default=nothing)
key = convert(UInt32, key)
return get(db, key, default)
end
export Database
end
| CANalyze | https://github.com/tsabelmann/CANalyze.jl.git |
|
[
"MIT"
] | 1.6.0 | 2bb2fd8988fa976a3e057bbe6197414d77d5e29d | code | 6387 | module Decode
import ..Utils
import ..Frames
import ..Signals
import ..Messages
"""
"""
function decode(signal::Signals.NamedSignal{T},
can_frame::Frames.CANFrame)::Union{Nothing,T} where {T}
try
sig = Signals.signal(signal)
return decode(sig, can_frame)
catch
return Signals.default(signal)
end
end
"""
"""
function decode(signal::Signals.UnnamedSignal{T}, can_frame::Frames.CANFrame,
default::D)::Union{T,D} where {T,D}
try
return decode(signal, can_frame)
catch
return default
end
end
"""
"""
function decode(signal::Signals.Bit, can_frame::Frames.CANFrame)::Bool
start = Signals.start(signal)
if start >= 8*Frames.dlc(can_frame)
throw(DomainError(start, "CANFrame does not have data at bit position"))
else
mask = Utils.mask(UInt64, 1, start)
value = Utils.from_bytes(UInt64, Frames.data(can_frame))
if mask & value != 0
return true
else
return false
end
end
end
"""
"""
function decode(signal::Signals.Unsigned{T}, can_frame::Frames.CANFrame) where {T}
start = Signals.start(signal)
length = Signals.length(signal)
factor = Signals.factor(signal)
offset = Signals.offset(signal)
byte_order = Signals.byte_order(signal)
if byte_order == :little_endian
end_bit = start + length - 1
if end_bit >= 8 * Frames.dlc(can_frame)
throw(DomainError(end_bit, "The bit($end_bit) cannot be selected"))
end
value = Utils.from_bytes(UInt64, Frames.data(can_frame))
value = value >> start
elseif byte_order == :big_endian
start_bit_in_byte = start % 8
start_byte = div(start, 8)
start = 8*start_byte + (7 - start_bit_in_byte)
new_shift = Int64(8*Frames.dlc(can_frame)) - Int64(start) - Int64(length)
if new_shift < 0
throw(DomainError(new_shift, "The bits cannot be selected"))
end
value = Utils.from_bytes(UInt64, reverse(Frames.data(can_frame)))
value = value >> new_shift
else
throw(DomainError(byte_order, "Byte order not supported"))
end
value = value & Utils.mask(UInt64, length)
result = T(value) * factor + offset
return result
end
function decode(signal::Signals.Signed{T}, can_frame::Frames.CANFrame) where {T}
start = Signals.start(signal)
length = Signals.length(signal)
factor = Signals.factor(signal)
offset = Signals.offset(signal)
byte_order = Signals.byte_order(signal)
if byte_order == :little_endian
end_bit = start + length - 1
if end_bit >= 8 * Frames.dlc(can_frame)
throw(DomainError(end_bit, "The bit($end_bit) cannot be selected"))
end
value = Utils.from_bytes(Int64, Frames.data(can_frame))
value = value >> start
elseif byte_order == :big_endian
start_bit_in_byte = start % 8
start_byte = div(start, 8)
start = 8*start_byte + (7 - start_bit_in_byte)
new_shift = Int64(8*Frames.dlc(can_frame)) - Int64(start) - Int64(length)
if new_shift < 0
throw(DomainError(new_shift, "The bits cannot be selected"))
end
value = Utils.from_bytes(Int64, reverse(Frames.data(can_frame)))
value = value >> new_shift
else
throw(DomainError(byte_order, "Byte order not supported"))
end
value = value & Utils.mask(Int64, length)
# sign extend value if most-significant bit is 1
if (value >> (length - 1)) & 0x01 != 0
value = value + ~Utils.mask(Int64, length)
end
result = T(value) * factor + offset
return result
end
"""
"""
function decode(signal::Signals.FloatSignal{T}, can_frame::Frames.CANFrame) where {T}
start = Signals.start(signal)
length = Signals.length(signal)
factor = Signals.factor(signal)
offset = Signals.offset(signal)
byte_order = Signals.byte_order(signal)
if byte_order == :little_endian
end_bit = start + length - 1
if end_bit >= 8 * Frames.dlc(can_frame)
throw(DomainError(end_bit, "The bit($end_bit) cannot be selected"))
end
value = Utils.from_bytes(UInt64, Frames.data(can_frame))
value = value >> start
elseif byte_order == :big_endian
start_bit_in_byte = start % 8
start_byte = div(start, 8)
start = 8*start_byte + (7 - start_bit_in_byte)
new_shift = Int64(8*Frames.dlc(can_frame)) - Int64(start) - Int64(length)
if new_shift < 0
throw(DomainError(new_shift, "The bits cannot be selected"))
end
value = Utils.from_bytes(UInt64, reverse(Frames.data(can_frame)))
value = value >> new_shift
else
throw(DomainError(byte_order, "Byte order not supported"))
end
value = value & Utils.mask(UInt64, length)
result = Utils.from_bytes(T, Utils.to_bytes(value))
result = factor * result + offset
return result
end
"""
"""
function decode(signal::Signals.Raw, can_frame::Frames.CANFrame)::UInt64
start = Signals.start(signal)
length = Signals.length(signal)
byte_order = Signals.byte_order(signal)
if byte_order == :little_endian
end_bit = start + length - 1
if end_bit >= 8 * Frames.dlc(can_frame)
throw(DomainError(end_bit, "The bit($end_bit) cannot be selected"))
end
value = Utils.from_bytes(UInt64, Frames.data(can_frame))
value = value >> start
elseif byte_order == :big_endian
start_bit_in_byte = start % 8
start_byte = div(start, 8)
start = 8*start_byte + (7 - start_bit_in_byte)
new_shift::Int16 = Int64(8*Frames.dlc(can_frame)) - Int64(start) - Int64(length)
if new_shift < 0
throw(DomainError(new_shift, "The bits cannot be selected"))
end
value = Utils.from_bytes(UInt64, reverse(Frames.data(can_frame)))
value = value >> new_shift
else
throw(DomainError(byte_order, "Byte order not supported"))
end
result = value & Utils.mask(UInt64, length)
return UInt64(result)
end
function decode(message::Messages.Message, can_frame::Frames.CANFrame)
d = Dict()
for (key, signal) in message
value = decode(signal, can_frame)
d[key] = value
end
return d
end
export decode
end
| CANalyze | https://github.com/tsabelmann/CANalyze.jl.git |
|
[
"MIT"
] | 1.6.0 | 2bb2fd8988fa976a3e057bbe6197414d77d5e29d | code | 92 | """
"""
module Encode
import ..Utils
import ..Frames
import ..Signals
import ..Messages
end
| CANalyze | https://github.com/tsabelmann/CANalyze.jl.git |
|
[
"MIT"
] | 1.6.0 | 2bb2fd8988fa976a3e057bbe6197414d77d5e29d | code | 3109 | module Frames
import Base
"""
"""
abstract type AbstractCANFrame end
"""
"""
mutable struct CANFrame <: AbstractCANFrame
frame_id::UInt32
data::Array{UInt8,1}
is_extended::Bool
function CANFrame(frame_id::UInt32, data::AbstractArray{UInt8};
is_extended::Bool=false)
if length(data) > 8
throw(DomainError(data, "CANFrame allows a maximum of 8 bytes"))
end
return new(frame_id, data, is_extended)
end
end
"""
"""
function CANFrame(frame_id::Integer, data::A; is_extended::Bool=false) where
{A <: AbstractArray{<:Integer}}
return CANFrame(convert(UInt32, frame_id), UInt8[data...]; is_extended=is_extended)
end
"""
"""
function CANFrame(frame_id::Integer, data::Integer...; is_extended::Bool=false)
return CANFrame(convert(UInt32, frame_id), UInt8[data...]; is_extended=is_extended)
end
"""
"""
function CANFrame(frame_id::Integer; is_extended=false)
return CANFrame(convert(UInt32, frame_id), UInt8[]; is_extended=is_extended)
end
"""
"""
mutable struct CANFdFrame <: AbstractCANFrame
frame_id::UInt32
data::Array{UInt8,1}
is_extended::Bool
"""
"""
function CANFdFrame(frame_id::UInt32, data::A; is_extended::Bool=false) where
{A <: AbstractArray{UInt8}}
if length(data) > 64
throw(DomainError(data, "CANFdFrame allows a maximum of 64 bytes"))
end
return new(frame_id, data, is_extended)
end
end
"""
"""
function CANFdFrame(frame_id::Integer, data::A; is_extended::Bool=false) where
{A <: AbstractArray{<:Integer}}
return CANFdFrame(convert(UInt32, frame_id), UInt8[data...]; is_extended)
end
"""
"""
function CANFdFrame(frame_id::Integer, data::Integer...; is_extended::Bool=false)
return CANFdFrame(convert(UInt32, frame_id), UInt8[data...]; is_extended)
end
"""
"""
function Base.:(==)(lhs::AbstractCANFrame, rhs::AbstractCANFrame)::Bool
return false
end
"""
"""
function Base.:(==)(lhs::CANFrame, rhs::CANFrame)::Bool
if frame_id(lhs) != frame_id(rhs)
return false
end
if data(lhs) != data(rhs)
return false
end
if is_extended(lhs) != is_extended(rhs)
return false
end
return true
end
"""
"""
function frame_id(frame::AbstractCANFrame)::UInt32
if is_extended(frame)
return frame.frame_id & 0x1F_FF_FF_FF
else
return frame.frame_id & 0x7_FF
end
end
"""
"""
function data(frame::AbstractCANFrame)::Array{UInt8,1}
return frame.data
end
"""
"""
function dlc(frame::AbstractCANFrame)::UInt8
return length(frame.data)
end
"""
"""
function is_standard(frame::AbstractCANFrame)::Bool
return !frame.is_extended
end
"""
"""
function is_extended(frame::AbstractCANFrame)::Bool
return frame.is_extended
end
"""
"""
function max_size(::Type{AbstractCANFrame})::UInt8
return 8
end
"""
"""
function max_size(::Type{CANFrame})::UInt8
return 8
end
"""
"""
function max_size(::Type{CANFdFrame})::UInt8
return 64
end
export CANFdFrame, CANFrame
export frame_id, data, dlc, is_extended, is_standard, max_size
end
| CANalyze | https://github.com/tsabelmann/CANalyze.jl.git |
|
[
"MIT"
] | 1.6.0 | 2bb2fd8988fa976a3e057bbe6197414d77d5e29d | code | 4053 | """The module provides the Message type that bundles signals.
"""
module Messages
import Base
import ..Signals
"""
Message
Messages model bundles of signals and enable the decoding of multiple signals. Additionally,
messages are defined using the number of bytes (`dlc`), a message name (`name`), and the
internal signals (`signals`).
# Fields
- `dlc::UInt8`: the number of required bytes
- `name::String`: the name of the message
- `signals::Dict{String, Signals.NamedSignal}`: a mapping of string
"""
mutable struct Message
frame_id::UInt32
dlc::UInt8
name::String
signals::Dict{String, Signals.NamedSignal}
function Message(frame_id::UInt32, dlc::UInt8, name::String,
signals::Dict{String, Signals.NamedSignal}; strict::Bool=false)
if name == ""
throw(DomainError(name, "name cannot be the empty string"))
end
if strict
e1 = enumerate(values(signals))
l = [Signals.overlap(v1,v2) for (i,v1) in e1 for (j,v2) in e1 if i < j]
do_overlap = any(l)
if do_overlap
throw(DomainError(do_overlap, "signals overlap"))
end
for signal in values(signals)
is_ok = Signals.check(signal, dlc)
if !is_ok
throw(DomainError(is_ok, "not enough data"))
end
end
end
return new(frame_id, dlc, name, signals)
end
end
function Message(frame_id::Integer, dlc::Integer, name::String,
signals::Signals.NamedSignal...; strict::Bool=false)
frame_id = convert(UInt32, frame_id)
dlc = convert(UInt8, dlc)
sigs = Dict{String, Signals.NamedSignal}()
for signal in signals
signal_name = Signals.name(signal)
if get(sigs, signal_name, nothing) != nothing
throw(DomainError(signal_name, "signal with same name already defined"))
else
sigs[signal_name] = signal
end
end
return Message(frame_id, dlc, name, sigs; strict=strict)
end
"""
"""
function frame_id(message::Message)::UInt32
return message.frame_id & 0x7F_FF_FF_FF
end
"""
dlc(message::Message) -> UInt8
Returns the number of bytes that the message requires and operates on.
# Arguments
- `message::Message`: the message
"""
function dlc(message::Message)::UInt8
return message.dlc
end
"""
name(message::Message) -> String
Returns the message name.
# Arguments
- `message::Message`: the message
"""
function name(message::Message)::String
return message.name
end
"""
Base.getindex(message::Message, index::String) -> Signals.NamedSignal
Returns the signal with the name `index` inside `message`.
# Arguments
- `message::Message`: the message
- `index::String`: the index, i.e., the name of the signal we want to retrieve
# Throws
- `KeyError`: the signal with the name `index` does not exist inside `message`
"""
function Base.getindex(message::Message, index::String)::Signals.NamedSignal
return message.signals[index]
end
"""
Base.get(message::Message, key::String, default)
Returns the signal with the name `key` inside `message` if a signal with such a name
exists, otherwise we return `default`.
# Arguments
- `message::Message`: the message
- `key::String`: the index, i.e., the name of the signal we want to retrieve
- `default`: a default value
"""
function Base.get(message::Message, key::String, default)
return get(message.signals, key, default)
end
"""
Base.iterate(iter::Message)
Enables the iteration over the inside dictionary `signals`.
# Arguments
- `iter::Message`: the message
"""
function Base.iterate(iter::Message)
return iterate(iter.signals)
end
"""
Base.iterate(iter::Message, state)
Enables the iteration over the inside dictionary `signals`.
# Arguments
- `iter::Message`: the message
- `state`: the state of the iterator
"""
function Base.iterate(iter::Message, state)
return iterate(iter.signals, state)
end
export Message, frame_id, dlc, name
end
| CANalyze | https://github.com/tsabelmann/CANalyze.jl.git |
|
[
"MIT"
] | 1.6.0 | 2bb2fd8988fa976a3e057bbe6197414d77d5e29d | code | 14521 | """The module provides signals, a mechanism that models data retrievable from or
written to CAN-bus data. A signal models one data entity, e.g., one variable inside the
CAN-bus data.
"""
module Signals
import Base
"""
"""
abstract type AbstractSignal{T} end
"""
"""
abstract type UnnamedSignal{T} <: AbstractSignal{T} end
"""
"""
abstract type AbstractIntegerSignal{T <: Integer} <: UnnamedSignal{T} end
"""
"""
abstract type AbstractFloatSignal{T <: AbstractFloat} <: UnnamedSignal{T} end
"""
"""
struct Bit <: AbstractIntegerSignal{Bool}
start::UInt16
end
"""
"""
function Bit(start::Integer)
start = convert(UInt16, start)
return Bit(start)
end
"""
"""
function Bit(; start::Integer=0)
return Bit(start)
end
"""
"""
function start(signal::Bit)::UInt16
return signal.start
end
"""
"""
function Base.length(signal::Bit)::UInt16
return 1
end
"""
"""
function byte_order(signal::Bit)::Symbol
return :little_endian
end
"""
"""
function Base.:(==)(lhs::Bit, rhs::Bit)
return start(lhs) == start(rhs)
end
"""
"""
struct Unsigned{T} <: AbstractFloatSignal{T}
start::UInt16
length::UInt16
factor::T
offset::T
byte_order::Symbol
"""
"""
function Unsigned(start::UInt16,
length::UInt16,
factor::T,
offset::T,
byte_order::Symbol) where {T <: AbstractFloat}
if byte_order != :little_endian && byte_order != :big_endian
throw(DomainError(byte_order, "Byte order not supported"))
end
if length == 0
throw(DomainError(length, "The length has to be greater or equal to 1"))
end
return new{T}(start, length, factor, offset, byte_order)
end
end
"""
"""
function Unsigned(start::Integer,
length::Integer,
factor::Union{Integer, AbstractFloat},
offset::Union{Integer, AbstractFloat},
byte_order::Symbol)
start = convert(UInt16, start)
length = convert(UInt16, length)
if factor isa Integer && offset isa Integer
factor = convert(Float64, factor)
offset = convert(Float64, offset)
else
factor, offset = promote(factor, offset)
end
return Unsigned(start, length, factor, offset, byte_order)
end
"""
"""
function Unsigned(; start::Integer,
length::Integer,
factor::Union{Integer, AbstractFloat},
offset::Union{Integer, AbstractFloat},
byte_order::Symbol=:little_endian)
return Unsigned(start, length, factor, offset, byte_order)
end
"""
"""
function Unsigned{T}(start::Integer,
length::Integer;
factor::Union{Integer, AbstractFloat}=one(T),
offset::Union{Integer, AbstractFloat}=zero(T),
byte_order::Symbol=:little_endian) where {T}
factor = convert(T, factor)
offset = convert(T, offset)
return Unsigned(start, length, factor, offset, byte_order)
end
"""
"""
function Unsigned{T}(; start::Integer,
length::Integer,
factor::Union{Integer, AbstractFloat}=one(T),
offset::Union{Integer, AbstractFloat}=zero(T),
byte_order::Symbol=:little_endian) where {T}
factor = convert(T, factor)
offset = convert(T, offset)
return Unsigned(start, length, factor, offset, byte_order)
end
"""
"""
function start(signal::Unsigned{T})::UInt16 where {T}
return signal.start
end
"""
"""
function Base.length(signal::Unsigned{T})::UInt16 where {T}
return signal.length
end
"""
"""
function factor(signal::Unsigned{T})::T where {T}
return signal.factor
end
"""
"""
function offset(signal::Unsigned{T})::T where {T}
return signal.offset
end
"""
"""
function byte_order(signal::Unsigned{T})::Symbol where {T}
return signal.byte_order
end
"""
"""
function Base.:(==)(lhs::F, rhs::F) where {T, F <: AbstractFloatSignal{T}}
if start(lhs) != start(rhs)
return false
end
if length(lhs) != length(rhs)
return false
end
if factor(lhs) != factor(rhs)
return false
end
if offset(lhs) != offset(rhs)
return false
end
if byte_order(lhs) != byte_order(rhs)
return false
end
return true
end
struct Signed{T} <: AbstractFloatSignal{T}
start::UInt16
length::UInt16
factor::T
offset::T
byte_order::Symbol
function Signed(start::UInt16,
length::UInt16,
factor::T,
offset::T,
byte_order::Symbol) where {T <: AbstractFloat}
if byte_order != :little_endian && byte_order != :big_endian
throw(DomainError(byte_order, "Byte order not supported"))
end
if length == 0
throw(DomainError(length, "The length has to be greater or equal to 1"))
end
return new{T}(start, length, factor, offset, byte_order)
end
end
"""
"""
function Signed(start::Integer,
length::Integer,
factor::Union{Integer, AbstractFloat},
offset::Union{Integer, AbstractFloat},
byte_order::Symbol)
start = convert(UInt16, start)
length = convert(UInt16, length)
if factor isa Integer && offset isa Integer
factor = convert(Float64, factor)
offset = convert(Float64, offset)
else
factor, offset = promote(factor, offset)
end
return Signed(start, length, factor, offset, byte_order)
end
"""
"""
function Signed(; start::Integer,
length::Integer,
factor::Union{Integer, AbstractFloat},
offset::Union{Integer, AbstractFloat},
byte_order::Symbol=:little_endian)
return Signed(start, length, factor, offset, byte_order)
end
"""
"""
function Signed{T}(start::Integer,
length::Integer;
factor::Union{Integer, AbstractFloat}=one(T),
offset::Union{Integer, AbstractFloat}=zero(T),
byte_order::Symbol=:little_endian) where {T}
factor = convert(T, factor)
offset = convert(T, offset)
return Signed(start, length, factor, offset, byte_order)
end
"""
"""
function Signed{T}(; start::Integer,
length::Integer,
factor::Union{Integer, AbstractFloat}=one(T),
offset::Union{Integer, AbstractFloat}=zero(T),
byte_order::Symbol=:little_endian) where {T}
factor = convert(T, factor)
offset = convert(T, offset)
return Signed(start, length, factor, offset, byte_order)
end
"""
"""
function start(signal::Signed{T})::UInt16 where {T}
return signal.start
end
"""
"""
function Base.length(signal::Signed{T})::UInt16 where {T}
return signal.length
end
"""
"""
function factor(signal::Signed{T})::T where {T}
return signal.factor
end
"""
"""
function offset(signal::Signed{T})::T where {T}
return signal.offset
end
"""
"""
function byte_order(signal::Signed{T})::Symbol where {T}
return signal.byte_order
end
"""
"""
struct FloatSignal{T} <: AbstractFloatSignal{T}
start::UInt16
factor::T
offset::T
byte_order::Symbol
function FloatSignal(start::UInt16, factor::T, offset::T,
byte_order::Symbol) where {T <: AbstractFloat}
new{T}(start, factor, offset, byte_order)
end
end
"""
"""
function FloatSignal(start::Integer,
factor::Union{Integer,AbstractFloat},
offset::Union{Integer,AbstractFloat},
byte_order::Symbol)
start = convert(UInt16, start)
if factor isa Integer && offset isa Integer
factor = convert(Float64, factor)
offset = convert(Float64, offset)
else
factor, offset = promote(factor, offset)
end
return FloatSignal(start, factor, offset, byte_order)
end
"""
"""
function FloatSignal(; start::Integer,
factor::Union{Integer,AbstractFloat},
offset::Union{Integer,AbstractFloat},
byte_order::Symbol)
return FloatSignal(start, factor, offset, byte_order)
end
"""
"""
function FloatSignal{T}(start::Integer;
factor::Union{Integer,AbstractFloat}=one(T),
offset::Union{Integer,AbstractFloat}=zero(T),
byte_order::Symbol=:little_endian) where {T}
factor = convert(T, factor)
offset = convert(T, offset)
return FloatSignal(start, factor, offset, byte_order)
end
function FloatSignal{T}(; start::Integer,
factor::Union{Integer,AbstractFloat}=one(T),
offset::Union{Integer,AbstractFloat}=zero(T),
byte_order::Symbol=:little_endian) where {T}
factor = convert(T, factor)
offset = convert(T, offset)
return FloatSignal(start, factor, offset, byte_order)
end
const Float16Signal = FloatSignal{Float16}
const Float32Signal = FloatSignal{Float32}
const Float64Signal = FloatSignal{Float64}
"""
"""
function start(signal::FloatSignal{T})::UInt16 where {T}
return signal.start
end
function Base.length(signal::FloatSignal{T})::UInt16 where {T}
return 8sizeof(T)
end
"""
"""
function factor(signal::FloatSignal{T})::T where {T}
return signal.factor
end
"""
"""
function offset(signal::FloatSignal{T})::T where {T}
return signal.offset
end
"""
"""
function byte_order(signal::FloatSignal{T})::Symbol where {T}
return signal.byte_order
end
"""
"""
struct Raw <: AbstractIntegerSignal{UInt64}
start::UInt16
length::UInt16
byte_order::Symbol
"""
"""
function Raw(start::UInt16, length::UInt16,byte_order::Symbol)
if length == 0
throw(DomainError(length, "The length has to be greater or equal to 1"))
end
if byte_order != :little_endian && byte_order != :big_endian
throw(DomainError(byte_order, "Byte order not supported"))
end
return new(start, length, byte_order)
end
end
"""
"""
function Raw(start::Integer, length::Integer, byte_order::Symbol)
start = convert(UInt16, start)
length = convert(UInt16, length)
return Raw(start, length, byte_order)
end
"""
"""
function Raw(; start::Integer,
length::Integer,
byte_order::Symbol=:little_endian) where {T}
return Raw(start, length, byte_order)
end
"""
"""
function start(signal::Raw)::UInt16
return signal.start
end
"""
"""
function Base.length(signal::Raw)::UInt16
return signal.length
end
"""
"""
function byte_order(signal::Raw)::Symbol
return signal.byte_order
end
"""
"""
struct NamedSignal{T} <: AbstractSignal{T}
name::String
unit::Union{Nothing,String}
default::Union{Nothing,T}
signal::UnnamedSignal{T}
function NamedSignal(name::String,
unit::Union{Nothing,String},
default::Union{Nothing,T},
signal::UnnamedSignal{T}) where {T}
if name == ""
throw(DomainError(name, "name cannot be the empty string"))
end
return new{T}(name, unit, default, signal)
end
end
"""
"""
function NamedSignal(; name::String,
unit::Union{Nothing,String}=nothing,
default::Union{Nothing,T}=nothing,
signal::UnnamedSignal{T}) where {T}
return NamedSignal(name, unit, default, signal)
end
"""
"""
function name(signal::NamedSignal{T})::String where {T}
return signal.name
end
"""
"""
function unit(signal::NamedSignal{T})::Union{Nothing,String} where {T}
return signal.unit
end
"""
"""
function default(signal::NamedSignal{T})::Union{Nothing,T} where {T}
return signal.default
end
"""
"""
function signal(signal::NamedSignal{T})::UnnamedSignal{T} where {T}
return signal.signal
end
const Signal = NamedSignal
"""
"""
struct Bits
bits::Set{UInt16}
end
"""
"""
function Bits(bits::Integer...)
Bits(Set(UInt16[bits...]))
end
"""
"""
function Bits(signal::AbstractFloatSignal{T}) where {T}
bits = Set{UInt16}()
start_bit = start(signal)
if byte_order(signal) == :little_endian
for i=0:length(signal)-1
bit_pos = start_bit + i
push!(bits, bit_pos)
end
elseif byte_order(signal) == :big_endian
for j=0:length(signal)-1
push!(bits, start_bit)
if start_bit % 8 == 0
start_byte = div(start_bit,8)
start_bit = 8 * (start_byte + 1) + 7
else
start_bit -= 1
end
end
end
return Bits(bits)
end
"""
"""
function Bits(signal::AbstractIntegerSignal{T}) where {T}
bits = Set{UInt16}()
start_bit = start(signal)
if byte_order(signal) == :little_endian
for i=0:length(signal)-1
bit_pos = start_bit + i
push!(bits, bit_pos)
end
elseif byte_order(signal) == :big_endian
for j=0:length(signal)-1
push!(bits, start_bit)
if start_bit % 8 == 0
start_byte = div(start_bit,8)
start_bit = 8 * (start_byte + 1) + 7
else
start_bit -= 1
end
end
end
return Bits(bits)
end
function Bits(sig::NamedSignal{T}) where {T}
return Bits(signal(sig))
end
function Base.:(==)(lhs::Bits, rhs::Bits)::Bool
return (lhs.bits) == (rhs.bits)
end
"""
"""
function share_bits(lhs::Bits, rhs::Bits)::Bool
return !isdisjoint(lhs.bits, rhs.bits)
end
"""
"""
function overlap(lhs::AbstractSignal{R}, rhs::AbstractSignal{S})::Bool where {R,S}
lhs_bits = Bits(lhs)
rhs_bits = Bits(rhs)
return share_bits(lhs_bits, rhs_bits)
end
function check(signal::UnnamedSignal{T}, available_bytes::UInt8)::Bool where {T}
bits = Bits(signal)
max_byte = max(UInt8[div(bit,8) for bit in bits.bits]...)
if max_byte < available_bytes
return true
else
return false
end
end
"""
"""
function check(sig::NamedSignal{T}, available_bytes::UInt8)::Bool where {T}
return check(signal(sig), available_bytes)
end
export Bit, Unsigned, Signed, Raw, Float16Signal, Float32Signal, Float64Signal
export Signal, FloatSignal
export NamedSignal
export start, factor, offset, byte_order
export name, unit, default, signal
end
| CANalyze | https://github.com/tsabelmann/CANalyze.jl.git |
|
[
"MIT"
] | 1.6.0 | 2bb2fd8988fa976a3e057bbe6197414d77d5e29d | code | 6383 | """The module provides utilities to convert numbers into and from byte representations,
functions to check whether the system is little-endian or big-endian, and functions to
create bitmasks.
"""
module Utils
"""
to_bytes(num::Number) -> Vector{UInt8}
Creates the byte representation of the number `num`.
# Arguments
- `num::Number`: the number from which we retrieve the bytes.
# Returns
- `Vector{UInt8}`: the bytes representation of the number `num`
# Examples
```jldoctest
using CANalyze.Utils
bytes = Utils.to_bytes(UInt16(0xAAFF))
# output
2-element Vector{UInt8}:
0xff
0xaa
```
"""
function to_bytes(num::Number)::Vector{UInt8}
return reinterpret(UInt8, [num])
end
"""
from_bytes(type::Type{T}, array::AbstractArray{UInt8}) where {T <: Number} -> T
Creates a value of type `T` constituted by the byte-array `array`. If the `array` length
is smaller than the size of `T`, `array` is filled with enough zeros.
# Arguments
- `type::Type{T}`: the type to which the byte-array is transformed
- `array::AbstractArray{UInt8}`: the byte array
# Returns
- `T`: the value constructed from the byte sequence
# Examples
```jldoctest
using CANalyze.Utils
bytes = Utils.from_bytes(UInt16, UInt8[0xFF, 0xAA])
# output
0xaaff
```
"""
function from_bytes(type::Type{T}, array::AbstractArray{UInt8})::T where {T <: Number}
if length(array) < sizeof(T)
for i=1:(sizeof(T) - length(array))
push!(array, UInt8(0))
end
end
values = reinterpret(type, array)
return values[1]
end
"""
is_little_endian() -> Bool
Returns whether the system has little-endian byte-order
# Returns
- `Bool`: The system has little-endian byte-order
"""
function is_little_endian()::Bool
x::UInt16 = 0x0001
lst = reinterpret(UInt8, [x])
if lst[1] == 0x01
return true
else
return false
end
end
"""
is_big_endian() -> Bool
Returns whether the system has big-endian byte-order
# Returns
- `Bool`: The system has big-endian byte-order
"""
function is_big_endian()::Bool
return !is_little_endian()
end
"""
mask(::Type{T}, length::UInt8, shift::UInt8) where {T <: Integer} -> T
Creates a mask of type `T` with `length` number of bits and right-shifted by `shift`
number of bits.
# Arguments
- `Type{T}`: the type of the mask
- `length::UInt8`: the number of bits
- `shift::UInt8`: the right-shift
# Returns
- `T`: the mask defined by `length` and `shift`
"""
function mask(::Type{T}, length::UInt8, shift::UInt8)::T where {T <: Integer}
ret::T = mask(T, length)
ret <<= shift
return ret
end
"""
mask(::Type{T}, length::Integer, shift::Integer) where {T <: Integer} -> T
Creates a mask of type `T` with `length` number of bits and right-shifted by `shift`
number of bits.
# Arguments
- `Type{T}`: the type of the mask
- `length::Integer`: the number of bits
- `shift::Integer`: the right-shift
# Returns
- `T`: the mask defined by `length` and `shift`
# Examples
```jldoctest
using CANalyze.Utils
m = Utils.mask(UInt64, 32, 16)
# output
0x0000ffffffff0000
```
"""
function mask(::Type{T}, length::Integer, shift::Integer)::T where {T <: Integer}
l = convert(UInt8, length)
s = convert(UInt8, shift)
return mask(T, l, s)
end
"""
mask(::Type{T}, length::UInt8) where {T <: Integer} -> T
Creates a mask of type `T` with `length` number of bits.
# Arguments
- `Type{T}`: the type of the mask
- `length::UInt8`: the number of bits
# Returns
- `T`: the mask defined by `length`
"""
function mask(::Type{T}, length::UInt8)::T where {T <: Integer}
ret = zero(T)
if length > 0
for i in 1:(length-1)
ret += 1
ret <<= 1
end
ret += 1
end
return ret
end
"""
mask(::Type{T}, length::Integer) where {T <: Integer} -> T
Creates a mask of type `T` with `length` number of bits.
# Arguments
- `Type{T}`: the type of the mask
- `length::Integer`: the number of bits
# Returns
- `T`: the mask defined by `length`
# Examples
```jldoctest
using CANalyze.Utils
m = Utils.mask(UInt64, 32)
# output
0x00000000ffffffff
```
"""
function mask(::Type{T}, length::Integer)::T where {T <: Integer}
l = convert(UInt8, length)
return mask(T, l)
end
"""
mask(::Type{T}) where {T <: Integer} -> T
Creates a full mask of type `T` with `8sizeof(T)` bits.
# Arguments
- `Type{T}`: the type of the mask
# Returns
- `T`: the full mask
# Examples
```jldoctest
using CANalyze.Utils
m = Utils.mask(UInt64)
# output
0xffffffffffffffff
```
"""
function mask(::Type{T})::T where {T <: Integer}
return full_mask(T)
end
"""
full_mask(::Type{T}) where {T <: Integer} -> T
Creates a full mask of type `T` with `8sizeof(T)` bits.
# Arguments
- `Type{T}`: the type of the mask
# Returns
- `T`: the full mask
# Examples
```jldoctest
using CANalyze.Utils
m = Utils.full_mask(Int8)
# output
-1
```
"""
function full_mask(::Type{T})::T where {T <: Integer}
ret::T = zero(T)
for i in 0:(8sizeof(T) - 2)
ret += 1
ret <<= 1
end
ret += 1
return ret
end
"""
zero_mask(::Type{T}) where {T <: Integer} -> T
Creates a zero mask of type `T` where every bit is unset.
# Arguments
- `Type{T}`: the type of the mask
# Returns
- `T`: the zero mask
# Examples
```jldoctest
using CANalyze.Utils
m = Utils.zero_mask(UInt8)
# output
0x00
```
"""
function zero_mask(::Type{T})::T where {T <: Integer}
return zero(T)
end
"""
bit_mask(::Type{T}, bits::Set{UInt16}) where {T <: Integer} -> T
Creates a bit mask of type `T` where every bit inside `bits` is set.
# Arguments
- `Type{T}`: the type of the mask
- `bits::Set{UInt16}`: the set of bits we want to set
# Returns
- `T`: the mask
# Examples
```jldoctest
using CANalyze.Utils
m = Utils.bit_mask(UInt8, Set{UInt16}([0,1,2,3,4,5,6,7]))
# output
0xff
```
"""
function bit_mask(::Type{T}, bits::Set{UInt16})::T where {T <: Integer}
result = zero(T)
for bit in bits
result |= mask(T, 1, bit)
end
return T(result)
end
function bit_mask(::Type{T}, bits::Integer...)::T where {T}
bits = Set{UInt16}(bits)
return bit_mask(T, bits)
end
function bit_mask(::Type{S}, bits::AbstractArray{T,N})::S where {S,T,N}
bits = Set{UInt16}(bits)
return bit_mask(S, bits)
end
export to_bytes, from_bytes
export is_little_endian, is_big_endian
export mask, zero_mask, full_mask, bit_mask
end
| CANalyze | https://github.com/tsabelmann/CANalyze.jl.git |
|
[
"MIT"
] | 1.6.0 | 2bb2fd8988fa976a3e057bbe6197414d77d5e29d | code | 5213 | using Test
@info "CANalyze.Databases tests..."
@testset "database" begin
import CANalyze.Signals
import CANalyze.Messages
import CANalyze.Databases
@testset "database_1" begin
signal1 = Signals.NamedSignal("A", nothing, nothing, Signals.Unsigned(0, 32, 1, 0, :little_endian))
signal2 = Signals.NamedSignal("B", nothing, nothing, Signals.Unsigned(40, 17, 2, 20, :big_endian))
signal3 = Signals.NamedSignal("C", nothing, nothing, Signals.Unsigned(32, 8, 2, 20, :little_endian))
m1 = Messages.Message(0xA, 8, "A", signal1, signal2, signal3; strict=true)
m2 = Messages.Message(0xB, 8, "B", signal1, signal2, signal3; strict=true)
d = Databases.Database(m1, m2)
@test true
end
@testset "database_2" begin
signal1 = Signals.NamedSignal("A", nothing, nothing, Signals.Unsigned(0, 32, 1, 0, :little_endian))
signal2 = Signals.NamedSignal("B", nothing, nothing, Signals.Unsigned(40, 17, 2, 20, :big_endian))
signal3 = Signals.NamedSignal("C", nothing, nothing, Signals.Unsigned(32, 8, 2, 20, :little_endian))
m1 = Messages.Message(0xA, 8, "A", signal1, signal2, signal3; strict=true)
m2 = Messages.Message(0xB, 8, "A", signal1, signal2, signal3; strict=true)
@test_throws DomainError Databases.Database(m1, m2)
end
@testset "database_3" begin
signal1 = Signals.NamedSignal("A", nothing, nothing, Signals.Unsigned(0, 32, 1, 0, :little_endian))
signal2 = Signals.NamedSignal("B", nothing, nothing, Signals.Unsigned(40, 17, 2, 20, :big_endian))
signal3 = Signals.NamedSignal("C", nothing, nothing, Signals.Unsigned(32, 8, 2, 20, :little_endian))
m1 = Messages.Message(0xA, 8, "A", signal1, signal2, signal3; strict=true)
m2 = Messages.Message(0xA, 8, "B", signal1, signal2, signal3; strict=true)
@test_throws DomainError Databases.Database(m1, m2)
end
@testset "get_1" begin
signal1 = Signals.NamedSignal("A", nothing, nothing, Signals.Unsigned(0, 32, 1, 0, :little_endian))
signal2 = Signals.NamedSignal("B", nothing, nothing, Signals.Unsigned(40, 17, 2, 20, :big_endian))
signal3 = Signals.NamedSignal("C", nothing, nothing, Signals.Unsigned(32, 8, 2, 20, :little_endian))
m1 = Messages.Message(0xA, 8, "A", signal1, signal2, signal3; strict=true)
m2 = Messages.Message(0xB, 8, "B", signal1, signal2, signal3; strict=true)
d = Databases.Database(m1, m2)
@test d["A"] == m1
@test d["B"] == m2
end
@testset "get_2" begin
signal1 = Signals.NamedSignal("A", nothing, nothing, Signals.Unsigned(0, 32, 1, 0, :little_endian))
signal2 = Signals.NamedSignal("B", nothing, nothing, Signals.Unsigned(40, 17, 2, 20, :big_endian))
signal3 = Signals.NamedSignal("C", nothing, nothing, Signals.Unsigned(32, 8, 2, 20, :little_endian))
m1 = Messages.Message(0xA, 8, "A", signal1, signal2, signal3; strict=true)
m2 = Messages.Message(0xB, 8, "B", signal1, signal2, signal3; strict=true)
d = Databases.Database(m1, m2)
@test_throws KeyError d["C"]
end
@testset "get_3" begin
signal1 = Signals.NamedSignal("A", nothing, nothing, Signals.Unsigned(0, 32, 1, 0, :little_endian))
signal2 = Signals.NamedSignal("B", nothing, nothing, Signals.Unsigned(40, 17, 2, 20, :big_endian))
signal3 = Signals.NamedSignal("C", nothing, nothing, Signals.Unsigned(32, 8, 2, 20, :little_endian))
m1 = Messages.Message(0xA, 8, "A", signal1, signal2, signal3; strict=true)
m2 = Messages.Message(0xB, 8, "B", signal1, signal2, signal3; strict=true)
d = Databases.Database(m1, m2)
@test d[0xA] == m1
@test d[0xB] == m2
end
@testset "get_4" begin
signal1 = Signals.NamedSignal("A", nothing, nothing, Signals.Unsigned(0, 32, 1, 0, :little_endian))
signal2 = Signals.NamedSignal("B", nothing, nothing, Signals.Unsigned(40, 17, 2, 20, :big_endian))
signal3 = Signals.NamedSignal("C", nothing, nothing, Signals.Unsigned(32, 8, 2, 20, :little_endian))
m1 = Messages.Message(0xA, 8, "A", signal1, signal2, signal3; strict=true)
m2 = Messages.Message(0xB, 8, "B", signal1, signal2, signal3; strict=true)
d = Databases.Database(m1, m2)
@test_throws KeyError d[0xC]
end
@testset "get_5" begin
signal1 = Signals.NamedSignal("A", nothing, nothing, Signals.Unsigned(0, 32, 1, 0, :little_endian))
signal2 = Signals.NamedSignal("B", nothing, nothing, Signals.Unsigned(40, 17, 2, 20, :big_endian))
signal3 = Signals.NamedSignal("C", nothing, nothing, Signals.Unsigned(32, 8, 2, 20, :little_endian))
m1 = Messages.Message(0xA, 8, "A", signal1, signal2, signal3; strict=true)
m2 = Messages.Message(0xB, 8, "B", signal1, signal2, signal3; strict=true)
d = Databases.Database(m1, m2)
@test get(d, "A", nothing) == m1
@test get(d, "B", nothing) == m2
@test get(d, "C", nothing) == nothing
@test get(d, 0xA, nothing) == m1
@test get(d, 0xB, nothing) == m2
@test get(d, 0xC, nothing) == nothing
end
end
| CANalyze | https://github.com/tsabelmann/CANalyze.jl.git |
|
[
"MIT"
] | 1.6.0 | 2bb2fd8988fa976a3e057bbe6197414d77d5e29d | code | 14897 | using Test
@info "CANalyze.Decode tests..."
@testset "bit" begin
import CANalyze.Utils
import CANalyze.Frames
import CANalyze.Signals
import CANalyze.Messages
import CANalyze.Decode
@testset "bit_1" begin
for start=0:63
m = Utils.mask(UInt64, 1, start)
signal = Signals.Bit(start=start)
frame = Frames.CANFrame(0x1FF, Utils.to_bytes(m))
@test Decode.decode(signal, frame)
end
end
@testset "bit_2" begin
for start=1:63
m = Utils.mask(UInt64, 1, start)
signal = Signals.Bit(start=start-1)
frame = Frames.CANFrame(0x1FF, Utils.to_bytes(m))
@test !Decode.decode(signal, frame)
end
end
@testset "bit_3" begin
signal = Signals.Bit(start=8)
frame = Frames.CANFrame(0x1FF, 1)
@test_throws DomainError Decode.decode(signal, frame)
end
@testset "bit_4" begin
signal = Signals.Bit(start=8)
frame = Frames.CANFrame(0x1FF, 1)
@test Decode.decode(signal, frame, nothing) == nothing
end
end
@testset "unsigned" begin
import CANalyze.Utils
import CANalyze.Frames
import CANalyze.Signals
import CANalyze.Messages
import CANalyze.Decode
@testset "unsigned_1" begin
for start=0:63
for len=1:(64-start)
m = Utils.mask(UInt64, len, start)
signal = Signals.Unsigned{Float64}(start=start, length=len, factor=2.0,
offset=1337,
byte_order=:little_endian)
frame = Frames.CANFrame(0x1FF, Utils.to_bytes(m))
decode = Decode.decode(signal, frame)
value = Utils.mask(UInt64, len) * Signals.factor(signal) + Signals.offset(signal)
@test decode == value
end
end
end
@testset "unsigned_2" begin
signal = Signals.Unsigned{Float64}(start=7, length=8, factor=2.0, offset=1337,
byte_order=:big_endian)
frame = Frames.CANFrame(0x1FF, [i for i=1:8])
decode = Decode.decode(signal, frame)
value = 1 * Signals.factor(signal) + Signals.offset(signal)
@test decode == value
end
@testset "unsigned_3" begin
signal = Signals.Unsigned{Float64}(start=7, length=16, factor=2.0, offset=1337,
byte_order=:big_endian)
frame = Frames.CANFrame(0x1FF, 0xAB, 0xCD)
decode = Decode.decode(signal, frame)
value = 0xABCD * Signals.factor(signal) + Signals.offset(signal)
@test decode == value
end
@testset "unsigned_4" begin
signal = Signals.Unsigned{Float64}(start=7, length=24, factor=2.0, offset=1337,
byte_order=:big_endian)
frame = Frames.CANFrame(0x1FF, 0xAB, 0xCD, 0xEF)
decode = Decode.decode(signal, frame)
value = 0xABCDEF * Signals.factor(signal) + Signals.offset(signal)
@test decode == value
end
@testset "unsigned_5" begin
signal = Signals.Unsigned{Float64}(start=8, length=1, factor=2.0, offset=1337,
byte_order=:little_endian)
frame = Frames.CANFrame(0x1FF, 0x01)
@test_throws DomainError Decode.decode(signal, frame)
end
@testset "unsigned_6" begin
signal = Signals.Unsigned{Float64}(start=6, length=8, factor=2.0, offset=1337,
byte_order=:big_endian)
frame = Frames.CANFrame(0x1FF, 0x01)
@test_throws DomainError Decode.decode(signal, frame)
end
end
@testset "signed" begin
import CANalyze.Utils
import CANalyze.Frames
import CANalyze.Signals
import CANalyze.Messages
import CANalyze.Decode
using Random
@testset "signed_1" begin
for start=0:62
for len=1:(64-start)
m = Utils.mask(UInt64, len-1, start)
signal = Signals.Signed{Float64}(start=start, length=len, factor=2.0,
offset=1337,
byte_order=:little_endian)
frame = Frames.CANFrame(0x1FF, Utils.to_bytes(m))
decode = Decode.decode(signal, frame)
value = Utils.mask(UInt64, len-1) * Signals.factor(signal) + Signals.offset(signal)
@test decode == value
end
end
end
@testset "signed_2" begin
for start=0:63
for len=1:(64-start)
m = Utils.mask(UInt64, len, start)
signal = Signals.Signed{Float64}(start=start, length=len, factor=2.0,
offset=1337,
byte_order=:little_endian)
frame = Frames.CANFrame(0x1FF, Utils.to_bytes(m))
decode = Decode.decode(signal, frame)
value = Utils.mask(Int64, len) + ~Utils.mask(Int64, len)
value = value * Signals.factor(signal) + Signals.offset(signal)
@test decode == value
end
end
end
@testset "signed_3" begin
for len=1:64
for choice=1:64-len
m = Utils.bit_mask(Int64, len-1, rand(0:(len-1), choice)...)
signal = Signals.Signed{Float64}(start=0, length=len, factor=2.0,
offset=1337,
byte_order=:little_endian)
frame = Frames.CANFrame(0x1FF, Utils.to_bytes(m))
decode = Decode.decode(signal, frame)
value = m + ~Utils.mask(Int64, len)
value = value * Signals.factor(signal) + Signals.offset(signal)
@test decode == value
end
end
end
@testset "signed_4" begin
signal = Signals.Signed{Float64}(start=7, length=8, factor=set=1337,
byte_order=:big_endian)
frame = Frames.CANFrame(0x1FF, 0xFE)
decode = Decode.decode(signal, frame)
value = -2 * Signals.factor(signal) + Signals.offset(signal)
@test decode == value
end
@testset "signed_5" begin
signal = Signals.Signed{Float64}(start=8, length=1, factor=2.0, offset=1337,
byte_order=:little_endian)
frame = Frames.CANFrame(0x1FF, 0x01)
@test_throws DomainError Decode.decode(signal, frame)
end
@testset "signed_6" begin
signal = Signals.Signed{Float64}(start=6, length=8, factor=2.0, offset=1337,
byte_order=:big_endian)
frame = Frames.CANFrame(0x1FF, 0x01)
@test_throws DomainError Decode.decode(signal, frame)
end
end
@testset "float_signal" begin
import CANalyze.Utils
import CANalyze.Frames
import CANalyze.Signals
import CANalyze.Messages
import CANalyze.Decode
using Random
@testset "float_signal_1" begin
for T in [Float16, Float32, Float64]
data = [i for i=0:(sizeof(T)-1)]
signal = Signals.FloatSignal{T}(start=0, factor=2.0, offset=1337,
byte_order=:little_endian)
frame = Frames.CANFrame(0x1FF, data)
decode = Decode.decode(signal, frame)
value = reinterpret(T, data)[1] * Signals.factor(signal) + Signals.offset(signal)
@test decode == value
end
end
@testset "float_signal_2" begin
for T in [Float16, Float32, Float64]
data = [i for i=0:(sizeof(T)-1)]
signal = Signals.FloatSignal{T}(start=7, factor=2.0, offset=1337,
byte_order=:big_endian)
frame = Frames.CANFrame(0x1FF, data)
decode = Decode.decode(signal, frame)
value = reinterpret(T, reverse(data))[1] * Signals.factor(signal)
value += Signals.offset(signal)
@test decode == value
end
end
@testset "float_signal_3" begin
signal = Signals.Float16Signal(start=1, byte_order=:little_endian)
frame = Frames.CANFrame(0x1FF, 0x01, 0x02)
@test_throws DomainError Decode.decode(signal, frame)
end
@testset "float_signal_4" begin
signal = Signals.Float16Signal(start=6, byte_order=:big_endian)
frame = Frames.CANFrame(0x1FF, 0x01, 0x02)
@test_throws DomainError Decode.decode(signal, frame)
end
@testset "float_signal_5" begin
signal = Signals.Float32Signal(start=1, byte_order=:little_endian)
frame = Frames.CANFrame(0x1FF, 0x01, 0x02, 0x03, 0x04)
@test_throws DomainError Decode.decode(signal, frame)
end
@testset "float_signal_6" begin
signal = Signals.Float32Signal(start=6, byte_order=:big_endian)
frame = Frames.CANFrame(0x1FF, 0x01, 0x02, 0x03, 0x04)
@test_throws DomainError Decode.decode(signal, frame)
end
@testset "float_signal_7" begin
signal = Signals.Float64Signal(start=1, byte_order=:little_endian)
frame = Frames.CANFrame(0x1FF, 0:7)
@test_throws DomainError Decode.decode(signal, frame)
end
@testset "float_signal_8" begin
signal = Signals.Float64Signal(start=6, byte_order=:big_endian)
frame = Frames.CANFrame(0x1FF, 0:7)
@test_throws DomainError Decode.decode(signal, frame)
end
end
@testset "raw" begin
import CANalyze.Utils
import CANalyze.Frames
import CANalyze.Signals
import CANalyze.Messages
import CANalyze.Decode
@testset "raw_1" begin
for start=0:63
for len=1:(64-start)
m = Utils.mask(UInt64, len, start)
signal = Signals.Raw(start=start, length=len, byte_order=:little_endian)
frame = Frames.CANFrame(0x1FF, Utils.to_bytes(m))
decode = Decode.decode(signal, frame)
value = Utils.mask(UInt64, len)
@test decode == value
end
end
end
@testset "raw_2" begin
signal = Signals.Raw(start=7, length=8, byte_order=:big_endian)
frame = Frames.CANFrame(0x1FF, [i for i=1:8])
decode = Decode.decode(signal, frame)
@test decode == 1
end
@testset "raw_3" begin
signal = Signals.Raw(start=7, length=16, byte_order=:big_endian)
frame = Frames.CANFrame(0x1FF, 0xAB, 0xCD)
decode = Decode.decode(signal, frame)
@test decode == 0xABCD
end
@testset "raw_4" begin
signal = Signals.Raw(start=7, length=24, byte_order=:big_endian)
frame = Frames.CANFrame(0x1FF, 0xAB, 0xCD, 0xEF)
decode = Decode.decode(signal, frame)
@test decode == 0xABCDEF
end
@testset "raw_5" begin
signal = Signals.Raw(start=7, length=64, byte_order=:big_endian)
frame = Frames.CANFrame(0x1FF, [i for i=1:8])
decode = Decode.decode(signal, frame)
@test decode == 0x01_02_03_04_05_06_07_08
end
@testset "raw_6" begin
signal = Signals.Raw(start=3, length=8, byte_order=:big_endian)
frame = Frames.CANFrame(0x1FF, 0x21, 0xAB)
decode = Decode.decode(signal, frame)
@test decode == 0x1A
end
@testset "raw_7" begin
signal = Signals.Raw(start=3, length=16, byte_order=:big_endian)
frame = Frames.CANFrame(0x1FF, 0x21, 0xAB, 0xCD)
decode = Decode.decode(signal, frame)
@test decode == 0x1ABC
end
@testset "raw_8" begin
signal = Signals.Raw(start=8, length=1, byte_order=:little_endian)
frame = Frames.CANFrame(0x1FF, 0x01)
@test_throws DomainError Decode.decode(signal, frame)
end
@testset "raw_9" begin
signal = Signals.Raw(start=6, length=8, byte_order=:big_endian)
frame = Frames.CANFrame(0x1FF, 0x01)
@test_throws DomainError Decode.decode(signal, frame)
end
end
@testset "named_signal" begin
import CANalyze.Utils
import CANalyze.Frames
import CANalyze.Signals
import CANalyze.Messages
import CANalyze.Decode
@testset "named_signal_1" begin
signal = Signals.Signed{Float64}(start=0,
length=16,
factor=2.0,
offset=1337,
byte_order=:little_endian)
named_signal = Signals.NamedSignal("SIG", nothing, nothing, signal)
frame = Frames.CANFrame(0x1FF, 0x01, 0x02)
@test Decode.decode(signal, frame) == Decode.decode(named_signal, frame)
end
@testset "named_signal_2" begin
signal = Signals.Signed{Float64}(start=1,
length=16,
factor=2.0,
offset=1337,
byte_order=:little_endian)
named_signal = Signals.NamedSignal("SIG", nothing, nothing, signal)
frame = Frames.CANFrame(0x1FF, 0x01, 0x02)
@test_throws DomainError Decode.decode(signal, frame)
@test Decode.decode(named_signal, frame) == nothing
end
@testset "named_signal_3" begin
signal = Signals.Signed{Float64}(start=1,
length=16,
factor=2.0,
offset=1337,
byte_order=:little_endian)
named_signal = Signals.NamedSignal("SIG", nothing, 42.0, signal)
frame = Frames.CANFrame(0x1FF, 0x01, 0x02)
@test_throws DomainError Decode.decode(signal, frame)
@test Decode.decode(named_signal, frame) == 42
end
end
@testset "message" begin
@testset "message_1" begin
sig1 = Signals.Signed{Float64}(start=0, length=8, byte_order=:little_endian)
sig2 = Signals.Signed{Float64}(start=8, length=8, byte_order=:little_endian)
sig3 = Signals.Signed{Float64}(start=16, length=8, byte_order=:little_endian)
named_signal_1 = Signals.NamedSignal("A", nothing, nothing, sig1)
named_signal_2 = Signals.NamedSignal("B", nothing, nothing, sig2)
named_signal_3 = Signals.NamedSignal("C", nothing, nothing, sig3)
signals = [named_signal_1, named_signal_2, named_signal_3]
frame = Frames.CANFrame(0x1FF, 0x01, 0x02, 0x03)
m = Messages.Message(0x1FF, 8, "M", named_signal_1, named_signal_2, named_signal_3)
value = Decode.decode(m, frame)
for signal in signals
@test value[Signals.name(signal)] == Decode.decode(signal, frame)
end
end
end
| CANalyze | https://github.com/tsabelmann/CANalyze.jl.git |
|
[
"MIT"
] | 1.6.0 | 2bb2fd8988fa976a3e057bbe6197414d77d5e29d | code | 2882 | using Test
@info "CANalyze.Frames tests..."
@testset "equal" begin
using CANalyze.Frames
@testset "equal_1" begin
frame1 = CANFrame(0x14, Integer[]; is_extended=true)
frame2 = CANFrame(0x14; is_extended=true)
@test frame1 == frame2
end
@testset "equal_2" begin
frame1 = CANFrame(0x14, Integer[]; is_extended=true)
frame2 = CANFrame(0x15, Integer[]; is_extended=true)
@test frame1 != frame2
end
@testset "equal_3" begin
frame1 = CANFrame(0x14, Integer[]; is_extended=false)
frame2 = CANFrame(0x14, Integer[]; is_extended=true)
@test frame1 != frame2
end
@testset "equal_4" begin
frame1 = CANFrame(0x14, Integer[]; is_extended=true)
frame2 = CANFrame(0x15, Integer[]; is_extended=true)
@test frame1 != frame2
end
@testset "equal_5" begin
frame1 = CANFrame(0x14, Integer[1,2,3,4]; is_extended=true)
frame2 = CANFrame(0x14, 1, 2, 3, 4; is_extended=true)
@test frame1 == frame2
end
end
@testset "frame_id" begin
using CANalyze.Frames
@testset "frame_id_1" begin
frame = CANFrame(0x0AFF, Integer[1,2,3,4]; is_extended=true)
@test frame_id(frame) == (0x0AFF & 0x01_FF_FF_FF)
end
@testset "frame_id_1" begin
frame = CANFrame(0x0AFF, Integer[1,2,3,4]; is_extended=false)
@test frame_id(frame) == (0x0AFF & 0x7FF)
end
end
@testset "data" begin
using CANalyze.Frames
for i=0:8
frame = CANFrame(0x0AFF, Integer[j for j=1:i]; is_extended=true)
@test data(frame) == UInt8[j for j=1:i]
end
end
@testset "dlc" begin
using CANalyze.Frames
for i=0:8
frame = CANFrame(0x0AFF, Integer[j for j=1:i]; is_extended=true)
@test dlc(frame) == i
end
end
@testset "is_extended" begin
using CANalyze.Frames
@testset "is_extended_1" begin
frame = CANFrame(0x0AFF; is_extended=true)
@test is_extended(frame) == true
@test is_standard(frame) == false
end
@testset "is_extended_2" begin
frame = CANFrame(0x0AFF; is_extended=false)
@test is_extended(frame) == false
@test is_standard(frame) == true
end
end
@testset "max_size" begin
using CANalyze.Frames
@testset "max_size_1" begin
frame = CANFrame(0x0AFF; is_extended=true)
@test max_size(typeof(frame)) == 8
end
@testset "max_size_2" begin
frame = CANFdFrame(0x0AFF; is_extended=true)
@test max_size(typeof(frame)) == 64
end
end
@testset "too_much_data" begin
using CANalyze.Frames
@testset "too_much_data_1" begin
@test_throws DomainError CANFrame(0x0AFF, [i for i=1:9]; is_extended=true)
end
@testset "too_much_data_2" begin
@test_throws DomainError CANFdFrame(0x0AFF, [i for i=1:65]; is_extended=true)
end
end
| CANalyze | https://github.com/tsabelmann/CANalyze.jl.git |
|
[
"MIT"
] | 1.6.0 | 2bb2fd8988fa976a3e057bbe6197414d77d5e29d | code | 6322 | using Test
@info "CANalyze.Messages tests..."
@testset "message" begin
import CANalyze.Signals
import CANalyze.Messages
@testset "message_1" begin
signal1 = Signals.NamedSignal("A", nothing, nothing, Signals.Unsigned(0, 32, 1, 0, :little_endian))
signal2 = Signals.NamedSignal("B", nothing, nothing, Signals.Unsigned(40, 17, 2, 20, :big_endian))
signal3 = Signals.NamedSignal("C", nothing, nothing, Signals.Unsigned(32, 8, 2, 20, :little_endian))
@test_throws DomainError Messages.Message(0x1FF, 8, "", signal1, signal2, signal3; strict=true)
end
@testset "message_2" begin
signal1 = Signals.NamedSignal("A", nothing, nothing, Signals.Unsigned(0, 32, 1, 0, :little_endian))
signal2 = Signals.NamedSignal("B", nothing, nothing, Signals.Unsigned(40, 17, 2, 20, :big_endian))
signal3 = Signals.NamedSignal("C", nothing, nothing, Signals.Unsigned(32, 8, 2, 20, :little_endian))
m = Messages.Message(0x1FF, 8, "ABC", signal1, signal2, signal3; strict=true)
@test true
end
@testset "message_3" begin
signal1 = Signals.NamedSignal("A", nothing, nothing, Signals.Unsigned(0, 32, 1, 0, :little_endian))
signal2 = Signals.NamedSignal("B", nothing, nothing, Signals.Unsigned(40, 17, 2, 20, :big_endian))
signal3 = Signals.NamedSignal("C", nothing, nothing, Signals.Unsigned(32, 9, 2, 20, :little_endian))
@test_throws DomainError Messages.Message(0x1FF, 8, "ABC", signal1, signal2, signal3; strict=true)
end
@testset "message_4" begin
signal1 = Signals.NamedSignal("A", nothing, nothing, Signals.Unsigned(0, 32, 1, 0, :little_endian))
signal2 = Signals.NamedSignal("B", nothing, nothing, Signals.Unsigned(40, 17, 2, 20, :big_endian))
signal3 = Signals.NamedSignal("C", nothing, nothing, Signals.Unsigned(32, 8, 2, 20, :little_endian))
@test_throws DomainError Messages.Message(0x1FF, 6, "ABC", signal1, signal2, signal3; strict=true)
end
@testset "message_4" begin
signal1 = Signals.NamedSignal("A", nothing, nothing, Signals.Unsigned(0, 32, 1, 0, :little_endian))
signal2 = Signals.NamedSignal("B", nothing, nothing, Signals.Unsigned(40, 17, 2, 20, :big_endian))
signal3 = Signals.NamedSignal("B", nothing, nothing, Signals.Unsigned(32, 8, 2, 20, :little_endian))
@test_throws DomainError Messages.Message(0x1FF, 8, "ABC", signal1, signal2, signal3; strict=true)
end
@testset "frame_id_1" begin
signal1 = Signals.NamedSignal("A", nothing, nothing, Signals.Unsigned(0, 32, 1, 0, :little_endian))
signal2 = Signals.NamedSignal("B", nothing, nothing, Signals.Unsigned(40, 17, 2, 20, :big_endian))
signal3 = Signals.NamedSignal("C", nothing, nothing, Signals.Unsigned(32, 8, 2, 20, :little_endian))
m = Messages.Message(0x1FF, 8, "ABC", signal1, signal2, signal3; strict=true)
@test Messages.frame_id(m) == 0x1FF
end
@testset "dlc_1" begin
signal1 = Signals.NamedSignal("A", nothing, nothing, Signals.Unsigned(0, 32, 1, 0, :little_endian))
signal2 = Signals.NamedSignal("B", nothing, nothing, Signals.Unsigned(40, 17, 2, 20, :big_endian))
signal3 = Signals.NamedSignal("C", nothing, nothing, Signals.Unsigned(32, 8, 2, 20, :little_endian))
m = Messages.Message(0x1FF, 8, "ABC", signal1, signal2, signal3; strict=true)
@test Messages.dlc(m) == 8
end
@testset "name_1" begin
signal1 = Signals.NamedSignal("A", nothing, nothing, Signals.Unsigned(0, 32, 1, 0, :little_endian))
signal2 = Signals.NamedSignal("B", nothing, nothing, Signals.Unsigned(40, 17, 2, 20, :big_endian))
signal3 = Signals.NamedSignal("C", nothing, nothing, Signals.Unsigned(32, 8, 2, 20, :little_endian))
m = Messages.Message(0x1FF, 8, "ABC", signal1, signal2, signal3; strict=true)
@test Messages.name(m) == "ABC"
end
@testset "get_1" begin
signal1 = Signals.NamedSignal("A", nothing, nothing, Signals.Unsigned(0, 32, 1, 0, :little_endian))
signal2 = Signals.NamedSignal("B", nothing, nothing, Signals.Unsigned(40, 17, 2, 20, :big_endian))
signal3 = Signals.NamedSignal("C", nothing, nothing, Signals.Unsigned(32, 8, 2, 20, :little_endian))
m = Messages.Message(0x1FF, 8, "ABC", signal1, signal2, signal3; strict=true)
@test m["A"] == signal1
@test m["B"] == signal2
@test m["C"] == signal3
end
@testset "get_2" begin
signal1 = Signals.NamedSignal("A", nothing, nothing, Signals.Unsigned(0, 32, 1, 0, :little_endian))
signal2 = Signals.NamedSignal("B", nothing, nothing, Signals.Unsigned(40, 17, 2, 20, :big_endian))
signal3 = Signals.NamedSignal("C", nothing, nothing, Signals.Unsigned(32, 8, 2, 20, :little_endian))
m = Messages.Message(0x1FF, 8, "ABC", signal1, signal2, signal3; strict=true)
@test_throws KeyError m["D"]
end
@testset "get_3" begin
signal1 = Signals.NamedSignal("A", nothing, nothing, Signals.Unsigned(0, 32, 1, 0, :little_endian))
signal2 = Signals.NamedSignal("B", nothing, nothing, Signals.Unsigned(40, 17, 2, 20, :big_endian))
signal3 = Signals.NamedSignal("C", nothing, nothing, Signals.Unsigned(32, 8, 2, 20, :little_endian))
m = Messages.Message(0x1FF, 8, "ABC", signal1, signal2, signal3; strict=true)
@test get(m, "A", nothing) == signal1
@test get(m, "B", nothing) == signal2
@test get(m, "C", nothing) == signal3
@test get(m, "D", nothing) == nothing
end
@testset "iterate_1" begin
signal1 = Signals.NamedSignal("A", nothing, nothing, Signals.Unsigned(0, 32, 1, 0, :little_endian))
signal2 = Signals.NamedSignal("B", nothing, nothing, Signals.Unsigned(40, 17, 2, 20, :big_endian))
signal3 = Signals.NamedSignal("C", nothing, nothing, Signals.Unsigned(32, 8, 2, 20, :little_endian))
signals = [signal1, signal2, signal3]
m = Messages.Message(0x1FF, 8, "ABC", signal1, signal2, signal3; strict=true)
for (n, sig) in m
if sig in signals
@test sig == m[n]
@test sig == m[Signals.name(sig)]
else
@test false
end
end
end
end
| CANalyze | https://github.com/tsabelmann/CANalyze.jl.git |
|
[
"MIT"
] | 1.6.0 | 2bb2fd8988fa976a3e057bbe6197414d77d5e29d | code | 21097 | using Test
@info "CANalyze.Signals tests..."
@testset "bit_signal" begin
using CANalyze.Signals
@testset "bit_signal_1" begin
signal = Bit(20)
@test true
end
@testset "bit_signal_2" begin
signal = Bit(start=20)
@test true
end
@testset "start_1" begin
signal = Bit(start=20)
@test start(signal) == 20
end
@testset "byte_order_1" begin
signal = Bit(start=20)
@test byte_order(signal) == :little_endian
end
@testset "length_1" begin
signal = Bit(start=20)
@test length(signal) == 1
end
end
@testset "unsigned_signal" begin
using CANalyze.Signals
@testset "unsigned_signal_1" begin
signal = Signals.Unsigned(0, 8, 1.0, 0.0, :little_endian)
@test true
end
@testset "unsigned_signal_2" begin
signal = Signals.Unsigned(start=0, length=8, factor=1.0, offset=0.0,
byte_order=:little_endian)
@test true
end
@testset "unsigned_signal_3" begin
signal = Signals.Unsigned{Float16}(0, 8)
@test true
end
@testset "unsigned_signal_4" begin
signal = Signals.Unsigned{Float16}(start=0, length=8)
@test true
end
@testset "unsigned_signal_5" begin
@test_throws DomainError Signals.Unsigned{Float16}(start=0, length=0)
end
@testset "unsigned_signal_6" begin
@test_throws DomainError Signals.Unsigned{Float16}(start=0, length=0,
byte_order=:mixed_endian)
end
@testset "start_1" begin
signal = Signals.Unsigned(23, 8, 1.0, 0.0, :little_endian)
@test start(signal) == 23
end
@testset "length_1" begin
signal = Signals.Unsigned(0, 8, 1.0, 0.0, :little_endian)
@test length(signal) == 8
end
@testset "factor_1" begin
signal = Signals.Unsigned(0, 8, 1.0, 0.0, :little_endian)
@test factor(signal) == 1
end
@testset "offset_1" begin
signal = Signals.Unsigned(0, 8, 1.0, 1337, :little_endian)
@test offset(signal) == 1337
end
@testset "byte_order_1" begin
signal = Signals.Unsigned(0, 8, 1.0, 0.0, :little_endian)
@test byte_order(signal) == :little_endian
end
@testset "byte_order_2" begin
signal = Signals.Unsigned(0, 8, 1.0, 0.0, :big_endian)
@test byte_order(signal) == :big_endian
end
end
@testset "signed_signal" begin
using CANalyze.Signals
@testset "signed_signal_1" begin
signal = Signals.Signed(0, 8, 1.0, 0.0, :little_endian)
@test true
end
@testset "signed_signal_2" begin
signal = Signals.Signed(start=0, length=8, factor=1.0, offset=0.0,
byte_order=:little_endian)
@test true
end
@testset "signed_signal_3" begin
signal = Signals.Signed{Float16}(0, 8)
@test true
end
@testset "signed_signal_4" begin
signal = Signals.Signed{Float16}(start=0, length=8)
@test true
end
@testset "signed_signal_5" begin
@test_throws DomainError Signals.Signed{Float16}(start=0, length=0)
end
@testset "signed_signal_6" begin
@test_throws DomainError Signals.Signed{Float16}(start=0, length=0,
byte_order=:mixed_endian)
end
@testset "start_1" begin
signal = Signals.Signed(23, 8, 1.0, 0.0, :little_endian)
@test start(signal) == 23
end
@testset "length_1" begin
signal = Signals.Signed(0, 8, 1.0, 0.0, :little_endian)
@test length(signal) == 8
end
@testset "factor_1" begin
signal = Signals.Signed(0, 8, 1.0, 0.0, :little_endian)
@test factor(signal) == 1
end
@testset "offset_1" begin
signal = Signals.Signed(0, 8, 1.0, 1337, :little_endian)
@test offset(signal) == 1337
end
@testset "byte_order_1" begin
signal = Signals.Signed(0, 8, 1.0, 0.0, :little_endian)
@test byte_order(signal) == :little_endian
end
@testset "byte_order_2" begin
signal = Signals.Signed(0, 8, 1.0, 0.0, :big_endian)
@test byte_order(signal) == :big_endian
end
end
@testset "float16_signal" begin
using CANalyze.Signals
@testset "float16_signal_1" begin
signal = Signals.Float16Signal(0)
@test true
end
@testset "float16_signal_2" begin
signal = Signals.Float16Signal(start=0, factor=1.0, offset=0.0,
byte_order=:little_endian)
@test true
end
@testset "float16_signal_3" begin
signal = Signals.Float16Signal(start=0, factor=1, offset=0,
byte_order=:little_endian)
@test true
end
@testset "start_1" begin
signal = Signals.Float16Signal(start=42, factor=1.0, offset=0.0,
byte_order=:little_endian)
@test start(signal) == 42
end
@testset "length_1" begin
signal = Signals.Float16Signal(start=0, factor=1.0, offset=0.0,
byte_order=:little_endian)
@test length(signal) == 16
end
@testset "factor_1" begin
signal = Signals.Float16Signal(start=0, factor=1.0, offset=0.0,
byte_order=:little_endian)
@test factor(signal) == 1
end
@testset "offset_1" begin
signal = Signals.Float16Signal(start=0, factor=1.0, offset=1337,
byte_order=:little_endian)
@test offset(signal) == 1337
end
@testset "byte_order_1" begin
signal = Signals.Float16Signal(start=0, factor=1.0, offset=0.0,
byte_order=:little_endian)
@test byte_order(signal) == :little_endian
end
@testset "byte_order_2" begin
signal = Signals.Float16Signal(start=0, factor=1.0, offset=0.0,
byte_order=:big_endian)
@test byte_order(signal) == :big_endian
end
end
@testset "float32_signal" begin
using CANalyze.Signals
@testset "float32_signal_1" begin
signal = Signals.Float32Signal(0)
@test true
end
@testset "float32_signal_2" begin
signal = Signals.Float32Signal(start=0, factor=1.0, offset=0.0,
byte_order=:little_endian)
@test true
end
@testset "float32_signal_3" begin
signal = Signals.Float32Signal(start=0, factor=1, offset=0,
byte_order=:little_endian)
@test true
end
@testset "start_1" begin
signal = Signals.Float32Signal(start=42, factor=1.0, offset=0.0,
byte_order=:little_endian)
@test start(signal) == 42
end
@testset "length_1" begin
signal = Signals.Float32Signal(start=0, factor=1.0, offset=0.0,
byte_order=:little_endian)
@test length(signal) == 32
end
@testset "factor_1" begin
signal = Signals.Float32Signal(start=0, factor=1.0, offset=0.0,
byte_order=:little_endian)
@test factor(signal) == 1
end
@testset "offset_1" begin
signal = Signals.Float32Signal(start=0, factor=1.0, offset=1337,
byte_order=:little_endian)
@test offset(signal) == 1337
end
@testset "byte_order_1" begin
signal = Signals.Float32Signal(start=0, factor=1.0, offset=0.0,
byte_order=:little_endian)
@test byte_order(signal) == :little_endian
end
@testset "byte_order_2" begin
signal = Signals.Float32Signal(start=0, factor=1.0, offset=0.0,
byte_order=:big_endian)
@test byte_order(signal) == :big_endian
end
end
@testset "float64_signal" begin
using CANalyze.Signals
@testset "float64_signal_1" begin
signal = Signals.Float64Signal(0)
@test true
end
@testset "float64_signal_2" begin
signal = Signals.Float64Signal(start=0, factor=1.0, offset=0.0,
byte_order=:little_endian)
@test true
end
@testset "float64_signal_3" begin
signal = Signals.Float64Signal(start=0, factor=1, offset=0,
byte_order=:little_endian)
@test true
end
@testset "start_1" begin
signal = Signals.Float64Signal(start=42, factor=1.0, offset=0.0,
byte_order=:little_endian)
@test start(signal) == 42
end
@testset "length_1" begin
signal = Signals.Float64Signal(start=0, factor=1.0, offset=0.0,
byte_order=:little_endian)
@test length(signal) == 64
end
@testset "factor_1" begin
signal = Signals.Float64Signal(start=0, factor=1.0, offset=0.0,
byte_order=:little_endian)
@test factor(signal) == 1
end
@testset "offset_1" begin
signal = Signals.Float64Signal(start=0, factor=1.0, offset=1337,
byte_order=:little_endian)
@test offset(signal) == 1337
end
@testset "byte_order_1" begin
signal = Signals.Float64Signal(start=0, factor=1.0, offset=0.0,
byte_order=:little_endian)
@test byte_order(signal) == :little_endian
end
@testset "byte_order_2" begin
signal = Signals.Float64Signal(start=0, factor=1.0, offset=0.0,
byte_order=:big_endian)
@test byte_order(signal) == :big_endian
end
end
@testset "float_signal" begin
using CANalyze.Signals
@testset "float_signal_1" begin
signal = Signals.FloatSignal(start=0, factor=2, offset=-1337,
byte_order=:big_endian)
@test true
end
end
@testset "raw_signal" begin
using CANalyze.Signals
@testset "raw_signal_1" begin
signal = Signals.Raw(0, 8, :little_endian)
@test true
end
@testset "raw_signal_2" begin
signal = Signals.Raw(start=0, length=8, byte_order=:little_endian)
@test true
end
@testset "raw_signal_3" begin
@test_throws DomainError Signals.Raw(start=0, length=0, byte_order=:little_endian)
end
@testset "raw_signal_4" begin
@test_throws DomainError Signals.Raw(start=0, length=1, byte_order=:mixed_endian)
end
@testset "start_1" begin
signal = Signals.Raw(start=42, length=8, byte_order=:little_endian)
@test start(signal) == 42
end
@testset "length_1" begin
signal = Signals.Raw(start=0, length=23, byte_order=:little_endian)
@test length(signal) == 23
end
@testset "byte_order_1" begin
signal = Signals.Raw(start=0, length=8, byte_order=:little_endian)
@test byte_order(signal) == :little_endian
end
@testset "byte_order_2" begin
signal = Signals.Raw(start=0, length=8, byte_order=:big_endian)
@test byte_order(signal) == :big_endian
end
end
@testset "named_signal" begin
using CANalyze.Signals
@testset "named_signal_1" begin
s = Signals.Raw(0, 8, :little_endian)
signal = Signals.NamedSignal("ABC", nothing, nothing, s)
@test true
end
@testset "named_signal_2" begin
s = Signals.Raw(0, 8, :little_endian)
signal = Signals.NamedSignal(name="ABC", unit=nothing, default=nothing,
signal=s)
@test true
end
@testset "named_signal_3" begin
s = Signals.Raw(0, 8, :little_endian)
@test_throws DomainError Signals.NamedSignal(name="",
unit=nothing,
default=nothing,
signal=s)
end
@testset "name_1" begin
s = Signals.Raw(0, 8, :little_endian)
signal = Signals.NamedSignal(name="ABC", unit=nothing, default=nothing,
signal=s)
@test name(signal) == "ABC"
end
@testset "unit_1" begin
s = Signals.Raw(0, 8, :little_endian)
signal = Signals.NamedSignal(name="ABC", unit=nothing, default=nothing,
signal=s)
@test unit(signal) == nothing
end
@testset "unit_2" begin
s = Signals.Raw(0, 8, :little_endian)
signal = Signals.NamedSignal(name="ABC", unit="Ah", default=nothing,
signal=s)
@test unit(signal) == "Ah"
end
@testset "default_1" begin
s = Signals.Raw(0, 8, :little_endian)
signal = Signals.NamedSignal(name="ABC", unit="Ah", default=nothing,
signal=s)
@test default(signal) == nothing
end
@testset "default_2" begin
s = Signals.Raw(0, 8, :little_endian)
signal = Signals.NamedSignal(name="ABC", unit="Ah", default=UInt(1337),
signal=s)
@test default(signal) == 1337
end
@testset "signal_1" begin
s = Signals.Raw(0, 8, :little_endian)
signal = Signals.NamedSignal(name="ABC", unit="Ah", default=nothing,
signal=s)
@test Signals.signal(signal) == s
end
end
@testset "bits" begin
using CANalyze.Signals
@testset "bit_1" begin
signal = Bit(42)
bits = Signals.Bits(signal)
@test bits == Signals.Bits(42)
end
@testset "unsigned_1" begin
signal = Signals.Unsigned(7, 5, 1.0, 0.0, :little_endian)
bits = Signals.Bits(signal)
@test bits == Signals.Bits(7, 8, 9, 10, 11)
end
@testset "unsigned_2" begin
signal = Signals.Unsigned(7, 5, 1.0, 0.0, :big_endian)
bits = Signals.Bits(signal)
@test bits == Signals.Bits(7, 6, 5, 4, 3)
end
@testset "signed_1" begin
signal = Signals.Signed(7, 5, 1.0, 0.0, :little_endian)
bits = Signals.Bits(signal)
@test bits == Signals.Bits(7, 8, 9, 10, 11)
end
@testset "signed_2" begin
signal = Signals.Signed(3, 5, 1.0, 0.0, :big_endian)
bits = Signals.Bits(signal)
@test bits == Signals.Bits(3, 2, 1, 0, 15)
end
@testset "float16_1" begin
signal = Signals.Float16Signal(0; byte_order=:little_endian)
bits = Signals.Bits(signal)
@test bits == Signals.Bits(Set{UInt16}([i for i=0:15]))
end
@testset "float16_2" begin
signal = Signals.Float16Signal(0; byte_order=:big_endian)
bits = Signals.Bits(signal)
@test bits == Signals.Bits(0, 15, 14, 13, 12, 11, 10, 9, 8, 23, 22, 21, 20, 19, 18, 17)
end
@testset "float32_1" begin
signal = Signals.Float32Signal(0; byte_order=:little_endian)
bits = Signals.Bits(signal)
@test bits == Signals.Bits(Set{UInt16}([i for i=0:31]))
end
@testset "float32_2" begin
signal = Signals.Float32Signal(39; byte_order=:big_endian)
bits = Signals.Bits(signal)
@test bits == Signals.Bits(Set{UInt16}([i for i=32:63]))
end
@testset "float64_1" begin
signal = Signals.Float64Signal(0; byte_order=:little_endian)
bits = Signals.Bits(signal)
@test bits == Signals.Bits(Set{UInt16}([i for i=0:63]))
end
@testset "float64_2" begin
signal = Signals.Float64Signal(7; byte_order=:big_endian)
bits = Signals.Bits(signal)
@test bits == Signals.Bits(Set{UInt16}([i for i=0:63]))
end
@testset "named_signal_1" begin
s = Signals.Float64Signal(7; byte_order=:big_endian)
signal = Signals.NamedSignal("ABC", nothing, nothing, s)
bits = Signals.Bits(signal)
@test bits == Signals.Bits(Set{UInt16}([i for i=0:63]))
end
end
@testset "share_bits" begin
using CANalyze.Signals
@testset "share_bits_1" begin
sig1 = Signals.Float16Signal(0; byte_order=:little_endian)
sig2 = Signals.Float16Signal(0; byte_order=:little_endian)
bits1 = Signals.Bits(sig1)
bits2 = Signals.Bits(sig2)
@test Signals.share_bits(bits1, bits2)
end
@testset "share_bits_2" begin
sig1 = Signals.Float16Signal(0; byte_order=:little_endian)
sig2 = Signals.Float16Signal(16; byte_order=:little_endian)
bits1 = Signals.Bits(sig1)
bits2 = Signals.Bits(sig2)
@test !Signals.share_bits(bits1, bits2)
end
end
@testset "overlap" begin
using CANalyze.Signals
@testset "overlap_1" begin
sig1 = Signals.Float16Signal(0; byte_order=:little_endian)
sig2 = Signals.Float16Signal(0; byte_order=:little_endian)
@test Signals.overlap(sig1, sig2)
end
@testset "overlap_2" begin
sig1 = Signals.Float16Signal(0; byte_order=:little_endian)
sig2 = Signals.Float16Signal(16; byte_order=:little_endian)
@test !Signals.overlap(sig1, sig2)
end
end
@testset "check" begin
using CANalyze.Signals
@testset "bit_1" begin
signal = Signals.Bit(0)
@test Signals.check(signal, UInt8(1))
end
@testset "bit_2" begin
signal = Signals.Bit(8)
@test !Signals.check(signal, UInt8(1))
end
@testset "unsigned_1" begin
signal = Signals.Unsigned(7, 5, 1.0, 0.0, :little_endian)
@test Signals.check(signal, UInt8(2))
end
@testset "unsigned_2" begin
signal = Signals.Unsigned(7, 9, 1.0, 0.0, :big_endian)
@test Signals.check(signal, UInt8(2))
end
@testset "signed_1" begin
signal = Signals.Signed(7, 5, 1.0, 0.0, :little_endian)
@test Signals.check(signal, UInt8(2))
end
@testset "signed_2" begin
signal = Signals.Signed(7, 9, 1.0, 0.0, :big_endian)
@test Signals.check(signal, UInt8(2))
end
@testset "float16_1" begin
signal = Signals.Float16Signal(0; byte_order=:little_endian)
@test Signals.check(signal, UInt8(2))
end
@testset "float16_2" begin
signal = Signals.Float16Signal(0; byte_order=:big_endian)
@test !Signals.check(signal, UInt8(2))
end
@testset "float32_1" begin
signal = Signals.Float32Signal(0; byte_order=:little_endian)
@test Signals.check(signal, UInt8(4))
end
@testset "float32_2" begin
signal = Signals.Float32Signal(0; byte_order=:big_endian)
@test !Signals.check(signal, UInt8(4))
end
@testset "float64_1" begin
signal = Signals.Float64Signal(0; byte_order=:little_endian)
@test Signals.check(signal, UInt8(8))
end
@testset "float64_2" begin
signal = Signals.Float64Signal(0; byte_order=:big_endian)
@test !Signals.check(signal, UInt8(8))
end
@testset "raw_1" begin
signal = Signals.Raw(0, 64, :little_endian)
@test Signals.check(signal, UInt8(8))
end
@testset "raw_2" begin
signal = Signals.Raw(0, 64, :big_endian)
@test Signals.check(signal, UInt8(9))
end
@testset "named_signal_1" begin
s = Signals.Raw(0, 64, :big_endian)
signal = Signals.NamedSignal("ABC", nothing, nothing, s)
@test Signals.check(signal, UInt8(9))
end
end
@testset "equal" begin
using CANalyze.Signals
@testset "bit_1" begin
bit1 = Signals.Bit(20)
bit2 = Signals.Bit(20)
@test bit1 == bit2
end
@testset "bit_2" begin
bit1 = Signals.Bit(20)
bit2 = Signals.Bit(21)
@test !(bit1 == bit2)
end
@testset "unsigned_1" begin
sig1 = Signals.Unsigned(0, 8, 1, 0, :little_endian)
sig2 = Signals.Unsigned(0, 8, 1, 0, :little_endian)
@test sig1 == sig2
end
@testset "unsigned_2" begin
sig1 = Signals.Unsigned(0, 8, 1, 0, :little_endian)
sig2 = Signals.Unsigned(1, 8, 1, 0, :little_endian)
@test !(sig1 == sig2)
end
@testset "unsigned_3" begin
sig1 = Signals.Unsigned(0, 8, 1, 0, :little_endian)
sig2 = Signals.Unsigned(0, 9, 1, 0, :little_endian)
@test !(sig1 == sig2)
end
@testset "unsigned_4" begin
sig1 = Signals.Unsigned(0, 8, 1, 0, :little_endian)
sig2 = Signals.Unsigned(0, 8, 2, 0, :little_endian)
@test !(sig1 == sig2)
end
@testset "unsigned_5" begin
sig1 = Signals.Unsigned(0, 8, 1, 0, :little_endian)
sig2 = Signals.Unsigned(0, 8, 1, -1, :little_endian)
@test !(sig1 == sig2)
end
@testset "unsigned_6" begin
sig1 = Signals.Unsigned(0, 8, 1, 0, :little_endian)
sig2 = Signals.Unsigned(0, 8, 1, 0, :big_endian)
@test !(sig1 == sig2)
end
end
| CANalyze | https://github.com/tsabelmann/CANalyze.jl.git |
|
[
"MIT"
] | 1.6.0 | 2bb2fd8988fa976a3e057bbe6197414d77d5e29d | code | 5062 | using Test
@info "CANalyze.Utils tests..."
@testset "endian" begin
using CANalyze.Utils
@testset "is_little_or_big_endian" begin
is_little = is_little_endian()
is_big = is_big_endian()
@test (is_little || is_big) == true
end
@testset "is_little_and_big_endian" begin
is_little = is_little_endian()
is_big = is_big_endian()
@test (is_little && is_big) == false
end
end
@testset "convert" begin
using CANalyze.Utils
@testset "to_bytes_1" begin
value = 1337
new_value = from_bytes(typeof(value), to_bytes(value))
@test value == new_value
end
@testset "from_bytes_1" begin
types = [UInt8, UInt16, UInt32, UInt64, UInt128]
for (i, type) in enumerate(types)
array = [UInt8(j) for j=1:2^(i-1)]
new_array = to_bytes(from_bytes(type, array))
@test array == new_array
end
end
@testset "from_bytes_2" begin
types = [Int8, Int16, Int32, Int64, Int128]
for (i, type) in enumerate(types)
array = [UInt8(j) for j=1:2^(i-1)]
new_array = to_bytes(from_bytes(type, array))
@test array == new_array
end
end
@testset "from_bytes_4" begin
types = [Float16, Float32, Float64]
for (i, type) in enumerate(types)
array = [UInt8(j) for j=1:2^i]
new_array = to_bytes(from_bytes(type, array))
@test array == new_array
end
end
end
@testset "mask" begin
using CANalyze.Utils
@testset "zero_mask" begin
@test zero_mask(UInt8) == zero(UInt8)
@test zero_mask(UInt16) == zero(UInt16)
@test zero_mask(UInt32) == zero(UInt32)
@test zero_mask(UInt64) == zero(UInt64)
@test zero_mask(UInt128) == zero(UInt128)
end
@testset "full_mask_1" begin
@test full_mask(UInt8) == UInt8(0xFF)
@test full_mask(UInt16) == UInt16(0xFFFF)
@test full_mask(UInt32) == UInt32(0xFFFFFFFF)
@test full_mask(UInt64) == UInt64(0xFFFFFFFFFFFFFFFF)
@test full_mask(UInt128) == UInt128(0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
end
@testset "full_mask_2" begin
@test mask(UInt8) == UInt8(0xFF)
@test mask(UInt16) == UInt16(0xFFFF)
@test mask(UInt32) == UInt32(0xFFFFFFFF)
@test mask(UInt64) == UInt64(0xFFFFFFFFFFFFFFFF)
@test mask(UInt128) == UInt128(0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
end
@testset "mask_1" begin
@test mask(UInt8, UInt8(0)) == UInt8(0b0)
@test mask(UInt8, UInt8(1)) == UInt8(0b1)
@test mask(UInt8, UInt8(2)) == UInt8(0b11)
@test mask(UInt8, UInt8(3)) == UInt8(0b111)
@test mask(UInt8, UInt8(4)) == UInt8(0b1111)
@test mask(UInt8, UInt8(5)) == UInt8(0b11111)
@test mask(UInt8, UInt8(6)) == UInt8(0b111111)
@test mask(UInt8, UInt8(7)) == UInt8(0b1111111)
@test mask(UInt8, UInt8(8)) == UInt8(0b11111111)
end
@testset "mask_2" begin
@test mask(UInt16, UInt8(0)) == UInt16(0b0)
value = UInt16(2)
for i in 1:16
@test mask(UInt16, UInt8(i)) == (value - 1)
value *= 2
end
end
@testset "mask_3" begin
@test mask(UInt32, UInt8(0)) == UInt32(0b0)
value = UInt16(2)
for i in 1:32
@test mask(UInt32, UInt8(i)) == (value - 1)
value *= 2
end
end
@testset "mask_4" begin
@test mask(UInt64, UInt8(0)) == UInt64(0b0)
value = UInt64(2)
for i in 1:64
@test mask(UInt64, UInt8(i)) == (value - 1)
value *= 2
end
end
@testset "mask_5" begin
@test mask(UInt128, UInt8(0)) == UInt128(0b0)
value = UInt128(2)
for i in 1:16
@test mask(UInt128, UInt8(i)) == (value - 1)
value *= 2
end
end
@testset "shifted_mask_1" begin
for i in 0:8
@test mask(UInt8, i, 0) == mask(UInt8, i)
end
end
@testset "shifted_mask_2" begin
for i in 0:16
@test mask(UInt16, i, 0) == mask(UInt16, i)
end
end
@testset "shifted_mask_3" begin
for i in 0:32
@test mask(UInt32, i, 0) == mask(UInt32, i)
end
end
@testset "shifted_mask_4" begin
for i in 0:64
@test mask(UInt64, i, 0) == mask(UInt64, i)
end
end
@testset "shifted_mask_5" begin
for i in 0:128
@test mask(UInt128, i, 0) == mask(UInt128, i)
end
end
@testset "bit_mask_1" begin
for T in [UInt8, UInt16, UInt32, UInt64, UInt128, Int8, Int16, Int32, Int64, Int128]
s = 8*sizeof(T) - 1
@test bit_mask(T, 0:s) == full_mask(T)
end
end
@testset "bit_mask_2" begin
for T in [UInt8, UInt16, UInt32, UInt64, UInt128, Int8, Int16, Int32, Int64, Int128]
s = 8*sizeof(T) - 1
@test bit_mask(T, s) == mask(T, 1, s)
end
end
end
| CANalyze | https://github.com/tsabelmann/CANalyze.jl.git |
|
[
"MIT"
] | 1.6.0 | 2bb2fd8988fa976a3e057bbe6197414d77d5e29d | code | 169 | using Test
@info "Starting tests..."
include("Utils.jl")
include("Frames.jl")
include("Signals.jl")
include("Messages.jl")
include("Databases.jl")
include("Decode.jl")
| CANalyze | https://github.com/tsabelmann/CANalyze.jl.git |
|
[
"MIT"
] | 1.6.0 | 2bb2fd8988fa976a3e057bbe6197414d77d5e29d | docs | 1274 | # CANalyze.jl
[![Build status](https://github.com/tsabelmann/CANalyze.jl/workflows/CI/badge.svg)](https://github.com/tsabelmann/CANalyze.jl/actions)
[![codecov](https://codecov.io/gh/tsabelmann/CANalyze.jl/branch/main/graph/badge.svg?token=V7VSDSOX1H)](https://codecov.io/gh/tsabelmann/CANalyze.jl)
[![Documentation](https://img.shields.io/badge/docs-latest-blue.svg)](https://tsabelmann.github.io/CANalyze.jl/dev)
[![Code Style: Blue](https://img.shields.io/badge/code%20style-blue-4495d1.svg)](https://github.com/invenia/BlueStyle)
*Julia package for analyzing CAN-bus data using messages and variables*
## Installation
Start julia and open the package mode by entering `]`. Then enter
```julia
add CANalyze
```
This will install the packages `CANalyze.jl` and all its dependencies.
## License / Terms of Usage
The source code of this project is licensed under the MIT license. This implies that
you are free to use, share, and adapt it. However, please give appropriate credit
by citing the project.
## Contact
If you have problems using the software, find mistakes, or have general questions please use
the [issue tracker](https://github.com/tsabelmann/CANTools.jl/issues) to contact us.
## Contributors
* [Tim Lucas Sabelmann](https://github.com/tsabelmann) | CANalyze | https://github.com/tsabelmann/CANalyze.jl.git |
|
[
"MIT"
] | 1.6.0 | 2bb2fd8988fa976a3e057bbe6197414d77d5e29d | docs | 103 | ```@meta
CurrentModule = CANalyze
```
# CANTools.Decode
```@autodocs
Modules = [CANalyze.Decode]
```
| CANalyze | https://github.com/tsabelmann/CANalyze.jl.git |
|
[
"MIT"
] | 1.6.0 | 2bb2fd8988fa976a3e057bbe6197414d77d5e29d | docs | 103 | ```@meta
CurrentModule = CANalyze
```
# CANalyze.Encode
```@autodocs
Modules = [CANalyze.Encode]
```
| CANalyze | https://github.com/tsabelmann/CANalyze.jl.git |
|
[
"MIT"
] | 1.6.0 | 2bb2fd8988fa976a3e057bbe6197414d77d5e29d | docs | 103 | ```@meta
CurrentModule = CANalyze
```
# CANalyze.Frames
```@autodocs
Modules = [CANalyze.Frames]
```
| CANalyze | https://github.com/tsabelmann/CANalyze.jl.git |
|
[
"MIT"
] | 1.6.0 | 2bb2fd8988fa976a3e057bbe6197414d77d5e29d | docs | 1272 | # CANalyze.jl
[![Build status](https://github.com/tsabelmann/CANalyze.jl/workflows/CI/badge.svg)](https://github.com/tsabelmann/CANalyze.jl/actions)
[![codecov](https://codecov.io/gh/tsabelmann/CANalyze.jl/branch/main/graph/badge.svg?token=V7VSDSOX1H)](https://codecov.io/gh/tsabelmann/CANalyze.jl)
[![Documentation](https://img.shields.io/badge/docs-latest-blue.svg)](https://tsabelmann.github.io/CANalyze.jl/dev)
[![Code Style: Blue](https://img.shields.io/badge/code%20style-blue-4495d1.svg)](https://github.com/invenia/BlueStyle)
*Julia package for analyzing CAN-bus data using messages and variables*
## Installation
Start julia and open the package mode by entering `]`. Then enter
```julia
add CANalyze
```
This will install the packages `CANalyze.jl` and all its dependencies.
## License / Terms of Usage
The source code of this project is licensed under the MIT license. This implies that
you are free to use, share, and adapt it. However, please give appropriate credit
by citing the project.
## Contact
If you have problems using the software, find mistakes, or have general questions please use
the [issue tracker](https://github.com/tsabelmann/CANTools.jl/issues) to contact us.
## Contributors
* [Tim Lucas Sabelmann](https://github.com/tsabelmann) | CANalyze | https://github.com/tsabelmann/CANalyze.jl.git |
|
[
"MIT"
] | 1.6.0 | 2bb2fd8988fa976a3e057bbe6197414d77d5e29d | docs | 107 | ```@meta
CurrentModule = CANalyze
```
# CANalyze.Messages
```@autodocs
Modules = [CANalyze.Messages]
```
| CANalyze | https://github.com/tsabelmann/CANalyze.jl.git |
|
[
"MIT"
] | 1.6.0 | 2bb2fd8988fa976a3e057bbe6197414d77d5e29d | docs | 105 | ```@meta
CurrentModule = CANalyze
```
# CANalyze.Signals
```@autodocs
Modules = [CANalyze.Signals]
```
| CANalyze | https://github.com/tsabelmann/CANalyze.jl.git |
|
[
"MIT"
] | 1.6.0 | 2bb2fd8988fa976a3e057bbe6197414d77d5e29d | docs | 101 | ```@meta
CurrentModule = CANalyze
```
# CANalyze.Utils
```@autodocs
Modules = [CANalyze.Utils]
```
| CANalyze | https://github.com/tsabelmann/CANalyze.jl.git |
|
[
"MIT"
] | 1.6.0 | 2bb2fd8988fa976a3e057bbe6197414d77d5e29d | docs | 1106 | ```@meta
CurrentModule = CANalyze
```
# Database
```julia
using CANalyze.Signals
using CANalyze.Messages
using CANalyze.Databases
sig1 = NamedSignal("A", nothing, nothing, Float32Signal(start=0, byte_order=:little_endian))
sig2 = NamedSignal("B", nothing, nothing, Unsigned(start=40,
length=17,
factor=2,
offset=20,
byte_order=:big_endian))
sig3 = NamedSignal("C", nothing, nothing, Unsigned(start=32,
length=8,
factor=2,
offset=20,
byte_order=:little_endian))
message1 = Message(0x1FD, 8, "A", sig1; strict=true)
message1 = Message(0x1FE, 8, "B", sig1, sig2; strict=true)
message2 = Message(0x1FF, 8, "C", sig1, sig2, sig3; strict=true)
database = Database(message1, message2, message3)
```
| CANalyze | https://github.com/tsabelmann/CANalyze.jl.git |
|
[
"MIT"
] | 1.6.0 | 2bb2fd8988fa976a3e057bbe6197414d77d5e29d | docs | 1432 | ```@meta
CurrentModule = CANalyze
```
# Decode
## Signal
```julia
using CANalyze.Frames
using CANalyze.Signals
using CANalyze.Decode
sig1 = Unsigned(start=0, length=8, factor=1.0, offset=-1337f0, byte_order=:little_endian)
sig2 = NamedSignal("A", nothing, nothing, Float32Signal(start=0, byte_order=:little_endian
frame = CANFrame(20, [1, 2, 3, 4, 5, 6, 7, 8])
value1 = decode(sig1, frame)
value2 = decode(sig2, frame)
```
## Message
```julia
using CANalyze.Frames
using CANalyze.Signals
using CANalyze.Messages
using CANalyze.Decode
sig1 = NamedSignal("A", nothing, nothing, Float32Signal(start=0, byte_order=:little_endian))
sig2 = NamedSignal("B", nothing, nothing, Unsigned(start=40,
length=17,
factor=2,
offset=20,
byte_order=:big_endian))
sig3 = NamedSignal("C", nothing, nothing, Unsigned(start=32,
length=8,
factor=2,
offset=20,
byte_order=:little_endian))
message = Message(0x1FF, 8, "ABC", sig1, sig2, sig3; strict=true)
frame = CANFrame(20, [1, 2, 3, 4, 5, 6, 7, 8])
value = decode(message, frame)
```
| CANalyze | https://github.com/tsabelmann/CANalyze.jl.git |
|
[
"MIT"
] | 1.6.0 | 2bb2fd8988fa976a3e057bbe6197414d77d5e29d | docs | 919 | ```@meta
CurrentModule = CANalyze
```
# Message
```julia
using CANalyze.Signals
using CANalyze.Messages
sig1 = NamedSignal("A", nothing, nothing, Float32Signal(start=0, byte_order=:little_endian))
sig2 = NamedSignal("B", nothing, nothing, Unsigned(start=40,
length=17,
factor=2,
offset=20,
byte_order=:big_endian))
sig3 = NamedSignal("C", nothing, nothing, Unsigned(start=32,
length=8,
factor=2,
offset=20,
byte_order=:little_endian))
message = Message(0x1FF, 8, "ABC", sig1, sig2, sig3; strict=true)
```
| CANalyze | https://github.com/tsabelmann/CANalyze.jl.git |
|
[
"MIT"
] | 1.6.0 | 2bb2fd8988fa976a3e057bbe6197414d77d5e29d | docs | 2264 | ```@meta
CurrentModule = CANalyze
```
# Signals
Signals are the basic blocks of the CAN-bus data analysis, i.e., decoding or
encoding CAN-bus data.
## Bit
```julia
using CANalyze.Signals
bit1 = Bit(20)
bit2 = Bit(start=20)
```
## Unsigned
```julia
using CANalyze.Signals
sig1 = Unsigned{Float32}(0, 1)
sig2 = Unsigned{Float64}(start=0, length=8, factor=2, offset=20)
sig3 = Unsigned(0, 8, 1, 0, :little_endian)
sig4 = Unsigned(start=0, length=8, factor=1.0, offset=-1337f0, byte_order=:little_endian)
```
## Signed
```julia
using CANalyze.Signals
sig1 = Signed{Float32}(0, 1)
sig2 = Signed{Float64}(start=3, length=16, factor=2, offset=20, byte_order=:big_endian)
sig3 = Signed(0, 8, 1, 0, :little_endian)
sig4 = Signed(start=0, length=8, factor=1.0, offset=-1337f0, byte_order=:little_endian)
```
## FloatSignal
```julia
using CANalyze.Signals
sig1 = FloatSignal(0, 1.0, 0.0, :little_endian)
sig2 = FloatSignal(start=0, factor=1.0, offset=0.0, byte_order=:little_endian)
```
## Float16Signal
```julia
using CANalyze.Signals
sig1 = FloatSignal{Float16}(0)
sig2 = FloatSignal{Float16}(0, factor=1.0, offset=0.0, byte_order=:little_endian)
sig3 = FloatSignal{Float16}(start=0, factor=1.0, offset0.0, byte_order=:little_endian)
```
## Float32Signal
```julia
using CANalyzes
sig1 = FloatSignal{Float32}(0)
sig2 = FloatSignal{Float32}(0, factor=1.0, offset=0.0, byte_order=:little_endian)
sig3 = FloatSignal{Float32}(start=0, factor=1.0, offset0.0, byte_order=:little_endian)
```
## Float64Signal
```julia
using CANalyze.Signals
sig1 = FloatSignal{Float64}(0)
sig2 = FloatSignal{Float64}(0, factor=1.0, offset=0.0, byte_order=:little_endian)
sig3 = FloatSignal{Float64}(start=0, factor=1.0, offset=0.0, byte_order=:little_endian)
```
## Raw
```julia
using CANalyze.Signals
sig1 = Raw(0, 8, :big_endian)
sig2 = Raw(start=21, length=7, byte_order=:little_endian)
```
## NamedSignal
```julia
using CANalyze.Signals
sig1 = NamedSignal("ABC",
nothing,
nothing,
Float32Signal(start=0, byte_order=:little_endian))
sig2 = NamedSignal(name="ABC",
unit=nothing,
default=nothing,
signal=Float32Signal(start=0, byte_order=:little_endian))
```
| CANalyze | https://github.com/tsabelmann/CANalyze.jl.git |
|
[
"MIT"
] | 0.2.2 | 2fdf8dec8ac5fbf4a19487210c6d3bb8dff95459 | code | 447 | using Documenter
using DiffPointRasterisation
makedocs(;
sitename="DiffPointRasterisation",
format=Documenter.HTML(),
modules=[DiffPointRasterisation],
pages=[
"Home" => "index.md",
"Batch of poses" => "batch.md",
"API" => "api.md",
],
checkdocs=:exports,
)
deploydocs(;
repo="github.com/microscopic-image-analysis/DiffPointRasterisation.jl.git",
devbranch="main",
push_preview=true,
) | DiffPointRasterisation | https://github.com/microscopic-image-analysis/DiffPointRasterisation.jl.git |
|
[
"MIT"
] | 0.2.2 | 2fdf8dec8ac5fbf4a19487210c6d3bb8dff95459 | code | 2789 | using DiffPointRasterisation
using FFTW
using Images
using LinearAlgebra
using StaticArrays
using Zygote
load_image(path) = load(path) .|> Gray |> channelview
init_points(n) = [2 * rand(Float32, 2) .- 1f0 for _ in 1:n]
target_image = load_image("data/julia.png")
points = init_points(5_000)
rotation = I(2)
translation = zeros(Float32, 2)
function model(points, log_bandwidth, log_weight)
# raster points to 2d-image
rough_image = raster(size(target_image), points, rotation, translation, 0f0, exp(log_weight))
# smooth image with gaussian kernel
kernel = gaussian_kernel(log_bandwidth, size(target_image)...)
image = convolve_image(rough_image, kernel)
image
end
function gaussian_kernel(log_σ::T, h=4*ceil(Int, σ) + 1, w=h) where {T}
σ = exp(log_σ)
mw = T(0.5 * (w + 1))
mh = T(0.5 * (h + 1))
gw = [exp(-(x - mw)^2/(2*σ^2)) for x=1:w]
gh = [exp(-(x - mh)^2/(2*σ^2)) for x=1:h]
gwn = gw / sum(gw)
ghn = gh / sum(gh)
ghn * gwn'
end
convolve_image(image, kernel) = irfft(rfft(image) .* rfft(kernel), size(image, 1))
function loss(points, log_bandwidth, log_weight)
model_image = model(points, log_bandwidth, log_weight)
# squared error plus regularization term for points
sum((model_image .- target_image).^2) + sum(stack(points).^2)
end
logrange(s, e, n) = round.(Int, exp.(range(log(s), log(e), n)))
function langevin!(points, log_bandwidth, log_weight, eps, n, update_bandwidth=true, update_weight=true, eps_after_init=eps; n_init=n, n_logs_init=15)
# Langevin sampling for points and optionally log_bandwidth and log_weight.
logs_init = logrange(1, n_init, n_logs_init)
log_every = false
logstep = 1
for i in 1:n
l, grads = Zygote.withgradient(loss, points, log_bandwidth, log_weight)
points .+= sqrt(eps) .* reinterpret(reshape, SVector{2, Float32}, randn(Float32, 2, length(points))) .- eps .* 0.5f0 .* grads[1]
if update_bandwidth
log_bandwidth += sqrt(eps) * randn(Float32) - eps * 0.5f0 * grads[2]
end
if update_weight
log_weight += sqrt(eps) * randn(Float32) - eps * 0.5f0 * grads[3]
end
if i == n_init
log_every = true
eps = eps_after_init
end
if log_every || (i in logs_init)
println("iteration $logstep, $i: loss = $l, bandwidth = $(exp(log_bandwidth)), weight = $(exp(log_weight))")
save("image_$logstep.png", Gray.(clamp01.(model(points, log_bandwidth, log_weight))))
logstep += 1
end
end
save("image_final.png", Gray.(clamp01.(model(points, log_bandwidth, log_weight))))
points, log_bandwidth
end
isinteractive() || langevin!(points, log(0.5f0), 0f0, 5f-6, 6_030, false, true, 4f-5; n_init=6_000)
| DiffPointRasterisation | https://github.com/microscopic-image-analysis/DiffPointRasterisation.jl.git |