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
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, "&nbsp;&nbsp;&nbsp;&nbsp;") 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, "&nbsp;&nbsp;&nbsp;&nbsp;") 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, "&amp;") : print(io, c)) : c == '<' ? (escape_html_chars ? print(io, "&lt;") : print(io, c)) : c == '>' ? (escape_html_chars ? print(io, "&gt;") : print(io, c)) : c == '"' ? (escape_html_chars ? print(io, "&quot;") : print(io, c)) : c == '\'' ? (escape_html_chars ? print(io, "&apos;") : 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
[ "MIT" ]
0.2.2
2fdf8dec8ac5fbf4a19487210c6d3bb8dff95459
code
11001
# We provide an explicit extension package for CUDA # since the pullback kernel profits a lot from # parallel reductions, which are relatively straightforwadly # expressed using while loops. # However KernelAbstractions currently does not play nicely # with while loops, see e.g. here: # https://github.com/JuliaGPU/KernelAbstractions.jl/issues/330 module DiffPointRasterisationCUDAExt using DiffPointRasterisation, CUDA using ArgCheck using FillArrays using StaticArrays const CuOrFillArray{T,N} = Union{CuArray{T,N},FillArrays.AbstractFill{T,N}} const CuOrFillVector{T} = CuOrFillArray{T,1} function raster_pullback_kernel!( ::Type{T}, ds_dout, points::AbstractVector{<:StaticVector{N_in}}, rotations::AbstractVector{<:StaticMatrix{N_out,N_in,TR}}, translations::AbstractVector{<:StaticVector{N_out,TT}}, out_weights, point_weights, shifts, scale, # outputs: ds_dpoints, ds_drotation, ds_dtranslation, ds_dout_weight, ds_dpoint_weight, ) where {T,TR,TT,N_in,N_out} n_voxel = blockDim().z points_per_workgroup = blockDim().x batchsize_per_workgroup = blockDim().y # @assert points_per_workgroup == 1 # @assert n_voxel == 2^N_out # @assert threadIdx().x == 1 n_threads_per_workgroup = n_voxel * batchsize_per_workgroup s = threadIdx().z b = threadIdx().y thread = (b - 1) * n_voxel + s neighbor_voxel_id = (blockIdx().z - 1) * n_voxel + s point_idx = (blockIdx().x - 1) * points_per_workgroup + threadIdx().x batch_idx = (blockIdx().y - 1) * batchsize_per_workgroup + b in_batch = batch_idx <= length(rotations) dimension1 = (N_out, n_voxel, batchsize_per_workgroup) ds_dpoint_rot_shared = CuDynamicSharedArray(T, dimension1) offset = sizeof(T) * prod(dimension1) dimension2 = (N_in, batchsize_per_workgroup) ds_dpoint_shared = CuDynamicSharedArray(T, dimension2, offset) dimension3 = (n_voxel, batchsize_per_workgroup) offset += sizeof(T) * prod(dimension2) ds_dpoint_weight_shared = CuDynamicSharedArray(T, dimension3, offset) rotation = @inbounds in_batch ? rotations[batch_idx] : @SMatrix zeros(TR, N_in, N_in) point = @inbounds points[point_idx] point_weight = @inbounds point_weights[point_idx] if in_batch translation = @inbounds translations[batch_idx] out_weight = @inbounds out_weights[batch_idx] shift = @inbounds shifts[neighbor_voxel_id] origin = (-@SVector ones(TT, N_out)) - translation coord_reference_voxel, deltas = DiffPointRasterisation.reference_coordinate_and_deltas( point, rotation, origin, scale ) voxel_idx = CartesianIndex( CartesianIndex(Tuple(coord_reference_voxel)) + CartesianIndex(shift), batch_idx ) ds_dweight_local = zero(T) if voxel_idx in CartesianIndices(ds_dout) @inbounds ds_dweight_local = DiffPointRasterisation.voxel_weight( deltas, shift, ds_dout[voxel_idx] ) factor = ds_dout[voxel_idx] * out_weight * point_weight ds_dcoord_part = SVector( factor .* ntuple( n -> DiffPointRasterisation.interpolation_weight( n, N_out, deltas, shift ), Val(N_out), ), ) @inbounds ds_dpoint_rot_shared[:, s, b] .= ds_dcoord_part .* scale else @inbounds ds_dpoint_rot_shared[:, s, b] .= zero(T) end @inbounds ds_dpoint_weight_shared[s, b] = ds_dweight_local * out_weight ds_dout_weight_local = ds_dweight_local * point_weight @inbounds CUDA.@atomic ds_dout_weight[batch_idx] += ds_dout_weight_local else @inbounds ds_dpoint_weight_shared[s, b] = zero(T) @inbounds ds_dpoint_rot_shared[:, s, b] .= zero(T) end # parallel summation of ds_dpoint_rot_shared over neighboring-voxel dimension # for a given thread-local batch index stride = 1 @inbounds while stride < n_voxel sync_threads() idx = 2 * stride * (s - 1) + 1 if idx <= n_voxel dim = 1 while dim <= N_out other_val_p = if idx + stride <= n_voxel ds_dpoint_rot_shared[dim, idx + stride, b] else zero(T) end ds_dpoint_rot_shared[dim, idx, b] += other_val_p dim += 1 end end stride *= 2 end sync_threads() if in_batch dim = s if dim <= N_out coef = ds_dpoint_rot_shared[dim, 1, b] @inbounds CUDA.@atomic ds_dtranslation[dim, batch_idx] += coef j = 1 while j <= N_in val = coef * point[j] @inbounds CUDA.@atomic ds_drotation[dim, j, batch_idx] += val j += 1 end end end # derivative of point with respect to rotation per batch dimension dim = s while dim <= N_in val = zero(T) j = 1 while j <= N_out @inbounds val += rotation[j, dim] * ds_dpoint_rot_shared[j, 1, b] j += 1 end @inbounds ds_dpoint_shared[dim, b] = val dim += n_voxel end # parallel summation of ds_dpoint_shared over batch dimension stride = 1 @inbounds while stride < batchsize_per_workgroup sync_threads() idx = 2 * stride * (b - 1) + 1 if idx <= batchsize_per_workgroup dim = s while dim <= N_in other_val_p = if idx + stride <= batchsize_per_workgroup ds_dpoint_shared[dim, idx + stride] else zero(T) end ds_dpoint_shared[dim, idx] += other_val_p dim += n_voxel end end stride *= 2 end # parallel summation of ds_dpoint_weight_shared over voxel and batch dimension stride = 1 @inbounds while stride < n_threads_per_workgroup sync_threads() idx = 2 * stride * (thread - 1) + 1 if idx <= n_threads_per_workgroup other_val_w = if idx + stride <= n_threads_per_workgroup ds_dpoint_weight_shared[idx + stride] else zero(T) end ds_dpoint_weight_shared[idx] += other_val_w end stride *= 2 end sync_threads() dim = thread while dim <= N_in val = ds_dpoint_shared[dim, 1] # batch might be split across blocks, so need atomic add @inbounds CUDA.@atomic ds_dpoints[dim, point_idx] += val dim += n_threads_per_workgroup end if thread == 1 val_w = ds_dpoint_weight_shared[1, 1] # batch might be split across blocks, so need atomic add @inbounds CUDA.@atomic ds_dpoint_weight[point_idx] += val_w end return nothing end # single image function raster_pullback!( ds_dout::CuArray{<:Number,N_out}, points::AbstractVector{<:StaticVector{N_in,<:Number}}, rotation::StaticMatrix{N_out,N_in,<:Number}, translation::StaticVector{N_out,<:Number}, background::Number, out_weight::Number, point_weight::CuOrFillVector{<:Number}, ds_dpoints::AbstractMatrix{<:Number}, ds_dpoint_weight::AbstractVector{<:Number}; kwargs..., ) where {N_in,N_out} return error( "Not implemented: raster_pullback! for single image not implemented on GPU. Consider using CPU arrays", ) end # batch of images function DiffPointRasterisation.raster_pullback!( ds_dout::CuArray{<:Number,N_out_p1}, points::CuVector{<:StaticVector{N_in,<:Number}}, rotation::CuVector{<:StaticMatrix{N_out,N_in,<:Number}}, translation::CuVector{<:StaticVector{N_out,<:Number}}, background::CuOrFillVector{<:Number}, out_weight::CuOrFillVector{<:Number}, point_weight::CuOrFillVector{<:Number}, ds_dpoints::CuMatrix{TP}, ds_drotation::CuArray{TR,3}, ds_dtranslation::CuMatrix{TT}, ds_dbackground::CuVector{<:Number}, ds_dout_weight::CuVector{OW}, ds_dpoint_weight::CuVector{PW}, ) where {N_in,N_out,N_out_p1,TP<:Number,TR<:Number,TT<:Number,OW<:Number,PW<:Number} T = promote_type(eltype(ds_dout), TP, TR, TT, OW, PW) batch_axis = axes(ds_dout, N_out_p1) @argcheck N_out == N_out_p1 - 1 @argcheck batch_axis == axes(rotation, 1) == axes(translation, 1) == axes(background, 1) == axes(out_weight, 1) @argcheck batch_axis == axes(ds_drotation, 3) == axes(ds_dtranslation, 2) == axes(ds_dbackground, 1) == axes(ds_dout_weight, 1) @argcheck N_out == N_out_p1 - 1 n_points = length(points) @argcheck length(ds_dpoint_weight) == n_points batch_size = length(batch_axis) ds_dbackground = vec( sum!(reshape(ds_dbackground, ntuple(_ -> 1, Val(N_out))..., batch_size), ds_dout) ) scale = SVector{N_out,T}(size(ds_dout)[1:(end - 1)]) / T(2) shifts = DiffPointRasterisation.voxel_shifts(Val(N_out)) ds_dpoints = fill!(ds_dpoints, zero(TP)) ds_drotation = fill!(ds_drotation, zero(TR)) ds_dtranslation = fill!(ds_dtranslation, zero(TT)) ds_dout_weight = fill!(ds_dout_weight, zero(OW)) ds_dpoint_weight = fill!(ds_dpoint_weight, zero(PW)) args = ( T, ds_dout, points, rotation, translation, out_weight, point_weight, shifts, scale, ds_dpoints, ds_drotation, ds_dtranslation, ds_dout_weight, ds_dpoint_weight, ) ndrange = (n_points, batch_size, 2^N_out) workgroup_size(threads) = (1, min(threads ÷ (2^N_out), batch_size), 2^N_out) function shmem(threads) _, bs_p_wg, n_voxel = workgroup_size(threads) return ((N_out + 1) * n_voxel + N_in) * bs_p_wg * sizeof(T) # ((N_out + 1) * threads + N_in * bs_p_wg) * sizeof(T) end let kernel = @cuda launch = false raster_pullback_kernel!(args...) config = CUDA.launch_configuration(kernel.fun; shmem) workgroup_sz = workgroup_size(config.threads) blocks = cld.(ndrange, workgroup_sz) kernel(args...; threads=workgroup_sz, blocks=blocks, shmem=shmem(config.threads)) end return (; points=ds_dpoints, rotation=ds_drotation, translation=ds_dtranslation, background=ds_dbackground, out_weight=ds_dout_weight, point_weight=ds_dpoint_weight, ) end function DiffPointRasterisation.default_ds_dpoints_batched( points::CuVector{<:AbstractVector{TP}}, N_in, batch_size ) where {TP<:Number} return similar(points, TP, (N_in, length(points))) end function DiffPointRasterisation.default_ds_dpoint_weight_batched( points::CuVector{<:AbstractVector{<:Number}}, T, batch_size ) return similar(points, T) end end # module
DiffPointRasterisation
https://github.com/microscopic-image-analysis/DiffPointRasterisation.jl.git
[ "MIT" ]
0.2.2
2fdf8dec8ac5fbf4a19487210c6d3bb8dff95459
code
3040
module DiffPointRasterisationChainRulesCoreExt using DiffPointRasterisation, ChainRulesCore, StaticArrays # single image function ChainRulesCore.rrule( ::typeof(DiffPointRasterisation.raster), grid_size, points::AbstractVector{<:StaticVector{N_in,T}}, rotation::AbstractMatrix{<:Number}, translation::AbstractVector{<:Number}, optional_args..., ) where {N_in,T<:Number} out = raster(grid_size, points, rotation, translation, optional_args...) function raster_pullback(ds_dout) out_pb = raster_pullback!( unthunk(ds_dout), points, rotation, translation, optional_args... ) ds_dpoints = reinterpret(reshape, SVector{N_in,T}, out_pb.points) return NoTangent(), NoTangent(), ds_dpoints, values(out_pb)[2:(3 + length(optional_args))]... end return out, raster_pullback end function ChainRulesCore.rrule( f::typeof(DiffPointRasterisation.raster), grid_size, points::AbstractVector{<:AbstractVector{<:Number}}, rotation::AbstractMatrix{<:Number}, translation::AbstractVector{<:Number}, optional_args..., ) return ChainRulesCore.rrule( f, grid_size, DiffPointRasterisation.inner_to_sized(points), rotation, translation, optional_args..., ) end # batch of images function ChainRulesCore.rrule( ::typeof(DiffPointRasterisation.raster), grid_size, points::AbstractVector{<:StaticVector{N_in,TP}}, rotation::AbstractVector{<:StaticMatrix{N_out,N_in,TR}}, translation::AbstractVector{<:StaticVector{N_out,TT}}, optional_args..., ) where {N_in,N_out,TP<:Number,TR<:Number,TT<:Number} out = raster(grid_size, points, rotation, translation, optional_args...) function raster_pullback(ds_dout) out_pb = raster_pullback!( unthunk(ds_dout), points, rotation, translation, optional_args... ) ds_dpoints = reinterpret(reshape, SVector{N_in,TP}, out_pb.points) L = N_out * N_in ds_drotation = reinterpret( reshape, SMatrix{N_out,N_in,TR,L}, reshape(out_pb.rotation, L, :) ) ds_dtranslation = reinterpret(reshape, SVector{N_out,TT}, out_pb.translation) return NoTangent(), NoTangent(), ds_dpoints, ds_drotation, ds_dtranslation, values(out_pb)[4:(3 + length(optional_args))]... end return out, raster_pullback end function ChainRulesCore.rrule( f::typeof(DiffPointRasterisation.raster), grid_size, points::AbstractVector{<:AbstractVector{<:Number}}, rotation::AbstractVector{<:AbstractMatrix{<:Number}}, translation::AbstractVector{<:AbstractVector{<:Number}}, optional_args..., ) return ChainRulesCore.rrule( f, grid_size, DiffPointRasterisation.inner_to_sized(points), DiffPointRasterisation.inner_to_sized(rotation), DiffPointRasterisation.inner_to_sized(translation), optional_args..., ) end end # module DiffPointRasterisationChainRulesCoreExt
DiffPointRasterisation
https://github.com/microscopic-image-analysis/DiffPointRasterisation.jl.git
[ "MIT" ]
0.2.2
2fdf8dec8ac5fbf4a19487210c6d3bb8dff95459
code
318
module DiffPointRasterisation using ArgCheck using Atomix using ChunkSplitters using FillArrays using KernelAbstractions using SimpleUnPack using StaticArrays using TestItems include("util.jl") include("raster.jl") include("raster_pullback.jl") include("interface.jl") export raster, raster!, raster_pullback! end
DiffPointRasterisation
https://github.com/microscopic-image-analysis/DiffPointRasterisation.jl.git
[ "MIT" ]
0.2.2
2fdf8dec8ac5fbf4a19487210c6d3bb8dff95459
code
20059
""" raster(grid_size, points, rotation, translation, [background, out_weight]) Interpolate points (multi-) linearly into an Nd-array of size `grid_size`. Before `points` are interpolated into the array, each point ``p`` is first transformed according to ```math \\hat{p} = R p + t ``` with `rotation` ``R`` and `translation` ``t``. Points ``\\hat{p}`` that fall into the N-dimensional hypercube with edges spanning from (-1, 1) in each dimension, are interpolated into the output array. The total weight of each point (`out_weight * point_weight`) is distributed onto the 2^N nearest pixels/voxels of the output array (according to the closeness of the voxel center to the coordinates of point ``\\hat{p}``) via N-linear interpolation. # Arguments - `grid_size`: Tuple of integers defining the output dimensions - `points::AbstractVector{<:AbstractVector}`: A vector of same length vectors representing points - `rotation`: Either a single matrix(-like object) or a vector of such, that linearly transform(s) `points` before rasterisation. - `translation`: Either a single vector or a vector of such, that translates `points` *after* `rotation`. If `rotation` includes a projection, `translation` thus needs to have the same length as `rotation * points[i]`. - `background`: Either a single number or a vector of such. - `out_weight`: Either a single number or a vector (one per image) of such. - `point_weight`: A vector of numbers (one per point). `rotation`, `translation`, `background` and `out_weight` can have an additional "batch" dimension (by providing them as vectors of single parameters. The length of these vectors must be the same for all four arguments). In this case, the output array will have dimensionality +1 with an additional axis on last position corresponding to the number of elements in the batch. See [Raster a single point cloud to a batch of poses](@ref) for more details. See also: [`raster!`](@ref) """ function raster end """ raster!(out, points, rotation, translation, [background, out_weight, point_weight]) Interpolate points (multi-) linearly into the Nd-array `out`. In-place version of [`raster`](@ref). See there for details. """ function raster! end ############################################### # Step 1: Allocate output ############################################### function raster(grid_size::Tuple, args...) eltypes = deep_eltype.(args) T = promote_type(eltypes...) points = args[1] rotation = args[2] if isa(rotation, AbstractMatrix) # non-batched out = similar(points, T, grid_size) else # batched @assert rotation isa AbstractVector{<:AbstractMatrix} batch_size = length(rotation) out = similar(points, T, (grid_size..., batch_size)) end return raster!(out, args...) end deep_eltype(el) = deep_eltype(typeof(el)) deep_eltype(t::Type) = t deep_eltype(t::Type{<:AbstractArray}) = deep_eltype(eltype(t)) ############################################### # Step 2: Fill default arguments if necessary ############################################### @inline raster!(out::AbstractArray{<:Number}, args::Vararg{Any,3}) = raster!(out, args..., default_background(args[2])) @inline raster!(out::AbstractArray{<:Number}, args::Vararg{Any,4}) = raster!(out, args..., default_out_weight(args[2])) @inline raster!(out::AbstractArray{<:Number}, args::Vararg{Any,5}) = raster!(out, args..., default_point_weight(args[1])) ############################################### # Step 3: Convenience interface for single image: # Convert arguments for single image to # length-1 vec of arguments ############################################### function raster!( out::AbstractArray{<:Number}, points::AbstractVector{<:AbstractVector{<:Number}}, rotation::AbstractMatrix{<:Number}, translation::AbstractVector{<:Number}, background::Number, weight::Number, point_weight::AbstractVector{<:Number}, ) return drop_last_dim( raster!( append_singleton_dim(out), points, @SVector([rotation]), @SVector([translation]), @SVector([background]), @SVector([weight]), point_weight, ), ) end ############################################### # Step 4: Convert arguments to canonical form, # i.e. vectors of statically sized arrays ############################################### function raster!(out::AbstractArray{<:Number}, args::Vararg{AbstractVector,6}) return raster!(out, inner_to_sized.(args)...) end ############################################### # Step 5: Error on inconsistent dimensions ############################################### # if N_out_rot == N_out_trans this should not be called # because the actual implementation specializes on N_out function raster!( ::AbstractArray{<:Number,N_out}, ::AbstractVector{<:StaticVector{N_in,<:Number}}, ::AbstractVector{<:StaticMatrix{N_out_rot,N_in_rot,<:Number}}, ::AbstractVector{<:StaticVector{N_out_trans,<:Number}}, ::AbstractVector{<:Number}, ::AbstractVector{<:Number}, ::AbstractVector{<:Number}, ) where {N_in,N_out,N_in_rot,N_out_rot,N_out_trans} if N_out_trans != N_out error( "Dimension of translation (got $N_out_trans) and output dimentsion (got $N_out) must agree!", ) end if N_out_rot != N_out error( "Row dimension of rotation (got $N_out_rot) and output dimentsion (got $N_out) must agree!", ) end if N_in_rot != N_in error( "Column dimension of rotation (got $N_in_rot) and points (got $N_in) must agree!", ) end return error("Dispatch error. Should not arrive here. Please file a bug.") end # now similar for pullback """ raster_pullback!( ds_dout, args...; [points, rotation, translation, background, out_weight, point_weight] ) Pullback for [`raster`](@ref) / [`raster!`](@ref). Take as input `ds_dout` the sensitivity of some quantity (`s` for "scalar") to the *output* `out` of the function `out = raster(grid_size, args...)` (or `out = raster!(out, args...)`), as well as the exact same arguments `args` that were passed to `raster`/`raster!`, and return the sensitivities of `s` to the *inputs* `args` of the function `raster`/`raster!`. Optionally, pre-allocated output arrays for each input sensitivity can be specified as keyword arguments with the name of the original argument to `raster` as key, and a nd-array as value, where the n-th dimension is the batch dimension. For example to provide a pre-allocated array for the sensitivity of `s` to the `translation` argument of `raster`, do: `sensitivities = raster_pullback!(ds_dout, args...; translation = [zeros(2) for _ in 1:8])` for 2-dimensional points and a batch size of 8. See also [Raster a single point cloud to a batch of poses](@ref) """ function raster_pullback! end ############################################### # Step 1: Fill default arguments if necessary ############################################### @inline raster_pullback!(ds_out::AbstractArray{<:Number}, args::Vararg{Any,3}; kwargs...) = raster_pullback!(ds_out, args..., default_background(args[2]); kwargs...) @inline raster_pullback!(ds_dout::AbstractArray{<:Number}, args::Vararg{Any,4}; kwargs...) = raster_pullback!(ds_dout, args..., default_out_weight(args[2]); kwargs...) @inline raster_pullback!(ds_dout::AbstractArray{<:Number}, args::Vararg{Any,5}; kwargs...) = raster_pullback!(ds_dout, args..., default_point_weight(args[1]); kwargs...) ############################################### # Step 2: Convert arguments to canonical form, # i.e. vectors of statically sized arrays ############################################### # single image function raster_pullback!( ds_dout::AbstractArray{<:Number}, points::AbstractVector{<:AbstractVector{<:Number}}, rotation::AbstractMatrix{<:Number}, translation::AbstractVector{<:Number}, background::Number, out_weight::Number, point_weight::AbstractVector{<:Number}; kwargs..., ) return raster_pullback!( ds_dout, inner_to_sized(points), to_sized(rotation), to_sized(translation), background, out_weight, point_weight; kwargs..., ) end # batch of images function raster_pullback!( ds_dout::AbstractArray{<:Number}, args::Vararg{AbstractVector,6}; kwargs... ) return raster_pullback!(ds_dout, inner_to_sized.(args)...; kwargs...) end ############################################### # Step 3: Allocate output ############################################### # single image function raster_pullback!( ds_dout::AbstractArray{<:Number,N_out}, inp_points::AbstractVector{<:StaticVector{N_in,TP}}, inp_rotation::StaticMatrix{N_out,N_in,<:Number}, inp_translation::StaticVector{N_out,<:Number}, inp_background::Number, inp_out_weight::Number, inp_point_weight::AbstractVector{PW}; points::AbstractMatrix{TP}=default_ds_dpoints_single(inp_points, N_in), point_weight::AbstractVector{PW}=similar(inp_points, PW), kwargs..., ) where {N_in,N_out,TP<:Number,PW<:Number} return raster_pullback!( ds_dout, inp_points, inp_rotation, inp_translation, inp_background, inp_out_weight, inp_point_weight, points, point_weight; kwargs..., ) end # batch of images function raster_pullback!( ds_dout::AbstractArray{<:Number}, inp_points::AbstractVector{<:StaticVector{N_in,TP}}, inp_rotation::AbstractVector{<:StaticMatrix{N_out,N_in,TR}}, inp_translation::AbstractVector{<:StaticVector{N_out,TT}}, inp_background::AbstractVector{TB}, inp_out_weight::AbstractVector{OW}, inp_point_weight::AbstractVector{PW}; points::AbstractArray{TP}=default_ds_dpoints_batched( inp_points, N_in, length(inp_rotation) ), rotation::AbstractArray{TR,3}=similar( inp_points, TR, (N_out, N_in, length(inp_rotation)) ), translation::AbstractMatrix{TT}=similar( inp_points, TT, (N_out, length(inp_translation)) ), background::AbstractVector{TB}=similar(inp_points, TB, (length(inp_background))), out_weight::AbstractVector{OW}=similar(inp_points, OW, (length(inp_out_weight))), point_weight::AbstractArray{PW}=default_ds_dpoint_weight_batched( inp_points, PW, length(inp_rotation) ), ) where {N_in,N_out,TP<:Number,TR<:Number,TT<:Number,TB<:Number,OW<:Number,PW<:Number} return raster_pullback!( ds_dout, inp_points, inp_rotation, inp_translation, inp_background, inp_out_weight, inp_point_weight, points, rotation, translation, background, out_weight, point_weight, ) end ############################################### # Step 4: Error on inconsistent dimensions ############################################### # single image function raster_pullback!( ::AbstractArray{<:Number,N_out}, ::AbstractVector{<:StaticVector{N_in,<:Number}}, ::StaticMatrix{N_out_rot,N_in_rot,<:Number}, ::StaticVector{N_out_trans,<:Number}, ::Number, ::Number, ::AbstractVector{<:Number}, ::AbstractMatrix{<:Number}, ::AbstractVector{<:Number}; kwargs..., ) where {N_in,N_out,N_in_rot,N_out_rot,N_out_trans} return error_dimensions(N_in, N_out, N_in_rot, N_out_rot, N_out_trans) end # batch of images function raster_pullback!( ::AbstractArray{<:Number,N_out_p1}, ::AbstractVector{<:StaticVector{N_in,<:Number}}, ::AbstractVector{<:StaticMatrix{N_out_rot,N_in_rot,<:Number}}, ::AbstractVector{<:StaticVector{N_out_trans,<:Number}}, ::AbstractVector{<:Number}, ::AbstractVector{<:Number}, ::AbstractVector{<:Number}, ::AbstractArray{<:Number}, ::AbstractArray{<:Number,3}, ::AbstractMatrix{<:Number}, ::AbstractVector{<:Number}, ::AbstractVector{<:Number}, ::AbstractArray{<:Number}, ) where {N_in,N_out_p1,N_in_rot,N_out_rot,N_out_trans} return error_dimensions(N_in, N_out_p1 - 1, N_in_rot, N_out_rot, N_out_trans) end function error_dimensions(N_in, N_out, N_in_rot, N_out_rot, N_out_trans) if N_out_trans != N_out error( "Dimension of translation (got $N_out_trans) and output dimentsion (got $N_out) must agree!", ) end if N_out_rot != N_out error( "Row dimension of rotation (got $N_out_rot) and output dimentsion (got $N_out) must agree!", ) end if N_in_rot != N_in error( "Column dimension of rotation (got $N_in_rot) and points (got $N_in) must agree!", ) end return error("Dispatch error. Should not arrive here. Please file a bug.") end default_background(rotation::AbstractMatrix, T=eltype(rotation)) = zero(T) function default_background( rotation::AbstractVector{<:AbstractMatrix}, T=eltype(eltype(rotation)) ) return Zeros(T, length(rotation)) end function default_background(rotation::AbstractArray{_T,3} where {_T}, T=eltype(rotation)) return Zeros(T, size(rotation, 3)) end default_out_weight(rotation::AbstractMatrix, T=eltype(rotation)) = one(T) function default_out_weight( rotation::AbstractVector{<:AbstractMatrix}, T=eltype(eltype(rotation)) ) return Ones(T, length(rotation)) end function default_out_weight(rotation::AbstractArray{_T,3} where {_T}, T=eltype(rotation)) return Ones(T, size(rotation, 3)) end function default_point_weight(points::AbstractVector{<:AbstractVector{T}}) where {T<:Number} return Ones(T, length(points)) end function default_ds_dpoints_single( points::AbstractVector{<:AbstractVector{TP}}, N_in ) where {TP<:Number} return similar(points, TP, (N_in, length(points))) end function default_ds_dpoints_batched( points::AbstractVector{<:AbstractVector{TP}}, N_in, batch_size ) where {TP<:Number} return similar(points, TP, (N_in, length(points), min(batch_size, Threads.nthreads()))) end function default_ds_dpoint_weight_batched( points::AbstractVector{<:AbstractVector{<:Number}}, T, batch_size ) return similar(points, T, (length(points), min(batch_size, Threads.nthreads()))) end @testitem "raster interface" begin include("../test/data.jl") @testset "no projection" begin local out @testset "canonical arguments (vec of staticarray)" begin out = raster( D.grid_size_3d, D.points_static, D.rotations_static, D.translations_3d_static, D.backgrounds, D.weights, D.point_weights, ) end @testset "reinterpret nd-array as vec-of-array" begin @test out ≈ raster( D.grid_size_3d, D.points_reinterp, D.rotations_reinterp, D.translations_3d_reinterp, D.backgrounds, D.weights, D.point_weights, ) end @testset "point as non-static vector" begin @test out ≈ raster( D.grid_size_3d, D.points, D.rotations_static, D.translations_3d_static, D.backgrounds, D.weights, D.point_weights, ) end @testset "rotation as non-static matrix" begin @test out ≈ raster( D.grid_size_3d, D.points_static, D.rotations, D.translations_3d_static, D.backgrounds, D.weights, D.point_weights, ) end @testset "translation as non-static vector" begin @test out ≈ raster( D.grid_size_3d, D.points_static, D.rotations_static, D.translations_3d, D.backgrounds, D.weights, D.point_weights, ) end @testset "all as non-static array" begin @test out ≈ raster( D.grid_size_3d, D.points, D.rotations, D.translations_3d, D.backgrounds, D.weights, D.point_weights, ) end out = raster( D.grid_size_3d, D.points_static, D.rotations_static, D.translations_3d_static, zeros(D.batch_size), ones(D.batch_size), ones(length(D.points_static)), ) @testset "default argmuments canonical" begin @test out ≈ raster( D.grid_size_3d, D.points_static, D.rotations_static, D.translations_3d_static, ) end @testset "default arguments all as non-static array" begin @test out ≈ raster(D.grid_size_3d, D.points, D.rotations, D.translations_3d) end end @testset "projection" begin local out @testset "canonical arguments (vec of staticarray)" begin out = raster( D.grid_size_2d, D.points_static, D.projections_static, D.translations_2d_static, D.backgrounds, D.weights, D.point_weights, ) end @testset "reinterpret nd-array as vec-of-array" begin @test out ≈ raster( D.grid_size_2d, D.points_reinterp, D.projections_reinterp, D.translations_2d_reinterp, D.backgrounds, D.weights, D.point_weights, ) end @testset "point as non-static vector" begin @test out ≈ raster( D.grid_size_2d, D.points, D.projections_static, D.translations_2d_static, D.backgrounds, D.weights, D.point_weights, ) end @testset "projection as non-static matrix" begin @test out ≈ raster( D.grid_size_2d, D.points_static, D.projections, D.translations_2d_static, D.backgrounds, D.weights, D.point_weights, ) end @testset "translation as non-static vector" begin @test out ≈ raster( D.grid_size_2d, D.points_static, D.projections_static, D.translations_2d, D.backgrounds, D.weights, D.point_weights, ) end @testset "all as non-static array" begin @test out ≈ raster( D.grid_size_2d, D.points_static, D.projections, D.translations_2d, D.backgrounds, D.weights, D.point_weights, ) end out = raster( D.grid_size_2d, D.points_static, D.projections_static, D.translations_2d_static, zeros(D.batch_size), ones(D.batch_size), ones(length(D.points_static)), ) @testset "default argmuments canonical" begin @test out ≈ raster( D.grid_size_2d, D.points_static, D.projections_static, D.translations_2d_static, ) end @testset "default arguments all as non-static array" begin @test out ≈ raster(D.grid_size_2d, D.points, D.projections, D.translations_2d) end end end
DiffPointRasterisation
https://github.com/microscopic-image-analysis/DiffPointRasterisation.jl.git
[ "MIT" ]
0.2.2
2fdf8dec8ac5fbf4a19487210c6d3bb8dff95459
code
12012
############################################### # Step 6: Actual implementation ############################################### function raster!( out::AbstractArray{T,N_out_p1}, points::AbstractVector{<:StaticVector{N_in,<:Number}}, rotation::AbstractVector{<:StaticMatrix{N_out,N_in,<:Number}}, translation::AbstractVector{<:StaticVector{N_out,<:Number}}, background::AbstractVector{<:Number}, out_weight::AbstractVector{<:Number}, point_weight::AbstractVector{<:Number}, ) where {T<:Number,N_in,N_out,N_out_p1} @argcheck N_out == N_out_p1 - 1 DimensionMismatch out_batch_dim = ndims(out) batch_size = size(out, out_batch_dim) @argcheck batch_size == length(rotation) == length(translation) == length(background) == length(out_weight) DimensionMismatch n_points = length(points) @argcheck length(point_weight) == n_points scale = SVector{N_out,T}(size(out)[1:(end - 1)]) / T(2) shifts = voxel_shifts(Val(N_out)) out .= reshape(background, ntuple(_ -> 1, Val(N_out))..., length(background)) args = (out, points, rotation, translation, out_weight, point_weight, shifts, scale) backend = get_backend(out) ndrange = (2^N_out, n_points, batch_size) workgroup_size = 1024 raster_kernel!(backend, workgroup_size, ndrange)(args...) return out end @kernel function raster_kernel!( out::AbstractArray{T}, points, rotations, translations::AbstractVector{<:StaticVector{N_out}}, out_weights, point_weights, shifts, scale, ) where {T,N_out} neighbor_voxel_id, point_idx, batch_idx = @index(Global, NTuple) point = @inbounds points[point_idx] rotation = @inbounds rotations[batch_idx] translation = @inbounds translations[batch_idx] weight = @inbounds out_weights[batch_idx] * point_weights[point_idx] shift = @inbounds shifts[neighbor_voxel_id] origin = (-@SVector ones(T, N_out)) - translation coord_reference_voxel, deltas = reference_coordinate_and_deltas( point, rotation, origin, scale ) voxel_idx = CartesianIndex( CartesianIndex(Tuple(coord_reference_voxel)) + CartesianIndex(shift), batch_idx ) if voxel_idx in CartesianIndices(out) val = voxel_weight(deltas, shift, weight) @inbounds Atomix.@atomic out[voxel_idx] += val end end """ reference_coordinate_and_deltas(point, rotation, origin, scale) Return - The cartesian coordinate of the voxel of an N-dimensional rectangular grid that is the one closest to the origin, out of the 2^N voxels that are next neighbours of the (N-dimensional) `point` - A Nx2 array containing coordinate-wise distances of the `scale`d `point` to the voxel that is * closest to the origin (out of the 2^N next neighbors) in the first column * furthest from the origin (out of the 2^N next neighbors) in the second column. The grid is implicitely assumed to discretize the hypercube ranging from (-1, 1) in each dimension. Before `point` is discretized into this grid, it is first translated by `-origin` and then scaled by `scale`. """ @inline function reference_coordinate_and_deltas( point::AbstractVector{T}, rotation, origin, scale ) where {T} projected_point = rotation * point # coordinate of transformed point in output coordinate system # which is defined by the (integer) coordinates of the pixels/voxels # in the output array. coord = (projected_point - origin) .* scale # round to **lower** integer (note the -1/2) coordinate ("upper left" if this were a matrix) coord_reference_voxel = round.(Int, coord .- T(0.5), RoundUp) # distance to lower integer coordinate (distance from "lower left" neighboring pixel # in units of fractional pixels): deltas_lower = coord - (coord_reference_voxel .- T(0.5)) # distances to lower (first column) and upper (second column) integer coordinates deltas = [deltas_lower one(T) .- deltas_lower] return coord_reference_voxel, deltas end @inline function voxel_weight(deltas, shift::NTuple{N,Int}, point_weight) where {N} lower_upper = mod1.(shift, 2) delta_idxs = SVector{N}(CartesianIndex.(ntuple(identity, Val(N)), lower_upper)) val = prod(@inbounds @view deltas[delta_idxs]) * point_weight return val end @testitem "raster correctness" begin using Rotations grid_size = (5, 5) points_single_center = [zeros(2)] points_single_1pix_right = [[0.0, 0.4]] points_single_1pix_up = [[-0.4, 0.0]] points_single_1pix_left = [[0.0, -0.4]] points_single_1pix_down = [[0.4, 0.0]] points_single_halfpix_down = [[0.2, 0.0]] points_single_halfpix_down_and_right = [[0.2, 0.2]] points_four_cross = reduce( vcat, [ points_single_1pix_right, points_single_1pix_up, points_single_1pix_left, points_single_1pix_down, ], ) no_rotation = Float64[1; 0;; 0; 1] rotation_90_deg = Float64[0; 1;; -1; 0] no_translation = zeros(2) translation_halfpix_right = [0.0, 0.2] translation_1pix_down = [0.4, 0.0] zero_background = 0.0 out_weight = 4.0 # -------- interpolations --------- out = raster( grid_size, points_single_center, no_rotation, no_translation, zero_background, out_weight, ) @test out ≈ [ 0 0 0 0 0 0 0 0 0 0 0 0 4 0 0 0 0 0 0 0 0 0 0 0 0 ] out = raster( grid_size, points_single_1pix_right, no_rotation, no_translation, zero_background, out_weight, ) @test out ≈ [ 0 0 0 0 0 0 0 0 0 0 0 0 0 4 0 0 0 0 0 0 0 0 0 0 0 ] out = raster( grid_size, points_single_halfpix_down, no_rotation, no_translation, zero_background, out_weight, ) @test out ≈ [ 0 0 0 0 0 0 0 0 0 0 0 0 2 0 0 0 0 2 0 0 0 0 0 0 0 ] out = raster( grid_size, points_single_halfpix_down_and_right, no_rotation, no_translation, zero_background, out_weight, ) @test out ≈ [ 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 1 1 0 0 0 0 0 0 ] # -------- translations --------- out = raster( grid_size, points_four_cross, no_rotation, no_translation, zero_background, out_weight, ) @test out ≈ [ 0 0 0 0 0 0 0 4 0 0 0 4 0 4 0 0 0 4 0 0 0 0 0 0 0 ] out = raster( grid_size, points_four_cross, no_rotation, translation_halfpix_right, zero_background, out_weight, ) @test out ≈ [ 0 0 0 0 0 0 0 2 2 0 0 2 2 2 2 0 0 2 2 0 0 0 0 0 0 ] out = raster( grid_size, points_four_cross, no_rotation, translation_1pix_down, zero_background, out_weight, ) @test out ≈ [ 0 0 0 0 0 0 0 0 0 0 0 0 4 0 0 0 4 0 4 0 0 0 4 0 0 ] # -------- rotations --------- out = raster( grid_size, points_single_1pix_right, rotation_90_deg, no_translation, zero_background, out_weight, ) @test out ≈ [ 0 0 0 0 0 0 0 4 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ] # -------- point weights --------- out = raster( grid_size, points_four_cross, no_rotation, no_translation, zero_background, 1.0, [1.0, 2.0, 3.0, 4.0], ) @test out ≈ [ 0 0 0 0 0 0 0 2 0 0 0 3 0 1 0 0 0 4 0 0 0 0 0 0 0 ] out = raster( grid_size, points_four_cross, no_rotation, translation_halfpix_right, zero_background, 2.0, [1.0, 2.0, 3.0, 4.0], ) @test out ≈ [ 0 0 0 0 0 0 0 2 2 0 0 3 3 1 1 0 0 4 4 0 0 0 0 0 0 ] end @testitem "raster inference and allocations" begin using BenchmarkTools, CUDA, StaticArrays include("../test/data.jl") # check type stability # single image @inferred DiffPointRasterisation.raster( D.grid_size_3d, D.points_static, D.rotation, D.translation_3d ) @inferred DiffPointRasterisation.raster( D.grid_size_2d, D.points_static, D.projection, D.translation_2d ) # batched canonical @inferred DiffPointRasterisation.raster( D.grid_size_3d, D.points_static, D.rotations_static, D.translations_3d_static ) @inferred DiffPointRasterisation.raster( D.grid_size_2d, D.points_static, D.projections_static, D.translations_2d_static ) # batched reinterpret reshape @inferred DiffPointRasterisation.raster( D.grid_size_3d, D.points_reinterp, D.rotations_reinterp, D.translations_3d_reinterp ) @inferred DiffPointRasterisation.raster( D.grid_size_2d, D.points_reinterp, D.projections_reinterp, D.translations_2d_reinterp, ) if CUDA.functional() # single image @inferred DiffPointRasterisation.raster( D.grid_size_3d, cu(D.points_static), cu(D.rotation), cu(D.translation_3d) ) @inferred DiffPointRasterisation.raster( D.grid_size_2d, cu(D.points_static), cu(D.projection), cu(D.translation_2d) ) # batched @inferred DiffPointRasterisation.raster( D.grid_size_3d, cu(D.points_static), cu(D.rotations_static), cu(D.translations_3d_static), ) @inferred DiffPointRasterisation.raster( D.grid_size_2d, cu(D.points_static), cu(D.projections_static), cu(D.translations_2d_static), ) end # Ideally the sinlge image (non batched) case would be allocation-free. # The switch to KernelAbstractions made this allocating. # set test to broken for now. out_3d = Array{Float64,3}(undef, D.grid_size_3d...) out_2d = Array{Float64,2}(undef, D.grid_size_2d...) allocations = @ballocated DiffPointRasterisation.raster!( $out_3d, $D.points_static, $D.rotation, $D.translation_3d ) evals = 1 samples = 1 @test allocations == 0 broken = true allocations = @ballocated DiffPointRasterisation.raster!( $out_2d, $D.points_static, $D.projection, $D.translation_2d ) evals = 1 samples = 1 @test allocations == 0 broken = true end @testitem "raster batched consistency" begin include("../test/data.jl") # raster out_3d = zeros(D.grid_size_3d..., D.batch_size) out_3d_batched = zeros(D.grid_size_3d..., D.batch_size) for (out_i, args...) in zip( eachslice(out_3d; dims=4), D.rotations, D.translations_3d, D.backgrounds, D.weights ) raster!(out_i, D.more_points, args..., D.more_point_weights) end DiffPointRasterisation.raster!( out_3d_batched, D.more_points, D.rotations, D.translations_3d, D.backgrounds, D.weights, D.more_point_weights, ) # raster_project out_2d = zeros(D.grid_size_2d..., D.batch_size) out_2d_batched = zeros(D.grid_size_2d..., D.batch_size) for (out_i, args...) in zip( eachslice(out_2d; dims=3), D.projections, D.translations_2d, D.backgrounds, D.weights, ) DiffPointRasterisation.raster!(out_i, D.more_points, args..., D.more_point_weights) end DiffPointRasterisation.raster!( out_2d_batched, D.more_points, D.projections, D.translations_2d, D.backgrounds, D.weights, D.more_point_weights, ) @test out_2d_batched ≈ out_2d end
DiffPointRasterisation
https://github.com/microscopic-image-analysis/DiffPointRasterisation.jl.git
[ "MIT" ]
0.2.2
2fdf8dec8ac5fbf4a19487210c6d3bb8dff95459
code
11615
# single image function raster_pullback!( ds_dout::AbstractArray{<:Number,N_out}, points::AbstractVector{<:StaticVector{N_in,<:Number}}, rotation::StaticMatrix{N_out,N_in,TR}, translation::StaticVector{N_out,TT}, background::Number, out_weight::OW, point_weight::AbstractVector{<:Number}, ds_dpoints::AbstractMatrix{TP}, ds_dpoint_weight::AbstractVector{PW}; accumulate_ds_dpoints=false, ) where {N_in,N_out,TP<:Number,TR<:Number,TT<:Number,OW<:Number,PW<:Number} T = promote_type(eltype(ds_dout), TP, TR, TT, OW, PW) @argcheck size(ds_dpoints, 1) == N_in @argcheck length(point_weight) == length(points) == length(ds_dpoint_weight) == size(ds_dpoints, 2) # The strategy followed here is to redo some of the calculations # made in the forward pass instead of caching them in the forward # pass and reusing them here. if !accumulate_ds_dpoints fill!(ds_dpoints, zero(TP)) fill!(ds_dpoint_weight, zero(PW)) end origin = (-@SVector ones(TT, N_out)) - translation scale = SVector{N_out,T}(size(ds_dout)) / 2 shifts = voxel_shifts(Val(N_out)) all_density_idxs = CartesianIndices(ds_dout) # initialize some output for accumulation ds_dtranslation = @SVector zeros(TT, N_out) ds_drotation = @SMatrix zeros(TR, N_out, N_in) ds_dout_weight = zero(OW) # loop over points for (pt_idx, point) in enumerate(points) point = SVector{N_in,TP}(point) point_weight_i = point_weight[pt_idx] coord_reference_voxel, deltas = reference_coordinate_and_deltas( point, rotation, origin, scale ) ds_dcoord = @SVector zeros(T, N_out) ds_dpoint_weight_i = zero(PW) # loop over voxels that are affected by point for shift in shifts voxel_idx = CartesianIndex(Tuple(coord_reference_voxel)) + CartesianIndex(shift) (voxel_idx in all_density_idxs) || continue ds_dout_i = ds_dout[voxel_idx] ds_dweight = voxel_weight(deltas, shift, ds_dout_i) ds_dout_weight += ds_dweight * point_weight_i ds_dpoint_weight_i += ds_dweight * out_weight factor = ds_dout_i * out_weight * point_weight_i # loop over dimensions of point ds_dcoord += SVector( factor .* ntuple(n -> interpolation_weight(n, N_out, deltas, shift), Val(N_out)), ) end scaled = ds_dcoord .* scale ds_dtranslation += scaled ds_drotation += scaled * point' ds_dpoint = rotation' * scaled @view(ds_dpoints[:, pt_idx]) .+= ds_dpoint ds_dpoint_weight[pt_idx] += ds_dpoint_weight_i end return (; points=ds_dpoints, rotation=ds_drotation, translation=ds_dtranslation, background=sum(ds_dout), out_weight=ds_dout_weight, point_weight=ds_dpoint_weight, ) end # batch of images function raster_pullback!( ds_dout::AbstractArray{<:Number,N_out_p1}, points::AbstractVector{<:StaticVector{N_in,<:Number}}, rotation::AbstractVector{<:StaticMatrix{N_out,N_in,<:Number}}, translation::AbstractVector{<:StaticVector{N_out,<:Number}}, background::AbstractVector{<:Number}, out_weight::AbstractVector{<:Number}, point_weight::AbstractVector{<:Number}, ds_dpoints::AbstractArray{<:Number,3}, ds_drotation::AbstractArray{<:Number,3}, ds_dtranslation::AbstractMatrix{<:Number}, ds_dbackground::AbstractVector{<:Number}, ds_dout_weight::AbstractVector{<:Number}, ds_dpoint_weight::AbstractMatrix{<:Number}, ) where {N_in,N_out,N_out_p1} batch_axis = axes(ds_dout, N_out_p1) @argcheck N_out == N_out_p1 - 1 @argcheck batch_axis == axes(rotation, 1) == axes(translation, 1) == axes(background, 1) == axes(out_weight, 1) @argcheck batch_axis == axes(ds_drotation, 3) == axes(ds_dtranslation, 2) == axes(ds_dbackground, 1) == axes(ds_dout_weight, 1) fill!(ds_dpoints, zero(eltype(ds_dpoints))) fill!(ds_dpoint_weight, zero(eltype(ds_dpoint_weight))) n_threads = size(ds_dpoints, 3) Threads.@threads for (idxs, ichunk) in chunks(batch_axis, n_threads) for i in idxs args_i = ( selectdim(ds_dout, N_out_p1, i), points, rotation[i], translation[i], background[i], out_weight[i], point_weight, ) result_i = raster_pullback!( args_i..., view(ds_dpoints, :, :, ichunk), view(ds_dpoint_weight, :, ichunk); accumulate_ds_dpoints=true, ) ds_drotation[:, :, i] .= result_i.rotation ds_dtranslation[:, i] = result_i.translation ds_dbackground[i] = result_i.background ds_dout_weight[i] = result_i.out_weight end end return (; points=dropdims(sum(ds_dpoints; dims=3); dims=3), rotation=ds_drotation, translation=ds_dtranslation, background=ds_dbackground, out_weight=ds_dout_weight, point_weight=dropdims(sum(ds_dpoint_weight; dims=2); dims=2), ) end function interpolation_weight(n, N, deltas, shift) val = @inbounds shift[n] == 1 ? one(eltype(deltas)) : -one(eltype(deltas)) # loop over other dimensions @inbounds for other_n in 1:N if n == other_n continue end val *= deltas[other_n, mod1(shift[other_n], 2)] end return val end @testitem "raster_pullback! inference and allocations" begin using BenchmarkTools, CUDA, Adapt include("../test/data.jl") ds_dout_3d = randn(D.grid_size_3d) ds_dout_3d_batched = randn(D.grid_size_3d..., D.batch_size) ds_dout_2d = randn(D.grid_size_2d) ds_dout_2d_batched = randn(D.grid_size_2d..., D.batch_size) ds_dpoints = similar(D.points_array) ds_dpoints_batched = similar( D.points_array, (size(D.points_array)..., Threads.nthreads()) ) ds_drotations = similar(D.rotations_array) ds_dprojections = similar(D.projections_array) ds_dtranslations_3d = similar(D.translations_3d_array) ds_dtranslations_2d = similar(D.translations_2d_array) ds_dbackgrounds = similar(D.backgrounds) ds_dweights = similar(D.weights) ds_dpoint_weights = similar(D.point_weights) ds_dpoint_weights_batched = similar( D.point_weights, (size(D.point_weights)..., Threads.nthreads()) ) args_batched_3d = ( ds_dout_3d_batched, D.points_static, D.rotations_static, D.translations_3d_static, D.backgrounds, D.weights, D.point_weights, ds_dpoints_batched, ds_drotations, ds_dtranslations_3d, ds_dbackgrounds, ds_dweights, ds_dpoint_weights_batched, ) args_batched_2d = ( ds_dout_2d_batched, D.points_static, D.projections_static, D.translations_2d_static, D.backgrounds, D.weights, D.point_weights, ds_dpoints_batched, ds_dprojections, ds_dtranslations_2d, ds_dbackgrounds, ds_dweights, ds_dpoint_weights_batched, ) function to_cuda(args) args_cu = adapt(CuArray, args) args_cu = Base.setindex(args_cu, args_cu[8][:, :, 1], 8) # ds_dpoint without batch dim return args_cu = Base.setindex(args_cu, args_cu[13][:, 1], 13) # ds_dpoint_weight without batch dim end # check type stability # single image @inferred DiffPointRasterisation.raster_pullback!( ds_dout_3d, D.points_static, D.rotation, D.translation_3d, D.background, D.weight, D.point_weights, ds_dpoints, ds_dpoint_weights, ) @inferred DiffPointRasterisation.raster_pullback!( ds_dout_2d, D.points_static, D.projection, D.translation_2d, D.background, D.weight, D.point_weights, ds_dpoints, ds_dpoint_weights, ) # batched @inferred DiffPointRasterisation.raster_pullback!(args_batched_3d...) @inferred DiffPointRasterisation.raster_pullback!(args_batched_2d...) if CUDA.functional() cu_args_3d = to_cuda(args_batched_3d) @inferred DiffPointRasterisation.raster_pullback!(cu_args_3d...) cu_args_2d = to_cuda(args_batched_2d) @inferred DiffPointRasterisation.raster_pullback!(cu_args_2d...) end # check that single-imge pullback is allocation-free allocations = @ballocated DiffPointRasterisation.raster_pullback!( $ds_dout_3d, $(D.points_static), $(D.rotation), $(D.translation_3d), $(D.background), $(D.weight), $(D.point_weights), $ds_dpoints, $ds_dpoint_weights, ) evals = 1 samples = 1 @test allocations == 0 end @testitem "raster_pullback! threaded" begin include("../test/data.jl") ds_dout = randn(D.grid_size_3d..., D.batch_size) ds_dargs_threaded = DiffPointRasterisation.raster_pullback!( ds_dout, D.more_points, D.rotations, D.translations_3d, D.backgrounds, D.weights, D.more_point_weights, ) ds_dpoints = Matrix{Float64}[] ds_dpoint_weight = Vector{Float64}[] for i in 1:(D.batch_size) ds_dargs_i = @views raster_pullback!( ds_dout[:, :, :, i], D.more_points, D.rotations[i], D.translations_3d[i], D.backgrounds[i], D.weights[i], D.more_point_weights, ) push!(ds_dpoints, ds_dargs_i.points) push!(ds_dpoint_weight, ds_dargs_i.point_weight) @views begin @test ds_dargs_threaded.rotation[:, :, i] ≈ ds_dargs_i.rotation @test ds_dargs_threaded.translation[:, i] ≈ ds_dargs_i.translation @test ds_dargs_threaded.background[i] ≈ ds_dargs_i.background @test ds_dargs_threaded.out_weight[i] ≈ ds_dargs_i.out_weight end end @test ds_dargs_threaded.points ≈ sum(ds_dpoints) @test ds_dargs_threaded.point_weight ≈ sum(ds_dpoint_weight) ds_dout = zeros(D.grid_size_2d..., D.batch_size) ds_dargs_threaded = DiffPointRasterisation.raster_pullback!( ds_dout, D.more_points, D.projections, D.translations_2d, D.backgrounds, D.weights, D.more_point_weights, ) ds_dpoints = Matrix{Float64}[] ds_dpoint_weight = Vector{Float64}[] for i in 1:(D.batch_size) ds_dargs_i = @views raster_pullback!( ds_dout[:, :, i], D.more_points, D.projections[i], D.translations_2d[i], D.backgrounds[i], D.weights[i], D.more_point_weights, ) push!(ds_dpoints, ds_dargs_i.points) push!(ds_dpoint_weight, ds_dargs_i.point_weight) @views begin @test ds_dargs_threaded.rotation[:, :, i] ≈ ds_dargs_i.rotation @test ds_dargs_threaded.translation[:, i] ≈ ds_dargs_i.translation @test ds_dargs_threaded.background[i] ≈ ds_dargs_i.background @test ds_dargs_threaded.out_weight[i] ≈ ds_dargs_i.out_weight end end @test ds_dargs_threaded.points ≈ sum(ds_dpoints) @test ds_dargs_threaded.point_weight ≈ sum(ds_dpoint_weight) end
DiffPointRasterisation
https://github.com/microscopic-image-analysis/DiffPointRasterisation.jl.git
[ "MIT" ]
0.2.2
2fdf8dec8ac5fbf4a19487210c6d3bb8dff95459
code
3425
""" digitstuple(k, Val(N)) Return a N-tuple containing the bit-representation of k """ digitstuple(k, ::Val{N}, int_type=Int64) where {N} = ntuple(i -> int_type(k >> (i - 1) % 2), N) @testitem "digitstuple" begin @test DiffPointRasterisation.digitstuple(5, Val(3)) == (1, 0, 1) @test DiffPointRasterisation.digitstuple(2, Val(2)) == (0, 1) @test DiffPointRasterisation.digitstuple(2, Val(4)) == (0, 1, 0, 0) end """ voxel_shifts(Val(N), [int_type]) Enumerate nearest neighbor coordinate shifts with respect to "upper left" voxel. For a N-dimensional voxel grid, return a 2^N-tuple of N-tuples, where each element of the outer tuple is a cartesian coordinate shift from the "upper left" voxel. """ voxel_shifts(::Val{N}, int_type=Int64) where {N} = ntuple(k -> digitstuple(k - 1, Val(N), int_type), Val(2^N)) @testitem "voxel_shifts" begin @inferred DiffPointRasterisation.voxel_shifts(Val(4)) @test DiffPointRasterisation.voxel_shifts(Val(1)) == ((0,), (1,)) @test DiffPointRasterisation.voxel_shifts(Val(2)) == ((0, 0), (1, 0), (0, 1), (1, 1)) @test DiffPointRasterisation.voxel_shifts(Val(3)) == ( (0, 0, 0), (1, 0, 0), (0, 1, 0), (1, 1, 0), (0, 0, 1), (1, 0, 1), (0, 1, 1), (1, 1, 1), ) end to_sized(arg::StaticArray{<:Any,<:Number}) = arg to_sized(arg::AbstractArray{T}) where {T<:Number} = SizedArray{Tuple{size(arg)...},T}(arg) inner_to_sized(arg::AbstractVector{<:Number}) = arg inner_to_sized(arg::AbstractVector{<:StaticArray}) = arg function inner_to_sized(arg::AbstractVector{<:AbstractArray{<:Number}}) return inner_to_sized(arg, Val(size(arg[1]))) end function inner_to_sized( arg::AbstractVector{<:AbstractArray{T}}, ::Val{sz} ) where {sz,T<:Number} return SizedArray{Tuple{sz...},T}.(arg) end @testitem "inner_to_sized" begin using StaticArrays @testset "vector" begin inp = randn(3) @inferred DiffPointRasterisation.inner_to_sized(inp) out = DiffPointRasterisation.inner_to_sized(inp) @test out === inp end @testset "vec of dynamic vec" begin inp = [randn(3) for _ in 1:5] out = DiffPointRasterisation.inner_to_sized(inp) @test out == inp @test out isa Vector{<:StaticVector{3}} end @testset "vec of static vec" begin inp = [@SVector randn(3) for _ in 1:5] @inferred DiffPointRasterisation.inner_to_sized(inp) out = DiffPointRasterisation.inner_to_sized(inp) @test out === inp @test out isa Vector{<:StaticVector{3}} end @testset "vec of dynamic matrix" begin inp = [randn(3, 2) for _ in 1:5] out = DiffPointRasterisation.inner_to_sized(inp) @test out == inp @test out isa Vector{<:StaticMatrix{3,2}} end end @inline append_singleton_dim(a) = reshape(a, size(a)..., 1) @inline append_singleton_dim(a::Number) = [a] @inline drop_last_dim(a) = dropdims(a; dims=ndims(a)) @testitem "append drop dim" begin using BenchmarkTools a = randn(2, 3, 4) a2 = DiffPointRasterisation.drop_last_dim( DiffPointRasterisation.append_singleton_dim(a) ) @test a2 === a broken = true allocations = @ballocated DiffPointRasterisation.drop_last_dim( DiffPointRasterisation.append_singleton_dim($a) ) evals = 1 samples = 1 @test allocations == 0 broken = true end
DiffPointRasterisation
https://github.com/microscopic-image-analysis/DiffPointRasterisation.jl.git
[ "MIT" ]
0.2.2
2fdf8dec8ac5fbf4a19487210c6d3bb8dff95459
code
1914
@testitem "ChainRules single" begin using ChainRulesTestUtils, ChainRulesCore include("data.jl") test_rrule( raster, D.grid_size_3d, D.points_static, D.rotation ⊢ D.rotation_tangent, D.translation_3d, D.background, D.weight, D.point_weights, ) # default arguments test_rrule( raster, D.grid_size_3d, D.points_static, D.rotation ⊢ D.rotation_tangent, D.translation_3d, ) test_rrule( raster, D.grid_size_2d, D.points_static, D.projection ⊢ D.projection_tangent, D.translation_2d, D.background, D.weight, D.point_weights, ) # default arguments test_rrule( raster, D.grid_size_2d, D.points_static, D.projection ⊢ D.projection_tangent, D.translation_2d, ) end @testitem "ChainRules batch" begin using ChainRulesTestUtils include("data.jl") test_rrule( raster, D.grid_size_3d, D.points_static, D.rotations_static ⊢ D.rotation_tangents_static, D.translations_3d_static, D.backgrounds, D.weights, D.point_weights, ) # default arguments test_rrule( raster, D.grid_size_3d, D.points_static, D.rotations_static ⊢ D.rotation_tangents_static, D.translations_3d_static, ) test_rrule( raster, D.grid_size_2d, D.points_static, D.projections_static ⊢ D.projection_tangents_static, D.translations_2d_static, D.backgrounds, D.weights, D.point_weights, ) # default arguments test_rrule( raster, D.grid_size_2d, D.points_static, D.projections_static ⊢ D.projection_tangents_static, D.translations_2d_static, ) end
DiffPointRasterisation
https://github.com/microscopic-image-analysis/DiffPointRasterisation.jl.git
[ "MIT" ]
0.2.2
2fdf8dec8ac5fbf4a19487210c6d3bb8dff95459
code
2849
@testitem "CUDA forward" begin using Adapt, CUDA CUDA.allowscalar(false) include("data.jl") include("util.jl") cuda_available = CUDA.functional() # no projection args = ( D.grid_size_3d, D.more_points, D.rotations_static, D.translations_3d_static, D.backgrounds, D.weights, D.more_point_weights, ) @test cuda_cpu_agree(raster, args...) skip = !cuda_available # default arguments args = (D.grid_size_3d, D.more_points, D.rotations_static, D.translations_3d_static) @test cuda_cpu_agree(raster, args...) skip = !cuda_available # projection args = ( D.grid_size_2d, D.more_points, D.projections_static, D.translations_2d_static, D.backgrounds, D.weights, D.more_point_weights, ) @test cuda_cpu_agree(raster, args...) skip = !cuda_available end @testitem "CUDA backward" begin using Adapt, CUDA CUDA.allowscalar(false) include("data.jl") include("util.jl") cuda_available = CUDA.functional() # no projection ds_dout_3d = randn(D.grid_size_3d..., D.batch_size) args = ( ds_dout_3d, D.more_points, D.rotations_static, D.translations_3d_static, D.backgrounds, D.weights, D.more_point_weights, ) @test cuda_cpu_agree(raster_pullback!, args...) skip = !cuda_available # default arguments args = (ds_dout_3d, D.more_points, D.rotations_static, D.translations_3d_static) @test cuda_cpu_agree(raster_pullback!, args...) skip = !cuda_available # projection ds_dout_2d = randn(D.grid_size_2d..., D.batch_size) args = ( ds_dout_2d, D.more_points, D.projections_static, D.translations_2d_static, D.backgrounds, D.weights, D.more_point_weights, ) @test cuda_cpu_agree(raster_pullback!, args...) skip = !cuda_available end # The follwing currently fails. # Not sure whether test_rrule is supposed to play nicely with CUDA. # @testitem "CUDA ChainRules" begin # using Adapt, CUDA, ChainRulesTestUtils # include("data.jl") # include("util.jl") # c(a) = adapt(CuArray, a) # if CUDA.functional() # ds_dout_3d = CUDA.randn(Float64, D.grid_size_3d..., D.batch_size) # args = (D.grid_size_3d, c(D.points), c(D.rotations) ⊢ c(D.rotation_tangents), c(D.translations_3d), c(D.backgrounds), c(D.weights)) # test_rrule(raster, args...; output_tangent=ds_dout_3d) # # ds_dout_2d = CUDA.randn(Float64, D.grid_size_2d..., D.batch_size) # args = (D.grid_size_2d, c(D.points), c(D.rotations) ⊢ c(D.rotation_tangents), c(D.translations_2d), c(D.backgrounds), c(D.weights)) # test_rrule(raster, args...; output_tangent=ds_dout_2d) # end # end
DiffPointRasterisation
https://github.com/microscopic-image-analysis/DiffPointRasterisation.jl.git
[ "MIT" ]
0.2.2
2fdf8dec8ac5fbf4a19487210c6d3bb8dff95459
code
3212
module D using Rotations, StaticArrays function batch_size_for_test() local batch_size = Threads.nthreads() + 1 while (Threads.nthreads() > 1) && (batch_size % Threads.nthreads() == 0) batch_size += 1 end return batch_size end const P = @SMatrix Float64[ 1 0 0 0 1 0 ] const grid_size_3d = (8, 8, 8) const grid_size_2d = (8, 8) const batch_size = batch_size_for_test() const points = [0.4 * randn(3) for _ in 1:10] const points_static = SVector{3}.(points) const points_array = Matrix{Float64}(undef, 3, length(points)) eachcol(points_array) .= points const points_reinterp = reinterpret(reshape, SVector{3,Float64}, points_array) const more_points = [0.4 * @SVector randn(3) for _ in 1:100_000] const rotation = rand(RotMatrix3{Float64}) const rotations_static = rand(RotMatrix3{Float64}, batch_size)::Vector{<:StaticMatrix} const rotations = (Array.(rotations_static))::Vector{Matrix{Float64}} const rotations_array = Array{Float64,3}(undef, 3, 3, batch_size) eachslice(rotations_array; dims=3) .= rotations const rotations_reinterp = reinterpret( reshape, SMatrix{3,3,Float64,9}, reshape(rotations_array, 9, :) ) const rotation_tangent = Array(rand(RotMatrix3)) const rotation_tangents_static = rand(RotMatrix3{Float64}, batch_size)::Vector{<:StaticMatrix} const rotation_tangents = (Array.(rotation_tangents_static))::Vector{Matrix{Float64}} const projection = P * rand(RotMatrix3) const projections_static = Ref(P) .* rand(RotMatrix3{Float64}, batch_size) const projections = (Array.(projections_static))::Vector{Matrix{Float64}} const projections_array = Array{Float64,3}(undef, 2, 3, batch_size) eachslice(projections_array; dims=3) .= projections const projections_reinterp = reinterpret( reshape, SMatrix{2,3,Float64,6}, reshape(projections_array, 6, :) ) const projection_tangent = Array(P * rand(RotMatrix3)) const projection_tangents_static = Ref(P) .* rand(RotMatrix3{Float64}, batch_size) const projection_tangents = (Array.(projection_tangents_static))::Vector{Matrix{Float64}} const translation_3d = 0.1 * @SVector randn(3) const translation_2d = 0.1 * @SVector randn(2) const translations_3d_static = [0.1 * @SVector randn(3) for _ in 1:batch_size] const translations_3d = (Array.(translations_3d_static))::Vector{Vector{Float64}} const translations_3d_array = Matrix{Float64}(undef, 3, batch_size) eachcol(translations_3d_array) .= translations_3d const translations_3d_reinterp = reinterpret( reshape, SVector{3,Float64}, translations_3d_array ) const translations_2d_static = [0.1 * @SVector randn(2) for _ in 1:batch_size] const translations_2d = (Array.(translations_2d_static))::Vector{Vector{Float64}} const translations_2d_array = Matrix{Float64}(undef, 2, batch_size) eachcol(translations_2d_array) .= translations_2d const translations_2d_reinterp = reinterpret( reshape, SVector{2,Float64}, translations_2d_array ) const background = 0.1 const backgrounds = collect(1:1.0:batch_size) const weight = rand() const weights = 10 .* rand(batch_size) const point_weights = let w = rand(length(points)) w ./ sum(w) end const more_point_weights = let w = rand(length(more_points)) w ./ sum(w) end end # module D
DiffPointRasterisation
https://github.com/microscopic-image-analysis/DiffPointRasterisation.jl.git
[ "MIT" ]
0.2.2
2fdf8dec8ac5fbf4a19487210c6d3bb8dff95459
code
206
using TestItemRunner: @run_package_tests, @testitem @testitem "Aqua.test_all" begin import Aqua Aqua.test_all(DiffPointRasterisation) end @run_package_tests # filter=ti-> occursin("CUDA", ti.name)
DiffPointRasterisation
https://github.com/microscopic-image-analysis/DiffPointRasterisation.jl.git
[ "MIT" ]
0.2.2
2fdf8dec8ac5fbf4a19487210c6d3bb8dff95459
code
1019
function run_cuda(f, args...) cu_args = adapt(CuArray, args) return f(cu_args...) end function cuda_cpu_agree(f, args...) out_cpu = f(args...) out_cuda = run_cuda(f, args...) return is_approx_equal(out_cuda, out_cpu) end function is_approx_equal(actual::AbstractArray, expected::AbstractArray) return Array(actual) ≈ expected end function is_approx_equal(actual::NamedTuple, expected::NamedTuple) actual_cpu = adapt(Array, actual) for prop in propertynames(expected) try actual_elem = getproperty(actual_cpu, prop) expected_elem = getproperty(expected, prop) if !(actual_elem ≈ expected_elem) throw( "Values differ:\nActual: $(string(actual_elem)) \nExpected: $(string(expected_elem))", ) return false end catch e println("Error while trying to compare element $(string(prop))") rethrow() end end return true end
DiffPointRasterisation
https://github.com/microscopic-image-analysis/DiffPointRasterisation.jl.git
[ "MIT" ]
0.2.2
2fdf8dec8ac5fbf4a19487210c6d3bb8dff95459
docs
7933
# DiffPointRasterisation *Differentiable rasterisation of point clouds in julia* [![Build Status](https://github.com/microscopic-image-analysis/DiffPointRasterisation.jl/actions/workflows/CI.yml/badge.svg?branch=main)](https://github.com/microscopic-image-analysis/DiffPointRasterisation.jl/actions/workflows/CI.yml?query=branch%3Amain) [![](https://img.shields.io/badge/docs-main-blue.svg)](https://microscopic-image-analysis.github.io/DiffPointRasterisation.jl/dev) [![Aqua QA](https://raw.githubusercontent.com/JuliaTesting/Aqua.jl/master/badge.svg)](https://github.com/JuliaTesting/Aqua.jl) ![](logo.gif) ## About This package provides a rasterisation routine for arbitrary-dimensional point cloud data that is fully (auto-)differentiable. The implementation uses multiple threads on CPU or GPU hardware if available. The roots of this package are in single-particle 3d reconstruction from tomographic data, and as such it comes with the following ins and out: - Currently only a single "channel" (e.g gray scale) is supported - If data is projected to a lower dimension (meaning the dimensionality of the output grid is lower than the dimensionality of the points) - Projections are always orthographic (currently no support for perspective projection) - no "z-blending": The contribution of each point to its output voxel is independent of the point's coordinate along the projection axis. ## Rasterisation interface The interface consists of a single function `raster` that accepts a point cloud (as a vector of m-dimensional vectors) and pose/projection parameters, (as well as optional weight and background parameters) and returns a n-dimensional (n <= m) array into which the points are rasterized, each point by default with a weight of 1 that is mulit-linearly interpolated into the neighboring grid cells. #### Simple Example ```julia-repl julia> using DiffPointRasterisation, LinearAlgebra julia> grid_size = (5, 5) # 2d grid with 5 x 5 pixels (5, 5) julia> rotation, translation = I(2), zeros(2) # pose parameters (Bool[1 0; 0 1], [0.0, 0.0]) ``` ```julia-repl julia> raster(grid_size, [zeros(2)], rotation, translation) # single point at center 5×5 Matrix{Float64}: 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 ``` ```julia-repl julia> raster(grid_size, [[0.2, 0.0]], rotation, translation) # single point half a pixel below center 5×5 Matrix{Float64}: 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.5 0.0 0.0 0.0 0.0 0.5 0.0 0.0 0.0 0.0 0.0 0.0 0.0 ``` ```julia-repl julia> raster(grid_size, [[0.2, -0.2]], I(2), zeros(2)) # single point half a pixel below and left of center 5×5 Matrix{Float64}: 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.25 0.25 0.0 0.0 0.0 0.25 0.25 0.0 0.0 0.0 0.0 0.0 0.0 0.0 ``` ## Differentiability Both, an explicit function that calculates derivatives of `raster`, as well as an integration to common automatic differentiation libraries in julia are provided. ### Automatic differentiation libraries This package provides rules for reverse-mode automatic differentiation libraries that are based on the [ChainRules.jl](https://juliadiff.org/ChainRulesCore.jl/dev/#ChainRules-roll-out-status) ecosystem. So using `raster(args...)` in a program that uses any of the ChainRules-based reverse-mode autodiff libraries should just work™. Gradients with respect to all parameters (except `grid_size`) are supported: #### Example using Zygote.jl we define a simple scalar "loss" that we want to differentiate: ```julia-repl julia> using Zygote julia> target_image = rand(grid_size...) 5×5 Matrix{Float64}: 0.345889 0.032283 0.589178 0.0625972 0.310929 0.404836 0.573265 0.350633 0.0417926 0.895955 0.174528 0.127555 0.0906833 0.639844 0.832502 0.189836 0.360597 0.243664 0.825484 0.667319 0.672631 0.520593 0.341701 0.101026 0.182172 julia> loss(params...) = sum((target_image .- raster(grid_size, params...)).^2) loss (generic function with 1 method) ``` some input parameters to `raster`: ```julia-repl julia> points = [2 * rand(2) .- 1 for _ in 1:5] # 5 random points 5-element Vector{Vector{Float64}}: [0.8457397177007744, 0.3482756109584688] [-0.6028188536164718, -0.612801322279686] [-0.47141692007256464, 0.6098964840013308] [-0.74526926786903, 0.6480225109030409] [-0.4044384373422192, -0.13171854413805173] julia> rotation = [ # explicit matrix for rotation (to satisfy Zygote) 1.0 0.0 0.0 1.0 ] 2×2 Matrix{Float64}: 1.0 0.0 0.0 1.0 ``` and let Zygote calculate the gradient of `loss` with respect to those parameters ```julia-repl julia> d_points, d_rotation, d_translation = Zygote.gradient(loss, points, rotation, translation); ulia> d_points 5-element Vector{StaticArraysCore.SVector{2, Float64}}: [-2.7703628931165025, 3.973371400200988] [-0.70462225282373, 1.0317734946448016] [-1.7117138793471494, -3.235178706903591] [-2.0683933141077886, -0.6732149105779637] [2.6278388385655904, 1.585621066861592] julia> d_rotation 2×2 reshape(::StaticArraysCore.SMatrix{2, 2, Float64, 4}, 2, 2) with eltype Float64: -0.632605 -3.26353 4.12402 -1.86668 julia> d_translation 2-element StaticArraysCore.SVector{2, Float64} with indices SOneTo(2): -4.62725350082958 2.6823723442258274 ``` ### Explicit interface The explicit interface for calculating derivatives of `raster` with respect to its arguments again consists of a single function called `raster_pullback!`: The function `raster_pullback!(ds_dout, raster_args...)` takes as input the sensitivity of some scalar quantity to the output of `raster(grid_size, raster_args...)`, `ds_dout`, and returns the sensitivity of said quantity to the *input arguments* `raster_args` of `raster` (hence the name pullback). #### Example We can repeat the above calculation using the explicit interface. To do that, we first have to calculate the sensitivity of the scalar output of `loss` to the output of `raster`. This could be done using an autodiff library, but here we do it manually: ```julia-repl julia> ds_dout = 2 .* (target_image .- raster(grid_size, points, rotation, translation)) # gradient of loss \w respect to output of raster 5×5 Matrix{Float64}: 0.152276 -0.417335 1.16347 -0.700428 -0.63595 0.285167 0.033845 -0.625258 -0.801198 0.760124 0.349055 0.25511 0.181367 1.27969 1.665 0.379672 0.721194 0.487329 1.65097 1.33464 1.34526 1.04119 0.454354 -1.3402 0.364343 ``` Then we can feed that into `raster_pullback!` together with the same arguments that were fed to `raster`: ```julia-repl julia> ds_din = raster_pullback!(ds_dout, points, rotation, translation); ``` We see that the result is the same as obtained via Zygote: ```julia-repl julia> ds_din.points 2×5 Matrix{Float64}: 2.77036 0.704622 1.71171 2.06839 -2.62784 -3.97337 -1.03177 3.23518 0.673215 -1.58562 julia> ds_din.rotation 2×2 StaticArraysCore.SMatrix{2, 2, Float64, 4} with indices SOneTo(2)×SOneTo(2): 0.632605 3.26353 -4.12402 1.86668 julia> ds_din.translation 2-element StaticArraysCore.SVector{2, Float64} with indices SOneTo(2): 4.62725350082958 -2.6823723442258274 ``` ## Timings **Points**|**Images**|**Pixel**|**Mode**|**Fwd time CPU**|**Fwd time CPUx8\***|**Fwd time GPU**|**Bwd time CPU**|**Bwd time CPUx8\***|**Bwd time GPU\*\*** :-----:|:-----:|:-----:|:-----:|:-----:|:-----:|:-----:|:-----:|:-----:|:-----: 10⁴|64|128²|3D → 2D|341 ms|73 ms|15 ms|37 ms|10 ms|1 ms 10⁴|64|1024²|3D → 2D|387 ms|101 ms|16 ms|78 ms|24 ms|2 ms 10⁵|64|128²|3D → 2D|3313 ms|741 ms|153 ms|374 ms|117 ms|9 ms 10⁵|64|1024²|3D → 2D|3499 ms|821 ms|154 ms|469 ms|173 ms|10 ms 10⁵|1|1024³|3D → 3D|493 ms|420 ms|24 ms|265 ms|269 ms|17 ms \* 8 julia threads on 4 hardware threads with hyperthreading \*\* 1 Nvidia HGX A100 GPU
DiffPointRasterisation
https://github.com/microscopic-image-analysis/DiffPointRasterisation.jl.git
[ "MIT" ]
0.2.2
2fdf8dec8ac5fbf4a19487210c6d3bb8dff95459
docs
254
# API Documentation ```@meta CurrentModule = DiffPointRasterisation ``` ## Exported functions ```@autodocs Modules = [DiffPointRasterisation] Private = false ``` ## Private functions ```@autodocs Modules = [DiffPointRasterisation] Public = false ```
DiffPointRasterisation
https://github.com/microscopic-image-analysis/DiffPointRasterisation.jl.git
[ "MIT" ]
0.2.2
2fdf8dec8ac5fbf4a19487210c6d3bb8dff95459
docs
1992
# Raster a single point cloud to a batch of poses To make best use of the hardware it is advantageous to raster a batch of poses at once. On GPU hardware this is currently also the only supported mode. To raster a single point cloud to a batch of `n` images, all parameters except the point cloud should be provided as `n`-vectors. This is a more flexible interface than the often used array with trailing batch dimension, since it allows to pass in a batch of parameters that have a more structured type than a simple array (e.g. a vector of `Rotation` objects from [Rotations.jl](https://github.com/JuliaGeometry/Rotations.jl)). ## Array with trailing batch dim to vec of array If you have data in the array with trailing batch dimension format, it is straightforward (and quite cheap) to reinterpret it as a batch-vector of single parameters: ```julia-repl julia> matrices = randn(2, 2, 3) # batch of 3 2x2-matrices as 3d-array 2×2×3 Array{Float64, 3}: [:, :, 1] = -0.947072 1.10155 0.328925 0.0957267 [:, :, 2] = -1.14336 1.71218 0.277723 0.436665 [:, :, 3] = -0.114541 -0.769275 0.321084 -0.215008 julia> using StaticArrays julia> vec_of_matrices = reinterpret(reshape, SMatrix{2, 2, Float64, 4}, reshape(matrices, 4, :)) 3-element reinterpret(reshape, SMatrix{2, 2, Float64, 4}, ::Matrix{Float64}) with eltype SMatrix{2, 2, Float64, 4}: [-0.947072487060636 1.1015531033643386; 0.3289251820481776 0.0957267306067441] [-1.143363316882325 1.712179045069409; 0.27772320359678004 0.4366650562384542] [-0.11454148373779363 -0.7692750798350269; 0.32108447348937047 -0.21500805160408776] ``` ## Pre-allocation for batched pullback [`raster_pullback!`](@ref) can be optionally provided with pre-allocated arrays for its output. For these arrays the expected format is actually in the nd-array with trailing batch dimension format. The rationale behind this is that the algorithm works better on continuous blocks of memory, since atomic operations are required.
DiffPointRasterisation
https://github.com/microscopic-image-analysis/DiffPointRasterisation.jl.git
[ "MIT" ]
0.2.2
2fdf8dec8ac5fbf4a19487210c6d3bb8dff95459
docs
1877
# DiffPointRasterisation *Differentiable rasterisation of point clouds in julia* DiffPointRasterisation.jl provides a rasterisation routine for arbitrary-dimensional point cloud data that is fully (auto-)differentiable. The implementation uses multiple threads on CPU or GPU hardware if available. ## Rasterisation interface The interface consists of a single function [`raster`](@ref) that accepts a point cloud (as a vector of m-dimensional vectors) and pose/projection parameters, (as well as optional weight and background parameters) and returns a n-dimensional (n <= m) array into which the points are rasterized, each point by default with a weight of 1 that is mulit-linearly interpolated into the neighboring grid cells. ## Differentiability Both, an explicit function that calculates derivatives of `raster`, as well as an integration to common automatic differentiation libraries in julia are provided. ### Automatic differentiation libraries Rules for reverse-mode automatic differentiation libraries that are based on the [ChainRules.jl](https://juliadiff.org/ChainRulesCore.jl/dev/#ChainRules-roll-out-status) ecosystem are provided via an extension package. So using `raster(args...)` in a program that uses any of the ChainRules-based reverse-mode autodiff libraries should just work™. Gradients with respect to all parameters (except `grid_size`) are supported. ### Explicit interface The explicit interface for calculating derivatives of `raster` with respect to its arguments again consists of a single function called [`raster_pullback!`](@ref): The function `raster_pullback!(ds_dout, raster_args...)` takes as input the sensitivity of some scalar quantity to the output of `raster(grid_size, raster_args...)`, `ds_dout`, and returns the sensitivity of said quantity to the *input arguments* `raster_args` of `raster` (hence the name pullback).
DiffPointRasterisation
https://github.com/microscopic-image-analysis/DiffPointRasterisation.jl.git
[ "MIT" ]
0.1.3
32574567d25366649afcc1445f543cdf953c0282
code
558
using NicePipes using Documenter makedocs(; modules=[NicePipes], authors="Simeon Schaub <[email protected]> and contributors", repo="https://github.com/simeonschaub/NicePipes.jl/blob/{commit}{path}#L{line}", sitename="NicePipes.jl", format=Documenter.HTML(; prettyurls=get(ENV, "CI", "false") == "true", canonical="https://simeonschaub.github.io/NicePipes.jl", assets=String[], ), pages=[ "Home" => "index.md", ], ) deploydocs(; repo="github.com/simeonschaub/NicePipes.jl", )
NicePipes
https://github.com/simeonschaub/NicePipes.jl.git
[ "MIT" ]
0.1.3
32574567d25366649afcc1445f543cdf953c0282
code
2084
module NicePipes if VERSION < v"1.3.0-rc4" @warn "Can't use binary artifacts, using your system's `grep` and `sed`." grep(f) = f("grep") sed(f) = f("sed") else using grep_jll, sed_jll end struct ShPipe{T,C} val::T cmd::C args::Cmd end # like Base.open, but doesn't throw if exitcode is non-zero and always returns process instead # of return value of f function _open(f::Function, cmds::Base.AbstractCmd, args...; kwargs...) P = open(cmds, args...; kwargs...) ret = try f(P) catch kill(P) rethrow() finally close(P.in) end wait(P) return P end function Base.show(io_out::IO, x::ShPipe) x.cmd() do cmd p = _open(`$cmd $(x.args)`, "w", io_out) do io_in show(io_in, MIME("text/plain"), x.val) end if x.cmd === grep && p.exitcode == 1 println(io_out, "No matches found!") elseif p.exitcode != 0 print(io_out, "Command $(p.cmd) failed with exit code $(p.exitcode)") elseif x.cmd === grep # delete additional newline print(io_out, "\033[1A") end end return nothing end struct ShPipeEndpoint{C} cmd::C args::Cmd end macro p_cmd(s) cmd, args = match(r"^(.*)\s(.*)$", s).captures return :(ShPipeEndpoint(f->f($cmd)), @cmd($args)) end (endpoint::ShPipeEndpoint)(val) = ShPipe(val, endpoint.cmd, endpoint.args) Base.:|(val, endpoint::ShPipeEndpoint) = val |> endpoint macro special_command(cmd) return quote export $(Symbol('@', cmd)) macro $cmd(args...) args = map(args) do arg # interpret raw_str as raw string if Meta.isexpr(arg, :macrocall) && arg.args[1] === Symbol("@raw_str") arg = arg.args[3] end return arg isa String ? string('"', arg, '"') : arg end args = join(args, ' ') return :(ShPipeEndpoint($$cmd, @cmd($args))) end end |> esc end @special_command grep @special_command sed end
NicePipes
https://github.com/simeonschaub/NicePipes.jl.git
[ "MIT" ]
0.1.3
32574567d25366649afcc1445f543cdf953c0282
code
751
using NicePipes using Test @static if Sys.iswindows() const LE = "\r\n" else const LE = "\n" end function test_show(x, show_x) io = IOBuffer() show(io, x) output = String(take!(io)) output = replace(output, LE*"\e[1A" => "") @test output == show_x end @testset "NicePipes.jl" begin a = ["foo", "bar"] show_a = [ "2-element $(Vector{String}):", " \"foo\"", " \"bar\"", ] test_show((a | @grep foo), show_a[2]) test_show((a | @grep -iv FoO), join(show_a[[1, 3]], LE)) test_show((3 | @grep 4), "No matches found!\n") test_show((a | @sed "/foo/d"), join(show_a[[1, 3]], LE)) test_show((a | @sed raw"s/f\(o\+\)/b\1/g"), show_a[1] * LE * " \"boo\"" * LE * show_a[3]) end
NicePipes
https://github.com/simeonschaub/NicePipes.jl.git
[ "MIT" ]
0.1.3
32574567d25366649afcc1445f543cdf953c0282
docs
1702
# NicePipes [![Build Status](https://github.com/simeonschaub/NicePipes.jl/workflows/CI/badge.svg)](https://github.com/simeonschaub/NicePipes.jl/actions) [![Coverage](https://codecov.io/gh/simeonschaub/NicePipes.jl/branch/master/graph/badge.svg)](https://codecov.io/gh/simeonschaub/NicePipes.jl) [![Stable](https://img.shields.io/badge/docs-stable-blue.svg)](https://simeonschaub.github.io/NicePipes.jl/stable) [![Dev](https://img.shields.io/badge/docs-dev-blue.svg)](https://simeonschaub.github.io/NicePipes.jl/dev) [![pkgeval](https://juliahub.com/docs/NicePipes/pkgeval.svg)](https://juliahub.com/ui/Packages/NicePipes/tVmGC) Pipe REPL `show` output into unix tools: ```julia julia> using NicePipes julia> methods(+) | @grep BigFloat [15] +(c::BigInt, x::BigFloat) in Base.MPFR at mpfr.jl:414 [22] +(a::BigFloat, b::BigFloat, c::BigFloat, d::BigFloat, e::BigFloat) in Base.MPFR at mpfr.jl:564 [23] +(a::BigFloat, b::BigFloat, c::BigFloat, d::BigFloat) in Base.MPFR at mpfr.jl:557 [24] +(a::BigFloat, b::BigFloat, c::BigFloat) in Base.MPFR at mpfr.jl:551 [25] +(x::BigFloat, c::BigInt) in Base.MPFR at mpfr.jl:410 [26] +(x::BigFloat, y::BigFloat) in Base.MPFR at mpfr.jl:379 [27] +(x::BigFloat, c::Union{UInt16, UInt32, UInt64, UInt8}) in Base.MPFR at mpfr.jl:386 [28] +(x::BigFloat, c::Union{Int16, Int32, Int64, Int8}) in Base.MPFR at mpfr.jl:394 [29] +(x::BigFloat, c::Union{Float16, Float32, Float64}) in Base.MPFR at mpfr.jl:402 [61] +(c::Union{UInt16, UInt32, UInt64, UInt8}, x::BigFloat) in Base.MPFR at mpfr.jl:390 [62] +(c::Union{Int16, Int32, Int64, Int8}, x::BigFloat) in Base.MPFR at mpfr.jl:398 [63] +(c::Union{Float16, Float32, Float64}, x::BigFloat) in Base.MPFR at mpfr.jl:406 ```
NicePipes
https://github.com/simeonschaub/NicePipes.jl.git
[ "MIT" ]
0.1.3
32574567d25366649afcc1445f543cdf953c0282
docs
107
```@meta CurrentModule = NicePipes ``` # NicePipes ```@index ``` ```@autodocs Modules = [NicePipes] ```
NicePipes
https://github.com/simeonschaub/NicePipes.jl.git
[ "MIT" ]
0.1.0
4c035c67eee91a19afdc5db63eb71464c5db32ba
code
820
using Documenter, DynamicNLPModels const _PAGES = [ "Introduction" => "index.md", "Quick Start"=>"guide.md", "API Manual" => "api.md" ] makedocs( sitename = "DynamicNLPModels", authors = "David Cole, Sungho Shin, Francois Pacaud", format = Documenter.LaTeX(platform="docker"), pages = _PAGES ) makedocs( sitename = "DynamicNLPModels", modules = [DynamicNLPModels], authors = "David Cole, Sungho Shin, Francois Pacaud", format = Documenter.HTML( prettyurls = get(ENV, "CI", nothing) == "true", sidebar_sitename = true, collapselevel = 1, ), pages = _PAGES, clean = false, ) deploydocs( repo = "github.com/MadNLP/DynamicNLPModels.jl.git", target = "build", devbranch = "main", devurl = "dev", push_preview = true, )
DynamicNLPModels
https://github.com/MadNLP/DynamicNLPModels.jl.git
[ "MIT" ]
0.1.0
4c035c67eee91a19afdc5db63eb71464c5db32ba
code
2952
using DynamicNLPModels, Random, LinearAlgebra, SparseArrays using MadNLP, QuadraticModels, MadNLPGPU, CUDA, NLPModels # Extend MadNLP functions function MadNLP.jac_dense!(nlp::DenseLQDynamicModel{T, V, M1, M2, M3}, x, jac) where {T, V, M1<: AbstractMatrix, M2 <: AbstractMatrix, M3 <: AbstractMatrix} NLPModels.increment!(nlp, :neval_jac) J = nlp.data.A copyto!(jac, J) end function MadNLP.hess_dense!(nlp::DenseLQDynamicModel{T, V, M1, M2, M3}, x, w1l, hess; obj_weight = 1.0) where {T, V, M1<: AbstractMatrix, M2 <: AbstractMatrix, M3 <: AbstractMatrix} NLPModels.increment!(nlp, :neval_hess) H = nlp.data.H copyto!(hess, H) end # Time horizon N = 3 # generate random Q, R, A, and B matrices Random.seed!(10) Q_rand = Random.rand(2, 2) Q = Q_rand * Q_rand' + I R_rand = Random.rand(1, 1) R = R_rand * R_rand' + I A_rand = rand(2, 2) A = A_rand * A_rand' + I B = rand(2, 1) # generate upper and lower bounds sl = rand(2) ul = fill(-15.0, 1) su = sl .+ 4 uu = ul .+ 10 s0 = sl .+ 2 # Define K matrix for numerical stability of condensed problem K = - [1.41175 2.47819;] # found from MatrixEquations.jl; ared(A, B, 1, 1) # Build model for 1 D heat transfer lq_dense = DenseLQDynamicModel(s0, A, B, Q, R, N; K = K, sl = sl, su = su, ul = ul, uu = uu) lq_sparse = SparseLQDynamicModel(s0, A, B, Q, R, N; sl = sl, su = su, ul = ul, uu = uu) # Solve the dense problem dense_options = Dict{Symbol, Any}( :kkt_system => MadNLP.DENSE_CONDENSED_KKT_SYSTEM, :linear_solver=> LapackCPUSolver, :max_iter=> 50, :jacobian_constant=>true, :hessian_constant=>true, :lapack_algorithm=>MadNLP.CHOLESKY ) d_ips = MadNLP.InteriorPointSolver(lq_dense, option_dict = dense_options) sol_ref_dense = MadNLP.optimize!(d_ips) # Solve the sparse problem sparse_options = Dict{Symbol, Any}( :max_iter=>50, :jacobian_constant=>true, :hessian_constant=>true, ) s_ips = MadNLP.InteriorPointSolver(lq_sparse, option_dict = sparse_options) sol_ref_sparse = MadNLP.optimize!(s_ips) # Solve the dense problem on the GPU gpu_options = Dict{Symbol, Any}( :kkt_system=>MadNLP.DENSE_CONDENSED_KKT_SYSTEM, :linear_solver=>LapackGPUSolver, :max_iter=>50, :jacobian_constant=>true, :hessian_constant=>true, :lapack_algorithm=>MadNLP.CHOLESKY ) gpu_ips = MadNLPGPU.CuInteriorPointSolver(lq_dense, option_dict = gpu_options) sol_ref_gpu = MadNLP.optimize!(gpu_ips) println("States from dense problem on CPU are ", get_s(sol_ref_dense, lq_dense)) println("States from dense problem on GPU are ", get_s(sol_ref_gpu, lq_dense)) println("States from sparse problem on CPU are ", get_s(sol_ref_sparse, lq_sparse)) println() println("Inputs from dense problem on CPU are ", get_u(sol_ref_dense, lq_dense)) println("Inputs from dense problem on GPU are ", get_u(sol_ref_gpu, lq_dense)) println("Inputs from sparse problem on CPU are ", get_u(sol_ref_sparse, lq_sparse))
DynamicNLPModels
https://github.com/MadNLP/DynamicNLPModels.jl.git
[ "MIT" ]
0.1.0
4c035c67eee91a19afdc5db63eb71464c5db32ba
code
542
module DynamicNLPModels import NLPModels import QuadraticModels import LinearAlgebra import SparseArrays import LinearOperators import CUDA import CUDA: CUBLAS import SparseArrays: SparseMatrixCSC export LQDynamicData, SparseLQDynamicModel, DenseLQDynamicModel export get_u, get_s, get_jacobian, add_jtsj!, reset_s0! include(joinpath("LinearQuadratic", "LinearQuadratic.jl")) include(joinpath("LinearQuadratic", "sparse.jl")) include(joinpath("LinearQuadratic", "dense.jl")) include(joinpath("LinearQuadratic", "tools.jl")) end # module
DynamicNLPModels
https://github.com/MadNLP/DynamicNLPModels.jl.git
[ "MIT" ]
0.1.0
4c035c67eee91a19afdc5db63eb71464c5db32ba
code
12791
abstract type AbstractLQDynData{T, V} end @doc raw""" LQDynamicData{T,V,M,MK} <: AbstractLQDynData{T,V} A struct to represent the features of the optimization problem ```math \begin{aligned} \min \frac{1}{2} &\; \sum_{i = 0}^{N - 1}(s_i^T Q s_i + 2 u_i^T S^T x_i + u_i^T R u_i) + \frac{1}{2} s_N^T Q_f s_N \\ \textrm{s.t.} &\; s_{i+1} = A s_i + B u_i + w_i \quad \forall i=0, 1, ..., N-1 \\ &\; u_i = Kx_i + v_i \quad \forall i = 0, 1, ..., N - 1 \\ &\; g^l \le E s_i + F u_i \le g^u \quad \forall i = 0, 1, ..., N-1\\ &\; s^l \le s \le s^u \\ &\; u^l \le u \le u^u \\ &\; s_0 = s0 \end{aligned} ``` --- Attributes include: - `s0`: initial state of system - `A` : constraint matrix for system states - `B` : constraint matrix for system inputs - `Q` : objective function matrix for system states from 0:(N-1) - `R` : objective function matrix for system inputs from 0:(N-1) - `N` : number of time steps - `Qf`: objective function matrix for system state at time N - `S` : objective function matrix for system states and inputs - `ns`: number of state variables - `nu`: number of input varaibles - `E` : constraint matrix for state variables - `F` : constraint matrix for input variables - `K` : feedback gain matrix - 'w' : constant term for dynamic constraints - `sl`: vector of lower bounds on state variables - `su`: vector of upper bounds on state variables - `ul`: vector of lower bounds on input variables - `uu`: vector of upper bounds on input variables - `gl`: vector of lower bounds on constraints - `gu`: vector of upper bounds on constraints see also `LQDynamicData(s0, A, B, Q, R, N; ...)` """ struct LQDynamicData{T, V, M, MK} <: AbstractLQDynData{T, V} s0::V A::M B::M Q::M R::M N::Int Qf::M S::M ns::Int nu::Int E::M F::M K::MK w::V sl::V su::V ul::V uu::V gl::V gu::V end @doc raw""" LQDynamicData(s0, A, B, Q, R, N; ...) -> LQDynamicData{T, V, M, MK} A constructor for building an object of type `LQDynamicData` for the optimization problem ```math \begin{aligned} \min \frac{1}{2} &\; \sum_{i = 0}^{N - 1}(s_i^T Q s_i + 2 u_i^T S^T x_i + u_i^T R u_i) + \frac{1}{2} s_N^T Q_f s_N \\ \textrm{s.t.} &\; s_{i+1} = A s_i + B u_i + w_i \quad \forall i=0, 1, ..., N-1 \\ &\; u_i = Kx_i + v_i \quad \forall i = 0, 1, ..., N - 1 \\ &\; gl \le E s_i + F u_i \le gu \quad \forall i = 0, 1, ..., N-1\\ &\; sl \le s \le su \\ &\; ul \le u \le uu \\ &\; s_0 = s0 \end{aligned} ``` --- - `s0`: initial state of system - `A` : constraint matrix for system states - `B` : constraint matrix for system inputs - `Q` : objective function matrix for system states from 0:(N-1) - `R` : objective function matrix for system inputs from 0:(N-1) - `N` : number of time steps The following attributes of the `LQDynamicData` type are detected automatically from the length of s0 and size of R - `ns`: number of state variables - `nu`: number of input varaibles The following keyward arguments are also accepted - `Qf = Q`: objective function matrix for system state at time N; dimensions must be ns x ns - `S = nothing`: objective function matrix for system state and inputs - `E = zeros(eltype(Q), 0, ns)` : constraint matrix for state variables - `F = zeros(eltype(Q), 0, nu)` : constraint matrix for input variables - `K = nothing` : feedback gain matrix - `w = zeros(eltype(Q), ns * N)` : constant term for dynamic constraints - `sl = fill(-Inf, ns)`: vector of lower bounds on state variables - `su = fill(Inf, ns)` : vector of upper bounds on state variables - `ul = fill(-Inf, nu)`: vector of lower bounds on input variables - `uu = fill(Inf, nu)` : vector of upper bounds on input variables - `gl = fill(-Inf, size(E, 1))` : vector of lower bounds on constraints - `gu = fill(Inf, size(E, 1))` : vector of upper bounds on constraints """ function LQDynamicData( s0::V, A::M, B::M, Q::M, R::M, N; Qf::M = Q, S::M = _init_similar(Q, size(Q, 1), size(R, 1), T), E::M = _init_similar(Q, 0, length(s0), T), F::M = _init_similar(Q, 0, size(R, 1), T), K::MK = nothing, w::V = _init_similar(s0, length(s0) * N, T), sl::V = (similar(s0) .= -Inf), su::V = (similar(s0) .= Inf), ul::V = (similar(s0, size(R, 1)) .= -Inf), uu::V = (similar(s0, size(R, 1)) .= Inf), gl::V = (similar(s0, size(E, 1)) .= -Inf), gu::V = (similar(s0, size(F, 1)) .= Inf), ) where { T, V <: AbstractVector{T}, M <: AbstractMatrix{T}, MK <: Union{Nothing, AbstractMatrix{T}}, } if size(Q, 1) != size(Q, 2) error("Q matrix is not square") end if size(R, 1) != size(R, 1) error("R matrix is not square") end if size(A, 2) != length(s0) error("Number of columns of A are not equal to the number of states") end if size(B, 2) != size(R, 1) error("Number of columns of B are not equal to the number of inputs") end if length(s0) != size(Q, 1) error("size of Q is not consistent with length of s0") end if !all(sl .<= su) error("lower bound(s) on s is > upper bound(s)") end if !all(ul .<= uu) error("lower bound(s) on u is > upper bound(s)") end if !all(sl .<= s0) || !all(s0 .<= su) error("s0 is not within the given upper and lower bounds") end if size(E, 1) != size(F, 1) error("E and F have different numbers of rows") end if !all(gl .<= gu) error("lower bound(s) on Es + Fu is > upper bound(s)") end if size(E, 2) != size(Q, 1) error("Dimensions of E are not the same as number of states") end if size(F, 2) != size(R, 1) error("Dimensions of F are not the same as the number of inputs") end if length(gl) != size(E, 1) error("Dimensions of gl do not match E and F") end if length(gu) != size(E, 1) error("Dimensions of gu do not match E and F") end if size(S, 1) != size(Q, 1) || size(S, 2) != size(R, 1) error("Dimensions of S do not match dimensions of Q and R") end if K != nothing if size(K, 1) != size(R, 1) || size(K, 2) != size(Q, 1) error("Dimensions of K do not match number of states and inputs") end end if Int(size(w, 1)) != Int(size(s0, 1) * N) error("Dimensions of w do not match ns") end ns = size(Q, 1) nu = size(R, 1) LQDynamicData{T, V, M, MK}( s0, A, B, Q, R, N, Qf, S, ns, nu, E, F, K, w, sl, su, ul, uu, gl, gu, ) end abstract type AbstractDynamicModel{T, V} <: QuadraticModels.AbstractQuadraticModel{T, V} end struct SparseLQDynamicModel{T, V, M1, M2, M3, MK} <: AbstractDynamicModel{T, V} meta::NLPModels.NLPModelMeta{T, V} counters::NLPModels.Counters data::QuadraticModels.QPData{T, V, M1, M2} dynamic_data::LQDynamicData{T, V, M3, MK} end """ Struct containing block matrices used for creating and resetting the `DenseLQDynamicModel`. A and B matrices are given in part by Jerez, Kerrigan, and Constantinides in section 4 of "A sparse and condensed QP formulation for predictive control of LTI systems" (doi:10.1016/j.automatica.2012.03.010). States are eliminated by the equation ``x = Ax_0 + Bu + \\hat{A}w`` where ``x = [x_0^T, x_1^T, ..., x_N^T]`` and ``u = [u_0^T, u_1^T, ..., u_{N-1}^T]`` --- - `A` : block A matrix given by Jerez et al. with ``n_s(N + 1)`` rows and ns columns - `B` : block B matrix given by Jerez et al. with ``n_s(N)`` rows and nu columns - `Aw` : length ``n_s(N + 1)`` vector corresponding to the linear term of the dynamic constraints - `h` : ``n_u(N) \\times n_s`` matrix for building the linear term of the objective function. Just needs to be multiplied by `s0`. - `h01`: ns x ns matrix for building the constant term fo the objective function. This can be found by taking ``s_0^T`` `h01` ``s_0`` - `h02`: similar to `h01`, but one side is multiplied by `Aw` rather than by `As0`. This will just be multiplied by `s0` once - `h_constant` : linear term in the objective function that arises from `Aw`. Not a function of `s0` - `h0_constant`: constant term in the objective function that arises from `Aw`. Not a function of `s0` - `d` : length ``n_c(N)`` term for the constraint bounds corresponding to `E` and `F`. Must be multiplied by `s0` and subtracted from `gl` and `gu`. Equal to the blocks (E + FK) A (see Jerez et al.) - `dw` : length ``n_c(N)`` term for the constraint bounds that arises from `w`. Equal to the blocks (E + FK) Aw - `KA` : size ``n_u(N)`` x ns matrix. Needs to be multiplied by `s0` and subtracted from `ul` and `uu` to update the algebraic constraints corresponding to the input bounds - `KAw`: similar to `KA`, but it is multiplied by Aw rather than A See also `reset_s0!` """ mutable struct DenseLQDynamicBlocks{T, V, M} A::M B::M Aw::V # Aw = block_matrix_A * w (result is a Vector; block_matrix A is like block_B, but with I instead of B) h::M # h = (QB + SKB + K^T R K B + K^T S^T B)^T A + (S + K^T R)^T A h01::M # h01 = A^T((Q + KTRK + KTST + SK))A where Q, K, R, S, and A are block matrices just needs to be multiplied by s0 on each side h02::V # h02 = wT block_matrix_AT (Q + KTRK + KTSK + SK) A; just needs to be multiplied by s0 on right h_constant::V # h_constant = BT (Q + KTRK + SK + KTST) block_matrix_A w + (RK + ST)B block_matrix_A w h0_constant::T # h0_constant = wT block_matrix_AT (Q + KTRK + KTSK + SK) block_matrix_A w d::M # d = (E + FK) A dw::V # dw = (E + FK) block_matrix_A w - constant term to be subtracted from d KA::M KAw::V end struct DenseLQDynamicModel{T, V, M1, M2, M3, M4, MK} <: AbstractDynamicModel{T, V} meta::NLPModels.NLPModelMeta{T, V} counters::NLPModels.Counters data::QuadraticModels.QPData{T, V, M1, M2} dynamic_data::LQDynamicData{T, V, M3, MK} blocks::DenseLQDynamicBlocks{T, V, M4} end """ LQJacobianOperator{T, V, M} Struct for storing the implicit Jacobian matrix. All data for the Jacobian can be stored in the first `nu` columns of `J`. This struct contains the needed data and storage arrays for calculating ``Jx``, ``J^T x``, and ``J^T \\Sigma J``. ``Jx`` and ``J^T x`` are performed through extensions to `LinearAlgebra.mul!()`. --- Attributes - `truncated_jac1`: Matrix of first `nu` columns of the Jacobian corresponding to Ax + Bu constraints - `truncated_jac2`: Matrix of first `nu` columns of the Jacobian corresponding to state variable bounds - `truncated_jac3`: Matrix of first `nu` columns of the Jacobian corresponding to input variable bounds - `N` : number of time steps - `nu` : number of inputs - `nc` : number of algebraic constraints of the form gl <= Es + Fu <= gu - `nsc`: number of bounded state variables - `nuc`: number of bounded input variables (if `K` is defined) - `SJ1`: placeholder for storing data when calculating `ΣJ` - `SJ2`: placeholder for storing data when calculating `ΣJ` - `SJ3`: placeholder for storing data when calculating `ΣJ` - `H_sub_block`: placeholder for storing data when adding `J^T ΣJ` to the Hessian """ struct LQJacobianOperator{T, M, A} <: LinearOperators.AbstractLinearOperator{T} truncated_jac1::A # tensor of Jacobian blocks corresponding Ex + Fu constraints truncated_jac2::A # tensor of Jacobian blocks corresponding to state variable limits truncated_jac3::A # tensor of Jacobian blocks corresponding to input variable limits N::Int # number of time steps nu::Int # number of inputs nc::Int # number of inequality constraints nsc::Int # number of state variables that are constrained nuc::Int # number of input variables that are constrained # Storage tensors for building Jx and J^Tx x1::A x2::A x3::A y::A # Storage tensors for building J^TΣJ SJ1::M SJ2::M SJ3::M # Storage block for adding J^TΣJ to H H_sub_block::M end function _init_similar(mat, dim1::Number, dim2::Number, dim3::Number, T::DataType) new_mat = similar(mat, dim1, dim2, dim3) fill!(new_mat, zero(T)) return new_mat end function _init_similar(mat, dim1::Number, dim2::Number, T = eltype(mat)) new_mat = similar(mat, dim1, dim2) fill!(new_mat, zero(T)) return new_mat end function _init_similar(mat, dim1::Number, T = eltype(mat)) new_mat = similar(mat, dim1) fill!(new_mat, zero(T)) return new_mat end
DynamicNLPModels
https://github.com/MadNLP/DynamicNLPModels.jl.git