licenses
sequencelengths
1
3
version
stringclasses
677 values
tree_hash
stringlengths
40
40
path
stringclasses
1 value
type
stringclasses
2 values
size
stringlengths
2
8
text
stringlengths
25
67.1M
package_name
stringlengths
2
41
repo
stringlengths
33
86
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
2269
# ------------------------------------------------------------------ # Licensed under the MIT License. See LICENSE in the project root. # ------------------------------------------------------------------ """ AbsoluteUnits() AbsoluteUnits(:) Converts the units of all columns in the table to absolute units. AbsoluteUnits(col₁, col₂, ..., colₙ) AbsoluteUnits([col₁, col₂, ..., colₙ]) AbsoluteUnits((col₁, col₂, ..., colₙ)) Converts the units of selected columns `col₁`, `col₂`, ..., `colₙ` to absolute units. AbsoluteUnits(regex) Converts the units of columns that match with `regex` to absolute units. # Examples ```julia AbsoluteUnits() AbsoluteUnits([2, 3, 5]) AbsoluteUnits([:b, :c, :e]) AbsoluteUnits(("b", "c", "e")) AbsoluteUnits(r"[bce]") ``` """ struct AbsoluteUnits{S<:ColumnSelector} <: StatelessFeatureTransform selector::S end AbsoluteUnits() = AbsoluteUnits(AllSelector()) AbsoluteUnits(cols) = AbsoluteUnits(selector(cols)) AbsoluteUnits(cols::C...) where {C<:Column} = AbsoluteUnits(selector(cols)) isrevertible(::Type{<:AbsoluteUnits}) = true _absunit(x) = _absunit(x, nonmissingtype(eltype(x))) _absunit(x, ::Type) = (x, NoUnits) _absunit(x, ::Type{Q}) where {Q<:AbstractQuantity} = (x, unit(Q)) function _absunit(x, ::Type{Q}) where {Q<:AffineQuantity} u = unit(Q) a = absoluteunit(u) y = map(v -> uconvert(a, v), x) (y, u) end function applyfeat(transform::AbsoluteUnits, feat, prep) cols = Tables.columns(feat) names = Tables.columnnames(cols) snames = transform.selector(names) tuples = map(names) do name x = Tables.getcolumn(cols, name) name ∈ snames ? _absunit(x) : (x, NoUnits) end columns = first.(tuples) units = last.(tuples) 𝒯 = (; zip(names, columns)...) newfeat = 𝒯 |> Tables.materializer(feat) newfeat, (snames, units) end _revunit(x, ::Units) = x _revunit(x, u::AffineUnits) = map(v -> uconvert(u, v), x) function revertfeat(::AbsoluteUnits, newfeat, fcache) cols = Tables.columns(newfeat) names = Tables.columnnames(cols) snames, units = fcache columns = map(names, units) do name, unit x = Tables.getcolumn(cols, name) name ∈ snames ? _revunit(x, unit) : x end 𝒯 = (; zip(names, columns)...) 𝒯 |> Tables.materializer(newfeat) end
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
1931
# ------------------------------------------------------------------ # Licensed under the MIT License. See LICENSE in the project root. # ------------------------------------------------------------------ """ Assert(; cond, msg="") Asserts all columns of the table by throwing a `AssertionError(msg)` if `cond(column)` returns `false`, otherwise returns the input table. The `msg` argument can be a string, or a function that receives the column name and returns a string, e.g.: `nm -> "error in column \$nm"`. Assert(col₁, col₂, ..., colₙ; cond, msg="") Assert([col₁, col₂, ..., colₙ]; cond, msg="") Assert((col₁, col₂, ..., colₙ); cond, msg="") Asserts the selected columns `col₁`, `col₂`, ..., `colₙ`. Assert(regex; cond, msg="") Asserts the columns that match with `regex`. # Examples ```julia Assert(cond=allunique, msg="assertion error") Assert([2, 3, 5], cond=x -> sum(x) > 100) Assert([:b, :c, :e], cond=x -> eltype(x) <: Integer) Assert(("b", "c", "e"), cond=allunique, msg=nm -> "error in column \$nm") Assert(r"[bce]", cond=x -> sum(x) > 100) ``` """ struct Assert{S<:ColumnSelector,C,M} <: StatelessFeatureTransform selector::S cond::C msg::M end Assert(selector::ColumnSelector; cond, msg="") = Assert(selector, cond, msg) Assert(; kwargs...) = Assert(AllSelector(); kwargs...) Assert(cols; kwargs...) = Assert(selector(cols); kwargs...) Assert(cols::C...; kwargs...) where {C<:Column} = Assert(selector(cols); kwargs...) isrevertible(::Type{<:Assert}) = true function applyfeat(transform::Assert, feat, prep) cols = Tables.columns(feat) names = Tables.columnnames(cols) snames = transform.selector(names) cond = transform.cond msg = transform.msg msgfun = msg isa AbstractString ? _ -> msg : msg for name in snames x = Tables.getcolumn(cols, name) _assert(cond(x), msgfun(name)) end feat, nothing end revertfeat(::Assert, newfeat, fcache) = newfeat
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
1170
# ------------------------------------------------------------------ # Licensed under the MIT License. See LICENSE in the project root. # ------------------------------------------------------------------ """ Center() Applies the center transform to all columns of the table. The center transform of the column `x`, with mean `μ`, is defined by `x .- μ`. Center(col₁, col₂, ..., colₙ) Center([col₁, col₂, ..., colₙ]) Center((col₁, col₂, ..., colₙ)) Applies the Center transform on columns `col₁`, `col₂`, ..., `colₙ`. Center(regex) Applies the Center transform on columns that match with `regex`. # Examples ```julia Center(1, 3, 5) Center([:a, :c, :e]) Center(("a", "c", "e")) Center(r"[ace]") ``` """ struct Center{S<:ColumnSelector} <: ColwiseFeatureTransform selector::S end Center() = Center(AllSelector()) Center(cols) = Center(selector(cols)) Center(cols::C...) where {C<:Column} = Center(selector(cols)) assertions(transform::Center) = [scitypeassert(Continuous, transform.selector)] isrevertible(::Type{<:Center}) = true colcache(::Center, x) = mean(x) colapply(::Center, x, μ) = @. x - μ colrevert(::Center, y, μ) = @. y + μ
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
1305
# ------------------------------------------------------------------ # Licensed under the MIT License. See LICENCE in the project root. # ------------------------------------------------------------------ """ Closure() The transform that applies the closure operation (i.e. `x ./ sum(x)`), to all rows of the input table. The rows of the output table sum to one. See also [`Remainder`](@ref). """ struct Closure <: StatelessFeatureTransform end isrevertible(::Type{Closure}) = true assertions(::Closure) = [scitypeassert(Continuous)] function applyfeat(::Closure, feat, prep) cols = Tables.columns(feat) names = Tables.columnnames(cols) # table as matrix and get the sum acros dims 2 X = Tables.matrix(feat) S = sum(X, dims=2) # divides each row by its sum (closure operation) Z = X ./ S # table with the old columns and the new values 𝒯 = (; zip(names, eachcol(Z))...) newfeat = 𝒯 |> Tables.materializer(feat) newfeat, S end function revertfeat(::Closure, newfeat, fcache) cols = Tables.columns(newfeat) names = Tables.columnnames(cols) # table as matrix Z = Tables.matrix(newfeat) # retrieve cache S = fcache # undo operation X = Z .* S # table with original columns 𝒯 = (; zip(names, eachcol(X))...) 𝒯 |> Tables.materializer(newfeat) end
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
1381
# ------------------------------------------------------------------ # Licensed under the MIT License. See LICENSE in the project root. # ------------------------------------------------------------------ """ Coalesce(; value) Replaces all `missing` values from the table with `value`. Coalesce(col₁, col₂, ..., colₙ; value) Coalesce([col₁, col₂, ..., colₙ]; value) Coalesce((col₁, col₂, ..., colₙ); value) Replaces all missing values from the columns `col₁`, `col₂`, ..., `colₙ` with `value`. Coalesce(regex; value) Replaces all missing values from the columns that match with `regex` with `value`. # Examples ```julia Coalesce(value=0) Coalesce(1, 3, 5, value=1) Coalesce([:a, :c, :e], value=2) Coalesce(("a", "c", "e"), value=3) Coalesce(r"[ace]", value=4) ``` ## Notes * The transform can alter the element type of columns from `Union{Missing,T}` to `T`. """ struct Coalesce{S<:ColumnSelector,T} <: ColwiseFeatureTransform selector::S value::T end Coalesce(; value) = Coalesce(AllSelector(), value) Coalesce(cols; value) = Coalesce(selector(cols), value) Coalesce(cols::C...; value) where {C<:Column} = Coalesce(selector(cols), value) parameters(transform::Coalesce) = (; value=transform.value) isrevertible(::Type{<:Coalesce}) = false colcache(::Coalesce, x) = nothing colapply(transform::Coalesce, x, c) = coalesce.(x, transform.value)
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
2074
# ------------------------------------------------------------------ # Licensed under the MIT License. See LICENSE in the project root. # ------------------------------------------------------------------ """ Coerce(col₁ => S₁, col₂ => S₂, ..., colₙ => Sₙ) Return a copy of the table, ensuring that the scientific types of the columns match the new specification. Coerce(S) Coerce all columns of the table with scientific type `S`. This transform uses the `DataScienceTraits.coerce` function. Please see their docstring for more details. # Examples ```julia import DataScienceTraits as DST Coerce(1 => DST.Continuous, 2 => DST.Continuous) Coerce(:a => DST.Continuous, :b => DST.Continuous) Coerce("a" => DST.Continuous, "b" => DST.Continuous) ``` """ struct Coerce{S<:ColumnSelector,T} <: StatelessFeatureTransform selector::S scitypes::T end Coerce() = throw(ArgumentError("cannot create Coerce transform without arguments")) Coerce(scitype::Type{<:SciType}) = Coerce(AllSelector(), scitype) Coerce(pairs::Pair{C,DataType}...) where {C<:Column} = Coerce(selector(first.(pairs)), collect(last.(pairs))) isrevertible(::Type{<:Coerce}) = true _typedict(scitype::Type{<:SciType}, snames) = Dict(nm => scitype for nm in snames) _typedict(scitypes::AbstractVector, snames) = Dict(zip(snames, scitypes)) function applyfeat(transform::Coerce, feat, prep) cols = Tables.columns(feat) names = Tables.columnnames(cols) types = Tables.schema(feat).types snames = transform.selector(names) typedict = _typedict(transform.scitypes, snames) columns = map(names) do name x = Tables.getcolumn(cols, name) name ∈ snames ? coerce(typedict[name], x) : x end 𝒯 = (; zip(names, columns)...) newfeat = 𝒯 |> Tables.materializer(feat) newfeat, types end function revertfeat(::Coerce, newfeat, fcache) cols = Tables.columns(newfeat) names = Tables.columnnames(cols) columns = map(fcache, names) do T, n x = Tables.getcolumn(cols, n) collect(T, x) end 𝒯 = (; zip(names, columns)...) 𝒯 |> Tables.materializer(newfeat) end
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
520
# ------------------------------------------------------------------ # Licensed under the MIT License. See LICENSE in the project root. # ------------------------------------------------------------------ """ ColTable() The transform that applies the function `Tables.columntable` to to the input table. """ struct ColTable <: StatelessFeatureTransform end isrevertible(::Type{ColTable}) = true applyfeat(::ColTable, feat, prep) = Tables.columntable(feat), feat revertfeat(::ColTable, newfeat, fcache) = fcache
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
1869
# ------------------------------------------------------------------ # Licensed under the MIT License. See LICENSE in the project root. # ------------------------------------------------------------------ """ Compose(; as=:CODA) Converts all columns of the table into parts of a composition in a new column named `as`, using the `CoDa.compose` function. Compose(col₁, col₂, ..., colₙ; as=:CODA) Compose([col₁, col₂, ..., colₙ]; as=:CODA) Compose((col₁, col₂, ..., colₙ); as=:CODA) Converts the selected columns `col₁`, `col₂`, ..., `colₙ` into parts of a composition. Compose(regex; as=:CODA) Converts the columns that match with `regex` into parts of a composition. # Examples ```julia Compose(as=:comp) Compose([2, 3, 5]) Compose([:b, :c, :e]) Compose(("b", "c", "e")) Compose(r"[bce]", as="COMP") ``` """ struct Compose{S<:ColumnSelector} <: StatelessFeatureTransform selector::S as::Symbol end Compose(selector::ColumnSelector; as=:CODA) = Compose(selector, Symbol(as)) Compose(; kwargs...) = Compose(AllSelector(); kwargs...) Compose(cols; kwargs...) = Compose(selector(cols); kwargs...) Compose(cols::C...; kwargs...) where {C<:Column} = Compose(selector(cols); kwargs...) isrevertible(::Type{<:Compose}) = true function applyfeat(transform::Compose, feat, prep) cols = Tables.columns(feat) names = Tables.columnnames(cols) snames = transform.selector(names) as = transform.as newfeat = compose(feat, snames; as) newfeat, (names, snames, as) end function revertfeat(::Compose, newfeat, fcache) cols = Tables.columns(newfeat) names, snames, as = fcache coda = Tables.getcolumn(cols, as) columns = map(names) do name if name ∈ snames Tables.getcolumn(coda, name) else Tables.getcolumn(cols, name) end end 𝒯 = (; zip(names, columns)...) 𝒯 |> Tables.materializer(newfeat) end
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
1419
# ------------------------------------------------------------------ # Licensed under the MIT License. See LICENSE in the project root. # ------------------------------------------------------------------ """ DropConstant() Drops the constant columns using the `allequal` function. """ struct DropConstant <: StatelessFeatureTransform end isrevertible(::Type{DropConstant}) = true function applyfeat(::DropConstant, feat, prep) cols = Tables.columns(feat) names = Tables.columnnames(cols) |> collect # constant columns cnames = filter(names) do name x = Tables.getcolumn(cols, name) allequal(x) end cinds = indexin(cnames, names) cvalues = [first(Tables.getcolumn(cols, nm)) for nm in cnames] # selected columns snames = setdiff(names, cnames) columns = [Tables.getcolumn(cols, nm) for nm in snames] 𝒯 = (; zip(snames, columns)...) newfeat = 𝒯 |> Tables.materializer(feat) newfeat, (cinds, cnames, cvalues) end function revertfeat(::DropConstant, newfeat, fcache) cols = Tables.columns(newfeat) names = Tables.columnnames(cols) |> collect columns = Any[Tables.getcolumn(cols, name) for name in names] cinds, cnames, cvalues = fcache nrows = _nrows(newfeat) for (i, cind) in enumerate(cinds) insert!(names, cind, cnames[i]) insert!(columns, cind, fill(cvalues[i], nrows)) end 𝒯 = (; zip(names, columns)...) 𝒯 |> Tables.materializer(newfeat) end
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
2528
# ------------------------------------------------------------------ # Licensed under the MIT License. See LICENSE in the project root. # ------------------------------------------------------------------ """ DropExtrema(; low=0.25, high=0.75) Drops rows where any of the values in all columns are outside the interval (`[quantile(col, low), quantile(col, high)]`). DropExtrema(col₁, col₂, ..., colₙ; low=0.25, high=0.75) DropExtrema([col₁, col₂, ..., colₙ]; low=0.25, high=0.75) DropExtrema((col₁, col₂, ..., colₙ); low=0.25, high=0.75) Drops rows where any of the values in columns `col₁`, `col₂`, ..., `colₙ` are outside the interval. DropExtrema(regex; low=0.25, high=0.75) Drops rows where any of the values in columns that match with `regex` are outside the interval. # Examples ```julia DropExtrema(low=0.3, high=0.7) DropExtrema(1, low=0.3, high=0.7) DropExtrema(:a, low=0.2, high=0.8) DropExtrema("a", low=0.3, high=0.7) DropExtrema(1, 3, 5, low=0, high=1) DropExtrema([:a, :c, :e], low=0.3, high=0.7) DropExtrema(("a", "c", "e"), low=0.25, high=0.75) DropExtrema(r"[ace]", low=0.3, high=0.7) ``` """ struct DropExtrema{S<:ColumnSelector,T} <: StatelessFeatureTransform selector::S low::T high::T function DropExtrema(selector::S, low::T, high::T) where {S<:ColumnSelector,T} _assert(0 ≤ low ≤ high ≤ 1, "invalid quantiles") new{S,T}(selector, low, high) end end DropExtrema(selector::ColumnSelector, low, high) = DropExtrema(selector, promote(low, high)...) DropExtrema(; low=0.25, high=0.75) = DropExtrema(AllSelector(), low, high) DropExtrema(cols; low=0.25, high=0.75) = DropExtrema(selector(cols), low, high) DropExtrema(cols::C...; low=0.25, high=0.75) where {C<:Column} = DropExtrema(selector(cols), low, high) parameters(transform::DropExtrema) = (low=transform.low, high=transform.high) isrevertible(::Type{<:DropExtrema}) = false function preprocess(transform::DropExtrema, feat) cols = Tables.columns(feat) names = Tables.columnnames(cols) snames = transform.selector(names) limits = map(snames) do name x = Tables.getcolumn(cols, name) low = convert(eltype(x), transform.low) high = convert(eltype(x), transform.high) name => quantile(x, (low, high)) end ftrans = Filter(row -> all(xl ≤ row[nm] ≤ xh for (nm, (xl, xh)) in limits)) fprep = preprocess(ftrans, feat) ftrans, fprep end function applyfeat(::DropExtrema, feat, prep) ftrans, fprep = prep newfeat, _ = applyfeat(ftrans, feat, fprep) newfeat, nothing end
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
2163
# ------------------------------------------------------------------ # Licensed under the MIT License. See LICENSE in the project root. # ------------------------------------------------------------------ """ DropMissing() DropMissing(:) Drop all rows with missing values in table. DropMissing(col₁, col₂, ..., colₙ) DropMissing([col₁, col₂, ..., colₙ]) DropMissing((col₁, col₂, ..., colₙ)) Drop all rows with missing values in selected columns `col₁`, `col₂`, ..., `colₙ`. DropMissing(regex) Drop all rows with missing values in columns that match with `regex`. # Examples ```julia DropMissing() DropMissing("b", "c", "e") DropMissing([2, 3, 5]) DropMissing((:b, :c, :e)) DropMissing(r"[bce]") ``` ## Notes * The transform can alter the element type of columns from `Union{Missing,T}` to `T`. * If the transformed column has only `missing` values, it will be converted to an empty column of type `Any`. """ struct DropMissing{S<:ColumnSelector} <: StatelessFeatureTransform selector::S end DropMissing() = DropMissing(AllSelector()) DropMissing(cols) = DropMissing(selector(cols)) DropMissing(cols::C...) where {C<:Column} = DropMissing(selector(cols)) isrevertible(::Type{<:DropMissing}) = false function preprocess(transform::DropMissing, feat) cols = Tables.columns(feat) names = Tables.columnnames(cols) snames = transform.selector(names) ftrans = Filter(row -> all(!ismissing(row[nm]) for nm in snames)) fprep = preprocess(ftrans, feat) ftrans, fprep, snames end _nonmissing(x) = _nonmissing(eltype(x), x) _nonmissing(::Type{T}, x) where {T} = x _nonmissing(::Type{Missing}, x) = [] _nonmissing(::Type{Union{Missing,T}}, x) where {T} = collect(T, x) function applyfeat(::DropMissing, feat, prep) # apply filter transform ftrans, fprep, snames = prep newfeat, _ = applyfeat(ftrans, feat, fprep) # drop Missing type cols = Tables.columns(newfeat) names = Tables.columnnames(cols) columns = map(names) do name x = Tables.getcolumn(cols, name) name ∈ snames ? _nonmissing(x) : x end 𝒯 = (; zip(names, columns)...) newfeat = 𝒯 |> Tables.materializer(feat) newfeat, nothing end
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
1351
# ------------------------------------------------------------------ # Licensed under the MIT License. See LICENSE in the project root. # ------------------------------------------------------------------ """ DropNaN() DropNaN(:) Drop all rows with NaN values in table. DropNaN(col₁, col₂, ..., colₙ) DropNaN([col₁, col₂, ..., colₙ]) DropNaN((col₁, col₂, ..., colₙ)) Drop all rows with NaN values in selected columns `col₁`, `col₂`, ..., `colₙ`. DropNaN(regex) Drop all rows with NaN values in columns that match with `regex`. # Examples ```julia DropNaN(2, 3, 4) DropNaN([:b, :c, :d]) DropNaN(("b", "c", "d")) DropNaN(r"[bcd]") ``` """ struct DropNaN{S<:ColumnSelector} <: StatelessFeatureTransform selector::S end DropNaN() = DropNaN(AllSelector()) DropNaN(cols) = DropNaN(selector(cols)) DropNaN(cols::C...) where {C<:Column} = DropNaN(selector(cols)) isrevertible(::Type{<:DropNaN}) = false _isnan(_) = false _isnan(x::Number) = isnan(x) function preprocess(transform::DropNaN, feat) cols = Tables.columns(feat) names = Tables.columnnames(cols) snames = transform.selector(names) ftrans = Filter(row -> all(!_isnan(row[nm]) for nm in snames)) fprep = preprocess(ftrans, feat) ftrans, fprep end function applyfeat(::DropNaN, feat, prep) ftrans, fprep = prep applyfeat(ftrans, feat, fprep) end
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
1985
# ------------------------------------------------------------------ # Licensed under the MIT License. See LICENSE in the project root. # ------------------------------------------------------------------ """ DropUnits() DropUnits(:) Drop units from all columns in the table. DropUnits(col₁, col₂, ..., colₙ) DropUnits([col₁, col₂, ..., colₙ]) DropUnits((col₁, col₂, ..., colₙ)) Drop units from selected columns `col₁`, `col₂`, ..., `colₙ`. DropUnits(regex) Drop units from columns that match with `regex`. # Examples ```julia DropUnits() DropUnits([2, 3, 5]) DropUnits([:b, :c, :e]) DropUnits(("b", "c", "e")) DropUnits(r"[bce]") ``` """ struct DropUnits{S<:ColumnSelector} <: StatelessFeatureTransform selector::S end DropUnits() = DropUnits(AllSelector()) DropUnits(cols) = DropUnits(selector(cols)) DropUnits(cols::C...) where {C<:Column} = DropUnits(selector(cols)) isrevertible(::Type{<:DropUnits}) = true _dropunit(x) = _dropunit(x, nonmissingtype(eltype(x))) _dropunit(x, ::Type{Q}) where {Q<:AbstractQuantity} = (map(ustrip, x), unit(Q)) _dropunit(x, ::Type) = (x, NoUnits) function applyfeat(transform::DropUnits, feat, prep) cols = Tables.columns(feat) names = Tables.columnnames(cols) snames = transform.selector(names) tuples = map(names) do name x = Tables.getcolumn(cols, name) name ∈ snames ? _dropunit(x) : (x, NoUnits) end columns = first.(tuples) units = last.(tuples) 𝒯 = (; zip(names, columns)...) newfeat = 𝒯 |> Tables.materializer(feat) newfeat, (snames, units) end _addunit(x, ::typeof(NoUnits)) = x _addunit(x, u::Units) = map(v -> v * u, x) function revertfeat(::DropUnits, newfeat, fcache) cols = Tables.columns(newfeat) names = Tables.columnnames(cols) snames, units = fcache columns = map(names, units) do name, unit x = Tables.getcolumn(cols, name) name ∈ snames ? _addunit(x, unit) : x end 𝒯 = (; zip(names, columns)...) 𝒯 |> Tables.materializer(newfeat) end
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
5202
# ------------------------------------------------------------------ # Licensed under the MIT License. See LICENSE in the project root. # ------------------------------------------------------------------ """ EigenAnalysis(proj; [maxdim], [pratio]) The eigenanalysis of the covariance with a given projection `proj`. Optionally specify the maximum number of dimensions in the output `maxdim` and the percentage of variance to retain `pratio`. ## Projections * `:V` - Uncorrelated variables (PCA transform) * `:VD` - Uncorrelated variables and variance one (DRS transform) * `:VDV` - Uncorrelated variables and variance one (SDS transformation) The `:V` projection used in the PCA transform projects the data on the eigenvectors V of the covariance matrix. The `:VD` projection used in the DRS transform. Similar to the `:V` projection, but the eigenvectors are multiplied by the squared inverse of the eigenvalues D. The `:VDV` projection used in the SDS transform. Similar to the `:VD` transform, but the data is projected back to the basis of the original variables using the Vᵀ matrix. See [https://geostatisticslessons.com/lessons/sphereingmaf](https://geostatisticslessons.com/lessons/sphereingmaf) for more details about these three variants of eigenanalysis. # Examples ```julia EigenAnalysis(:V) EigenAnalysis(:VD) EigenAnalysis(:VDV) EigenAnalysis(:V, maxdim=3) EigenAnalysis(:VD, pratio=0.99) EigenAnalysis(:VDV, maxdim=3, pratio=0.99) ``` """ struct EigenAnalysis <: FeatureTransform proj::Symbol maxdim::Union{Int,Nothing} pratio::Float64 function EigenAnalysis(proj, maxdim, pratio) _assert(proj ∈ (:V, :VD, :VDV), "invalid projection") _assert(0 ≤ pratio ≤ 1, "invalid pratio") new(proj, maxdim, pratio) end end EigenAnalysis(proj; maxdim=nothing, pratio=1.0) = EigenAnalysis(proj, maxdim, pratio) assertions(::EigenAnalysis) = [scitypeassert(Continuous)] parameters(transform::EigenAnalysis) = (proj=transform.proj, maxdim=transform.maxdim, pratio=transform.pratio) isrevertible(::Type{EigenAnalysis}) = true function applyfeat(transform::EigenAnalysis, feat, prep) # original columns names cols = Tables.columns(feat) onames = Tables.columnnames(cols) # table as matrix X = Tables.matrix(feat) # center the data μ = mean(X, dims=1) Y = X .- μ # eigenanalysis of covariance S, S⁻¹ = eigenmatrices(transform, Y) # project the data Z = Y * S # column names names = Symbol.(:PC, 1:size(Z, 2)) # table with transformed columns 𝒯 = (; zip(names, eachcol(Z))...) newfeat = 𝒯 |> Tables.materializer(feat) newfeat, (μ, S, S⁻¹, onames) end function revertfeat(::EigenAnalysis, newfeat, fcache) # table as matrix Z = Tables.matrix(newfeat) # retrieve cache μ, S, S⁻¹, onames = fcache # undo projection Y = Z * S⁻¹ # undo centering X = Y .+ μ # table with original columns 𝒯 = (; zip(onames, eachcol(X))...) 𝒯 |> Tables.materializer(newfeat) end function reapplyfeat(transform::EigenAnalysis, feat, fcache) # table as matrix X = Tables.matrix(feat) # retrieve cache μ, S, S⁻¹, onames = fcache # center the data Y = X .- μ # project the data Z = Y * S # column names names = Symbol.(:PC, 1:size(Z, 2)) # table with transformed columns 𝒯 = (; zip(names, eachcol(Z))...) 𝒯 |> Tables.materializer(feat) end _maxdim(maxdim::Int, Y) = maxdim _maxdim(::Nothing, Y) = size(Y, 2) function outdim(transform, Y, λ) pratio = transform.pratio csums = cumsum(λ) ratios = csums ./ last(csums) mdim = _maxdim(transform.maxdim, Y) pdim = findfirst(≥(pratio), ratios) min(mdim, pdim) end function eigenmatrices(transform, Y) proj = transform.proj Σ = cov(Y) λ, V = eigen(Σ, sortby=λ -> -real(λ)) if proj == :V S = V S⁻¹ = transpose(V) elseif proj == :VD Λ = Diagonal(sqrt.(λ)) S = V * inv(Λ) S⁻¹ = Λ * transpose(V) elseif proj == :VDV Λ = Diagonal(sqrt.(λ)) S = V * inv(Λ) * transpose(V) S⁻¹ = V * Λ * transpose(V) end d = outdim(transform, Y, λ) S[:, 1:d], S⁻¹[1:d, :] end """ PCA([options]) Principal component analysis. See [`EigenAnalysis`](@ref) for detailed description of the available options. # Examples ```julia PCA(maxdim=2) PCA(pratio=0.86) PCA(maxdim=2, pratio=0.86) ``` ## Notes * `PCA()` is shortcut for `ZScore() → EigenAnalysis(:V)`. """ PCA(; maxdim=nothing, pratio=1.0) = ZScore() → EigenAnalysis(:V, maxdim, pratio) """ DRS([options]) Dimension reduction sphering. See [`EigenAnalysis`](@ref) for detailed description of the available options. # Examples ```julia DRS(maxdim=3) DRS(pratio=0.87) DRS(maxdim=3, pratio=0.87) ``` ## Notes * `DRS()` is shortcut for `ZScore() → EigenAnalysis(:VD)`. """ DRS(; maxdim=nothing, pratio=1.0) = ZScore() → EigenAnalysis(:VD, maxdim, pratio) """ SDS([options]) Standardized data sphering. See [`EigenAnalysis`](@ref) for detailed description of the available options. # Examples ```julia SDS() SDS(maxdim=4) SDS(pratio=0.88) SDS(maxdim=4, pratio=0.88) ``` ## Notes * `SDS()` is shortcut for `ZScore() → EigenAnalysis(:VDV)`. """ SDS(; maxdim=nothing, pratio=1.0) = ZScore() → EigenAnalysis(:VDV, maxdim, pratio)
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
1217
# ------------------------------------------------------------------ # Licensed under the MIT License. See LICENSE in the project root. # ------------------------------------------------------------------ """ Filter(pred) Filters the table returning only the rows where the predicate `pred` is `true`. # Examples ```julia Filter(row -> sum(row) > 10) Filter(row -> row.a == true && row.b < 30) Filter(row -> row."a" == true && row."b" < 30) Filter(row -> row[1] == true && row[2] < 30) Filter(row -> row[:a] == true && row[:b] < 30) Filter(row -> row["a"] == true && row["b"] < 30) ``` ## Notes * The schema of the table is preserved by the transform. """ struct Filter{F} <: StatelessFeatureTransform pred::F end isrevertible(::Type{<:Filter}) = false function preprocess(transform::Filter, feat) # lazy row iterator rows = tablerows(feat) # selected indices sinds = Int[] for (i, row) in enumerate(rows) transform.pred(row) && push!(sinds, i) end sinds end function applyfeat(::Filter, feat, prep) # preprocessed indices sinds = prep # selected rows srows = Tables.subset(feat, sinds, viewhint=true) newfeat = srows |> Tables.materializer(feat) newfeat, nothing end
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
2119
# ------------------------------------------------------------------ # Licensed under the MIT License. See LICENSE in the project root. # ------------------------------------------------------------------ """ Functional(fun) The transform that applies a `fun` elementwise. Functional(col₁ => fun₁, col₂ => fun₂, ..., colₙ => funₙ) Apply the corresponding `funᵢ` function to each `colᵢ` column. # Examples ```julia Functional(exp) Functional(log) Functional(1 => exp, 2 => log) Functional(:a => exp, :b => log) Functional("a" => exp, "b" => log) ``` """ struct Functional{S<:ColumnSelector,F} <: StatelessFeatureTransform selector::S fun::F end Functional(fun) = Functional(AllSelector(), fun) Functional(pairs::Pair{C}...) where {C<:Column} = Functional(selector(first.(pairs)), last.(pairs)) Functional() = throw(ArgumentError("cannot create Functional transform without arguments")) isrevertible(transform::Functional) = isinvertible(transform) _hasinverse(f) = !(invfun(f) isa NoInverse) isinvertible(transform::Functional{AllSelector}) = _hasinverse(transform.fun) isinvertible(transform::Functional) = all(_hasinverse, transform.fun) inverse(transform::Functional{AllSelector}) = Functional(transform.selector, invfun(transform.fun)) inverse(transform::Functional) = Functional(transform.selector, invfun.(transform.fun)) _fundict(transform::Functional{AllSelector}, names) = Dict(nm => transform.fun for nm in names) _fundict(transform::Functional, names) = Dict(zip(names, transform.fun)) function applyfeat(transform::Functional, feat, prep) cols = Tables.columns(feat) names = Tables.columnnames(cols) snames = transform.selector(names) fundict = _fundict(transform, snames) columns = map(names) do name x = Tables.getcolumn(cols, name) if name ∈ snames fun = fundict[name] map(fun, x) else x end end 𝒯 = (; zip(names, columns)...) newfeat = 𝒯 |> Tables.materializer(feat) newfeat, nothing end function revertfeat(transform::Functional, newfeat, fcache) ofeat, _ = applyfeat(inverse(transform), newfeat, nothing) ofeat end
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
3122
const SCALES = [:quantile, :linear] """ Indicator(col; k=10, scale=:quantile, categ=false) Transforms continuous variable into `k` indicator variables defined by half-intervals of `col` values in a given `scale`. Optionally, specify the `categ` option to return binary categorical values as opposed to raw 1s and 0s. Given a sequence of increasing threshold values `t1 < t2 < ... < tk`, the indicator transform converts a continuous variable `Z` into a sequence of `k` variables `Z_1 = Z <= t1`, `Z_2 = Z <= t2`, ..., `Z_k = Z <= tk`. ## Scales: * `:quantile` - threshold values are calculated using the `quantile(Z, p)` function with a linear range of probabilities. * `:linear` - threshold values are calculated using a linear range. # Examples ```julia Indicator(1, k=3) Indicator(:a, k=6, scale=:linear) Indicator("a", k=9, scale=:linear, categ=true) ``` """ struct Indicator{S<:SingleColumnSelector} <: StatelessFeatureTransform selector::S k::Int scale::Symbol categ::Bool function Indicator(selector::S, k, scale, categ) where {S<:SingleColumnSelector} if k < 1 throw(ArgumentError("`k` must be greater than or equal to 1")) end if scale ∉ SCALES throw(ArgumentError("invalid `scale` option, use `:quantile` or `:linear`")) end new{S}(selector, k, scale, categ) end end Indicator(col::Column; k=10, scale=:quantile, categ=false) = Indicator(selector(col), k, scale, categ) assertions(transform::Indicator) = [scitypeassert(Continuous, transform.selector)] parameters(transform::Indicator) = (k=transform.k, scale=transform.scale) isrevertible(::Type{<:Indicator}) = true function _intervals(transform::Indicator, x) k = transform.k ts = if transform.scale === :quantile quantile(x, range(0, 1, k + 1)) else range(extrema(x)..., k + 1) end ts[(begin + 1):end] end function applyfeat(transform::Indicator, feat, prep) cols = Tables.columns(feat) names = Tables.columnnames(cols) |> collect columns = Any[Tables.getcolumn(cols, nm) for nm in names] name = selectsingle(transform.selector, names) ind = findfirst(==(name), names) x = columns[ind] k = transform.k ts = _intervals(transform, x) tuples = map(1:k) do i nm = Symbol("$(name)_$i") while nm ∈ names nm = Symbol("$(nm)_") end (nm, x .≤ ts[i]) end newnames = first.(tuples) newcolumns = last.(tuples) # convert to categorical arrays if necessary newcolumns = transform.categ ? categorical.(newcolumns, levels=[false, true]) : newcolumns splice!(names, ind, newnames) splice!(columns, ind, newcolumns) inds = ind:(ind + length(newnames) - 1) 𝒯 = (; zip(names, columns)...) newfeat = 𝒯 |> Tables.materializer(feat) newfeat, (name, x, inds) end function revertfeat(::Indicator, newfeat, fcache) cols = Tables.columns(newfeat) names = Tables.columnnames(cols) |> collect columns = Any[Tables.getcolumn(cols, nm) for nm in names] oname, ocolumn, inds = fcache splice!(names, inds, [oname]) splice!(columns, inds, [ocolumn]) 𝒯 = (; zip(names, columns)...) 𝒯 |> Tables.materializer(newfeat) end
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
2226
# ------------------------------------------------------------------ # Licensed under the MIT License. See LICENSE in the project root. # ------------------------------------------------------------------ """ Levels(col₁ => levels₁, col₂ => levels₂, ..., colₙ => levelsₙ; ordered=nothing) Convert columns `col₁`, `col₂`, ..., `colₙ` to categorical arrays with given levels `levels₁`, `levels₂`, ..., `levelsₙ`. Optionally, specify which columns are `ordered`. # Examples ```julia Levels(1 => 1:3, 2 => ["a", "b"], ordered=r"a") Levels(:a => 1:3, :b => ["a", "b"], ordered=[:a]) Levels("a" => 1:3, "b" => ["a", "b"], ordered=["b"]) ``` """ struct Levels{S<:ColumnSelector,O<:ColumnSelector,L} <: StatelessFeatureTransform selector::S ordered::O levels::L end Levels(pairs::Pair{C}...; ordered=nothing) where {C<:Column} = Levels(selector(first.(pairs)), selector(ordered), last.(pairs)) Levels(; kwargs...) = throw(ArgumentError("cannot create Levels transform without arguments")) assertions(transform::Levels) = [scitypeassert(Categorical, transform.selector)] isrevertible(::Type{<:Levels}) = true _revfun(x) = y -> Array(y) function _revfun(x::CategoricalArray) l, o = levels(x), isordered(x) y -> categorical(y, levels=l, ordered=o) end function applyfeat(transform::Levels, feat, prep) cols = Tables.columns(feat) names = Tables.columnnames(cols) snames = transform.selector(names) ordered = transform.ordered(snames) leveldict = Dict(zip(snames, transform.levels)) results = map(names) do name x = Tables.getcolumn(cols, name) if name ∈ snames o = name ∈ ordered l = leveldict[name] y = categorical(x, levels=l, ordered=o) revfun = _revfun(x) y, revfun else x, identity end end columns, fcache = first.(results), last.(results) 𝒯 = (; zip(names, columns)...) newfeat = 𝒯 |> Tables.materializer(feat) newfeat, fcache end function revertfeat(::Levels, newfeat, fcache) cols = Tables.columns(newfeat) names = Tables.columnnames(cols) columns = map(names, fcache) do name, revfun y = Tables.getcolumn(cols, name) revfun(y) end 𝒯 = (; zip(names, columns)...) 𝒯 |> Tables.materializer(newfeat) end
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
1982
# ------------------------------------------------------------------ # Licensed under the MIT License. See LICENSE in the project root. # ------------------------------------------------------------------ """ LogRatio Parent type of all log-ratio transforms. See also [`ALR`](@ref), [`CLR`](@ref), [`ILR`](@ref). """ abstract type LogRatio <: StatelessFeatureTransform end # log-ratio transform interface function refvar end function newvars end function applymatrix end function revertmatrix end isrevertible(::Type{<:LogRatio}) = true assertions(::LogRatio) = [scitypeassert(Continuous)] function applyfeat(transform::LogRatio, feat, prep) cols = Tables.columns(feat) onames = Tables.columnnames(cols) varnames = collect(onames) # reference variable rvar = refvar(transform, varnames) _assert(rvar ∈ varnames, "invalid reference variable") rind = findfirst(==(rvar), varnames) # permute columns if necessary perm = rind ≠ lastindex(varnames) pfeat = if perm popat!(varnames, rind) push!(varnames, rvar) feat |> Select(varnames) else feat end # apply transform X = Tables.matrix(pfeat) Y = applymatrix(transform, X) # new variable names newnames = newvars(transform, varnames) # return same table type 𝒯 = (; zip(newnames, eachcol(Y))...) newfeat = 𝒯 |> Tables.materializer(feat) newfeat, (rind, perm, onames) end function revertfeat(transform::LogRatio, newfeat, fcache) # revert transform Y = Tables.matrix(newfeat) X = revertmatrix(transform, Y) # retrieve cache rind, perm, onames = fcache # revert the permutation if necessary if perm n = length(onames) inds = collect(1:(n - 1)) insert!(inds, rind, n) X = X[:, inds] end # return same table type 𝒯 = (; zip(onames, eachcol(X))...) 𝒯 |> Tables.materializer(newfeat) end # ---------------- # IMPLEMENTATIONS # ---------------- include("logratio/alr.jl") include("logratio/clr.jl") include("logratio/ilr.jl")
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
3471
# ------------------------------------------------------------------ # Licensed under the MIT License. See LICENSE in the project root. # ------------------------------------------------------------------ """ LowHigh(; low=0.25, high=0.75) Applies the LowHigh transform to all columns of the table. The LowHigh transform of the column `x` is defined by `(x .- xl) ./ (xh - xl)`, where `xl = quantile(x, low)` and `xh = quantile(x, high)`. LowHigh(col₁, col₂, ..., colₙ; low=0.25, high=0.75) LowHigh([col₁, col₂, ..., colₙ]; low=0.25, high=0.75) LowHigh((col₁, col₂, ..., colₙ); low=0.25, high=0.75) Applies the LowHigh transform on columns `col₁`, `col₂`, ..., `colₙ`. LowHigh(regex; low=0.25, high=0.75) Applies the LowHigh transform on columns that match with `regex`. # Examples ```julia LowHigh() LowHigh(low=0, high=1) LowHigh(low=0.3, high=0.7) LowHigh(1, 3, 5, low=0, high=1) LowHigh([:a, :c, :e], low=0.3, high=0.7) LowHigh(("a", "c", "e"), low=0.25, high=0.75) LowHigh(r"[ace]", low=0.3, high=0.7) ``` """ struct LowHigh{S<:ColumnSelector,T} <: ColwiseFeatureTransform selector::S low::T high::T function LowHigh(selector::S, low::T, high::T) where {S<:ColumnSelector,T} _assert(0 ≤ low ≤ high ≤ 1, "invalid quantiles") new{S,T}(selector, low, high) end end LowHigh(selector::ColumnSelector, low, high) = LowHigh(selector, promote(low, high)...) LowHigh(; low=0.25, high=0.75) = LowHigh(AllSelector(), low, high) LowHigh(cols; low=0.25, high=0.75) = LowHigh(selector(cols), low, high) LowHigh(cols::C...; low=0.25, high=0.75) where {C<:Column} = LowHigh(selector(cols), low, high) assertions(transform::LowHigh) = [scitypeassert(Continuous, transform.selector)] parameters(transform::LowHigh) = (low=transform.low, high=transform.high) isrevertible(::Type{<:LowHigh}) = true function colcache(transform::LowHigh, x) low = convert(eltype(x), transform.low) high = convert(eltype(x), transform.high) xl, xh = quantile(x, (low, high)) xl == xh && ((xl, xh) = (zero(xl), one(xh))) (; xl, xh) end colapply(::LowHigh, x, c) = @. (x - c.xl) / (c.xh - c.xl) colrevert(::LowHigh, y, c) = @. (c.xh - c.xl) * y + c.xl """ MinMax() Applies the MinMax transform to all columns of the table. The MinMax transform is equivalent to `LowHigh(low=0, high=1)`. MinMax(col₁, col₂, ..., colₙ) MinMax([col₁, col₂, ..., colₙ]) MinMax((col₁, col₂, ..., colₙ)) Applies the MinMax transform on columns `col₁`, `col₂`, ..., `colₙ`. MinMax(regex) Applies the MinMax transform on columns that match with `regex`. # Examples ```julia MinMax(1, 3, 5) MinMax([:a, :c, :e]) MinMax(("a", "c", "e")) MinMax(r"[ace]") ``` See also [`LowHigh`](@ref). """ MinMax(args...) = LowHigh(args...; low=0, high=1) """ Interquartile() Applies the Interquartile transform to all columns of the table. The Interquartile transform is equivalent to `LowHigh(low=0.25, high=0.75)`. Interquartile(col₁, col₂, ..., colₙ) Interquartile([col₁, col₂, ..., colₙ]) Interquartile((col₁, col₂, ..., colₙ)) Applies the Interquartile transform on columns `col₁`, `col₂`, ..., `colₙ`. Interquartile(regex) Applies the Interquartile transform on columns that match with `regex`. # Examples ```julia Interquartile(1, 3, 5) Interquartile([:a, :c, :e]) Interquartile(("a", "c", "e")) Interquartile(r"[ace]") ``` See also [`LowHigh`](@ref). """ Interquartile(args...) = LowHigh(args...; low=0.25, high=0.75)
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
3664
# ------------------------------------------------------------------ # Licensed under the MIT License. See LICENSE in the project root. # ------------------------------------------------------------------ """ Map(cols₁ => fun₁ => target₁, cols₂ => fun₂, ..., colsₙ => funₙ => targetₙ) Applies the `funᵢ` function to the columns selected by `colsᵢ` using the `map` function and saves the result in a new column named `targetᵢ`. The column selection can be a single column identifier (index or name), a collection of identifiers or a regular expression (regex). Passing a target column name is optional and when omitted a new name is generated by joining the function name with the selected column names. If the target column already exists in the table, the original column will be replaced. # Examples ```julia Map(1 => sin) Map(:a => sin, "b" => cos => :cos_b) Map([2, 3] => ((b, c) -> 2b + c)) Map([:a, :c] => ((a, c) -> 2a * 3c) => :col1) Map(["c", "a"] => ((c, a) -> 3c / a) => :col1, "c" => tan) Map(r"[abc]" => ((a, b, c) -> a^2 - 2b + c) => "col1") ``` ## Notes * Anonymous functions must be passed with parentheses as in the examples above; * Some function names are treated in a special way, they are: * Anonymous functions: `#1` -> `f1`; * Composed functions: `outer ∘ inner` -> `outer_inner`; * `Base.Fix1` functions: `Base.Fix1(f, x)` -> `fix1_f`; * `Base.Fix2` functions: `Base.Fix2(f, x)` -> `fix2_f`; """ struct Map <: StatelessFeatureTransform selectors::Vector{ColumnSelector} funs::Vector{Function} targets::Vector{Union{Nothing,Symbol}} end Map() = throw(ArgumentError("cannot create Map transform without arguments")) # utility types const TargetName = Union{Symbol,AbstractString} const PairWithTarget = Pair{<:Any,<:Pair{<:Function,<:TargetName}} const PairWithoutTarget = Pair{<:Any,<:Function} const MapPair = Union{PairWithTarget,PairWithoutTarget} # utility functions _extract(p::PairWithTarget) = selector(first(p)), first(last(p)), Symbol(last(last(p))) _extract(p::PairWithoutTarget) = selector(first(p)), last(p), nothing function Map(pairs::MapPair...) tuples = map(_extract, pairs) selectors = [t[1] for t in tuples] funs = [t[2] for t in tuples] targets = [t[3] for t in tuples] Map(selectors, funs, targets) end isrevertible(::Type{Map}) = false _funname(fun::Base.Fix1) = "fix1_" * _funname(fun.f) _funname(fun::Base.Fix2) = "fix2_" * _funname(fun.f) _funname(fun::ComposedFunction) = _funname(fun.outer) * "_" * _funname(fun.inner) _funname(fun) = string(fun) function _makename(snames, fun) funname = _funname(fun) if contains(funname, "#") # anonymous functions funname = replace(funname, "#" => "f") end Symbol(funname, :_, join(snames, "_")) end function applyfeat(transform::Map, feat, prep) cols = Tables.columns(feat) onames = Tables.columnnames(cols) selectors = transform.selectors funs = transform.funs targets = transform.targets # new names and columns names = collect(onames) columns = Any[Tables.getcolumn(cols, nm) for nm in onames] # mapped columns mapped = map(selectors, funs, targets) do selector, fun, target snames = selector(names) newname = isnothing(target) ? _makename(snames, fun) : target scolumns = (Tables.getcolumn(cols, nm) for nm in snames) newcolumn = map(fun, scolumns...) newname => newcolumn end for (name, column) in mapped if name ∈ onames i = findfirst(==(name), onames) columns[i] = column else push!(names, name) push!(columns, column) end end 𝒯 = (; zip(names, columns)...) newfeat = 𝒯 |> Tables.materializer(feat) newfeat, nothing end
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
2405
# ------------------------------------------------------------------ # Licensed under the MIT License. See LICENSE in the project root. # ------------------------------------------------------------------ """ OneHot(col; categ=false) Transforms categorical column `col` into one-hot columns of levels returned by the `levels` function of CategoricalArrays.jl. The `categ` option can be used to convert resulting columns to categorical arrays as opposed to boolean vectors. # Examples ```julia OneHot(1) OneHot(:a) OneHot("a") OneHot("a", categ=true) ``` """ struct OneHot{S<:SingleColumnSelector} <: StatelessFeatureTransform selector::S categ::Bool end OneHot(col::Column; categ=false) = OneHot(selector(col), categ) assertions(transform::OneHot) = [scitypeassert(Categorical, transform.selector)] isrevertible(::Type{<:OneHot}) = true _categ(x) = categorical(x), identity function _categ(x::CategoricalArray) l, o = levels(x), isordered(x) revfun = y -> categorical(y, levels=l, ordered=o) x, revfun end function applyfeat(transform::OneHot, feat, prep) cols = Tables.columns(feat) names = Tables.columnnames(cols) |> collect columns = Any[Tables.getcolumn(cols, nm) for nm in names] name = selectsingle(transform.selector, names) ind = findfirst(==(name), names) x, revfun = _categ(columns[ind]) xlevels = levels(x) onehot = map(xlevels) do l nm = Symbol("$(name)_$l") while nm ∈ names nm = Symbol("$(nm)_") end nm, x .== l end newnames = first.(onehot) newcolumns = last.(onehot) # convert to categorical arrays if necessary newcolumns = transform.categ ? categorical.(newcolumns, levels=[false, true]) : newcolumns splice!(names, ind, newnames) splice!(columns, ind, newcolumns) inds = ind:(ind + length(newnames) - 1) 𝒯 = (; zip(names, columns)...) newfeat = 𝒯 |> Tables.materializer(feat) newfeat, (name, inds, xlevels, revfun) end function revertfeat(::OneHot, newfeat, fcache) cols = Tables.columns(newfeat) names = Tables.columnnames(cols) |> collect columns = Any[Tables.getcolumn(cols, nm) for nm in names] oname, inds, levels, revfun = fcache y = map(zip(columns[inds]...)) do row levels[findfirst(==(true), row)] end ocolumn = revfun(y) splice!(names, inds, [oname]) splice!(columns, inds, [ocolumn]) 𝒯 = (; zip(names, columns)...) 𝒯 |> Tables.materializer(newfeat) end
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
4917
# ------------------------------------------------------------------ # Licensed under the MIT License. See LICENSE in the project root. # ------------------------------------------------------------------ """ ParallelTableTransform(transforms) A transform where `transforms` are applied in parallel. It [`isrevertible`](@ref) if any of the constituent `transforms` is revertible. In this case, the [`revert`](@ref) is performed with the first revertible transform in the list. # Examples ```julia LowHigh(low=0.3, high=0.6) ⊔ EigenAnalysis(:VDV) ZScore() ⊔ EigenAnalysis(:V) ``` ## Notes * Metadata is transformed with the first revertible transform in the list of `transforms`. """ struct ParallelTableTransform <: TableTransform transforms::Vector{Transform} end # AbstractTrees interface AbstractTrees.nodevalue(::ParallelTableTransform) = ParallelTableTransform AbstractTrees.children(p::ParallelTableTransform) = p.transforms Base.show(io::IO, p::ParallelTableTransform) = print(io, join(p.transforms, " ⊔ ")) function Base.show(io::IO, ::MIME"text/plain", p::ParallelTableTransform) tree = repr_tree(p, context=io) print(io, tree[begin:(end - 1)]) # remove \n at end end isrevertible(p::ParallelTableTransform) = any(isrevertible, p.transforms) function apply(p::ParallelTableTransform, table) # apply transforms in parallel pool = CachingPool(workers()) vals = pmap(t -> apply(t, table), pool, p.transforms) # retrieve tables and caches tables = first.(vals) caches = last.(vals) # features and metadata splits = divide.(tables) feats = first.(splits) metas = last.(splits) # check the number of rows of generated tables _assert(allequal(_nrows(f) for f in feats), "parallel branches must produce the same number of rows") # table with concatenated features newfeat = tablehcat(feats) # propagate metadata newmeta = first(metas) # attach new features and metatada newtable = attach(newfeat, newmeta) # find first revertible transform ind = findfirst(isrevertible, p.transforms) # save info to revert transform rinfo = if isnothing(ind) nothing else fcols = Tables.columns.(feats) fnames = Tables.columnnames.(fcols) ncols = length.(fnames) nrcols = ncols[ind] start = sum(ncols[1:(ind - 1)]) + 1 finish = start + nrcols - 1 range = start:finish (ind, range) end newtable, (caches, rinfo) end function revert(p::ParallelTableTransform, newtable, cache) # retrieve cache caches = cache[1] rinfo = cache[2] _assert(!isnothing(rinfo), "transform is not revertible") # features and metadata newfeat, newmeta = divide(newtable) # retrieve info to revert transform ind = rinfo[1] range = rinfo[2] rtrans = p.transforms[ind] rcache = caches[ind] # columns of transformed table fcols = Tables.columns(newfeat) names = Tables.columnnames(fcols) # subset of features to revert rnames = names[range] rcols = [Tables.getcolumn(fcols, j) for j in range] rfeat = (; zip(rnames, rcols)...) |> Tables.materializer(newfeat) # propagate metadata rtable = attach(rfeat, newmeta) # revert transform revert(rtrans, rtable, rcache) end function reapply(p::ParallelTableTransform, table, cache) # retrieve caches caches = cache[1] # reapply transforms in parallel pool = CachingPool(workers()) tables = pmap((t, c) -> reapply(t, table, c), pool, p.transforms, caches) # features and metadata splits = divide.(tables) feats = first.(splits) metas = last.(splits) # check the number of rows of generated tables _assert(allequal(_nrows(f) for f in feats), "parallel branches must produce the same number of rows") # table with concatenated features newfeat = tablehcat(feats) # metadata of the first table newmeta = first(metas) # attach new features and metatada attach(newfeat, newmeta) end function tablehcat(tables) # concatenate columns allnames = Symbol[] allcolumns = [] for table in tables cols = Tables.columns(table) names = Tables.columnnames(cols) for name in names column = Tables.getcolumn(cols, name) while name ∈ allnames name = Symbol(name, :_) end push!(allnames, name) push!(allcolumns, column) end end # table with concatenated columns 𝒯 = (; zip(allnames, allcolumns)...) 𝒯 |> Tables.materializer(first(tables)) end """ transform₁ ⊔ transform₂ ⊔ ⋯ ⊔ transformₙ Create a [`ParallelTableTransform`](@ref) transform with `[transform₁, transform₂, …, transformₙ]`. """ ⊔(t1::Transform, t2::Transform) = ParallelTableTransform([t1, t2]) ⊔(t1::Transform, t2::ParallelTableTransform) = ParallelTableTransform([t1; t2.transforms]) ⊔(t1::ParallelTableTransform, t2::Transform) = ParallelTableTransform([t1.transforms; t2]) ⊔(t1::ParallelTableTransform, t2::ParallelTableTransform) = ParallelTableTransform([t1.transforms; t2.transforms])
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
5922
# ------------------------------------------------------------------ # Licensed under the MIT License. See LICENSE in the project root. # ------------------------------------------------------------------ """ ProjectionPursuit(; tol=1e-6, maxiter=100, deg=5, perc=0.9, n=100, rng=Random.default_rng()) The projection pursuit multivariate transform converts any multivariate distribution into the standard multivariate Gaussian distribution. This iterative algorithm repeatedly finds a direction of projection `α` that maximizes a score of non-Gaussianity known as the projection index `I(α)`. The samples projected along `α` are then transformed with the [`Quantile`](@ref) transform to remove the non-Gaussian structure. The other coordinates in the rotated orthonormal basis `Q = [α ...]` are left untouched. The non-singularity of `Q` is controlled by assuring that `norm(det(Q)) ≥ tol`. The iterative process terminates whenever the transformed samples are "more Gaussian" than `perc`% of `n` randomly generated samples from the standard multivariate Gaussian distribution, or when the number of iterations reaches a maximum `maxiter`. # Examples ```julia ProjectionPursuit() ProjectionPursuit(deg=10) ProjectionPursuit(perc=0.85, n=50) ProjectionPursuit(tol=1e-4, maxiter=250, deg=5, perc=0.95, n=100) # with rng using Random rng = MersenneTwister(2) ProjectionPursuit(perc=0.85, n=50, rng=rng) ``` See [https://doi.org/10.2307/2289161](https://doi.org/10.2307/2289161) for further details. """ struct ProjectionPursuit{T,RNG} <: StatelessFeatureTransform tol::T maxiter::Int deg::Int perc::T n::Int rng::RNG end ProjectionPursuit(; tol=1e-6, maxiter=100, deg=5, perc=0.9, n=100, rng=Random.default_rng()) = ProjectionPursuit{typeof(tol),typeof(rng)}(tol, maxiter, deg, perc, n, rng) assertions(::ProjectionPursuit) = [scitypeassert(Continuous)] parameters(transform::ProjectionPursuit) = (tol=transform.tol, deg=transform.deg, perc=transform.perc, n=transform.n) isrevertible(::Type{<:ProjectionPursuit}) = true # transforms a row of random variables into a convex combination # of random variables with values in [-1,1] and standard normal distribution rscore(Z, α) = 2 .* cdf.(Normal(), Z * α) .- 1 # projection index of sample along a given direction function pindex(transform, Z, α) d = transform.deg r = rscore(Z, α) I = (3 / 2) * mean(r)^2 if d > 1 Pⱼ₋₂, Pⱼ₋₁ = ones(length(r)), r for j in 2:d Pⱼ₋₂, Pⱼ₋₁ = Pⱼ₋₁, (1 / j) * ((2j - 1) * r .* Pⱼ₋₁ - (j - 1) * Pⱼ₋₂) I += ((2j + 1) / 2) * (mean(Pⱼ₋₁))^2 end end I end # j-th element of the canonical basis in ℝᵈ basis(d, j) = float(1:d .== j) # index for all vectors in the canonical basis function pbasis(transform, Z) q = size(Z, 2) [pindex(transform, Z, basis(q, j)) for j in 1:q] end # projection index of the standard multivariate Gaussian function gaussquantiles(transform, N, q) n = transform.n p = 1.0 - transform.perc rng = transform.rng Is = [pbasis(transform, randn(rng, N, q)) for i in 1:n] I = reduce(hcat, Is) quantile.(eachrow(I), p) end function alphaguess(transform, Z) q = size(Z, 2) # objective function func(α) = pindex(transform, Z, α) # evaluate objective along axes j = argmax(j -> func(basis(q, j)), 1:q) α = basis(q, j) I = func(α) # evaluate objective along diagonals diag(α, s, e) = (1 / √(2 + 2s * α ⋅ e)) * (α + s * e) for eᵢ in basis.(q, 1:q) d₊ = diag(α, +1, eᵢ) d₋ = diag(α, -1, eᵢ) f₊ = func(d₊) f₋ = α ⋅ eᵢ != 1.0 ? func(d₋) : 0.0 f, d = f₊ > f₋ ? (f₊, d₊) : (f₋, d₋) if f > I α = d I = f end end α end function neldermead(transform, Z, α₀) f(α) = -pindex(transform, Z, α ./ norm(α)) optimise(f, α₀, 1 / 2, xtol_rel=10eps()) |> first end function alphamax(transform, Z) α = alphaguess(transform, Z) neldermead(transform, Z, α) end function orthobasis(transform, α) tol = transform.tol rng = transform.rng q = length(α) Q, R = qr([α rand(rng, q, q - 1)]) while norm(diag(R)) < tol Q, R = qr([α rand(rng, q, q - 1)]) end Q end function rmstructure(transform, Z, α) # find orthonormal basis for rotation Q = orthobasis(transform, α) # remove structure of first rotated axis newtable, qcache = apply(Quantile(1), Tables.table(Z * Q)) # undo rotation, i.e recover original axis-aligned features Z₊ = Tables.matrix(newtable) * Q' Z₊, (Q, qcache) end sphering() = Quantile() → EigenAnalysis(:VDV) function applyfeat(transform::ProjectionPursuit, feat, prep) # original columns names cols = Tables.columns(feat) onames = Tables.columnnames(cols) # preprocess the data to approximately spherical shape ptable, pcache = apply(sphering(), feat) # initialize scores and Gaussian quantiles Z = Tables.matrix(ptable) I = pbasis(transform, Z) g = gaussquantiles(transform, size(Z)...) iter = 0 caches = [] while any(I .> g) && iter ≤ transform.maxiter # choose direction with maximum projection index α = alphamax(transform, Z) # remove non-Gaussian structure Z, cache = rmstructure(transform, Z, α) # update the scores along original axes I = pbasis(transform, Z) # store cache and continue push!(caches, cache) iter += 1 end # new column names names = Symbol.(:PP, 1:size(Z, 2)) 𝒯 = (; zip(names, eachcol(Z))...) newtable = 𝒯 |> Tables.materializer(feat) newtable, (pcache, caches, onames) end function revertfeat(::ProjectionPursuit, newfeat, fcache) # caches to retrieve transform steps pcache, caches, onames = fcache Z = Tables.matrix(newfeat) for (Q, qcache) in reverse(caches) table = revert(Quantile(1), Tables.table(Z * Q), qcache) Z = Tables.matrix(table) * Q' end table = revert(sphering(), Tables.table(Z), pcache) Z = Tables.matrix(table) 𝒯 = (; zip(onames, eachcol(Z))...) 𝒯 |> Tables.materializer(newfeat) end
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
2791
# ------------------------------------------------------------------ # Licensed under the MIT License. See LICENSE in the project root. # ------------------------------------------------------------------ """ Quantile(; dist=Normal()) The quantile transform to a given `distribution`. Quantile(col₁, col₂, ..., colₙ; dist=Normal()) Quantile([col₁, col₂, ..., colₙ]; dist=Normal()) Quantile((col₁, col₂, ..., colₙ); dist=Normal()) Applies the Quantile transform on columns `col₁`, `col₂`, ..., `colₙ`. Quantile(regex; dist=Normal()) Applies the Quantile transform on columns that match with `regex`. # Examples ```julia using Distributions Quantile() Quantile(dist=Normal()) Quantile(1, 3, 5, dist=Beta()) Quantile([:a, :c, :e], dist=Gamma()) Quantile(("a", "c", "e"), dist=Beta()) Quantile(r"[ace]", dist=Normal()) ``` """ struct Quantile{S<:ColumnSelector,D} <: ColwiseFeatureTransform selector::S dist::D end Quantile(; dist=Normal()) = Quantile(AllSelector(), dist) Quantile(cols; dist=Normal()) = Quantile(selector(cols), dist) Quantile(cols::C...; dist=Normal()) where {C<:Column} = Quantile(selector(cols), dist) assertions(transform::Quantile) = [scitypeassert(Continuous, transform.selector)] parameters(transform::Quantile) = (; dist=transform.dist) isrevertible(::Type{<:Quantile}) = true function colcache(::Quantile, x) s = qsmooth(x) d = EmpiricalDistribution(s) d, s end function colapply(transform::Quantile, x, c) d, s = c origin, target = d, transform.dist qtransform(s, origin, target) end function colrevert(transform::Quantile, y, c) d, _ = c origin, target = transform.dist, d qtransform(y, origin, target) end # transform samples from original to target distribution function qtransform(samples, origin, target) # avoid evaluating the quantile at 0 or 1 pmin = 0.0 + 1e-3 pmax = 1.0 - 1e-3 map(samples) do sample prob = cdf(origin, sample) quantile(target, clamp(prob, pmin, pmax)) end end # helper function that replaces repated values # by an increasing sequence of values between # the previous and the next non-repated value function qsmooth(values) permut = sortperm(values) sorted = float.(values[permut]) bounds = findall(>(zero(eltype(sorted))), diff(sorted)) if !isempty(bounds) i = 1 j = first(bounds) qlinear!(sorted, i, j, sorted[j], sorted[j + 1]) for k in 1:(length(bounds) - 1) i = bounds[k] + 1 j = bounds[k + 1] qlinear!(sorted, i, j, sorted[i - 1], sorted[j]) end i = last(bounds) + 1 j = length(sorted) qlinear!(sorted, i, j, sorted[i - 1], sorted[j]) end sorted[sortperm(permut)] end function qlinear!(x, i, j, l, u) if i < j for k in i:j x[k] = (u - l) * (k - i) / (j - i) + l end end end
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
2025
# ------------------------------------------------------------------ # Licensed under the MIT License. See LICENCE in the project root. # ------------------------------------------------------------------ """ Remainder([total]) The transform that takes a table with columns `x₁, x₂, …, xₙ` and returns a new table with an additional column containing the remainder value `xₙ₊₁ = total .- (x₁ + x₂ + ⋯ + xₙ)` If the `total` value is not specified, then default to the maximum sum across rows. See also [`Closure`](@ref). """ struct Remainder{T<:Union{Number,Nothing}} <: FeatureTransform total::T end Remainder() = Remainder(nothing) isrevertible(::Type{<:Remainder}) = true assertions(::Remainder) = [scitypeassert(Continuous)] parameters(transform::Remainder) = (; total=transform.total) function applyfeat(transform::Remainder, feat, prep) cols = Tables.columns(feat) names = Tables.columnnames(cols) |> collect # design matrix X = Tables.matrix(feat) # sum of each row S = sum(X, dims=2) # retrieve the total total = if isnothing(transform.total) maximum(S) else t = convert(eltype(X), transform.total) # make sure that the total is valid _assert(all(≤(t), S), "the sum for each row must be less than total") t end # create a column with the remainder Z = [X (total .- S)] # create new column name rname = :remainder while rname ∈ names rname = Symbol(rname, :_) end push!(names, rname) # table with new column 𝒯 = (; zip(names, eachcol(Z))...) newfeat = 𝒯 |> Tables.materializer(feat) newfeat, (total, rname) end function revertfeat(::Remainder, newfeat, fcache) cols = Tables.columns(newfeat) names = Tables.columnnames(cols) _, rname = fcache onames = setdiff(names, [rname]) 𝒯 = (; (nm => Tables.getcolumn(cols, nm) for nm in onames)...) 𝒯 |> Tables.materializer(newfeat) end function reapplyfeat(::Remainder, feat, fcache) total, _ = fcache newfeat, _ = applyfeat(Remainder(total), feat, nothing) newfeat end
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
2710
# ------------------------------------------------------------------ # Licensed under the MIT License. See LICENSE in the project root. # ------------------------------------------------------------------ """ Rename(:col₁ => :newcol₁, :col₂ => :newcol₂, ..., :colₙ => :newcolₙ) Rename([:col₁ => :newcol₁, :col₂ => :newcol₂, ..., :colₙ => :newcolₙ]) Renames the columns `col₁`, `col₂`, ..., `colₙ` to `newcol₁`, `newcol₂`, ..., `newcolₙ`. Rename(fun) Renames the table columns using the modification function `fun` that takes a string as input and returns another string with the new name. # Examples ```julia Rename(1 => :x, 3 => :y) Rename(:a => :x, :c => :y) Rename("a" => "x", "c" => "y") Rename([1 => "x", 3 => "y"]) Rename([:a => "x", :c => "y"]) Rename(["a", "c"] .=> [:x, :y]) Rename(nm -> nm * "_suffix") ``` """ struct Rename{S<:ColumnSelector,N} <: StatelessFeatureTransform selector::S newnames::N function Rename(selector::S, newnames::N) where {S<:ColumnSelector,N} if newnames isa AbstractVector _assert(allunique(newnames), "new names must be unique") end new{S,N}(selector, newnames) end end Rename() = throw(ArgumentError("cannot create Rename transform without arguments")) Rename(fun) = Rename(AllSelector(), fun) Rename(pairs::Pair{C,Symbol}...) where {C<:Column} = Rename(selector(first.(pairs)), collect(last.(pairs))) Rename(pairs::Pair{C,S}...) where {C<:Column,S<:AbstractString} = Rename(selector(first.(pairs)), collect(Symbol.(last.(pairs)))) Rename(pairs::AbstractVector{Pair{C,Symbol}}) where {C<:Column} = Rename(selector(first.(pairs)), last.(pairs)) Rename(pairs::AbstractVector{Pair{C,S}}) where {C<:Column,S<:AbstractString} = Rename(selector(first.(pairs)), Symbol.(last.(pairs))) isrevertible(::Type{<:Rename}) = true _newnames(newnames::AbstractVector{Symbol}, snames) = newnames _newnames(fun, snames) = [Symbol(fun(string(name))) for name in snames] function applyfeat(transform::Rename, feat, prep) cols = Tables.columns(feat) names = Tables.columnnames(cols) snames = transform.selector(names) tnames = _newnames(transform.newnames, snames) _assert(tnames ⊈ setdiff(names, snames), "duplicate names") mapnames = Dict(zip(snames, tnames)) newnames = [get(mapnames, nm, nm) for nm in names] columns = [Tables.getcolumn(cols, nm) for nm in names] 𝒯 = (; zip(newnames, columns)...) newfeat = 𝒯 |> Tables.materializer(feat) newfeat, names end function revertfeat(::Rename, newfeat, fcache) cols = Tables.columns(newfeat) names = Tables.columnnames(cols) columns = [Tables.getcolumn(cols, nm) for nm in names] 𝒯 = (; zip(fcache, columns)...) 𝒯 |> Tables.materializer(newfeat) end
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
3072
# ------------------------------------------------------------------ # Licensed under the MIT License. See LICENSE in the project root. # ------------------------------------------------------------------ """ Replace(cols₁ => pred₁ => new₁, pred₂ => new₂, ..., colsₙ => predₙ => newₙ) Replaces all values where `predᵢ` predicate returns `true` with `newᵢ` value in the the columns selected by `colsᵢ`. Passing a column selection is optional and when omitted all columns in the table will be selected. The column selection can be a single column identifier (index or name), a collection of identifiers, or a regular expression (regex). The predicate can be a function that accepts a single argument and returns a boolean, or a value. If the predicate is a value, it will be transformed into the following function: `x -> x === value`. # Examples ```julia Replace(1 => -1, 5 => -5) Replace(2 => 0.0 => 1.5, 5.0 => 5.5) Replace(:b => 0.0 => 1.5, 5.0 => 5.5) Replace("b" => 0.0 => 1.5, 5.0 => 5.5) Replace([1, 3] => >(5) => 5) Replace([:a, :c] => isequal(2) => -2) Replace(["a", "c"] => (x -> 4 < x < 6) => 0) Replace(r"[abc]" => (x -> isodd(x) && x > 10) => 2) ``` ## Notes * Anonymous functions must be passed with parentheses as in the examples above. * Replacements are applied in the sequence in which they are defined, therefore, if there is more than one replacement for the same column, the first valid one will be applied. """ struct Replace <: StatelessFeatureTransform selectors::Vector{ColumnSelector} preds::Vector{Function} news::Vector{Any} end Replace() = throw(ArgumentError("cannot create Replace transform without arguments")) # utility functions _extract(p::Pair) = AllSelector(), _pred(first(p)), last(p) _extract(p::Pair{<:Any,<:Pair}) = selector(first(p)), _pred(first(last(p))), last(last(p)) _pred(f::Function) = f _pred(v) = Base.Fix2(===, v) function Replace(pairs::Pair...) tuples = map(_extract, pairs) selectors = [t[1] for t in tuples] preds = [t[2] for t in tuples] news = Any[t[3] for t in tuples] Replace(selectors, preds, news) end isrevertible(::Type{<:Replace}) = false function applyfeat(transform::Replace, feat, prep) cols = Tables.columns(feat) names = Tables.columnnames(cols) selectors = transform.selectors preds = transform.preds news = transform.news # preprocess all replacements prepreps = map(selectors, preds, news) do selector, pred, new snames = selector(names) snames => pred => new end # join replacements of each column colreps = map(names) do name pairs = filter(p -> name ∈ first(p), prepreps) reps = isempty(pairs) ? nothing : map(last, pairs) name => reps end columns = map(colreps) do (name, reps) x = Tables.getcolumn(cols, name) if isnothing(reps) x else map(x) do v for (pred, new) in reps if pred(v) return new end end v end end end 𝒯 = (; zip(names, columns)...) newfeat = 𝒯 |> Tables.materializer(feat) newfeat, nothing end
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
514
# ------------------------------------------------------------------ # Licensed under the MIT License. See LICENSE in the project root. # ------------------------------------------------------------------ """ RowTable() The transform that applies the function `Tables.rowtable` to to the input table. """ struct RowTable <: StatelessFeatureTransform end isrevertible(::Type{RowTable}) = true applyfeat(::RowTable, feat, prep) = Tables.rowtable(feat), feat revertfeat(::RowTable, newfeat, fcache) = fcache
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
1884
# ------------------------------------------------------------------ # Licensed under the MIT License. See LICENSE in the project root. # ------------------------------------------------------------------ """ Sample(size, [weights]; replace=true, ordered=false, rng=default_rng()) Sample `size` rows of table using `weights` with or without replacement depending on the option `replace`. The option `ordered` can be used to return samples in the same order of the original table. # Examples ```julia Sample(1000) Sample(1000, replace=false) Sample(1000, replace=false, ordered=true) # with rng using Random rng = MersenneTwister(2) Sample(1000, rng=rng) # with weights Sample(10, rand(100)) ``` """ struct Sample{W,RNG} <: StatelessFeatureTransform size::Int weights::W replace::Bool ordered::Bool rng::RNG end Sample(size::Int; replace=false, ordered=false, rng=Random.default_rng()) = Sample(size, nothing, replace, ordered, rng) Sample(size::Int, weights::AbstractWeights; replace=false, ordered=false, rng=Random.default_rng()) = Sample(size, weights, replace, ordered, rng) Sample(size::Int, weights; kwargs...) = Sample(size, Weights(collect(weights)); kwargs...) isrevertible(::Type{<:Sample}) = false function preprocess(transform::Sample, feat) # retrieve valid indices inds = 1:_nrows(feat) size = transform.size weights = transform.weights replace = transform.replace ordered = transform.ordered rng = transform.rng # sample a subset of indices sinds = if isnothing(weights) sample(rng, inds, size; replace, ordered) else sample(rng, inds, weights, size; replace, ordered) end sinds end function applyfeat(::Sample, feat, prep) # preprocessed indices sinds = prep # selected rows srows = Tables.subset(feat, sinds, viewhint=true) newfeat = srows |> Tables.materializer(feat) newfeat, nothing end
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
1256
# ------------------------------------------------------------------ # Licensed under the MIT License. See LICENSE in the project root. # ------------------------------------------------------------------ """ Satisfies(pred) Selects the columns where `pred(column)` returns `true`. # Examples ```julia Satisfies(allunique) Satisfies(x -> sum(x) > 100) Satisfies(x -> eltype(x) <: Integer) ``` """ struct Satisfies{F} <: StatelessFeatureTransform pred::F end isrevertible(::Type{<:Satisfies}) = false function applyfeat(transform::Satisfies, feat, prep) pred = transform.pred cols = Tables.columns(feat) names = Tables.columnnames(cols) snames = filter(names) do name x = Tables.getcolumn(cols, name) pred(x) end strans = Select(snames) newfeat, _ = applyfeat(strans, feat, prep) newfeat, nothing end """ Only(S) Selects the columns that have scientific type `S`. # Examples ```julia using DataScienceTraits Only(Continuous) ``` """ Only(S::Type{<:SciType}) = Satisfies(x -> elscitype(x) <: S) """ Except(S) Selects the columns that don't have scientific type `S`. # Examples ```julia using DataScienceTraits Except(Categorical) ``` """ Except(S::Type{<:SciType}) = Satisfies(x -> !(elscitype(x) <: S))
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
2821
# ------------------------------------------------------------------ # Licensed under the MIT License. See LICENSE in the project root. # ------------------------------------------------------------------ """ Select(col₁, col₂, ..., colₙ) Select([col₁, col₂, ..., colₙ]) Select((col₁, col₂, ..., colₙ)) The transform that selects columns `col₁`, `col₂`, ..., `colₙ`. Select(col₁ => newcol₁, col₂ => newcol₂, ..., colₙ => newcolₙ) Selects the columns `col₁`, `col₂`, ..., `colₙ` and rename them to `newcol₁`, `newcol₂`, ..., `newcolₙ`. Select(regex) Selects the columns that match with `regex`. # Examples ```julia Select(1, 3, 5) Select([:a, :c, :e]) Select(("a", "c", "e")) Select(1 => :x, 3 => :y) Select(:a => :x, :b => :y) Select("a" => "x", "b" => "y") Select(r"[ace]") ``` """ struct Select{S<:ColumnSelector} <: StatelessFeatureTransform selector::S newnames::Union{Vector{Symbol},Nothing} end Select(spec) = Select(selector(spec), nothing) Select(cols::C...) where {C<:Column} = Select(cols) Select(pairs::Pair{C,Symbol}...) where {C<:Column} = Select(selector(first.(pairs)), collect(last.(pairs))) Select(pairs::Pair{C,S}...) where {C<:Column,S<:AbstractString} = Select(selector(first.(pairs)), collect(Symbol.(last.(pairs)))) Select() = throw(ArgumentError("cannot create Select transform without arguments")) isrevertible(::Type{<:Select}) = false # utils _newnames(::Nothing, select) = select _newnames(names::Vector{Symbol}, select) = names function applyfeat(transform::Select, feat, prep) cols = Tables.columns(feat) names = collect(Tables.columnnames(cols)) select = transform.selector(names) newnames = _newnames(transform.newnames, select) newfeat = TableSelection(feat, newnames, select) newfeat, nothing end """ Reject(col₁, col₂, ..., colₙ) Reject([col₁, col₂, ..., colₙ]) Reject((col₁, col₂, ..., colₙ)) The transform that discards columns `col₁`, `col₂`, ..., `colₙ`. Reject(regex) Discards the columns that match with `regex`. # Examples ```julia Reject(:b, :d, :f) Reject(["b", "d", "f"]) Reject((2, 4, 6)) Reject(r"[bdf]") ``` """ struct Reject{S<:ColumnSelector} <: StatelessFeatureTransform selector::S end Reject(cols) = Reject(selector(cols)) Reject(cols::C...) where {C<:Column} = Reject(selector(cols)) # argument errors Reject() = throw(ArgumentError("cannot create Reject transform without arguments")) Reject(::AllSelector) = throw(ArgumentError("cannot reject all columns")) isrevertible(::Type{<:Reject}) = false function applyfeat(transform::Reject, feat, prep) cols = Tables.columns(feat) names = Tables.columnnames(cols) reject = transform.selector(names) select = setdiff(names, reject) strans = Select(select) newfeat, _ = applyfeat(strans, feat, prep) newfeat, nothing end
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
1610
# ------------------------------------------------------------------ # Licensed under the MIT License. See LICENSE in the project root. # ------------------------------------------------------------------ """ Sort(col₁, col₂, ..., colₙ; kwargs...) Sort([col₁, col₂, ..., colₙ]; kwargs...) Sort((col₁, col₂, ..., colₙ); kwargs...) Sort the rows of selected columns `col₁`, `col₂`, ..., `colₙ` by forwarding the `kwargs` to the `sortperm` function. Sort(regex; kwargs...) Sort the rows of columns that match with `regex`. # Examples ```julia Sort(:a) Sort(:a, :c, rev=true) Sort([1, 3, 5], by=row -> abs.(row)) Sort(("a", "c", "e")) Sort(r"[ace]") ``` """ struct Sort{S<:ColumnSelector,T} <: StatelessFeatureTransform selector::S kwargs::T end Sort(cols; kwargs...) = Sort(selector(cols), values(kwargs)) Sort(cols::C...; kwargs...) where {C<:Column} = Sort(selector(cols), values(kwargs)) Sort(; kwargs...) = throw(ArgumentError("cannot create Sort transform without arguments")) isrevertible(::Type{<:Sort}) = false function preprocess(transform::Sort, feat) cols = Tables.columns(feat) names = Tables.columnnames(cols) snames = transform.selector(names) # use selected columns to calculate new indices scols = Tables.getcolumn.(Ref(cols), snames) stups = collect(zip(scols...)) sortperm(stups; transform.kwargs...) end function applyfeat(::Sort, feat, prep) # collect all rows rows = Tables.rowtable(feat) # sorting indices sinds = prep # sorted rows srows = view(rows, sinds) newfeat = srows |> Tables.materializer(feat) newfeat, nothing end
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
1390
# ------------------------------------------------------------------ # Licensed under the MIT License. See LICENSE in the project root. # ------------------------------------------------------------------ """ StdFeats() Standardizes the columns of the table based on scientific types: * `Continuous`: `ZScore` * `Categorical`: `Identity` * `Unknown`: `Identity` """ struct StdFeats <: StatelessFeatureTransform end isrevertible(::Type{StdFeats}) = true _stdfun(x) = _stdfun(elscitype(x), x) _stdfun(::Type, x) = identity, identity function _stdfun(::Type{Continuous}, x) μ = mean(x) σ = std(x, mean=μ) stdfun = x -> zscore(x, μ, σ) revfun = y -> revzscore(y, μ, σ) stdfun, revfun end function applyfeat(::StdFeats, feat, prep) cols = Tables.columns(feat) names = Tables.columnnames(cols) tuples = map(names) do name x = Tables.getcolumn(cols, name) stdfun, revfun = _stdfun(x) stdfun(x), revfun end columns = first.(tuples) fcache = last.(tuples) 𝒯 = (; zip(names, columns)...) newfeat = 𝒯 |> Tables.materializer(feat) newfeat, fcache end function revertfeat(::StdFeats, newfeat, fcache) cols = Tables.columns(newfeat) names = Tables.columnnames(cols) columns = map(names, fcache) do name, revfun y = Tables.getcolumn(cols, name) revfun(y) end 𝒯 = (; zip(names, columns)...) 𝒯 |> Tables.materializer(newfeat) end
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
3173
# ------------------------------------------------------------------ # Licensed under the MIT License. See LICENSE in the project root. # ------------------------------------------------------------------ const SPECS = [:uppersnake, :uppercamel, :upperflat, :snake, :camel, :flat] """ StdNames(spec = :uppersnake) Standardizes column names according to given `spec`. Default to `:uppersnake` case specification. # Specs * `:uppersnake` - Upper Snake Case, e.g. COLUMN_NAME * `:uppercamel` - Upper Camel Case, e.g. ColumnName * `:upperflat` - Upper Flat Case, e.g. COLUMNNAME * `:snake` - Snake Case, e.g. column_name * `:camel` - Camel Case, e.g. columnName * `:flat` - Flat Case, e.g. columnname """ struct StdNames <: StatelessFeatureTransform spec::Symbol function StdNames(spec=:uppersnake) if spec ∉ SPECS throw(ArgumentError("invalid specification, use one of these: $SPECS")) end new(spec) end end isrevertible(::Type{StdNames}) = true function applyfeat(transform::StdNames, feat, prep) # retrieve spec spec = transform.spec # retrieve column names cols = Tables.columns(feat) oldnames = Tables.columnnames(cols) # clean column names names = map(nm -> _clean(string(nm)), oldnames) # apply spec spec === :uppersnake && (names = _uppersnake.(names)) spec === :uppercamel && (names = _uppercamel.(names)) spec === :upperflat && (names = _upperflat.(names)) spec === :snake && (names = _snake.(names)) spec === :camel && (names = _camel.(names)) spec === :flat && (names = _flat.(names)) # make names unique newnames = _makeunique(names) # rename transform rtrans = Rename(selector(oldnames), Symbol.(newnames)) newfeat, rfcache = applyfeat(rtrans, feat, prep) newfeat, (rtrans, rfcache) end function revertfeat(::StdNames, newfeat, fcache) rtrans, rfcache = fcache revertfeat(rtrans, newfeat, rfcache) end const DELIMS = [' ', '\t', '-', '_'] function _clean(name) nm = strip(name, DELIMS) filter(c -> isdigit(c) || isletter(c) || c ∈ DELIMS, nm) end function _makeunique(names) newnames = String[] for name in names while name ∈ newnames name = name * "_" end push!(newnames, name) end newnames end _uppersnake(name) = _isuppersnake(name) ? name : join(uppercase.(split(name, DELIMS)), '_') _uppercamel(name) = _isuppercamel(name) ? name : join(titlecase.(split(name, DELIMS))) _upperflat(name) = _isupperflat(name) ? name : replace(uppercase(name), DELIMS => "") _snake(name) = _issnake(name) ? name : join(lowercase.(split(name, DELIMS)), '_') function _camel(name) _iscamel(name) && return name first, others... = split(name, DELIMS) join([lowercase(first); titlecase.(others)]) end _flat(name) = _isflat(name) ? name : replace(lowercase(name), DELIMS => "") _isuppersnake(name) = occursin(r"^[A-Z0-9]+(_[A-Z0-9]+)+$", name) _isuppercamel(name) = occursin(r"^[A-Z][a-z0-9]*([A-Z][a-z0-9]*)+$", name) _isupperflat(name) = occursin(r"^[A-Z0-9]+$", name) _issnake(name) = occursin(r"^[a-z0-9]+(_[a-z0-9]+)+$", name) _iscamel(name) = occursin(r"^[a-z][a-z0-9]*([A-Z][a-z0-9]*)+$", name) _isflat(name) = occursin(r"^[a-z0-9]+$", name)
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
2315
# ------------------------------------------------------------------ # Licensed under the MIT License. See LICENSE in the project root. # ------------------------------------------------------------------ """ Unit(unit) Converts the units of all columns in the table to `unit`. Unit(cols₁ => unit₁, cols₂ => unit₂, ..., colsₙ => unitₙ) Converts the units of selected columns `cols₁`, `cols₂`, ..., `colsₙ` to `unit₁`, `unit₂`, ... `unitₙ`. The column selection can be a single column identifier (index or name), a collection of identifiers or a regular expression (regex). # Examples ```julia Unit(u"m") Unit(1 => u"km", :b => u"K", "c" => u"s") Unit([2, 3] => u"cm") Unit([:a, :c] => u"cm") Unit(["a", "c"] => u"cm") Unit(r"[abc]" => u"km") ``` """ struct Unit <: StatelessFeatureTransform selectors::Vector{ColumnSelector} units::Vector{Units} end Unit() = throw(ArgumentError("cannot create Unit transform without arguments")) Unit(unit::Units) = Unit([AllSelector()], [unit]) Unit(pairs::Pair...) = Unit(collect(selector.(first.(pairs))), collect(last.(pairs))) isrevertible(::Type{<:Unit}) = true _uconvert(u, x) = _uconvert(nonmissingtype(eltype(x)), u, x) _uconvert(::Type, _, x) = (x, nothing) _uconvert(::Type{Q}, u, x) where {Q<:AbstractQuantity} = (map(v -> uconvert(u, v), x), unit(Q)) function applyfeat(transform::Unit, feat, prep) cols = Tables.columns(feat) names = Tables.columnnames(cols) selectors = transform.selectors units = transform.units pairs = mapreduce(vcat, selectors, units) do selector, u snames = selector(names) snames .=> u end unitdict = Dict(pairs) tuples = map(names) do name x = Tables.getcolumn(cols, name) if haskey(unitdict, name) u = unitdict[name] _uconvert(u, x) else (x, nothing) end end columns = first.(tuples) ounits = last.(tuples) 𝒯 = (; zip(names, columns)...) newfeat = 𝒯 |> Tables.materializer(feat) newfeat, ounits end function revertfeat(::Unit, newfeat, fcache) cols = Tables.columns(newfeat) names = Tables.columnnames(cols) ounits = fcache columns = map(names, ounits) do name, u x = Tables.getcolumn(cols, name) isnothing(u) ? x : map(v -> uconvert(u, v), x) end 𝒯 = (; zip(names, columns)...) 𝒯 |> Tables.materializer(newfeat) end
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
1677
# ------------------------------------------------------------------ # Licensed under the MIT License. See LICENSE in the project root. # ------------------------------------------------------------------ """ Unitify() Add units to columns of the table using bracket syntax. A column named `col [unit]` will be renamed to a unitful column `col` with a valid `unit` from Unitful.jl. In the case that the `unit` is not recognized by Unitful.jl, no units are added. Empty brackets are also allowed to represent columns without units, e.g. `col []`. """ struct Unitify <: StatelessFeatureTransform end isrevertible(::Type{Unitify}) = true function _unitify(name) m = match(r"(.*)\[(.*)\]", string(name)) if !isnothing(m) namestr, unitstr = m.captures newname = Symbol(strip(namestr)) unit = if !isempty(unitstr) try uparse(unitstr) catch @warn "The unit \"$unitstr\" is not valid" NoUnits end else NoUnits end newname, unit else name, NoUnits end end function applyfeat(::Unitify, feat, prep) cols = Tables.columns(feat) names = Tables.columnnames(cols) pairs = map(names) do name x = Tables.getcolumn(cols, name) newname, unit = _unitify(name) newname => _addunit(x, unit) end newfeat = (; pairs...) |> Tables.materializer(feat) newfeat, names end function revertfeat(::Unitify, newfeat, fcache) cols = Tables.columns(newfeat) names = Tables.columnnames(cols) onames = fcache ocolumns = map(names) do name x = Tables.getcolumn(cols, name) first(_dropunit(x)) end 𝒯 = (; zip(onames, ocolumns)...) 𝒯 |> Tables.materializer(newfeat) end
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
526
# ------------------------------------------------------------------ # Licensed under the MIT License. See LICENSE in the project root. # ------------------------------------------------------------------ zscore(x, μ, σ) = @. (x - μ) / σ revzscore(y, μ, σ) = @. σ * y + μ _assert(cond, msg) = cond || throw(AssertionError(msg)) function scitypeassert(S, selector=AllSelector()) Assert( selector, cond=x -> elscitype(x) <: S, msg=nm -> "the elements of the column '$nm' are not of scientific type $S" ) end
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
1305
# ------------------------------------------------------------------ # Licensed under the MIT License. See LICENSE in the project root. # ------------------------------------------------------------------ """ ZScore() Applies the z-score transform (a.k.a. normal score) to all columns of the table. The z-score transform of the column `x`, with mean `μ` and standard deviation `σ`, is defined by `(x .- μ) ./ σ`. ZScore(col₁, col₂, ..., colₙ) ZScore([col₁, col₂, ..., colₙ]) ZScore((col₁, col₂, ..., colₙ)) Applies the ZScore transform on columns `col₁`, `col₂`, ..., `colₙ`. ZScore(regex) Applies the ZScore transform on columns that match with `regex`. # Examples ```julia ZScore(1, 3, 5) ZScore([:a, :c, :e]) ZScore(("a", "c", "e")) ZScore(r"[ace]") ``` """ struct ZScore{S<:ColumnSelector} <: ColwiseFeatureTransform selector::S end ZScore() = ZScore(AllSelector()) ZScore(cols) = ZScore(selector(cols)) ZScore(cols::C...) where {C<:Column} = ZScore(selector(cols)) assertions(transform::ZScore) = [scitypeassert(Continuous, transform.selector)] isrevertible(::Type{<:ZScore}) = true function colcache(::ZScore, x) μ = mean(x) σ = std(x, mean=μ) (μ=μ, σ=σ) end colapply(::ZScore, x, c) = zscore(x, c.μ, c.σ) colrevert(::ZScore, y, c) = revzscore(y, c.μ, c.σ)
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
760
# ------------------------------------------------------------------ # Licensed under the MIT License. See LICENSE in the project root. # ------------------------------------------------------------------ """ ALR([refvar]) Additive log-ratio transform. Optionally, specify the reference variable `refvar` for the ratios. Default to the last column of the input table. """ struct ALR{T<:Union{Symbol,Nothing}} <: LogRatio refvar::T end ALR() = ALR(nothing) refvar(transform::ALR, names) = isnothing(transform.refvar) ? last(names) : transform.refvar newvars(::ALR, names) = Symbol.(:ARL, 1:(length(names) - 1)) applymatrix(::ALR, X) = mapslices(alr ∘ Composition, X, dims=2) revertmatrix(::ALR, Y) = mapslices(CoDa.components ∘ alrinv, Y, dims=2)
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
512
# ------------------------------------------------------------------ # Licensed under the MIT License. See LICENSE in the project root. # ------------------------------------------------------------------ """ CLR() Centered log-ratio transform. """ struct CLR <: LogRatio end refvar(::CLR, names) = last(names) newvars(::CLR, names) = Symbol.(:CLR, 1:length(names)) applymatrix(::CLR, X) = mapslices(clr ∘ Composition, X, dims=2) revertmatrix(::CLR, Y) = mapslices(CoDa.components ∘ clrinv, Y, dims=2)
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
761
# ------------------------------------------------------------------ # Licensed under the MIT License. See LICENSE in the project root. # ------------------------------------------------------------------ """ ILR([refvar]) Isometric log-ratio transform. Optionally, specify the reference variable `refvar` for the ratios. Default to the last column of the input table. """ struct ILR{T<:Union{Symbol,Nothing}} <: LogRatio refvar::T end ILR() = ILR(nothing) refvar(transform::ILR, names) = isnothing(transform.refvar) ? last(names) : transform.refvar newvars(::ILR, names) = Symbol.(:ILR, 1:(length(names) - 1)) applymatrix(::ILR, X) = mapslices(ilr ∘ Composition, X, dims=2) revertmatrix(::ILR, Y) = mapslices(CoDa.components ∘ ilrinv, Y, dims=2)
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
193
@testset "Distributions" begin values = randn(1000) d = TT.EmpiricalDistribution(values) @test 0.0 ≤ cdf(d, rand()) ≤ 1.0 @test minimum(values) ≤ quantile(d, 0.5) ≤ maximum(values) end
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
2570
@testset "Metadata" begin @testset "ConstMeta" begin a = rand(10) b = rand(10) c = rand(10) d = rand(10) t = Table(; a, b, c, d) m = ConstMeta(fill(1, 10)) mt = MetaTable(t, m) T = Select(1, 3) mn, mc = apply(T, mt) tn, tc = apply(T, t) @test mn.meta == m @test mn.table == tn T = Rename(:a => :x, :c => :y) mn, mc = apply(T, mt) tn, tc = apply(T, t) @test mn.meta == m @test mn.table == tn mtₒ = revert(T, mn, mc) @test mtₒ == mt T = Functional(exp) mn, mc = apply(T, mt) tn, tc = apply(T, t) @test mn.meta == m @test mn.table == tn mtₒ = revert(T, mn, mc) @test mtₒ.meta == mt.meta @test Tables.matrix(mtₒ.table) ≈ Tables.matrix(mt.table) T = (Functional(exp) → MinMax()) ⊔ Center() mn, mc = apply(T, mt) tn, tc = apply(T, t) @test mn.meta == m @test mn.table == tn mtₒ = revert(T, mn, mc) @test mtₒ.meta == mt.meta @test Tables.matrix(mtₒ.table) ≈ Tables.matrix(mt.table) end @testset "VarMeta" begin a = rand(10) b = rand(10) c = rand(10) d = rand(10) t = Table(; a, b, c, d) m = VarMeta(fill(1, 10)) mt = MetaTable(t, m) T = Reject(1, 3) mn, mc = apply(T, mt) tn, tc = apply(T, t) @test mn.meta == VarMeta(m.data .+ 2) @test mn.table == tn T = Rename(:b => :x, :d => :y) mn, mc = apply(T, mt) tn, tc = apply(T, t) @test mn.meta == VarMeta(m.data .+ 2) @test mn.table == tn mtₒ = revert(T, mn, mc) @test mtₒ == mt T = Functional(exp) mn, mc = apply(T, mt) tn, tc = apply(T, t) @test mn.meta == VarMeta(m.data .+ 2) @test mn.table == tn mtₒ = revert(T, mn, mc) @test mtₒ.meta == mt.meta @test Tables.matrix(mtₒ.table) ≈ Tables.matrix(mt.table) # first revertible branch has two transforms, # so metadata is increased by 2 + 2 = 4 T = (Functional(exp) → MinMax()) ⊔ Center() mn, mc = apply(T, mt) tn, tc = apply(T, t) @test mn.meta == VarMeta(m.data .+ 4) @test mn.table == tn mtₒ = revert(T, mn, mc) @test mtₒ.meta == mt.meta @test Tables.matrix(mtₒ.table) ≈ Tables.matrix(mt.table) # first revertible branch has one transform, # so metadata is increased by 2 T = Center() ⊔ (Functional(exp) → MinMax()) mn, mc = apply(T, mt) tn, tc = apply(T, t) @test mn.meta == VarMeta(m.data .+ 2) @test mn.table == tn mtₒ = revert(T, mn, mc) @test mtₒ.meta == mt.meta @test Tables.matrix(mtₒ.table) ≈ Tables.matrix(mt.table) end end
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
829
# meta tables abstract type Metadata end struct VarMeta <: Metadata data::Vector{Int} end struct ConstMeta <: Metadata data::Vector{Int} end Base.:(==)(a::Metadata, b::Metadata) = a.data == b.data struct MetaTable{T,M<:Metadata} table::T meta::M end Base.:(==)(a::MetaTable, b::MetaTable) = a.table == b.table && a.meta == b.meta TT.divide(metatable::MetaTable) = metatable.table, metatable.meta TT.attach(feat, meta::Metadata) = MetaTable(feat, meta) function TT.applymeta(::TT.FeatureTransform, meta::VarMeta, prep) VarMeta(meta.data .+ 2), nothing end function TT.revertmeta(::TT.FeatureTransform, newmeta::VarMeta, mcache) VarMeta(newmeta.data .- 2) end TT.applymeta(::TT.FeatureTransform, meta::ConstMeta, prep) = meta, nothing TT.revertmeta(::TT.FeatureTransform, newmeta::ConstMeta, mcache) = newmeta
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
1230
using TableTransforms using CoDa using Tables using Unitful using TypedTables using CategoricalArrays using LinearAlgebra using Distributions using StatsBase using Statistics using DelimitedFiles using ReferenceTests using PairPlots using ImageIO using Random using Test import CairoMakie as Mke import ColumnSelectors as CS import DataScienceTraits as DST const TT = TableTransforms # set default configurations for plots Mke.activate!(type="png") # environment settings isCI = "CI" ∈ keys(ENV) islinux = Sys.islinux() visualtests = !isCI || (isCI && islinux) datadir = joinpath(@__DIR__, "data") # using MersenneTwister for backward # compatibility with old Julia versions rng = MersenneTwister(42) # for functor tests in Functional testset struct Polynomial{T<:Real} coeffs::Vector{T} end Polynomial(args::T...) where {T<:Real} = Polynomial(collect(args)) (p::Polynomial)(x) = sum(a * x^(i - 1) for (i, a) in enumerate(p.coeffs)) include("metatable.jl") # list of tests testfiles = ["distributions.jl", "tableselection.jl", "tablerows.jl", "transforms.jl", "metadata.jl", "shows.jl"] @testset "TableTransforms.jl" begin for testfile in testfiles println("Testing $testfile...") include(testfile) end end
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
14528
@testset "Shows" begin @testset "Assert" begin T = Assert(:a, :b, :c, cond=allunique) # compact mode iostr = sprint(show, T) @test iostr == "Assert(selector: [:a, :b, :c], cond: allunique, msg: \"\")" # full mode iostr = sprint(show, MIME("text/plain"), T) @test iostr == """ Assert transform ├─ selector: [:a, :b, :c] ├─ cond: allunique └─ msg: \"\"""" end @testset "Select" begin T = Select(:a, :b, :c) # compact mode iostr = sprint(show, T) @test iostr == "Select(selector: [:a, :b, :c], newnames: nothing)" # full mode iostr = sprint(show, MIME("text/plain"), T) @test iostr == """ Select transform ├─ selector: [:a, :b, :c] └─ newnames: nothing""" # selection with renaming T = Select(:a => :x, :b => :y) # compact mode iostr = sprint(show, T) @test iostr == "Select(selector: [:a, :b], newnames: [:x, :y])" # full mode iostr = sprint(show, MIME("text/plain"), T) @test iostr == """ Select transform ├─ selector: [:a, :b] └─ newnames: [:x, :y]""" end @testset "Reject" begin T = Reject(:a, :b, :c) # compact mode iostr = sprint(show, T) @test iostr == "Reject(selector: [:a, :b, :c])" # full mode iostr = sprint(show, MIME("text/plain"), T) @test iostr == """ Reject transform └─ selector: [:a, :b, :c]""" end @testset "Satisfies" begin T = Satisfies(allunique) # compact mode iostr = sprint(show, T) @test iostr == "Satisfies(pred: allunique)" # full mode iostr = sprint(show, MIME("text/plain"), T) @test iostr == """ Satisfies transform └─ pred: allunique""" end @testset "Rename" begin T = Rename(:a => :x, :c => :y) # compact mode iostr = sprint(show, T) @test iostr == "Rename(selector: [:a, :c], newnames: [:x, :y])" # full mode iostr = sprint(show, MIME("text/plain"), T) @test iostr == """ Rename transform ├─ selector: [:a, :c] └─ newnames: [:x, :y]""" end @testset "StdNames" begin T = StdNames(:upperflat) # compact mode iostr = sprint(show, T) @test iostr == "StdNames(spec: :upperflat)" # full mode iostr = sprint(show, MIME("text/plain"), T) @test iostr == """ StdNames transform └─ spec: :upperflat""" end @testset "StdFeats" begin T = StdFeats() # compact mode iostr = sprint(show, T) @test iostr == "StdFeats()" # full mode iostr = sprint(show, MIME("text/plain"), T) @test iostr == "StdFeats transform" end @testset "Sort" begin T = Sort([:a, :c], rev=true) # compact mode iostr = sprint(show, T) @test iostr == "Sort(selector: [:a, :c], kwargs: (rev = true,))" # full mode iostr = sprint(show, MIME("text/plain"), T) @test iostr == """ Sort transform ├─ selector: [:a, :c] └─ kwargs: (rev = true,)""" end @testset "Sample" begin T = Sample(30, replace=false, ordered=true) # compact mode iostr = sprint(show, T) @test iostr == "Sample(size: 30, weights: nothing, replace: false, ordered: true, rng: TaskLocalRNG())" # full mode iostr = sprint(show, MIME("text/plain"), T) @test iostr == """ Sample transform ├─ size: 30 ├─ weights: nothing ├─ replace: false ├─ ordered: true └─ rng: TaskLocalRNG()""" end @testset "Filter" begin pred = row -> row.c ≥ 2 && row.e > 4 T = Filter(pred) # compact mode iostr = sprint(show, T) @test iostr == "Filter(pred: $(nameof(pred)))" # full mode iostr = sprint(show, MIME("text/plain"), T) @test iostr == """ Filter transform └─ pred: $(typeof(pred))()""" end @testset "DropMissing" begin T = DropMissing(:a, :b, :c) # compact mode iostr = sprint(show, T) @test iostr == "DropMissing(selector: [:a, :b, :c])" # full mode iostr = sprint(show, MIME("text/plain"), T) @test iostr == """ DropMissing transform └─ selector: [:a, :b, :c]""" end @testset "DropNaN" begin T = DropNaN(:a, :b, :c) # compact mode iostr = sprint(show, T) @test iostr == "DropNaN(selector: [:a, :b, :c])" # full mode iostr = sprint(show, MIME("text/plain"), T) @test iostr == """ DropNaN transform └─ selector: [:a, :b, :c]""" end @testset "DropExtrema" begin T = DropExtrema("a", low=0.25, high=0.75) # compact mode iostr = sprint(show, T) @test iostr == "DropExtrema(selector: [:a], low: 0.25, high: 0.75)" # full mode iostr = sprint(show, MIME("text/plain"), T) @test iostr == """ DropExtrema transform ├─ selector: [:a] ├─ low: 0.25 └─ high: 0.75""" end @testset "DropUnits" begin T = DropUnits(:a, :b, :c) # compact mode iostr = sprint(show, T) @test iostr == "DropUnits(selector: [:a, :b, :c])" # full mode iostr = sprint(show, MIME("text/plain"), T) @test iostr == """ DropUnits transform └─ selector: [:a, :b, :c]""" end @testset "DropConstant" begin T = DropConstant() # compact mode iostr = sprint(show, T) @test iostr == "DropConstant()" # full mode iostr = sprint(show, MIME("text/plain"), T) @test iostr == "DropConstant transform" end @testset "AbsoluteUnits" begin T = AbsoluteUnits(:a, :b, :c) # compact mode iostr = sprint(show, T) @test iostr == "AbsoluteUnits(selector: [:a, :b, :c])" # full mode iostr = sprint(show, MIME("text/plain"), T) @test iostr == """ AbsoluteUnits transform └─ selector: [:a, :b, :c]""" end @testset "Unitify" begin T = Unitify() # compact mode iostr = sprint(show, T) @test iostr == "Unitify()" # full mode iostr = sprint(show, MIME("text/plain"), T) @test iostr == "Unitify transform" end @testset "Unit" begin T = Unit(:a => u"m", [:b, :c] => u"s") # compact mode iostr = sprint(show, T) @test iostr == "Unit(selectors: ColumnSelector[:a, [:b, :c]], units: Units[m, s])" # full mode iostr = sprint(show, MIME("text/plain"), T) @test iostr == """ Unit transform ├─ selectors: ColumnSelectors.ColumnSelector[:a, [:b, :c]] └─ units: Unitful.Units[m, s]""" end @testset "Map" begin fun = (a, b) -> 2a + b T = Map(:a => sin, [:a, :b] => fun => :c) # compact mode iostr = sprint(show, T) @test iostr == "Map(selectors: ColumnSelector[:a, [:a, :b]], funs: Function[sin, $(nameof(fun))], targets: Union{Nothing, Symbol}[nothing, :c])" # full mode iostr = sprint(show, MIME("text/plain"), T) @test iostr == """ Map transform ├─ selectors: ColumnSelectors.ColumnSelector[:a, [:a, :b]] ├─ funs: Function[sin, $(typeof(fun))()] └─ targets: Union{Nothing, Symbol}[nothing, :c]""" end @testset "Replace" begin T = Replace(1 => -1, 5 => -5) # compact mode iostr = sprint(show, T) @test iostr == "Replace(selectors: ColumnSelector[all, all], preds: Function[Fix2{typeof(===), Int64}(===, 1), Fix2{typeof(===), Int64}(===, 5)], news: Any[-1, -5])" # full mode iostr = sprint(show, MIME("text/plain"), T) @test iostr == """ Replace transform ├─ selectors: ColumnSelectors.ColumnSelector[all, all] ├─ preds: Function[Base.Fix2{typeof(===), Int64}(===, 1), Base.Fix2{typeof(===), Int64}(===, 5)] └─ news: Any[-1, -5]""" end @testset "Coalesce" begin T = Coalesce(value=0) # compact mode iostr = sprint(show, T) @test iostr == "Coalesce(selector: all, value: 0)" # full mode iostr = sprint(show, MIME("text/plain"), T) @test iostr == """ Coalesce transform ├─ selector: all └─ value: 0""" end @testset "Coerce" begin T = Coerce(:a => DST.Continuous, :b => DST.Categorical) # compact mode iostr = sprint(show, T) @test iostr == "Coerce(selector: [:a, :b], scitypes: DataType[Continuous, Categorical])" # full mode iostr = sprint(show, MIME("text/plain"), T) @test iostr == """ Coerce transform ├─ selector: [:a, :b] └─ scitypes: DataType[DataScienceTraits.Continuous, DataScienceTraits.Categorical]""" end @testset "Levels" begin T = Levels(:a => ["n", "y"], :b => 1:3, ordered=r"[ab]") # compact mode iostr = sprint(show, T) @test iostr == "Levels(selector: [:a, :b], ordered: r\"[ab]\", levels: ([\"n\", \"y\"], 1:3))" # full mode iostr = sprint(show, MIME("text/plain"), T) @test iostr == """ Levels transform ├─ selector: [:a, :b] ├─ ordered: r"[ab]" └─ levels: (["n", "y"], 1:3)""" end @testset "OneHot" begin T = OneHot(:a) # compact mode iostr = sprint(show, T) @test iostr == "OneHot(selector: :a, categ: false)" # full mode iostr = sprint(show, MIME("text/plain"), T) @test iostr == """ OneHot transform ├─ selector: :a └─ categ: false""" end @testset "Identity" begin T = Identity() # compact mode iostr = sprint(show, T) @test iostr == "Identity()" # full mode iostr = sprint(show, MIME("text/plain"), T) @test iostr == "Identity transform" end @testset "Center" begin T = Center() # compact mode iostr = sprint(show, T) @test iostr == "Center(selector: all)" # full mode iostr = sprint(show, MIME("text/plain"), T) @test iostr == """ Center transform └─ selector: all""" end @testset "LowHigh" begin T = LowHigh() # compact mode iostr = sprint(show, T) @test iostr == "LowHigh(selector: all, low: 0.25, high: 0.75)" # full mode iostr = sprint(show, MIME("text/plain"), T) @test iostr == """ LowHigh transform ├─ selector: all ├─ low: 0.25 └─ high: 0.75""" end @testset "ZScore" begin T = ZScore() # compact mode iostr = sprint(show, T) @test iostr == "ZScore(selector: all)" # full mode iostr = sprint(show, MIME("text/plain"), T) @test iostr == """ ZScore transform └─ selector: all""" end @testset "Quantile" begin T = Quantile() # compact mode iostr = sprint(show, T) @test iostr == "Quantile(selector: all, dist: Normal{Float64}(μ=0.0, σ=1.0))" # full mode iostr = sprint(show, MIME("text/plain"), T) @test iostr == """ Quantile transform ├─ selector: all └─ dist: Normal{Float64}(μ=0.0, σ=1.0)""" end @testset "Functional" begin T = Functional(log) # compact mode iostr = sprint(show, T) @test iostr == "Functional(selector: all, fun: log)" # full mode iostr = sprint(show, MIME("text/plain"), T) @test iostr == """ Functional transform ├─ selector: all └─ fun: log""" end @testset "EigenAnalysis" begin T = EigenAnalysis(:VDV) # compact mode iostr = sprint(show, T) @test iostr == "EigenAnalysis(proj: :VDV, maxdim: nothing, pratio: 1.0)" # full mode iostr = sprint(show, MIME("text/plain"), T) @test iostr == """ EigenAnalysis transform ├─ proj: :VDV ├─ maxdim: nothing └─ pratio: 1.0""" end @testset "Closure" begin T = Closure() # compact mode iostr = sprint(show, T) @test iostr == "Closure()" # full mode iostr = sprint(show, MIME("text/plain"), T) @test iostr == "Closure transform" end @testset "Remainder" begin T = Remainder() # compact mode iostr = sprint(show, T) @test iostr == "Remainder(total: nothing)" # full mode iostr = sprint(show, MIME("text/plain"), T) @test iostr == """ Remainder transform └─ total: nothing""" end @testset "Compose" begin T = Compose(:a, :b, :c) # compact mode iostr = sprint(show, T) @test iostr == "Compose(selector: [:a, :b, :c], as: :CODA)" # full mode iostr = sprint(show, MIME("text/plain"), T) @test iostr == """ Compose transform ├─ selector: [:a, :b, :c] └─ as: :CODA""" end @testset "RowTable" begin T = RowTable() # compact mode iostr = sprint(show, T) @test iostr == "RowTable()" # full mode iostr = sprint(show, MIME("text/plain"), T) @test iostr == "RowTable transform" end @testset "ColTable" begin T = ColTable() # compact mode iostr = sprint(show, T) @test iostr == "ColTable()" # full mode iostr = sprint(show, MIME("text/plain"), T) @test iostr == "ColTable transform" end @testset "SequentialTransform" begin t1 = Select(:x, :z) t2 = ZScore() t3 = LowHigh(low=0, high=1) pipeline = t1 → t2 → t3 # compact mode iostr = sprint(show, pipeline) @test iostr == "Select(selector: [:x, :z], newnames: nothing) → ZScore(selector: all) → LowHigh(selector: all, low: 0, high: 1)" # full mode iostr = sprint(show, MIME("text/plain"), pipeline) @test iostr == """ SequentialTransform ├─ Select(selector: [:x, :z], newnames: nothing) ├─ ZScore(selector: all) └─ LowHigh(selector: all, low: 0, high: 1)""" end @testset "ParallelTableTransform" begin t1 = LowHigh(low=0.3, high=0.6) t2 = EigenAnalysis(:VDV) t3 = Functional(exp) pipeline = t1 ⊔ t2 ⊔ t3 # compact mode iostr = sprint(show, pipeline) @test iostr == "LowHigh(selector: all, low: 0.3, high: 0.6) ⊔ EigenAnalysis(proj: :VDV, maxdim: nothing, pratio: 1.0) ⊔ Functional(selector: all, fun: exp)" # full mode iostr = sprint(show, MIME("text/plain"), pipeline) @test iostr == """ ParallelTableTransform ├─ LowHigh(selector: all, low: 0.3, high: 0.6) ├─ EigenAnalysis(proj: :VDV, maxdim: nothing, pratio: 1.0) └─ Functional(selector: all, fun: exp)""" # parallel and sequential f1 = ZScore() f2 = LowHigh() f3 = Functional(exp) f4 = Interquartile() pipeline = (f1 → f2) ⊔ (f3 → f4) # compact mode iostr = sprint(show, pipeline) @test iostr == "ZScore(selector: all) → LowHigh(selector: all, low: 0.25, high: 0.75) ⊔ Functional(selector: all, fun: exp) → LowHigh(selector: all, low: 0.25, high: 0.75)" # full mode iostr = sprint(show, MIME("text/plain"), pipeline) @test iostr == """ ParallelTableTransform ├─ SequentialTransform │ ├─ ZScore(selector: all) │ └─ LowHigh(selector: all, low: 0.25, high: 0.75) └─ SequentialTransform ├─ Functional(selector: all, fun: exp) └─ LowHigh(selector: all, low: 0.25, high: 0.75)""" end end
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
1963
@testset "tablerows" begin #-------------- # COLUMN TABLE #-------------- # table rows tb = (a=[1, 2, 3], b=[4, 5, 6]) rows = TT.tablerows(tb) @test rows isa TT.CTableRows # iterator interface @test length(rows) == 3 row, state = iterate(rows) @test row.a == 1 @test row.b == 4 row, state = iterate(rows, state) @test row.a == 2 @test row.b == 5 row, state = iterate(rows, state) @test row.a == 3 @test row.b == 6 @test isnothing(iterate(rows, state)) # table row row = first(rows) @test row isa TT.CTableRow # AbstractRow interface @test Tables.columnnames(row) == (:a, :b) @test Tables.getcolumn(row, 1) == 1 @test Tables.getcolumn(row, :a) == 1 # column access @test row."a" == 1 @test row[1] == 1 @test row[:a] == 1 @test row["a"] == 1 # iterator interface @test length(row) == 2 item, state = iterate(row) @test item == 1 item, state = iterate(row, state) @test item == 4 @test isnothing(iterate(row, state)) #----------- # ROW TABLE #----------- # table rows tb = [(a=1, b=4), (a=2, b=5), (a=3, b=6)] rows = TT.tablerows(tb) @test rows isa TT.RTableRows # iterator interface @test length(rows) == 3 row, state = iterate(rows) @test row.a == 1 @test row.b == 4 row, state = iterate(rows, state) @test row.a == 2 @test row.b == 5 row, state = iterate(rows, state) @test row.a == 3 @test row.b == 6 @test isnothing(iterate(rows, state)) # table row row = first(rows) @test row isa TT.RTableRow # AbstractRow interface @test Tables.columnnames(row) == (:a, :b) @test Tables.getcolumn(row, 2) == 4 @test Tables.getcolumn(row, :b) == 4 # column access @test row."b" == 4 @test row[2] == 4 @test row[:b] == 4 @test row["b"] == 4 # iterator interface @test length(row) == 2 item, state = iterate(row) @test item == 1 item, state = iterate(row, state) @test item == 4 @test isnothing(iterate(row, state)) end
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
2141
@testset "TableSelection" begin a = rand(10) b = rand(10) c = rand(10) d = rand(10) e = rand(10) f = rand(10) t = Table(; a, b, c, d, e, f) # Tables.jl interface select = [:a, :b, :e] newnames = select s = TT.TableSelection(t, newnames, select) @test Tables.istable(s) == true @test Tables.columnaccess(s) == true @test Tables.rowaccess(s) == false @test Tables.columns(s) === s @test Tables.columnnames(s) == [:a, :b, :e] @test Tables.schema(s).names == (:a, :b, :e) @test Tables.schema(s).types == (Float64, Float64, Float64) @test Tables.materializer(s) == Tables.materializer(t) # getcolumn cols = Tables.columns(t) @test Tables.getcolumn(s, :a) == Tables.getcolumn(cols, :a) @test Tables.getcolumn(s, 1) == Tables.getcolumn(cols, 1) @test Tables.getcolumn(s, 3) == Tables.getcolumn(cols, :e) # selectin with renaming select = [:c, :d, :f] newnames = [:x, :y, :z] s = TT.TableSelection(t, newnames, select) @test Tables.columnnames(s) == [:x, :y, :z] @test Tables.getcolumn(s, :x) == t.c @test Tables.getcolumn(s, :y) == t.d @test Tables.getcolumn(s, :z) == t.f @test Tables.getcolumn(s, 1) == t.c @test Tables.getcolumn(s, 2) == t.d @test Tables.getcolumn(s, 3) == t.f # row table select = [:a, :b, :e] newnames = select rt = Tables.rowtable(t) s = TT.TableSelection(rt, newnames, select) cols = Tables.columns(rt) @test Tables.getcolumn(s, :a) == Tables.getcolumn(cols, :a) @test Tables.getcolumn(s, 1) == Tables.getcolumn(cols, 1) @test Tables.getcolumn(s, 3) == Tables.getcolumn(cols, :e) # throws @test_throws AssertionError TT.TableSelection(t, [:a, :b, :z], [:a, :b, :z]) @test_throws AssertionError TT.TableSelection(t, [:x, :y, :z], [:c, :d, :k]) s = TT.TableSelection(t, [:a, :b, :e], [:a, :b, :e]) @test_throws ErrorException Tables.getcolumn(s, :f) @test_throws ErrorException Tables.getcolumn(s, 4) s = TT.TableSelection(t, [:x, :y, :z], [:c, :d, :f]) @test_throws ErrorException Tables.getcolumn(s, :c) @test_throws ErrorException Tables.getcolumn(s, 4) @test_throws ErrorException Tables.getcolumn(s, -2) end
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
857
transformfiles = [ "assert.jl", "select.jl", "rename.jl", "satisfies.jl", "stdnames.jl", "stdfeats.jl", "sort.jl", "sample.jl", "filter.jl", "dropmissing.jl", "dropnan.jl", "dropextrema.jl", "dropunits.jl", "dropconstant.jl", "absoluteunits.jl", "unitify.jl", "unit.jl", "map.jl", "replace.jl", "coalesce.jl", "coerce.jl", "levels.jl", "indicator.jl", "onehot.jl", "identity.jl", "center.jl", "lowhigh.jl", "zscore.jl", "quantile.jl", "functional.jl", "eigenanalysis.jl", "projectionpursuit.jl", "closure.jl", "remainder.jl", "compose.jl", "logratio.jl", "rowtable.jl", "coltable.jl", "sequential.jl", "parallel.jl" ] @testset "Transforms" begin for transformfile in transformfiles println("Testing $transformfile...") include("transforms/$transformfile") end end
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
5041
@testset "AbsoluteUnits" begin @test isrevertible(AbsoluteUnits()) a = [7, 4, 4, 7, 4, 1, 1, 6, 4, 7] * u"°C" b = [4, 5, 4, missing, 6, 6, missing, 4, 4, 1] * u"K" c = [3.9, 3.8, 3.5, 6.5, 7.7, 1.5, 0.6, 5.7, 4.7, 4.8] * u"K" d = [6.3, 4.7, 7.6, missing, 1.2, missing, 5.9, 0.2, 1.9, 4.2] * u"°C" e = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"] t = Table(; a, b, c, d, e) T = AbsoluteUnits() n, c = apply(T, t) @test unit(eltype(n.a)) === u"K" @test unit(nonmissingtype(eltype(n.b))) === u"K" @test unit(eltype(n.c)) === u"K" @test unit(nonmissingtype(eltype(n.d))) === u"K" @test eltype(n.e) === String @test n.e == t.e tₒ = revert(T, n, c) @test t.a == tₒ.a @test isequal(t.b, tₒ.b) @test t.c == tₒ.c @test all(isapprox.(skipmissing(t.d), skipmissing(tₒ.d))) @test t.e == tₒ.e # args... # integers T = AbsoluteUnits(1, 2) n, c = apply(T, t) @test unit(eltype(n.a)) === u"K" @test unit(nonmissingtype(eltype(n.b))) === u"K" @test unit(eltype(n.c)) === u"K" @test unit(nonmissingtype(eltype(n.d))) === u"°C" tₒ = revert(T, n, c) @test t.a == tₒ.a @test isequal(t.b, tₒ.b) @test t.c == tₒ.c @test isequal(t.d, tₒ.d) @test t.e == tₒ.e # symbols T = AbsoluteUnits(:a, :b) n, c = apply(T, t) @test unit(eltype(n.a)) === u"K" @test unit(nonmissingtype(eltype(n.b))) === u"K" @test unit(eltype(n.c)) === u"K" @test unit(nonmissingtype(eltype(n.d))) === u"°C" tₒ = revert(T, n, c) @test t.a == tₒ.a @test isequal(t.b, tₒ.b) @test t.c == tₒ.c @test isequal(t.d, tₒ.d) @test t.e == tₒ.e # strings T = AbsoluteUnits("a", "b") n, c = apply(T, t) @test unit(eltype(n.a)) === u"K" @test unit(nonmissingtype(eltype(n.b))) === u"K" @test unit(eltype(n.c)) === u"K" @test unit(nonmissingtype(eltype(n.d))) === u"°C" tₒ = revert(T, n, c) @test t.a == tₒ.a @test isequal(t.b, tₒ.b) @test t.c == tₒ.c @test isequal(t.d, tₒ.d) @test t.e == tₒ.e # vector # integers T = AbsoluteUnits([3, 4]) n, c = apply(T, t) @test unit(eltype(n.a)) === u"°C" @test unit(nonmissingtype(eltype(n.b))) === u"K" @test unit(eltype(n.c)) === u"K" @test unit(nonmissingtype(eltype(n.d))) === u"K" tₒ = revert(T, n, c) @test t.a == tₒ.a @test isequal(t.b, tₒ.b) @test t.c == tₒ.c @test all(isapprox.(skipmissing(t.d), skipmissing(tₒ.d))) @test t.e == tₒ.e # symbols T = AbsoluteUnits([:c, :d]) n, c = apply(T, t) @test unit(eltype(n.a)) === u"°C" @test unit(nonmissingtype(eltype(n.b))) === u"K" @test unit(eltype(n.c)) === u"K" @test unit(nonmissingtype(eltype(n.d))) === u"K" tₒ = revert(T, n, c) @test t.a == tₒ.a @test isequal(t.b, tₒ.b) @test t.c == tₒ.c @test all(isapprox.(skipmissing(t.d), skipmissing(tₒ.d))) @test t.e == tₒ.e # strings T = AbsoluteUnits(["c", "d"]) n, c = apply(T, t) @test unit(eltype(n.a)) === u"°C" @test unit(nonmissingtype(eltype(n.b))) === u"K" @test unit(eltype(n.c)) === u"K" @test unit(nonmissingtype(eltype(n.d))) === u"K" tₒ = revert(T, n, c) @test t.a == tₒ.a @test isequal(t.b, tₒ.b) @test t.c == tₒ.c @test all(isapprox.(skipmissing(t.d), skipmissing(tₒ.d))) @test t.e == tₒ.e # tuple # integers T = AbsoluteUnits((1, 4, 5)) n, c = apply(T, t) @test unit(eltype(n.a)) === u"K" @test unit(nonmissingtype(eltype(n.b))) === u"K" @test unit(eltype(n.c)) === u"K" @test unit(nonmissingtype(eltype(n.d))) === u"K" @test eltype(n.e) === String @test n.e == t.e tₒ = revert(T, n, c) @test t.a == tₒ.a @test isequal(t.b, tₒ.b) @test t.c == tₒ.c @test all(isapprox.(skipmissing(t.d), skipmissing(tₒ.d))) @test t.e == tₒ.e # symbols T = AbsoluteUnits((:a, :d, :e)) n, c = apply(T, t) @test unit(eltype(n.a)) === u"K" @test unit(nonmissingtype(eltype(n.b))) === u"K" @test unit(eltype(n.c)) === u"K" @test unit(nonmissingtype(eltype(n.d))) === u"K" @test eltype(n.e) === String @test n.e == t.e tₒ = revert(T, n, c) @test t.a == tₒ.a @test isequal(t.b, tₒ.b) @test t.c == tₒ.c @test all(isapprox.(skipmissing(t.d), skipmissing(tₒ.d))) @test t.e == tₒ.e # strings T = AbsoluteUnits(("a", "d", "e")) n, c = apply(T, t) @test unit(eltype(n.a)) === u"K" @test unit(nonmissingtype(eltype(n.b))) === u"K" @test unit(eltype(n.c)) === u"K" @test unit(nonmissingtype(eltype(n.d))) === u"K" @test eltype(n.e) === String @test n.e == t.e tₒ = revert(T, n, c) @test t.a == tₒ.a @test isequal(t.b, tₒ.b) @test t.c == tₒ.c @test all(isapprox.(skipmissing(t.d), skipmissing(tₒ.d))) @test t.e == tₒ.e # regex T = AbsoluteUnits(r"[ade]") n, c = apply(T, t) @test unit(eltype(n.a)) === u"K" @test unit(nonmissingtype(eltype(n.b))) === u"K" @test unit(eltype(n.c)) === u"K" @test unit(nonmissingtype(eltype(n.d))) === u"K" @test eltype(n.e) === String @test n.e == t.e tₒ = revert(T, n, c) @test t.a == tₒ.a @test isequal(t.b, tₒ.b) @test t.c == tₒ.c @test all(isapprox.(skipmissing(t.d), skipmissing(tₒ.d))) @test t.e == tₒ.e end
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
1187
@testset "Assert" begin @test isrevertible(Assert(cond=allunique)) a = [1, 2, 3, 4, 5, 6] b = [6, 5, 4, 3, 2, 1] c = [1, 2, 3, 4, 6, 6] d = [6, 6, 4, 3, 2, 1] t = Table(; a, b, c, d) T = Assert(1, 2, cond=allunique) n, c = apply(T, t) @test n == t tₒ = revert(T, n, c) @test tₒ == n == t T = Assert(1, 2, 3, cond=allunique) @test_throws AssertionError apply(T, t) T = Assert([:c, :d], cond=x -> sum(x) > 21) n, c = apply(T, t) @test n == t tₒ = revert(T, n, c) @test tₒ == n == t T = Assert([:b, :c, :d], cond=x -> sum(x) > 21) @test_throws AssertionError apply(T, t) T = Assert(("a", "b"), cond=allunique) n, c = apply(T, t) @test n == t tₒ = revert(T, n, c) @test tₒ == n == t T = Assert(("a", "b", "c"), cond=allunique, msg="assertion error") @test_throws AssertionError apply(T, t) @test_throws "assertion error" apply(T, t) T = Assert(r"[cd]", cond=x -> sum(x) > 21) n, c = apply(T, t) @test n == t tₒ = revert(T, n, c) @test tₒ == n == t T = Assert(r"[bcd]", cond=x -> sum(x) > 21, msg=nm -> "error in column $nm") @test_throws AssertionError apply(T, t) @test_throws "error in column b" apply(T, t) end
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
1454
@testset "Center" begin x = rand(rng, Normal(2, 1), 4000) y = rand(rng, Normal(5, 1), 4000) t = Table(; x, y) T = Center() n, c = apply(T, t) μ = mean(Tables.matrix(n), dims=1) @test isapprox(μ[1], 0; atol=1e-6) @test isapprox(μ[2], 0; atol=1e-6) tₒ = revert(T, n, c) @test Tables.matrix(t) ≈ Tables.matrix(tₒ) # row table rt = Tables.rowtable(t) T = Center() n, c = apply(T, rt) @test Tables.isrowtable(n) rtₒ = revert(T, n, c) @test Tables.matrix(rt) ≈ Tables.matrix(rtₒ) # colspec z = x + y t = Table(; x, y, z) T = Center(1, 2) n, c = apply(T, t) μ = mean(Tables.matrix(n), dims=1) @test isapprox(μ[1], 0; atol=1e-6) @test isapprox(μ[2], 0; atol=1e-6) tₒ = revert(T, n, c) @test Tables.matrix(t) ≈ Tables.matrix(tₒ) T = Center([:x, :y]) n, c = apply(T, t) μ = mean(Tables.matrix(n), dims=1) @test isapprox(μ[1], 0; atol=1e-6) @test isapprox(μ[2], 0; atol=1e-6) tₒ = revert(T, n, c) @test Tables.matrix(t) ≈ Tables.matrix(tₒ) T = Center(("x", "y")) n, c = apply(T, t) μ = mean(Tables.matrix(n), dims=1) @test isapprox(μ[1], 0; atol=1e-6) @test isapprox(μ[2], 0; atol=1e-6) tₒ = revert(T, n, c) @test Tables.matrix(t) ≈ Tables.matrix(tₒ) T = Center(r"[xy]") n, c = apply(T, t) μ = mean(Tables.matrix(n), dims=1) @test isapprox(μ[1], 0; atol=1e-6) @test isapprox(μ[2], 0; atol=1e-6) tₒ = revert(T, n, c) @test Tables.matrix(t) ≈ Tables.matrix(tₒ) end
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
334
@testset "Closure" begin @test isrevertible(Closure()) a = [2.0, 66.0, 0.0] b = [4.0, 22.0, 2.0] c = [4.0, 12.0, 98.0] t = Table(; a, b, c) T = Closure() n, c = apply(T, t) tₒ = revert(T, n, c) @test Tables.matrix(n) ≈ [0.2 0.4 0.4; 0.66 0.22 0.12; 0.00 0.02 0.98] @test Tables.matrix(tₒ) ≈ Tables.matrix(t) end
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
2190
@testset "Coalesce" begin @test !isrevertible(Coalesce(value=0)) @test TT.parameters(Coalesce(value=0)) == (; value=0) a = [3, 2, missing, 4, 5, 3] b = [missing, 4, 4, 5, 8, 5] c = [1, 1, 6, 2, 4, missing] d = [4, 3, 7, 5, 4, missing] e = [missing, 5, 2, 6, 5, 2] f = [4, missing, 3, 4, 5, 2] t = Table(; a, b, c, d, e, f) T = Coalesce(value=0) n, c = apply(T, t) @test n.a == [3, 2, 0, 4, 5, 3] @test n.b == [0, 4, 4, 5, 8, 5] @test n.c == [1, 1, 6, 2, 4, 0] @test n.d == [4, 3, 7, 5, 4, 0] @test n.e == [0, 5, 2, 6, 5, 2] @test n.f == [4, 0, 3, 4, 5, 2] # table schema after apply T = Coalesce(value=0) n, c = apply(T, t) ntypes = Tables.schema(n).types @test ntypes[1] == Int @test ntypes[2] == Int @test ntypes[3] == Int @test ntypes[4] == Int @test ntypes[5] == Int @test ntypes[6] == Int # row table rt = Tables.rowtable(t) T = Coalesce(value=0) n, c = apply(T, rt) @test Tables.isrowtable(n) # colspec T = Coalesce(1, 3, 5, value=0) n, c = apply(T, t) @test n.a == [3, 2, 0, 4, 5, 3] @test isequal(n.b, [missing, 4, 4, 5, 8, 5]) @test n.c == [1, 1, 6, 2, 4, 0] @test isequal(n.d, [4, 3, 7, 5, 4, missing]) @test n.e == [0, 5, 2, 6, 5, 2] @test isequal(n.f, [4, missing, 3, 4, 5, 2]) T = Coalesce([:b, :d, :f], value=0) n, c = apply(T, t) @test isequal(n.a, [3, 2, missing, 4, 5, 3]) @test n.b == [0, 4, 4, 5, 8, 5] @test isequal(n.c, [1, 1, 6, 2, 4, missing]) @test n.d == [4, 3, 7, 5, 4, 0] @test isequal(n.e, [missing, 5, 2, 6, 5, 2]) @test n.f == [4, 0, 3, 4, 5, 2] T = Coalesce(("a", "c", "e"), value=0) n, c = apply(T, t) @test n.a == [3, 2, 0, 4, 5, 3] @test isequal(n.b, [missing, 4, 4, 5, 8, 5]) @test n.c == [1, 1, 6, 2, 4, 0] @test isequal(n.d, [4, 3, 7, 5, 4, missing]) @test n.e == [0, 5, 2, 6, 5, 2] @test isequal(n.f, [4, missing, 3, 4, 5, 2]) T = Coalesce(r"[bdf]", value=0) n, c = apply(T, t) @test isequal(n.a, [3, 2, missing, 4, 5, 3]) @test n.b == [0, 4, 4, 5, 8, 5] @test isequal(n.c, [1, 1, 6, 2, 4, missing]) @test n.d == [4, 3, 7, 5, 4, 0] @test isequal(n.e, [missing, 5, 2, 6, 5, 2]) @test n.f == [4, 0, 3, 4, 5, 2] end
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
1606
@testset "Coerce" begin a = [1, 2, 3, 4, 5] b = [1.0, 2.0, 3.0, 4.0, 5.0] t = Table(; a, b) T = Coerce(1 => DST.Continuous, 2 => DST.Categorical) n, c = apply(T, t) @test eltype(n.a) <: Float64 @test eltype(n.b) <: Int n, c = apply(T, t) tₒ = revert(T, n, c) @test eltype(tₒ.a) == eltype(t.a) @test eltype(tₒ.b) == eltype(t.b) T = Coerce(:a => DST.Continuous, :b => DST.Categorical) n, c = apply(T, t) @test eltype(n.a) <: Float64 @test eltype(n.b) <: Int n, c = apply(T, t) tₒ = revert(T, n, c) @test eltype(tₒ.a) == eltype(t.a) @test eltype(tₒ.b) == eltype(t.b) T = Coerce("a" => DST.Continuous, "b" => DST.Categorical) n, c = apply(T, t) @test eltype(n.a) <: Float64 @test eltype(n.b) <: Int n, c = apply(T, t) tₒ = revert(T, n, c) @test eltype(tₒ.a) == eltype(t.a) @test eltype(tₒ.b) == eltype(t.b) T = Coerce(DST.Continuous) n, c = apply(T, t) @test eltype(n.a) <: Float64 @test eltype(n.b) <: Float64 n, c = apply(T, t) tₒ = revert(T, n, c) @test eltype(tₒ.a) == eltype(t.a) @test eltype(tₒ.b) == eltype(t.b) T = Coerce(DST.Categorical) n, c = apply(T, t) @test eltype(n.a) <: Int @test eltype(n.b) <: Int n, c = apply(T, t) tₒ = revert(T, n, c) @test eltype(tₒ.a) == eltype(t.a) @test eltype(tₒ.b) == eltype(t.b) # row table rt = Tables.rowtable(t) T = Coerce(:a => DST.Continuous, :b => DST.Categorical) n, c = apply(T, rt) @test Tables.isrowtable(n) rtₒ = revert(T, n, c) @test rt == rtₒ # error: cannot create Coerce transform without arguments @test_throws ArgumentError Coerce() end
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
280
@testset "ColTable" begin a = [3, 2, 1, 4, 5, 3] b = [1, 4, 4, 5, 8, 5] c = [1, 1, 6, 2, 4, 1] t = Table(; a, b, c) T = ColTable() n, c = apply(T, t) tₒ = revert(T, n, c) @test typeof(n) <: NamedTuple @test Tables.columnaccess(n) @test typeof(tₒ) <: Table end
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
1322
@testset "Compose" begin @test isrevertible(Compose()) a = rand(10) b = rand(10) c = rand(10) t = Table(; a, b, c) T = Compose() n, c = apply(T, t) @test Tables.schema(n).names == (:CODA,) @test n.CODA isa CoDaArray @test n.CODA == CoDaArray(t) tₒ = revert(T, n, c) @test tₒ == t T = Compose(as=:comp) n, c = apply(T, t) @test Tables.schema(n).names == (:comp,) @test n.comp isa CoDaArray @test n.comp == CoDaArray(t) tₒ = revert(T, n, c) @test tₒ == t T = Compose(1, 2) n, c = apply(T, t) @test Tables.schema(n).names == (:c, :CODA) @test n.CODA isa CoDaArray @test n.CODA == CoDaArray((a=t.a, b=t.b)) tₒ = revert(T, n, c) @test tₒ == t T = Compose([:a, :c]) n, c = apply(T, t) @test Tables.schema(n).names == (:b, :CODA) @test n.CODA isa CoDaArray @test n.CODA == CoDaArray((a=t.a, c=t.c)) tₒ = revert(T, n, c) @test tₒ == t T = Compose(("b", "c")) n, c = apply(T, t) @test Tables.schema(n).names == (:a, :CODA) @test n.CODA isa CoDaArray @test n.CODA == CoDaArray((b=t.b, c=t.c)) tₒ = revert(T, n, c) @test tₒ == t T = Compose(r"[ab]", as="COMP") n, c = apply(T, t) @test Tables.schema(n).names == (:c, :COMP) @test n.COMP isa CoDaArray @test n.COMP == CoDaArray((a=t.a, b=t.b)) tₒ = revert(T, n, c) @test tₒ == t end
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
664
@testset "DropConstant" begin @test isrevertible(DropUnits()) a = [4, 6, 7, 8, 1, 2] b = fill(5, 6) c = [1.9, 7.4, 8.6, 8.9, 2.4, 7.7] d = fill(5.5, 6) t = Table(; a, b, c, d) T = DropConstant() n, c = apply(T, t) @test Tables.schema(n).names == (:a, :c) @test Tables.getcolumn(n, :a) == t.a @test Tables.getcolumn(n, :c) == t.c tₒ = revert(T, n, c) @test t == tₒ # revert with different number of rows T = DropConstant() _, c = apply(T, t) n = Table(; a=[t.a; [3, 4, 7, 2]], c=[t.c; [5.3, 4.9, 3.1, 6.8]]) r = revert(T, n, c) @test r.a == n.a @test r.b == fill(5, 10) @test r.c == n.c @test r.d == fill(5.5, 10) end
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
2197
@testset "DropExtrema" begin @test !isrevertible(DropExtrema(:a)) @test TT.parameters(DropExtrema(:a)) == (low=0.25, high=0.75) a = [6.9, 9.0, 7.8, 0.0, 5.1, 4.8, 1.1, 8.0, 5.4, 7.9] b = [7.7, 4.2, 6.3, 1.4, 4.4, 0.5, 3.0, 6.1, 1.9, 1.5] c = [6.1, 7.7, 5.7, 2.8, 2.8, 6.7, 8.4, 5.0, 8.9, 1.0] d = [1.0, 2.8, 6.2, 1.9, 8.1, 6.2, 4.0, 6.9, 4.1, 1.4] e = [1.5, 8.9, 4.1, 1.6, 5.9, 1.3, 4.9, 3.5, 2.4, 6.3] f = [1.9, 2.1, 9.0, 6.2, 1.3, 8.9, 6.2, 3.8, 5.1, 2.3] t = Table(; a, b, c, d, e, f) T = DropExtrema(1) n, c = apply(T, t) @test n.a == [6.9, 7.8, 5.1, 5.4] @test n.b == [7.7, 6.3, 4.4, 1.9] @test n.c == [6.1, 5.7, 2.8, 8.9] @test n.d == [1.0, 6.2, 8.1, 4.1] @test n.e == [1.5, 4.1, 5.9, 2.4] @test n.f == [1.9, 9.0, 1.3, 5.1] T = DropExtrema(1, 2) n, c = apply(T, t) @test n.a == [5.1, 5.4] @test n.b == [4.4, 1.9] @test n.c == [2.8, 8.9] @test n.d == [8.1, 4.1] @test n.e == [5.9, 2.4] @test n.f == [1.3, 5.1] T = DropExtrema(:c, low=0.3, high=0.7) n, c = apply(T, t) @test n.a == [6.9, 7.8, 4.8, 8.0] @test n.b == [7.7, 6.3, 0.5, 6.1] @test n.c == [6.1, 5.7, 6.7, 5.0] @test n.d == [1.0, 6.2, 6.2, 6.9] @test n.e == [1.5, 4.1, 1.3, 3.5] @test n.f == [1.9, 9.0, 8.9, 3.8] T = DropExtrema([:c, :d], low=0.3, high=0.7) n, c = apply(T, t) @test n.a == [7.8, 4.8] @test n.b == [6.3, 0.5] @test n.c == [5.7, 6.7] @test n.d == [6.2, 6.2] @test n.e == [4.1, 1.3] @test n.f == [9.0, 8.9] T = DropExtrema("e", low=0.2, high=0.8) n, c = apply(T, t) @test n.a == [7.8, 0.0, 5.1, 1.1, 8.0, 5.4] @test n.b == [6.3, 1.4, 4.4, 3.0, 6.1, 1.9] @test n.c == [5.7, 2.8, 2.8, 8.4, 5.0, 8.9] @test n.d == [6.2, 1.9, 8.1, 4.0, 6.9, 4.1] @test n.e == [4.1, 1.6, 5.9, 4.9, 3.5, 2.4] @test n.f == [9.0, 6.2, 1.3, 6.2, 3.8, 5.1] T = DropExtrema(("e", "f"), low=0.2, high=0.8) n, c = apply(T, t) @test n.a == [0.0, 1.1, 8.0, 5.4] @test n.b == [1.4, 3.0, 6.1, 1.9] @test n.c == [2.8, 8.4, 5.0, 8.9] @test n.d == [1.9, 4.0, 6.9, 4.1] @test n.e == [1.6, 4.9, 3.5, 2.4] @test n.f == [6.2, 6.2, 3.8, 5.1] # error: invalid quantiles @test_throws AssertionError DropExtrema(:a, low=0, high=1.4) end
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
7156
@testset "DropMissing" begin @test !isrevertible(DropMissing()) a = [3, 2, missing, 4, 5, 3] b = [missing, 4, 4, 5, 8, 5] c = [1, 1, 6, 2, 4, missing] d = [4, 3, 7, 5, 4, missing] e = [missing, 5, 2, 6, 5, 2] f = [4, missing, 3, 4, 5, 2] t = Table(; a, b, c, d, e, f) T = DropMissing() n, c = apply(T, t) @test n.a == [4, 5] @test n.b == [5, 8] @test n.c == [2, 4] @test n.d == [5, 4] @test n.e == [6, 5] @test n.f == [4, 5] # args... # integers T = DropMissing(1, 3, 4) n, c = apply(T, t) @test isequal(n.a, [3, 2, 4, 5]) @test isequal(n.b, [missing, 4, 5, 8]) @test isequal(n.c, [1, 1, 2, 4]) @test isequal(n.d, [4, 3, 5, 4]) @test isequal(n.e, [missing, 5, 6, 5]) @test isequal(n.f, [4, missing, 4, 5]) # symbols T = DropMissing(:a, :c, :d) n, c = apply(T, t) @test isequal(n.a, [3, 2, 4, 5]) @test isequal(n.b, [missing, 4, 5, 8]) @test isequal(n.c, [1, 1, 2, 4]) @test isequal(n.d, [4, 3, 5, 4]) @test isequal(n.e, [missing, 5, 6, 5]) @test isequal(n.f, [4, missing, 4, 5]) # strings T = DropMissing("a", "c", "d") n, c = apply(T, t) @test isequal(n.a, [3, 2, 4, 5]) @test isequal(n.b, [missing, 4, 5, 8]) @test isequal(n.c, [1, 1, 2, 4]) @test isequal(n.d, [4, 3, 5, 4]) @test isequal(n.e, [missing, 5, 6, 5]) @test isequal(n.f, [4, missing, 4, 5]) # vector # integers T = DropMissing([1, 3, 4]) n, c = apply(T, t) @test isequal(n.a, [3, 2, 4, 5]) @test isequal(n.b, [missing, 4, 5, 8]) @test isequal(n.c, [1, 1, 2, 4]) @test isequal(n.d, [4, 3, 5, 4]) @test isequal(n.e, [missing, 5, 6, 5]) @test isequal(n.f, [4, missing, 4, 5]) # symbols T = DropMissing([:a, :c, :d]) n, c = apply(T, t) @test isequal(n.a, [3, 2, 4, 5]) @test isequal(n.b, [missing, 4, 5, 8]) @test isequal(n.c, [1, 1, 2, 4]) @test isequal(n.d, [4, 3, 5, 4]) @test isequal(n.e, [missing, 5, 6, 5]) @test isequal(n.f, [4, missing, 4, 5]) # strings T = DropMissing(["a", "c", "d"]) n, c = apply(T, t) @test isequal(n.a, [3, 2, 4, 5]) @test isequal(n.b, [missing, 4, 5, 8]) @test isequal(n.c, [1, 1, 2, 4]) @test isequal(n.d, [4, 3, 5, 4]) @test isequal(n.e, [missing, 5, 6, 5]) @test isequal(n.f, [4, missing, 4, 5]) # tuple # integers T = DropMissing((1, 3, 4)) n, c = apply(T, t) @test isequal(n.a, [3, 2, 4, 5]) @test isequal(n.b, [missing, 4, 5, 8]) @test isequal(n.c, [1, 1, 2, 4]) @test isequal(n.d, [4, 3, 5, 4]) @test isequal(n.e, [missing, 5, 6, 5]) @test isequal(n.f, [4, missing, 4, 5]) # symbols T = DropMissing((:a, :c, :d)) n, c = apply(T, t) @test isequal(n.a, [3, 2, 4, 5]) @test isequal(n.b, [missing, 4, 5, 8]) @test isequal(n.c, [1, 1, 2, 4]) @test isequal(n.d, [4, 3, 5, 4]) @test isequal(n.e, [missing, 5, 6, 5]) @test isequal(n.f, [4, missing, 4, 5]) # strings T = DropMissing(("a", "c", "d")) n, c = apply(T, t) @test isequal(n.a, [3, 2, 4, 5]) @test isequal(n.b, [missing, 4, 5, 8]) @test isequal(n.c, [1, 1, 2, 4]) @test isequal(n.d, [4, 3, 5, 4]) @test isequal(n.e, [missing, 5, 6, 5]) @test isequal(n.f, [4, missing, 4, 5]) # regex T = DropMissing(r"[acd]") n, c = apply(T, t) @test isequal(n.a, [3, 2, 4, 5]) @test isequal(n.b, [missing, 4, 5, 8]) @test isequal(n.c, [1, 1, 2, 4]) @test isequal(n.d, [4, 3, 5, 4]) @test isequal(n.e, [missing, 5, 6, 5]) @test isequal(n.f, [4, missing, 4, 5]) # table schema after apply and revert T = DropMissing() n, c = apply(T, t) ntypes = Tables.schema(n).types @test ntypes[1] == Int @test ntypes[2] == Int @test ntypes[3] == Int @test ntypes[4] == Int @test ntypes[5] == Int @test ntypes[6] == Int T = DropMissing([:a, :c, :d]) n, c = apply(T, t) ntypes = Tables.schema(n).types @test ntypes[1] == Int @test ntypes[2] == Union{Missing,Int} @test ntypes[3] == Int @test ntypes[4] == Int @test ntypes[5] == Union{Missing,Int} @test ntypes[6] == Union{Missing,Int} T = DropMissing([:b, :e, :f]) n, c = apply(T, t) ntypes = Tables.schema(n).types @test ntypes[1] == Union{Missing,Int} @test ntypes[2] == Int @test ntypes[3] == Union{Missing,Int} @test ntypes[4] == Union{Missing,Int} @test ntypes[5] == Int @test ntypes[6] == Int # reapply test T = DropMissing() n1, c1 = apply(T, t) n2 = reapply(T, t, c1) @test n1 == n2 # row table rt = Tables.rowtable(t) T = DropMissing() n, c = apply(T, rt) @test Tables.isrowtable(n) # missing value columns a = fill(missing, 6) b = [missing, 4, 4, 5, 8, 5] c = [1, 1, 6, 2, 4, missing] d = [4, 3, 7, 5, 4, missing] e = [missing, 5, 2, 6, 5, 2] f = fill(missing, 6) t = Table(; a, b, c, d, e, f) T = DropMissing() n, c = apply(T, t) ntypes = Tables.schema(n).types @test isequal(n.a, []) @test isequal(n.b, []) @test isequal(n.c, []) @test isequal(n.d, []) @test isequal(n.e, []) @test isequal(n.f, []) @test ntypes[1] == Any @test ntypes[2] == Int @test ntypes[3] == Int @test ntypes[4] == Int @test ntypes[5] == Int @test ntypes[6] == Any T = DropMissing(:a) n, c = apply(T, t) ntypes = Tables.schema(n).types @test isequal(n.a, []) @test isequal(n.b, []) @test isequal(n.c, []) @test isequal(n.d, []) @test isequal(n.e, []) @test isequal(n.f, []) @test ntypes[1] == Any @test ntypes[2] == Union{Missing,Int} @test ntypes[3] == Union{Missing,Int} @test ntypes[4] == Union{Missing,Int} @test ntypes[5] == Union{Missing,Int} @test ntypes[6] == Missing T = DropMissing(:f) n, c = apply(T, t) ntypes = Tables.schema(n).types @test isequal(n.a, []) @test isequal(n.b, []) @test isequal(n.c, []) @test isequal(n.d, []) @test isequal(n.e, []) @test isequal(n.f, []) @test ntypes[1] == Missing @test ntypes[2] == Union{Missing,Int} @test ntypes[3] == Union{Missing,Int} @test ntypes[4] == Union{Missing,Int} @test ntypes[5] == Union{Missing,Int} @test ntypes[6] == Any T = DropMissing(:b, :c, :d, :e) n, c = apply(T, t) ntypes = Tables.schema(n).types @test isequal(n.a, fill(missing, 4)) @test isequal(n.b, [4, 4, 5, 8]) @test isequal(n.c, [1, 6, 2, 4]) @test isequal(n.d, [3, 7, 5, 4]) @test isequal(n.e, [5, 2, 6, 5]) @test isequal(n.f, fill(missing, 4)) @test ntypes[1] == Missing @test ntypes[2] == Int @test ntypes[3] == Int @test ntypes[4] == Int @test ntypes[5] == Int @test ntypes[6] == Missing # throws: empty selection @test_throws ArgumentError DropMissing(()) @test_throws ArgumentError DropMissing(Symbol[]) @test_throws ArgumentError DropMissing(String[]) # throws: regex doesn't match any names in input table @test_throws AssertionError apply(DropMissing(r"g"), t) # throws: columns that do not exist in the original table @test_throws AssertionError apply(DropMissing(:g, :h), t) @test_throws AssertionError apply(DropMissing([:g, :h]), t) @test_throws AssertionError apply(DropMissing((:g, :h)), t) @test_throws AssertionError apply(DropMissing("g", "h"), t) @test_throws AssertionError apply(DropMissing(["g", "h"]), t) @test_throws AssertionError apply(DropMissing(("g", "h")), t) end
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
3526
@testset "DropNaN" begin @test !isrevertible(DropNaN()) a = [1.8, 0.5, 1.2, 3.7, 5.0, NaN] b = [6.0f0, 5.4f0, 5.4f0, NaN32, 5.5f0, 2.6f0] c = [4.9, 5.1, NaN, 5.1, 8.6, 4.4] * u"m" d = [NaN32, 1.0f0, 8.8f0, 0.1f0, 1.5f0, 9.5f0] * u"m" e = ["yes", "no", "no", "yes", "yes", "no"] t = Table(; a, b, c, d, e) T = DropNaN() n, c = apply(T, t) @test n.a == [0.5, 5.0] @test n.b == [5.4f0, 5.5f0] @test n.c == [5.1, 8.6] * u"m" @test n.d == [1.0f0, 1.5f0] * u"m" @test n.e == ["no", "yes"] # args... # integers T = DropNaN(1, 3) n, c = apply(T, t) @test isequal(n.a, [1.8, 0.5, 3.7, 5.0]) @test isequal(n.b, [6.0f0, 5.4f0, NaN32, 5.5f0]) @test isequal(n.c, [4.9, 5.1, 5.1, 8.6] * u"m") @test isequal(n.d, [NaN32, 1.0f0, 0.1f0, 1.5f0] * u"m") @test isequal(n.e, ["yes", "no", "yes", "yes"]) # symbols T = DropNaN(:a, :c) n, c = apply(T, t) @test isequal(n.a, [1.8, 0.5, 3.7, 5.0]) @test isequal(n.b, [6.0f0, 5.4f0, NaN32, 5.5f0]) @test isequal(n.c, [4.9, 5.1, 5.1, 8.6] * u"m") @test isequal(n.d, [NaN32, 1.0f0, 0.1f0, 1.5f0] * u"m") @test isequal(n.e, ["yes", "no", "yes", "yes"]) # strings T = DropNaN("a", "c") n, c = apply(T, t) @test isequal(n.a, [1.8, 0.5, 3.7, 5.0]) @test isequal(n.b, [6.0f0, 5.4f0, NaN32, 5.5f0]) @test isequal(n.c, [4.9, 5.1, 5.1, 8.6] * u"m") @test isequal(n.d, [NaN32, 1.0f0, 0.1f0, 1.5f0] * u"m") @test isequal(n.e, ["yes", "no", "yes", "yes"]) # vector # integers T = DropNaN([2, 4]) n, c = apply(T, t) @test isequal(n.a, [0.5, 1.2, 5.0, NaN]) @test isequal(n.b, [5.4f0, 5.4f0, 5.5f0, 2.6f0]) @test isequal(n.c, [5.1, NaN, 8.6, 4.4] * u"m") @test isequal(n.d, [1.0f0, 8.8f0, 1.5f0, 9.5f0] * u"m") @test isequal(n.e, ["no", "no", "yes", "no"]) # symbols T = DropNaN([:b, :d]) n, c = apply(T, t) @test isequal(n.a, [0.5, 1.2, 5.0, NaN]) @test isequal(n.b, [5.4f0, 5.4f0, 5.5f0, 2.6f0]) @test isequal(n.c, [5.1, NaN, 8.6, 4.4] * u"m") @test isequal(n.d, [1.0f0, 8.8f0, 1.5f0, 9.5f0] * u"m") @test isequal(n.e, ["no", "no", "yes", "no"]) # strings T = DropNaN(["b", "d"]) n, c = apply(T, t) @test isequal(n.a, [0.5, 1.2, 5.0, NaN]) @test isequal(n.b, [5.4f0, 5.4f0, 5.5f0, 2.6f0]) @test isequal(n.c, [5.1, NaN, 8.6, 4.4] * u"m") @test isequal(n.d, [1.0f0, 8.8f0, 1.5f0, 9.5f0] * u"m") @test isequal(n.e, ["no", "no", "yes", "no"]) # tuple # integers T = DropNaN((1, 2, 3)) n, c = apply(T, t) @test isequal(n.a, [1.8, 0.5, 5.0]) @test isequal(n.b, [6.0f0, 5.4f0, 5.5f0]) @test isequal(n.c, [4.9, 5.1, 8.6] * u"m") @test isequal(n.d, [NaN32, 1.0f0, 1.5f0] * u"m") @test isequal(n.e, ["yes", "no", "yes"]) # symbols T = DropNaN((:a, :b, :c)) n, c = apply(T, t) @test isequal(n.a, [1.8, 0.5, 5.0]) @test isequal(n.b, [6.0f0, 5.4f0, 5.5f0]) @test isequal(n.c, [4.9, 5.1, 8.6] * u"m") @test isequal(n.d, [NaN32, 1.0f0, 1.5f0] * u"m") @test isequal(n.e, ["yes", "no", "yes"]) # strings T = DropNaN(("a", "b", "c")) n, c = apply(T, t) @test isequal(n.a, [1.8, 0.5, 5.0]) @test isequal(n.b, [6.0f0, 5.4f0, 5.5f0]) @test isequal(n.c, [4.9, 5.1, 8.6] * u"m") @test isequal(n.d, [NaN32, 1.0f0, 1.5f0] * u"m") @test isequal(n.e, ["yes", "no", "yes"]) # regex T = DropNaN(r"[bcd]") n, c = apply(T, t) @test isequal(n.a, [0.5, 5.0, NaN]) @test isequal(n.b, [5.4f0, 5.5f0, 2.6f0]) @test isequal(n.c, [5.1, 8.6, 4.4] * u"m") @test isequal(n.d, [1.0f0, 1.5f0, 9.5f0] * u"m") @test isequal(n.e, ["no", "yes", "no"]) end
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
5800
@testset "DropUnits" begin @test isrevertible(DropUnits()) a = [7, 4, 4, 7, 4, 1, 1, 6, 4, 7] * u"m/s" b = [4, 5, 4, missing, 6, 6, missing, 4, 4, 1] * u"m^2" c = [3.9, 3.8, 3.5, 6.5, 7.7, 1.5, 0.6, 5.7, 4.7, 4.8] * u"km/hr" d = [6.3, 4.7, 7.6, missing, 1.2, missing, 5.9, 0.2, 1.9, 4.2] * u"km^2" e = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"] t = Table(; a, b, c, d, e) T = DropUnits() n, c = apply(T, t) @test eltype(n.a) === Int @test unit(eltype(n.a)) === NoUnits @test nonmissingtype(eltype(n.b)) === Int @test unit(nonmissingtype(eltype(n.b))) === NoUnits @test eltype(n.c) === Float64 @test unit(eltype(n.c)) === NoUnits @test nonmissingtype(eltype(n.d)) === Float64 @test unit(nonmissingtype(eltype(n.d))) === NoUnits @test eltype(n.e) === String @test n.e == t.e tₒ = revert(T, n, c) @test t.a == tₒ.a @test isequal(t.b, tₒ.b) @test t.c == tₒ.c @test isequal(t.d, tₒ.d) @test t.e == tₒ.e # args... # integers T = DropUnits(1, 2) n, c = apply(T, t) @test eltype(n.a) === Int @test unit(eltype(n.a)) === NoUnits @test nonmissingtype(eltype(n.b)) === Int @test unit(nonmissingtype(eltype(n.b))) === NoUnits @test unit(eltype(n.c)) === u"km/hr" @test unit(nonmissingtype(eltype(n.d))) === u"km^2" tₒ = revert(T, n, c) @test t.a == tₒ.a @test isequal(t.b, tₒ.b) @test t.c == tₒ.c @test isequal(t.d, tₒ.d) @test t.e == tₒ.e # symbols T = DropUnits(:a, :b) n, c = apply(T, t) @test eltype(n.a) === Int @test unit(eltype(n.a)) === NoUnits @test nonmissingtype(eltype(n.b)) === Int @test unit(nonmissingtype(eltype(n.b))) === NoUnits @test unit(eltype(n.c)) === u"km/hr" @test unit(nonmissingtype(eltype(n.d))) === u"km^2" tₒ = revert(T, n, c) @test t.a == tₒ.a @test isequal(t.b, tₒ.b) @test t.c == tₒ.c @test isequal(t.d, tₒ.d) @test t.e == tₒ.e # strings T = DropUnits("a", "b") n, c = apply(T, t) @test eltype(n.a) === Int @test unit(eltype(n.a)) === NoUnits @test nonmissingtype(eltype(n.b)) === Int @test unit(nonmissingtype(eltype(n.b))) === NoUnits @test unit(eltype(n.c)) === u"km/hr" @test unit(nonmissingtype(eltype(n.d))) === u"km^2" tₒ = revert(T, n, c) @test t.a == tₒ.a @test isequal(t.b, tₒ.b) @test t.c == tₒ.c @test isequal(t.d, tₒ.d) @test t.e == tₒ.e # vector # integers T = DropUnits([3, 4]) n, c = apply(T, t) @test unit(eltype(n.a)) === u"m/s" @test unit(nonmissingtype(eltype(n.b))) === u"m^2" @test eltype(n.c) === Float64 @test unit(eltype(n.c)) === NoUnits @test nonmissingtype(eltype(n.d)) === Float64 @test unit(nonmissingtype(eltype(n.d))) === NoUnits tₒ = revert(T, n, c) @test t.a == tₒ.a @test isequal(t.b, tₒ.b) @test t.c == tₒ.c @test isequal(t.d, tₒ.d) @test t.e == tₒ.e # symbols T = DropUnits([:c, :d]) n, c = apply(T, t) @test unit(eltype(n.a)) === u"m/s" @test unit(nonmissingtype(eltype(n.b))) === u"m^2" @test eltype(n.c) === Float64 @test unit(eltype(n.c)) === NoUnits @test nonmissingtype(eltype(n.d)) === Float64 @test unit(nonmissingtype(eltype(n.d))) === NoUnits tₒ = revert(T, n, c) @test t.a == tₒ.a @test isequal(t.b, tₒ.b) @test t.c == tₒ.c @test isequal(t.d, tₒ.d) @test t.e == tₒ.e # strings T = DropUnits(["c", "d"]) n, c = apply(T, t) @test unit(eltype(n.a)) === u"m/s" @test unit(nonmissingtype(eltype(n.b))) === u"m^2" @test eltype(n.c) === Float64 @test unit(eltype(n.c)) === NoUnits @test nonmissingtype(eltype(n.d)) === Float64 @test unit(nonmissingtype(eltype(n.d))) === NoUnits tₒ = revert(T, n, c) @test t.a == tₒ.a @test isequal(t.b, tₒ.b) @test t.c == tₒ.c @test isequal(t.d, tₒ.d) @test t.e == tₒ.e # tuple # integers T = DropUnits((2, 4, 5)) n, c = apply(T, t) @test unit(eltype(n.a)) === u"m/s" @test nonmissingtype(eltype(n.b)) === Int @test unit(nonmissingtype(eltype(n.b))) === NoUnits @test unit(eltype(n.c)) === u"km/hr" @test nonmissingtype(eltype(n.d)) === Float64 @test unit(nonmissingtype(eltype(n.d))) === NoUnits @test eltype(n.e) === String @test n.e == t.e tₒ = revert(T, n, c) @test t.a == tₒ.a @test isequal(t.b, tₒ.b) @test t.c == tₒ.c @test isequal(t.d, tₒ.d) @test t.e == tₒ.e # symbols T = DropUnits((:b, :d, :e)) n, c = apply(T, t) @test unit(eltype(n.a)) === u"m/s" @test nonmissingtype(eltype(n.b)) === Int @test unit(nonmissingtype(eltype(n.b))) === NoUnits @test unit(eltype(n.c)) === u"km/hr" @test nonmissingtype(eltype(n.d)) === Float64 @test unit(nonmissingtype(eltype(n.d))) === NoUnits @test eltype(n.e) === String @test n.e == t.e tₒ = revert(T, n, c) @test t.a == tₒ.a @test isequal(t.b, tₒ.b) @test t.c == tₒ.c @test isequal(t.d, tₒ.d) @test t.e == tₒ.e # strings T = DropUnits(("b", "d", "e")) n, c = apply(T, t) @test unit(eltype(n.a)) === u"m/s" @test nonmissingtype(eltype(n.b)) === Int @test unit(nonmissingtype(eltype(n.b))) === NoUnits @test unit(eltype(n.c)) === u"km/hr" @test nonmissingtype(eltype(n.d)) === Float64 @test unit(nonmissingtype(eltype(n.d))) === NoUnits @test eltype(n.e) === String @test n.e == t.e tₒ = revert(T, n, c) @test t.a == tₒ.a @test isequal(t.b, tₒ.b) @test t.c == tₒ.c @test isequal(t.d, tₒ.d) @test t.e == tₒ.e # regex T = DropUnits(r"[ace]") n, c = apply(T, t) @test eltype(n.a) === Int @test unit(eltype(n.a)) === NoUnits @test unit(nonmissingtype(eltype(n.b))) === u"m^2" @test eltype(n.c) === Float64 @test unit(eltype(n.c)) === NoUnits @test unit(nonmissingtype(eltype(n.d))) === u"km^2" @test n.e == t.e @test eltype(n.e) === String tₒ = revert(T, n, c) @test t.a == tₒ.a @test isequal(t.b, tₒ.b) @test t.c == tₒ.c @test isequal(t.d, tₒ.d) @test t.e == tₒ.e end
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
4971
@testset "EigenAnalysis" begin @test TT.parameters(EigenAnalysis(:V)) == (proj=:V, maxdim=nothing, pratio=1.0) # PCA test x = rand(Normal(0, 10), 1500) y = x + rand(Normal(0, 2), 1500) t = Table(; x, y) T = EigenAnalysis(:V) n, c = apply(T, t) Σ = cov(Tables.matrix(n)) @test Σ[1, 1] > 1 @test isapprox(Σ[1, 2], 0; atol=1e-6) @test isapprox(Σ[2, 1], 0; atol=1e-6) @test Σ[2, 2] > 1 tₒ = revert(T, n, c) @test Tables.matrix(t) ≈ Tables.matrix(tₒ) # DRS test x = rand(Normal(0, 10), 1500) y = x + rand(Normal(0, 2), 1500) t = Table(; x, y) T = EigenAnalysis(:VD) n, c = apply(T, t) Σ = cov(Tables.matrix(n)) @test isapprox(Σ[1, 2], 0; atol=1e-6) @test isapprox(Σ[2, 1], 0; atol=1e-6) @test isapprox(Σ[1, 1], 1; atol=1e-6) @test isapprox(Σ[2, 2], 1; atol=1e-6) tₒ = revert(T, n, c) @test Tables.matrix(t) ≈ Tables.matrix(tₒ) # SDS test x = rand(Normal(0, 10), 1500) y = x + rand(Normal(0, 2), 1500) t = Table(; x, y) T = EigenAnalysis(:VDV) n, c = apply(T, t) Σ = cov(Tables.matrix(n)) @test isapprox(Σ[1, 2], 0; atol=1e-6) @test isapprox(Σ[2, 1], 0; atol=1e-6) @test isapprox(Σ[1, 1], 1; atol=1e-6) @test isapprox(Σ[2, 2], 1; atol=1e-6) tₒ = revert(T, n, c) @test Tables.matrix(t) ≈ Tables.matrix(tₒ) x = rand(rng, Normal(0, 10), 4000) y = x + rand(rng, Normal(0, 2), 4000) t₁ = Table(; x, y) t₂, c₂ = apply(EigenAnalysis(:V), t₁) t₃, c₃ = apply(EigenAnalysis(:VD), t₁) t₄, c₄ = apply(EigenAnalysis(:VDV), t₁) t₅, c₅ = apply(PCA(), t₁) t₆, c₆ = apply(DRS(), t₁) t₇, c₇ = apply(SDS(), t₁) # visual tests if visualtests kwargs = (; bodyaxis=(; aspect=Mke.DataAspect())) fig = Mke.Figure(size=(1000, 1000)) pairplot(fig[1, 1], t₁; kwargs...) pairplot(fig[1, 2], t₂; kwargs...) pairplot(fig[2, 1], t₃; kwargs...) pairplot(fig[2, 2], t₄; kwargs...) @test_reference joinpath(datadir, "eigenanalysis-1.png") fig fig = Mke.Figure(size=(1500, 1000)) pairplot(fig[1, 1], t₂; kwargs...) pairplot(fig[1, 2], t₃; kwargs...) pairplot(fig[1, 3], t₄; kwargs...) pairplot(fig[2, 1], t₅; kwargs...) pairplot(fig[2, 2], t₆; kwargs...) pairplot(fig[2, 3], t₇; kwargs...) @test_reference joinpath(datadir, "eigenanalysis-2.png") fig end # row table x = rand(Normal(0, 10), 1500) y = x + rand(Normal(0, 2), 1500) t = Table(; x, y) rt = Tables.rowtable(t) T = EigenAnalysis(:V) n, c = apply(T, rt) @test Tables.isrowtable(n) rtₒ = revert(T, n, c) @test Tables.matrix(rt) ≈ Tables.matrix(rtₒ) # maxdim x = randn(1000) y = x + randn(1000) z = 2x - y + randn(1000) t = Table(; x, y, z) # PCA T = PCA(maxdim=2) n, c = apply(T, t) Σ = cov(Tables.matrix(n)) @test Tables.columnnames(n) == (:PC1, :PC2) @test isapprox(Σ[1, 2], 0; atol=1e-6) @test isapprox(Σ[2, 1], 0; atol=1e-6) # DRS T = DRS(maxdim=2) n, c = apply(T, t) Σ = cov(Tables.matrix(n)) @test Tables.columnnames(n) == (:PC1, :PC2) @test isapprox(Σ[1, 2], 0; atol=1e-6) @test isapprox(Σ[2, 1], 0; atol=1e-6) @test isapprox(Σ[1, 1], 1; atol=1e-6) @test isapprox(Σ[2, 2], 1; atol=1e-6) # SDS T = SDS(maxdim=2) n, c = apply(T, t) Σ = cov(Tables.matrix(n)) @test Tables.columnnames(n) == (:PC1, :PC2) @test isapprox(Σ[1, 2], 0; atol=1e-6) @test isapprox(Σ[2, 1], 0; atol=1e-6) @test isapprox(Σ[1, 1], 1; atol=1e-6) @test isapprox(Σ[2, 2], 1; atol=1e-6) # pratio a = randn(rng, 1000) b = randn(rng, 1000) c = a + randn(rng, 1000) d = b - randn(rng, 1000) e = 3d + c - randn(rng, 1000) t = Table(; a, b, c, d, e) # PCA T = PCA(pratio=0.90) n, c = apply(T, t) Σ = cov(Tables.matrix(n)) @test Tables.columnnames(n) == (:PC1, :PC2, :PC3) @test isapprox(Σ[1, 2], 0; atol=1e-6) @test isapprox(Σ[1, 3], 0; atol=1e-6) @test isapprox(Σ[2, 1], 0; atol=1e-6) @test isapprox(Σ[2, 3], 0; atol=1e-6) @test isapprox(Σ[3, 1], 0; atol=1e-6) @test isapprox(Σ[3, 2], 0; atol=1e-6) # DRS T = DRS(pratio=0.90) n, c = apply(T, t) Σ = cov(Tables.matrix(n)) @test Tables.columnnames(n) == (:PC1, :PC2, :PC3) @test isapprox(Σ[1, 2], 0; atol=1e-6) @test isapprox(Σ[1, 3], 0; atol=1e-6) @test isapprox(Σ[2, 1], 0; atol=1e-6) @test isapprox(Σ[2, 3], 0; atol=1e-6) @test isapprox(Σ[3, 1], 0; atol=1e-6) @test isapprox(Σ[3, 2], 0; atol=1e-6) @test isapprox(Σ[1, 1], 1; atol=1e-6) @test isapprox(Σ[2, 2], 1; atol=1e-6) @test isapprox(Σ[3, 3], 1; atol=1e-6) # SDS T = SDS(pratio=0.90) n, c = apply(T, t) Σ = cov(Tables.matrix(n)) @test Tables.columnnames(n) == (:PC1, :PC2, :PC3) @test isapprox(Σ[1, 2], 0; atol=1e-6) @test isapprox(Σ[1, 3], 0; atol=1e-6) @test isapprox(Σ[2, 1], 0; atol=1e-6) @test isapprox(Σ[2, 3], 0; atol=1e-6) @test isapprox(Σ[3, 1], 0; atol=1e-6) @test isapprox(Σ[3, 2], 0; atol=1e-6) @test isapprox(Σ[1, 1], 1; atol=1e-6) @test isapprox(Σ[2, 2], 1; atol=1e-6) @test isapprox(Σ[3, 3], 1; atol=1e-6) end
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
2847
@testset "Filter" begin @test !isrevertible(Filter(allunique)) a = [3, 2, 1, 4, 5, 3] b = [2, 4, 4, 5, 8, 5] c = [1, 1, 6, 2, 4, 1] d = [4, 3, 7, 5, 4, 1] e = [5, 5, 2, 6, 5, 2] f = [4, 4, 3, 4, 5, 2] t = Table(; a, b, c, d, e, f) T = Filter(row -> all(≤(5), row)) n, c = apply(T, t) @test n.a == [3, 2, 3] @test n.b == [2, 4, 5] @test n.c == [1, 1, 1] @test n.d == [4, 3, 1] @test n.e == [5, 5, 2] @test n.f == [4, 4, 2] T = Filter(row -> any(>(5), row)) n, c = apply(T, t) @test n.a == [1, 4, 5] @test n.b == [4, 5, 8] @test n.c == [6, 2, 4] @test n.d == [7, 5, 4] @test n.e == [2, 6, 5] @test n.f == [3, 4, 5] T = Filter(row -> row.a ≥ 3) n, c = apply(T, t) @test n.a == [3, 4, 5, 3] @test n.b == [2, 5, 8, 5] @test n.c == [1, 2, 4, 1] @test n.d == [4, 5, 4, 1] @test n.e == [5, 6, 5, 2] @test n.f == [4, 4, 5, 2] T = Filter(row -> row.c ≥ 2 && row.e > 4) n, c = apply(T, t) @test n.a == [4, 5] @test n.b == [5, 8] @test n.c == [2, 4] @test n.d == [5, 4] @test n.e == [6, 5] @test n.f == [4, 5] T = Filter(row -> row.b == 4 || row.f == 4) n, c = apply(T, t) @test n.a == [3, 2, 1, 4] @test n.b == [2, 4, 4, 5] @test n.c == [1, 1, 6, 2] @test n.d == [4, 3, 7, 5] @test n.e == [5, 5, 2, 6] @test n.f == [4, 4, 3, 4] # column access T = Filter(row -> row."b" == 4 || row."f" == 4) n, c = apply(T, t) @test n.a == [3, 2, 1, 4] @test n.b == [2, 4, 4, 5] @test n.c == [1, 1, 6, 2] @test n.d == [4, 3, 7, 5] @test n.e == [5, 5, 2, 6] @test n.f == [4, 4, 3, 4] T = Filter(row -> row[2] == 4 || row[6] == 4) n, c = apply(T, t) @test n.a == [3, 2, 1, 4] @test n.b == [2, 4, 4, 5] @test n.c == [1, 1, 6, 2] @test n.d == [4, 3, 7, 5] @test n.e == [5, 5, 2, 6] @test n.f == [4, 4, 3, 4] T = Filter(row -> row[:b] == 4 || row[:f] == 4) n, c = apply(T, t) @test n.a == [3, 2, 1, 4] @test n.b == [2, 4, 4, 5] @test n.c == [1, 1, 6, 2] @test n.d == [4, 3, 7, 5] @test n.e == [5, 5, 2, 6] @test n.f == [4, 4, 3, 4] T = Filter(row -> row["b"] == 4 || row["f"] == 4) n, c = apply(T, t) @test n.a == [3, 2, 1, 4] @test n.b == [2, 4, 4, 5] @test n.c == [1, 1, 6, 2] @test n.d == [4, 3, 7, 5] @test n.e == [5, 5, 2, 6] @test n.f == [4, 4, 3, 4] # reapply test T = Filter(row -> all(≤(5), row)) n1, c1 = apply(T, t) n2 = reapply(T, t, c1) @test n1 == n2 # row table rt = Tables.rowtable(t) T = Filter(row -> row.b == 4 || row.f == 4) n, c = apply(T, rt) @test Tables.isrowtable(n) # performance tests trng = MersenneTwister(2) # test rng x = rand(trng, 100_000) y = rand(trng, 100_000) c = CoDaArray((a=rand(trng, 100_000), b=rand(trng, 100_000), c=rand(trng, 100_000))) t = (; x, y, c) T = Filter(row -> row.x > 0.5) @test @elapsed(apply(T, t)) < 0.5 end
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
2782
@testset "Functional" begin x = rand(0:0.001:1, 100) y = rand(0:0.001:1, 100) t = Table(; x, y) T = Functional(exp) n, c = apply(T, t) @test all(x -> 1 ≤ x ≤ ℯ, n.x) @test all(y -> 1 ≤ y ≤ ℯ, n.y) tₒ = revert(T, n, c) @test Tables.matrix(tₒ) ≈ Tables.matrix(t) x = rand(1:0.001:ℯ, 100) y = rand(1:0.001:ℯ, 100) t = Table(; x, y) T = Functional(log) n, c = apply(T, t) @test all(x -> 0 ≤ x ≤ 1, n.x) @test all(y -> 0 ≤ y ≤ 1, n.y) tₒ = revert(T, n, c) @test Tables.matrix(tₒ) ≈ Tables.matrix(t) # identity x = rand(100) y = x + rand(100) t = Table(; x, y) T = Functional(identity) n, c = apply(T, t) @test t == n tₒ = revert(T, n, c) @test tₒ == t T = Functional(x -> x) n, c = apply(T, t) @test t == n @test !isrevertible(T) # functor tests x = rand(100) y = rand(100) t = Table(; x, y) f = Polynomial(1, 2, 3) # f(x) = 1 + 2x + 3x² T = Functional(f) n, c = apply(T, t) @test f.(x) == n.x @test f.(y) == n.y @test all(≥(1), n.x) @test all(≥(1), n.y) @test !isrevertible(T) # apply functions to specific columns x = rand(0:0.001:1, 100) y = rand(1:0.001:ℯ, 100) z = x + y t = Table(; x, y, z) T = Functional(1 => exp, 2 => log) n, c = apply(T, t) @test all(x -> 1 ≤ x ≤ ℯ, n.x) @test all(y -> 0 ≤ y ≤ 1, n.y) @test t.z == n.z tₒ = revert(T, n, c) @test Tables.matrix(tₒ) ≈ Tables.matrix(t) T = Functional(:x => exp, :y => log) n, c = apply(T, t) @test all(x -> 1 ≤ x ≤ ℯ, n.x) @test all(y -> 0 ≤ y ≤ 1, n.y) @test t.z == n.z tₒ = revert(T, n, c) @test Tables.matrix(tₒ) ≈ Tables.matrix(t) T = Functional("x" => exp, "y" => log) n, c = apply(T, t) @test all(x -> 1 ≤ x ≤ ℯ, n.x) @test all(y -> 0 ≤ y ≤ 1, n.y) @test t.z == n.z tₒ = revert(T, n, c) @test Tables.matrix(tₒ) ≈ Tables.matrix(t) T = Functional(1 => log, 2 => exp) @test isrevertible(T) T = Functional(:x => log, :y => exp) @test isrevertible(T) T = Functional("x" => log, "y" => exp) @test isrevertible(T) T = Functional(1 => abs, 2 => log) @test !isrevertible(T) T = Functional(:x => abs, :y => log) @test !isrevertible(T) T = Functional("x" => abs, "y" => log) @test !isrevertible(T) # row table x = rand(0:0.001:1, 100) y = rand(0:0.001:1, 100) t = Table(; x, y) rt = Tables.rowtable(t) T = Functional(exp) n, c = apply(T, rt) @test Tables.isrowtable(n) rtₒ = revert(T, n, c) @test Tables.matrix(rtₒ) ≈ Tables.matrix(rt) # throws @test_throws ArgumentError Functional() t = Table(x=rand(15), y=rand(15)) T = Functional(Polynomial(1, 2, 3)) n, c = apply(T, t) @test_throws AssertionError revert(T, n, c) T = Functional(:x => abs, :y => log) n, c = apply(T, t) @test_throws AssertionError revert(T, n, c) end
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
323
@testset "Identity" begin x = rand(10) y = rand(10) t = Table(; x, y) T = Identity() n, c = apply(T, t) @test t == n tₒ = revert(T, n, c) @test t == tₒ # row table rt = Tables.rowtable(t) T = Identity() n, c = apply(T, rt) @test Tables.isrowtable(n) rtₒ = revert(T, n, c) @test rt == rtₒ end
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
3785
@testset "Indicator" begin @test TT.parameters(Indicator(:a)) == (k=10, scale=:quantile) a = [5.8, 6.4, 6.4, 9.8, 7.6, 8.2, 4.5, 2.5, 1.7, 2.3] b = [8.4, 1.4, 7.2, 1.8, 9.4, 1.0, 2.0, 5.2, 9.4, 6.2] c = [4.1, 5.6, 7.1, 9.1, 5.9, 9.5, 5.7, 9.2, 6.6, 9.9] d = [7.5, 2.2, 1.6, 2.8, 1.2, 1.5, 3.7, 2.0, 8.3, 8.2] t = Table(; a, b, c, d) T = Indicator(:a, k=1, scale=:quantile) n, c = apply(T, t) @test Tables.columnnames(n) == (:a_1, :b, :c, :d) @test n.a_1 == Bool[1, 1, 1, 1, 1, 1, 1, 1, 1, 1] @test n.a_1 isa BitVector tₒ = revert(T, n, c) @test t == tₒ T = Indicator(:b, k=2, scale=:quantile) n, c = apply(T, t) @test Tables.columnnames(n) == (:a, :b_1, :b_2, :c, :d) @test n.b_1 == Bool[0, 1, 0, 1, 0, 1, 1, 1, 0, 0] @test n.b_2 == Bool[1, 1, 1, 1, 1, 1, 1, 1, 1, 1] @test n.b_1 isa BitVector @test n.b_2 isa BitVector tₒ = revert(T, n, c) @test t == tₒ T = Indicator(:c, k=3, scale=:quantile, categ=true) n, c = apply(T, t) @test Tables.columnnames(n) == (:a, :b, :c_1, :c_2, :c_3, :d) @test n.c_1 == categorical(Bool[1, 1, 0, 0, 1, 0, 1, 0, 0, 0]) @test n.c_2 == categorical(Bool[1, 1, 1, 0, 1, 0, 1, 0, 1, 0]) @test n.c_3 == categorical(Bool[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]) @test n.c_1 isa CategoricalVector{Bool} @test n.c_2 isa CategoricalVector{Bool} @test n.c_3 isa CategoricalVector{Bool} tₒ = revert(T, n, c) @test t == tₒ T = Indicator(:d, k=4, scale=:quantile, categ=true) n, c = apply(T, t) @test Tables.columnnames(n) == (:a, :b, :c, :d_1, :d_2, :d_3, :d_4) @test n.d_1 == categorical(Bool[0, 0, 1, 0, 1, 1, 0, 0, 0, 0]) @test n.d_2 == categorical(Bool[0, 1, 1, 0, 1, 1, 0, 1, 0, 0]) @test n.d_3 == categorical(Bool[0, 1, 1, 1, 1, 1, 1, 1, 0, 0]) @test n.d_4 == categorical(Bool[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]) @test n.d_1 isa CategoricalVector{Bool} @test n.d_2 isa CategoricalVector{Bool} @test n.d_3 isa CategoricalVector{Bool} @test n.d_4 isa CategoricalVector{Bool} tₒ = revert(T, n, c) @test t == tₒ T = Indicator(:a, k=1, scale=:linear) n, c = apply(T, t) @test Tables.columnnames(n) == (:a_1, :b, :c, :d) @test n.a_1 == Bool[1, 1, 1, 1, 1, 1, 1, 1, 1, 1] @test n.a_1 isa BitVector tₒ = revert(T, n, c) @test t == tₒ T = Indicator(:b, k=2, scale=:linear) n, c = apply(T, t) @test Tables.columnnames(n) == (:a, :b_1, :b_2, :c, :d) @test n.b_1 == Bool[0, 1, 0, 1, 0, 1, 1, 1, 0, 0] @test n.b_2 == Bool[1, 1, 1, 1, 1, 1, 1, 1, 1, 1] @test n.b_1 isa BitVector @test n.b_2 isa BitVector tₒ = revert(T, n, c) @test t == tₒ T = Indicator(:c, k=3, scale=:linear, categ=true) n, c = apply(T, t) @test Tables.columnnames(n) == (:a, :b, :c_1, :c_2, :c_3, :d) @test n.c_1 == categorical(Bool[1, 1, 0, 0, 1, 0, 1, 0, 0, 0]) @test n.c_2 == categorical(Bool[1, 1, 1, 0, 1, 0, 1, 0, 1, 0]) @test n.c_3 == categorical(Bool[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]) @test n.c_1 isa CategoricalVector{Bool} @test n.c_2 isa CategoricalVector{Bool} @test n.c_3 isa CategoricalVector{Bool} tₒ = revert(T, n, c) @test t == tₒ T = Indicator(:d, k=4, scale=:linear, categ=true) n, c = apply(T, t) @test Tables.columnnames(n) == (:a, :b, :c, :d_1, :d_2, :d_3, :d_4) @test n.d_1 == categorical(Bool[0, 1, 1, 1, 1, 1, 0, 1, 0, 0]) @test n.d_2 == categorical(Bool[0, 1, 1, 1, 1, 1, 1, 1, 0, 0]) @test n.d_3 == categorical(Bool[0, 1, 1, 1, 1, 1, 1, 1, 0, 0]) @test n.d_4 == categorical(Bool[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]) @test n.d_1 isa CategoricalVector{Bool} @test n.d_2 isa CategoricalVector{Bool} @test n.d_3 isa CategoricalVector{Bool} @test n.d_4 isa CategoricalVector{Bool} tₒ = revert(T, n, c) @test t == tₒ @test_throws ArgumentError Indicator(:a, k=0) @test_throws ArgumentError Indicator(:a, scale=:test) end
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
3818
@testset "Levels" begin a = Bool[1, 0, 1, 0, 1, 1] b = ["n", "y", "n", "y", "y", "y"] c = [2, 3, 1, 2, 1, 3] t = Table(; a, b, c) T = Levels(2 => ["n", "y", "m"]) n, c = apply(T, t) @test levels(n.b) == ["n", "y", "m"] @test isordered(n.b) == false tₒ = revert(T, n, c) @test Tables.schema(tₒ) == Tables.schema(t) @test tₒ == t T = Levels(:b => ["n", "y", "m"], :c => 1:4, ordered=[:c]) n, c = apply(T, t) @test levels(n.b) == ["n", "y", "m"] @test isordered(n.b) == false @test levels(n.c) == [1, 2, 3, 4] @test isordered(n.c) == true tₒ = revert(T, n, c) @test Tables.schema(tₒ) == Tables.schema(t) @test tₒ == t T = Levels("b" => ["n", "y", "m"], "c" => 1:4, ordered=["b"]) n, c = apply(T, t) @test levels(n.b) == ["n", "y", "m"] @test isordered(n.b) == true @test levels(n.c) == [1, 2, 3, 4] @test isordered(n.c) == false tₒ = revert(T, n, c) @test Tables.schema(tₒ) == Tables.schema(t) @test tₒ == t a = categorical(["yes", "no", "no", "no", "yes"]) b = categorical([1, 2, 4, 2, 8], ordered=false) c = categorical([1, 2, 1, 2, 1]) d = categorical([1, 23, 5, 7, 7]) e = categorical([2, 3, 1, 4, 1]) t = Table(; a, b, c, d, e) T = Levels(:a => ["yes", "no"], :c => [1, 2, 4], :d => [1, 23, 5, 7], :e => 1:5) n, c = apply(T, t) @test levels(n.a) == ["yes", "no"] @test levels(n.c) == [1, 2, 4] @test levels(n.d) == [1, 23, 5, 7] @test levels(n.e) == [1, 2, 3, 4, 5] tₒ = revert(T, n, c) @test levels(tₒ.a) == ["no", "yes"] @test levels(tₒ.c) == [1, 2] @test levels(tₒ.e) == [1, 2, 3, 4] T = Levels("a" => ["yes", "no"], "c" => [1, 2, 4]) n, c = apply(T, t) @test levels(n.a) == ["yes", "no"] @test levels(n.c) == [1, 2, 4] tₒ = revert(T, n, c) @test levels(tₒ.a) == ["no", "yes"] @test levels(tₒ.c) == [1, 2] T = Levels(:a => ["yes", "no"], :c => [1, 2, 4], :d => [1, 23, 5, 7]) n, c = apply(T, t) @test levels(n.a) == ["yes", "no"] @test levels(n.c) == [1, 2, 4] @test levels(n.d) == [1, 23, 5, 7] tₒ = revert(T, n, c) @test levels(tₒ.a) == ["no", "yes"] @test levels(tₒ.c) == [1, 2] T = Levels("a" => ["yes", "no"], "c" => [1, 2, 4], "e" => 5:-1:1, ordered=["e"]) n, c = apply(T, t) @test levels(n.a) == ["yes", "no"] @test levels(n.c) == [1, 2, 4] @test levels(n.e) == [5, 4, 3, 2, 1] @test isordered(n.a) == false @test isordered(n.c) == false @test isordered(n.e) == true tₒ = revert(T, n, c) @test levels(tₒ.e) == [1, 2, 3, 4] @test isordered(tₒ.e) == false T = Levels(:a => ["yes", "no"], :c => [1, 2, 4], :d => [1, 23, 5, 7], ordered=[:a, :d]) n, c = apply(T, t) @test levels(n.a) == ["yes", "no"] @test levels(n.c) == [1, 2, 4] @test levels(n.d) == [1, 23, 5, 7] @test isordered(n.a) == true @test isordered(n.c) == false @test isordered(n.d) == true tₒ = revert(T, n, c) @test isordered(tₒ.a) == false a = [0.1, 0.1, 0.2, 0.2, 0.1, 0.2] b = ["n", "y", "n", "y", "y", "y"] c = [2, 3, 1, 2, 1, 3] t = Table(; a, b, c) # throws: Levels without arguments @test_throws ArgumentError Levels() # throws: columns that do not exist in the original table T = Levels(:x => ["n", "y", "m"], :y => 1:4) @test_throws AssertionError apply(T, t) T = Levels("x" => ["n", "y", "m"], "y" => 1:4) @test_throws AssertionError apply(T, t) # throws: non categorical column T = Levels(:a => [0.1, 0.2, 0.3], ordered=[:a]) @test_throws AssertionError apply(T, t) # throws: invalid ordered column selection T = Levels(:b => ["n", "y", "m"], :c => 1:4, ordered=[:a]) @test_throws AssertionError apply(T, t) T = Levels("b" => ["n", "y", "m"], "c" => 1:4, ordered=["a"]) @test_throws AssertionError apply(T, t) T = Levels("b" => ["n", "y", "m"], "c" => 1:4, ordered=r"xy") @test_throws AssertionError apply(T, t) end
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
1096
@testset "LogRatio" begin @test isrevertible(ALR()) @test isrevertible(CLR()) @test isrevertible(ILR()) a = [1.0, 0.0, 1.0] b = [2.0, 2.0, 2.0] c = [3.0, 3.0, 0.0] t = Table(; a, b, c) T = ALR() n, c = apply(T, t) @test Tables.schema(n).names == (:ARL1, :ARL2) @test n == t |> ALR(:c) talr = revert(T, n, c) T = CLR() n, c = apply(T, t) @test Tables.schema(n).names == (:CLR1, :CLR2, :CLR3) tclr = revert(T, n, c) T = ILR() n, c = apply(T, t) @test Tables.schema(n).names == (:ILR1, :ILR2) @test n == t |> ILR(:c) tilr = revert(T, n, c) @test Tables.matrix(talr) ≈ Tables.matrix(tclr) @test Tables.matrix(tclr) ≈ Tables.matrix(tilr) @test Tables.matrix(talr) ≈ Tables.matrix(tilr) # permute columns a = [1.0, 0.0, 1.0] b = [2.0, 2.0, 2.0] c = [3.0, 3.0, 0.0] t1 = Table(; a, c, b) t2 = Table(; c, a, b) T = ALR(:c) n1, c1 = apply(T, t1) n2, c2 = apply(T, t2) @test n1 == n2 tₒ = revert(T, n1, c1) @test Tables.schema(tₒ).names == (:a, :c, :b) tₒ = revert(T, n2, c2) @test Tables.schema(tₒ).names == (:c, :a, :b) end
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
2073
@testset "LowHigh" begin @test TT.parameters(LowHigh(:a)) == (low=0.25, high=0.75) # constant column x = fill(3.0, 10) y = rand(10) t = Table(; x, y) T = MinMax() n, c = apply(T, t) @test n.x == x @test n.y != y tₒ = revert(T, n, c) @test Tables.matrix(t) ≈ Tables.matrix(tₒ) x = rand(rng, Normal(4, 3), 4000) y = rand(rng, Normal(7, 5), 4000) t = Table(; x, y) T = LowHigh(low=0, high=1) n, c = apply(T, t) @test all(≤(1), n.x) @test all(≥(0), n.x) @test all(≤(1), n.y) @test all(≥(0), n.y) tₒ = revert(T, n, c) @test Tables.matrix(t) ≈ Tables.matrix(tₒ) # row table rt = Tables.rowtable(t) T = LowHigh() n, c = apply(T, rt) @test Tables.isrowtable(n) rtₒ = revert(T, n, c) @test Tables.matrix(rt) ≈ Tables.matrix(rtₒ) # columntype does not change for FT in (Float16, Float32) t = Table(; x=rand(FT, 10)) for T in (MinMax(), Interquartile(), LowHigh(low=0, high=0.5)) n, c = apply(T, t) @test Tables.columntype(t, :x) == Tables.columntype(n, :x) tₒ = revert(T, n, c) @test Tables.columntype(t, :x) == Tables.columntype(tₒ, :x) end end # colspec z = x + y t = Table(; x, y, z) T = LowHigh(1, 2, low=0, high=1) n, c = apply(T, t) @test all(≤(1), n.x) @test all(≥(0), n.x) @test all(≤(1), n.y) @test all(≥(0), n.y) tₒ = revert(T, n, c) @test Tables.matrix(t) ≈ Tables.matrix(tₒ) T = LowHigh([:x, :y], low=0, high=1) n, c = apply(T, t) @test all(≤(1), n.x) @test all(≥(0), n.x) @test all(≤(1), n.y) @test all(≥(0), n.y) tₒ = revert(T, n, c) @test Tables.matrix(t) ≈ Tables.matrix(tₒ) T = LowHigh(("x", "y"), low=0, high=1) n, c = apply(T, t) @test all(≤(1), n.x) @test all(≥(0), n.x) @test all(≤(1), n.y) @test all(≥(0), n.y) tₒ = revert(T, n, c) @test Tables.matrix(t) ≈ Tables.matrix(tₒ) T = LowHigh(r"[xy]", low=0, high=1) n, c = apply(T, t) @test all(≤(1), n.x) @test all(≥(0), n.x) @test all(≤(1), n.y) @test all(≥(0), n.y) tₒ = revert(T, n, c) @test Tables.matrix(t) ≈ Tables.matrix(tₒ) end
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
2822
@testset "Map" begin @test !isrevertible(Map(:a => sin)) a = [4, 7, 8, 5, 8, 1] b = [1, 9, 1, 7, 9, 4] c = [2, 8, 6, 3, 2, 2] d = [7, 5, 9, 5, 3, 4] t = Table(; a, b, c, d) T = Map(1 => sin) n, c = apply(T, t) @test Tables.schema(n).names == (:a, :b, :c, :d, :sin_a) @test n.sin_a == sin.(t.a) T = Map(:b => cos) n, c = apply(T, t) @test Tables.schema(n).names == (:a, :b, :c, :d, :cos_b) @test n.cos_b == cos.(t.b) T = Map("c" => tan) n, c = apply(T, t) @test Tables.schema(n).names == (:a, :b, :c, :d, :tan_c) @test n.tan_c == tan.(t.c) T = Map(:a => sin => :a) n, c = apply(T, t) @test Tables.schema(n).names == (:a, :b, :c, :d) @test n.a == sin.(t.a) T = Map(:a => sin => "a") n, c = apply(T, t) @test Tables.schema(n).names == (:a, :b, :c, :d) @test n.a == sin.(t.a) T = Map([2, 3] => ((b, c) -> 2b + c) => :op1) n, c = apply(T, t) @test Tables.schema(n).names == (:a, :b, :c, :d, :op1) @test n.op1 == @. 2 * t.b + t.c T = Map([:a, :c] => ((a, c) -> 2a * 3c) => :op1) n, c = apply(T, t) @test Tables.schema(n).names == (:a, :b, :c, :d, :op1) @test n.op1 == @. 2 * t.a * 3 * t.c T = Map(["c", "a"] => ((c, a) -> 3c / a) => :op1, "c" => tan) n, c = apply(T, t) @test Tables.schema(n).names == (:a, :b, :c, :d, :op1, :tan_c) @test n.op1 == @. 3 * t.c / t.a @test n.tan_c == tan.(t.c) T = Map(r"[abc]" => ((a, b, c) -> a^2 - 2b + c) => "op1") n, c = apply(T, t) @test Tables.schema(n).names == (:a, :b, :c, :d, :op1) @test n.op1 == @. t.a^2 - 2 * t.b + t.c # generated names # normal function T = Map([:c, :d] => hypot) n, c = apply(T, t) @test Tables.schema(n).names == (:a, :b, :c, :d, :hypot_c_d) @test n.hypot_c_d == hypot.(t.c, t.d) # anonymous function f = a -> a^2 + 3 fname = replace(string(f), "#" => "f") colname = Symbol(fname, :_a) T = Map(:a => f) n, c = apply(T, t) @test Tables.schema(n).names == (:a, :b, :c, :d, colname) @test Tables.getcolumn(n, colname) == f.(t.a) # composed function f = sin ∘ cos T = Map(:b => f) n, c = apply(T, t) @test Tables.schema(n).names == (:a, :b, :c, :d, :sin_cos_b) @test n.sin_cos_b == f.(t.b) f = sin ∘ cos ∘ tan T = Map(:c => sin ∘ cos ∘ tan) n, c = apply(T, t) @test Tables.schema(n).names == (:a, :b, :c, :d, :sin_cos_tan_c) @test n.sin_cos_tan_c == f.(t.c) # Base.Fix1 f = Base.Fix1(hypot, 2) T = Map(:d => f) n, c = apply(T, t) @test Tables.schema(n).names == (:a, :b, :c, :d, :fix1_hypot_d) @test n.fix1_hypot_d == f.(t.d) # Base.Fix2 f = Base.Fix2(hypot, 2) T = Map(:a => f) n, c = apply(T, t) @test Tables.schema(n).names == (:a, :b, :c, :d, :fix2_hypot_a) @test n.fix2_hypot_a == f.(t.a) # error: cannot create Map transform without arguments @test_throws ArgumentError Map() end
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
3530
@testset "OneHot" begin a = Bool[0, 1, 1, 0, 1, 1] b = ["m", "f", "m", "m", "m", "f"] c = [3, 2, 2, 1, 1, 3] d = categorical(a) e = categorical(b) f = categorical(c) t = Table(; a, b, c, d, e, f) T = OneHot(1; categ=true) n, c = apply(T, t) @test Tables.columnnames(n) == (:a_false, :a_true, :b, :c, :d, :e, :f) @test n.a_false == categorical(Bool[1, 0, 0, 1, 0, 0]) @test n.a_true == categorical(Bool[0, 1, 1, 0, 1, 1]) @test n.a_false isa CategoricalVector{Bool} @test n.a_true isa CategoricalVector{Bool} tₒ = revert(T, n, c) @test Tables.schema(tₒ) == Tables.schema(t) @test tₒ == t T = OneHot(:b; categ=true) n, c = apply(T, t) @test Tables.columnnames(n) == (:a, :b_f, :b_m, :c, :d, :e, :f) @test n.b_f == categorical(Bool[0, 1, 0, 0, 0, 1]) @test n.b_m == categorical(Bool[1, 0, 1, 1, 1, 0]) @test n.b_f isa CategoricalVector{Bool} @test n.b_m isa CategoricalVector{Bool} tₒ = revert(T, n, c) @test Tables.schema(tₒ) == Tables.schema(t) @test tₒ == t T = OneHot("c"; categ=true) n, c = apply(T, t) @test Tables.columnnames(n) == (:a, :b, :c_1, :c_2, :c_3, :d, :e, :f) @test n.c_1 == categorical(Bool[0, 0, 0, 1, 1, 0]) @test n.c_2 == categorical(Bool[0, 1, 1, 0, 0, 0]) @test n.c_3 == categorical(Bool[1, 0, 0, 0, 0, 1]) @test n.c_1 isa CategoricalVector{Bool} @test n.c_2 isa CategoricalVector{Bool} @test n.c_3 isa CategoricalVector{Bool} tₒ = revert(T, n, c) @test Tables.schema(tₒ) == Tables.schema(t) @test tₒ == t T = OneHot(4; categ=false) n, c = apply(T, t) @test Tables.columnnames(n) == (:a, :b, :c, :d_false, :d_true, :e, :f) @test n.d_false == Bool[1, 0, 0, 1, 0, 0] @test n.d_true == Bool[0, 1, 1, 0, 1, 1] tₒ = revert(T, n, c) @test Tables.schema(tₒ) == Tables.schema(t) @test tₒ == t T = OneHot(:e; categ=false) n, c = apply(T, t) @test Tables.columnnames(n) == (:a, :b, :c, :d, :e_f, :e_m, :f) @test n.e_f == Bool[0, 1, 0, 0, 0, 1] @test n.e_m == Bool[1, 0, 1, 1, 1, 0] tₒ = revert(T, n, c) @test Tables.schema(tₒ) == Tables.schema(t) @test tₒ == t T = OneHot("f"; categ=false) n, c = apply(T, t) @test Tables.columnnames(n) == (:a, :b, :c, :d, :e, :f_1, :f_2, :f_3) @test n.f_1 == Bool[0, 0, 0, 1, 1, 0] @test n.f_2 == Bool[0, 1, 1, 0, 0, 0] @test n.f_3 == Bool[1, 0, 0, 0, 0, 1] tₒ = revert(T, n, c) @test Tables.schema(tₒ) == Tables.schema(t) @test tₒ == t # name formatting b = categorical(["m", "f", "m", "m", "m", "f"]) b_f = rand(6) b_m = rand(6) t = Table(; b, b_f, b_m) T = OneHot(:b; categ=false) n, c = apply(T, t) @test Tables.columnnames(n) == (:b_f_, :b_m_, :b_f, :b_m) @test n.b_f_ == Bool[0, 1, 0, 0, 0, 1] @test n.b_m_ == Bool[1, 0, 1, 1, 1, 0] tₒ = revert(T, n, c) @test t == tₒ b = categorical(["m", "f", "m", "m", "m", "f"]) b_f = rand(6) b_m = rand(6) b_f_ = rand(6) b_m_ = rand(6) t = Table(; b, b_f, b_m, b_f_, b_m_) T = OneHot(:b; categ=false) n, c = apply(T, t) @test Tables.columnnames(n) == (:b_f__, :b_m__, :b_f, :b_m, :b_f_, :b_m_) @test n.b_f__ == Bool[0, 1, 0, 0, 0, 1] @test n.b_m__ == Bool[1, 0, 1, 1, 1, 0] tₒ = revert(T, n, c) @test t == tₒ # throws a = Bool[0, 1, 1, 0, 1, 1] b = rand(6) t = Table(; a, b) # non categorical column @test_throws AssertionError apply(OneHot(:b), t) @test_throws AssertionError apply(OneHot("b"), t) # invalid column selection @test_throws AssertionError apply(OneHot(:c), t) @test_throws AssertionError apply(OneHot("c"), t) end
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
1572
@testset "Parallel" begin x = rand(Normal(0, 10), 1500) y = x + rand(Normal(0, 2), 1500) z = y + rand(Normal(0, 5), 1500) t = Table(; x, y, z) T = LowHigh(low=0.3, high=0.6) ⊔ EigenAnalysis(:VDV) n, c = apply(T, t) tₒ = revert(T, n, c) @test Tables.matrix(t) ≈ Tables.matrix(tₒ) # check cardinality of parallel transform T = ZScore() ⊔ EigenAnalysis(:V) n = T(t) @test length(Tables.columnnames(n)) == 6 # distributivity with respect to sequential transform T₁ = Center() T₂ = LowHigh(low=0.2, high=0.8) T₃ = EigenAnalysis(:VD) P₁ = T₁ → (T₂ ⊔ T₃) P₂ = (T₁ → T₂) ⊔ (T₁ → T₃) n₁ = P₁(t) n₂ = P₂(t) @test Tables.matrix(n₁) ≈ Tables.matrix(n₂) # row table rt = Tables.rowtable(t) T = LowHigh(low=0.3, high=0.6) ⊔ EigenAnalysis(:VDV) n, c = apply(T, rt) @test Tables.isrowtable(n) rtₒ = revert(T, n, c) @test Tables.matrix(rt) ≈ Tables.matrix(rtₒ) # reapply with parallel transform t = Table(x=rand(100)) T = ZScore() ⊔ Quantile() n1, c1 = apply(T, t) n2 = reapply(T, t, c1) @test n1 == n2 # https://github.com/JuliaML/TableTransforms.jl/issues/80 t = (a=rand(3), b=rand(3)) T = Select(:a) ⊔ Select(:b) n, c = apply(T, t) @test t == n # https://github.com/JuliaML/TableTransforms.jl/issues/223 t = (a=1:4, b=5:8) left = Select(:a) → Filter(row -> row.a < 4) right = Select(:b) → Filter(row -> row.b < 7) T = left ⊔ right @test_throws AssertionError apply(T, t) t1 = (a=1:4, b=4:7) t2 = (a=1:4, b=5:8) n, c = apply(T, t1) @test_throws AssertionError reapply(T, t2, c) end
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
1502
@testset "ProjectionPursuit" begin @test TT.parameters(ProjectionPursuit()) == (tol=1.0e-6, deg=5, perc=0.9, n=100) rng = MersenneTwister(42) N = 10_000 a = [2randn(rng, N ÷ 2) .+ 6; randn(rng, N ÷ 2)] b = [3randn(rng, N ÷ 2); 2randn(rng, N ÷ 2)] c = randn(rng, N) d = c .+ 0.6randn(rng, N) t = (; a, b, c, d) T = ProjectionPursuit(rng=MersenneTwister(2)) n, c = apply(T, t) @test Tables.columnnames(n) == (:PP1, :PP2, :PP3, :PP4) μ = mean(Tables.matrix(n), dims=1) Σ = cov(Tables.matrix(n)) @test all(isapprox.(μ, 0, atol=1e-8)) @test all(isapprox.(Σ, I(4), atol=1e-8)) tₒ = revert(T, n, c) if visualtests fig = Mke.Figure(size=(800, 800)) pairplot(fig[1, 1], n) @test_reference joinpath(datadir, "projectionpursuit-1.png") fig fig = Mke.Figure(size=(1600, 800)) pairplot(fig[1, 1], t) pairplot(fig[1, 2], tₒ) @test_reference joinpath(datadir, "projectionpursuit-2.png") fig end a = rand(rng, Arcsine(3), 4000) b = rand(rng, BetaPrime(2), 4000) t = Table(; a, b) T = ProjectionPursuit(rng=MersenneTwister(2)) n, c = apply(T, t) μ = mean(Tables.matrix(n), dims=1) Σ = cov(Tables.matrix(n)) @test all(isapprox.(μ, 0, atol=1e-8)) @test all(isapprox.(Σ, I(2), atol=1e-8)) tₒ = revert(T, n, c) if visualtests fig = Mke.Figure(size=(1500, 500)) pairplot(fig[1, 1], t) pairplot(fig[1, 2], n) pairplot(fig[1, 3], tₒ) @test_reference joinpath(datadir, "projectionpursuit-3.png") fig end end
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
1676
@testset "Quantile" begin @test TT.parameters(Quantile()) == (; dist=Normal()) t = Table(z=rand(100)) T = Quantile() n, c = apply(T, t) tₒ = revert(T, n, c) @test all(-4 .< extrema(n.z) .< 4) @test all(0 .≤ extrema(tₒ.z) .≤ 1) # constant column x = fill(3.0, 10) y = rand(10) t = Table(; x, y) T = Quantile() n, c = apply(T, t) @test maximum(abs, n.x - x) < 0.1 @test n.y != y tₒ = revert(T, n, c) @test tₒ.x == t.x # row table rt = Tables.rowtable(t) T = Quantile() n, c = apply(T, rt) @test Tables.isrowtable(n) rtₒ = revert(T, n, c) for (row, rowₒ) in zip(rt, rtₒ) @test row.x == rowₒ.x end # colspec x = fill(3.0, 100) y = rand(100) z = rand(100) t = Table(; x, y, z) T = Quantile(1, 2) n, c = apply(T, t) @test maximum(abs, n.x - x) < 0.1 @test n.y != y tₒ = revert(T, n, c) @test tₒ.x == t.x T = Quantile([:z]) n, c = apply(T, t) tₒ = revert(T, n, c) @test all(-4 .< extrema(n.z) .< 4) @test all(0 .≤ extrema(tₒ.z) .≤ 1) T = Quantile(("x", "y")) n, c = apply(T, t) @test maximum(abs, n.x - x) < 0.1 @test n.y != y tₒ = revert(T, n, c) @test tₒ.x == t.x T = Quantile(r"z") n, c = apply(T, t) tₒ = revert(T, n, c) @test all(-4 .< extrema(n.z) .< 4) @test all(0 .≤ extrema(tₒ.z) .≤ 1) # smooth repeated values x = readdlm(joinpath(datadir, "quantile.dat")) t = (; x=vec(x)) n = t |> Quantile() if visualtests # visualize histogram and theoretical pdf fig = Mke.Figure(size=(800, 800)) Mke.hist(fig[1, 1], n.x, normalization=:pdf) Mke.plot!(fig[1, 1], Normal()) @test_reference joinpath(datadir, "quantile.png") fig end end
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
1014
@testset "Remainder" begin @test isrevertible(Remainder()) @test TT.parameters(Remainder()) == (; total=nothing) a = [2.0, 66.0, 0.0] b = [4.0, 22.0, 2.0] c = [4.0, 12.0, 98.0] t = Table(; a, b, c) T = Remainder() n, c = apply(T, t) total = first(first(c)) tₒ = revert(T, n, c) Xt = Tables.matrix(t) Xn = Tables.matrix(n) @test Xn[:, 1:(end - 1)] == Xt @test all(x -> 0 ≤ x ≤ total, Xn[:, end]) @test Tables.schema(n).names == (:a, :b, :c, :remainder) @test Tables.schema(tₒ).names == (:a, :b, :c) t = Table(a=[1.0, 10.0, 0.0], b=[1.0, 5.0, 0.0], c=[4.0, 2.0, 1.0]) n = reapply(T, t, c) Xn = Tables.matrix(n) @test all(x -> 0 ≤ x ≤ total, Xn[:, end]) t = Table(a=[1.0, 10.0, 0.0], b=[1.0, 5.0, 0.0], remainder=[4.0, 2.0, 1.0]) n = t |> Remainder(18.3) @test Tables.schema(n).names == (:a, :b, :remainder, :remainder_) n1, c1 = apply(Remainder(), t) n2 = reapply(Remainder(), t, c1) @test n1 == n2 @test_throws AssertionError apply(Remainder(8.3), t) end
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
3868
@testset "Rename" begin a = rand(10) b = rand(10) c = rand(10) d = rand(10) t = Table(; a, b, c, d) # integer => symbol T = Rename(1 => :x, 3 => :y) n, c = apply(T, t) @test Tables.columnnames(n) == (:x, :b, :y, :d) tₒ = revert(T, n, c) @test t == tₒ T = Rename(2 => :x, 4 => :y) n, c = apply(T, t) @test Tables.columnnames(n) == (:a, :x, :c, :y) tₒ = revert(T, n, c) @test t == tₒ # integer => string T = Rename(1 => "x", 3 => "y") n, c = apply(T, t) @test Tables.columnnames(n) == (:x, :b, :y, :d) tₒ = revert(T, n, c) @test t == tₒ T = Rename(2 => "x", 4 => "y") n, c = apply(T, t) @test Tables.columnnames(n) == (:a, :x, :c, :y) tₒ = revert(T, n, c) @test t == tₒ # symbol = symbol T = Rename(:a => :x) n, c = apply(T, t) @test Tables.columnnames(n) == (:x, :b, :c, :d) tₒ = revert(T, n, c) @test t == tₒ T = Rename(:a => :x, :c => :y) n, c = apply(T, t) @test Tables.columnnames(n) == (:x, :b, :y, :d) tₒ = revert(T, n, c) @test t == tₒ T = Rename(:b => :x, :d => :y) n, c = apply(T, t) @test Tables.columnnames(n) == (:a, :x, :c, :y) tₒ = revert(T, n, c) @test t == tₒ # symbol => string T = Rename(:a => "x", :c => "y") n, c = apply(T, t) @test Tables.columnnames(n) == (:x, :b, :y, :d) tₒ = revert(T, n, c) @test t == tₒ T = Rename(:b => "x", :d => "y") n, c = apply(T, t) @test Tables.columnnames(n) == (:a, :x, :c, :y) tₒ = revert(T, n, c) @test t == tₒ # string => symbol T = Rename("a" => :x) n, c = apply(T, t) @test Tables.columnnames(n) == (:x, :b, :c, :d) tₒ = revert(T, n, c) @test t == tₒ T = Rename("a" => :x, "c" => :y) n, c = apply(T, t) @test Tables.columnnames(n) == (:x, :b, :y, :d) tₒ = revert(T, n, c) @test t == tₒ T = Rename("b" => :x, "d" => :y) n, c = apply(T, t) @test Tables.columnnames(n) == (:a, :x, :c, :y) tₒ = revert(T, n, c) @test t == tₒ # string => string T = Rename("a" => "x", "c" => "y") n, c = apply(T, t) @test Tables.columnnames(n) == (:x, :b, :y, :d) tₒ = revert(T, n, c) @test t == tₒ T = Rename("b" => "x", "d" => "y") n, c = apply(T, t) @test Tables.columnnames(n) == (:a, :x, :c, :y) tₒ = revert(T, n, c) @test t == tₒ # row table rt = Tables.rowtable(t) T = Rename(:a => :x, :c => :y) n, c = apply(T, rt) @test Tables.isrowtable(n) rtₒ = revert(T, n, c) @test rt == rtₒ # reapply test T = Rename(:b => :x, :d => :y) n1, c1 = apply(T, t) n2 = reapply(T, t, c1) @test n1 == n2 # vector of pairs T = Rename([1 => :x, 3 => :y]) n, c = apply(T, t) @test Tables.schema(n).names == (:x, :b, :y, :d) tₒ = revert(T, n, c) @test t == tₒ T = Rename([2, 4] .=> ["x", "y"]) n, c = apply(T, t) @test Tables.schema(n).names == (:a, :x, :c, :y) tₒ = revert(T, n, c) @test t == tₒ T = Rename([:a => :x, :c => :y]) n, c = apply(T, t) @test Tables.schema(n).names == (:x, :b, :y, :d) tₒ = revert(T, n, c) @test t == tₒ T = Rename([:b, :d] .=> ["x", "y"]) n, c = apply(T, t) @test Tables.schema(n).names == (:a, :x, :c, :y) tₒ = revert(T, n, c) @test t == tₒ T = Rename(["a" => :x, "c" => :y]) n, c = apply(T, t) @test Tables.schema(n).names == (:x, :b, :y, :d) tₒ = revert(T, n, c) @test t == tₒ T = Rename(["b", "d"] .=> ["x", "y"]) n, c = apply(T, t) @test Tables.schema(n).names == (:a, :x, :c, :y) tₒ = revert(T, n, c) @test t == tₒ T = Rename(nm -> nm * "_test") n, c = apply(T, t) @test Tables.schema(n).names == (:a_test, :b_test, :c_test, :d_test) tₒ = revert(T, n, c) @test t == tₒ # error: cannot create Rename transform without arguments @test_throws ArgumentError Rename() # error: new names must be unique @test_throws AssertionError Rename(:a => :x, :b => :x) @test_throws AssertionError apply(Rename(:a => :c, :b => :d), t) end
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
4080
@testset "Replace" begin @test !isrevertible(Replace(1 => -1, 5 => -5)) a = [3, 2, 1, 4, 5, 3] b = [2, 4, 4, 5, 8, 5] c = [1, 1, 6, 2, 4, 1] d = [4, 3, 7, 5, 4, 1] e = [5, 5, 2, 6, 5, 2] f = [4, 4, 3, 4, 5, 2] t = Table(; a, b, c, d, e, f) # replace with a value of the same type T = Replace(1 => -1, 5 => -5) n, c = apply(T, t) @test n.a == [3, 2, -1, 4, -5, 3] @test n.b == [2, 4, 4, -5, 8, -5] @test n.c == [-1, -1, 6, 2, 4, -1] @test n.d == [4, 3, 7, -5, 4, -1] @test n.e == [-5, -5, 2, 6, -5, 2] @test n.f == [4, 4, 3, 4, -5, 2] # with colspec T = Replace(2 => 4 => -4, :c => 1 => -1, "e" => 5 => -5) n, c = apply(T, t) @test n.a == [3, 2, 1, 4, 5, 3] @test n.b == [2, -4, -4, 5, 8, 5] @test n.c == [-1, -1, 6, 2, 4, -1] @test n.d == [4, 3, 7, 5, 4, 1] @test n.e == [-5, -5, 2, 6, -5, 2] @test n.f == [4, 4, 3, 4, 5, 2] T = Replace([2, 5] => 5 => -5) n, c = apply(T, t) @test n.a == [3, 2, 1, 4, 5, 3] @test n.b == [2, 4, 4, -5, 8, -5] @test n.c == [1, 1, 6, 2, 4, 1] @test n.d == [4, 3, 7, 5, 4, 1] @test n.e == [-5, -5, 2, 6, -5, 2] @test n.f == [4, 4, 3, 4, 5, 2] T = Replace([:b, :e] => 5 => -5) n, c = apply(T, t) @test n.a == [3, 2, 1, 4, 5, 3] @test n.b == [2, 4, 4, -5, 8, -5] @test n.c == [1, 1, 6, 2, 4, 1] @test n.d == [4, 3, 7, 5, 4, 1] @test n.e == [-5, -5, 2, 6, -5, 2] @test n.f == [4, 4, 3, 4, 5, 2] T = Replace(["b", "e"] => 5 => -5) n, c = apply(T, t) @test n.a == [3, 2, 1, 4, 5, 3] @test n.b == [2, 4, 4, -5, 8, -5] @test n.c == [1, 1, 6, 2, 4, 1] @test n.d == [4, 3, 7, 5, 4, 1] @test n.e == [-5, -5, 2, 6, -5, 2] @test n.f == [4, 4, 3, 4, 5, 2] T = Replace(r"[be]" => 5 => -5) n, c = apply(T, t) @test n.a == [3, 2, 1, 4, 5, 3] @test n.b == [2, 4, 4, -5, 8, -5] @test n.c == [1, 1, 6, 2, 4, 1] @test n.d == [4, 3, 7, 5, 4, 1] @test n.e == [-5, -5, 2, 6, -5, 2] @test n.f == [4, 4, 3, 4, 5, 2] # with predicates T = Replace([:b, :d] => >(4) => 0) n, c = apply(T, t) @test n.a == [3, 2, 1, 4, 5, 3] @test n.b == [2, 4, 4, 0, 0, 0] @test n.c == [1, 1, 6, 2, 4, 1] @test n.d == [4, 3, 0, 0, 4, 1] @test n.e == [5, 5, 2, 6, 5, 2] @test n.f == [4, 4, 3, 4, 5, 2] T = Replace([:a, :f] => (x -> 1 < x < 5) => 0) n, c = apply(T, t) @test n.a == [0, 0, 1, 0, 5, 0] @test n.b == [2, 4, 4, 5, 8, 5] @test n.c == [1, 1, 6, 2, 4, 1] @test n.d == [4, 3, 7, 5, 4, 1] @test n.e == [5, 5, 2, 6, 5, 2] @test n.f == [0, 0, 0, 0, 5, 0] # table schema after apply T = Replace(1 => -1, 5 => -5) n, c = apply(T, t) types = Tables.schema(t).types @test types == Tables.schema(n).types # replace with a value of another type T = Replace(1 => 1.5, 5 => 5.5, 4 => true) n, c = apply(T, t) @test n.a == Real[3, 2, 1.5, true, 5.5, 3] @test n.b == Real[2, true, true, 5.5, 8, 5.5] @test n.c == Real[1.5, 1.5, 6, 2, true, 1.5] @test n.d == Real[true, 3, 7, 5.5, true, 1.5] @test n.e == Real[5.5, 5.5, 2, 6, 5.5, 2] @test n.f == Real[true, true, 3, true, 5.5, 2] # table schema after apply T = Replace(1 => 1.5, 5 => 5.5, 4 => true) n, c = apply(T, t) ntypes = Tables.schema(n).types @test ntypes[1] == Real @test ntypes[2] == Real @test ntypes[3] == Real @test ntypes[4] == Real @test ntypes[5] == Real @test ntypes[6] == Real # no occurrences T = Replace(10 => 11, 20 => 30) n, c = apply(T, t) @test t == n # columns with different types a = [3, 2, 1, 4, 5, 3] b = [2.5, 4.5, 4.7, 2.5, 2.5, 5.3] c = [true, false, false, false, true, false] d = ['a', 'b', 'c', 'd', 'e', 'a'] t = Table(; a, b, c, d) T = Replace(3 => -3, 2.5 => 2.0, true => false, 'a' => 'A') n, c = apply(T, t) @test n.a == [-3, 2, 1, 4, 5, -3] @test n.b == [2.0, 4.5, 4.7, 2.0, 2.0, 5.3] @test n.c == [false, false, false, false, false, false] @test n.d == ['A', 'b', 'c', 'd', 'e', 'A'] # row table rt = Tables.rowtable(t) T = Replace(3 => -3, 2.5 => 2.0) n, c = apply(T, rt) @test Tables.isrowtable(n) # throws @test_throws ArgumentError Replace() end
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
273
@testset "RowTable" begin a = [3, 2, 1, 4, 5, 3] b = [1, 4, 4, 5, 8, 5] c = [1, 1, 6, 2, 4, 1] t = Table(; a, b, c) T = RowTable() n, c = apply(T, t) tₒ = revert(T, n, c) @test typeof(n) <: Vector @test Tables.rowaccess(n) @test typeof(tₒ) <: Table end
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
2295
@testset "Sample" begin @test !isrevertible(Sample(30)) a = [3, 6, 2, 7, 8, 3] b = [8, 5, 1, 2, 3, 4] c = [1, 8, 5, 2, 9, 4] t = Table(; a, b, c) T = Sample(30, replace=true) n, c = apply(T, t) @test length(n.a) == 30 T = Sample(6, replace=false) n, c = apply(T, t) @test n.a ⊆ t.a @test n.b ⊆ t.b @test n.c ⊆ t.c T = Sample(30, replace=true, ordered=true) n, c = apply(T, t) trows = Tables.rowtable(t) @test unique(Tables.rowtable(n)) == trows T = Sample(6, replace=false, ordered=true) n, c = apply(T, t) @test n.a ⊆ t.a @test n.b ⊆ t.b @test n.c ⊆ t.c @test Tables.rowtable(n) == trows T = Sample(8, replace=true, rng=MersenneTwister(2)) n, c = apply(T, t) @test n.a == [3, 7, 8, 2, 2, 6, 2, 6] @test n.b == [8, 2, 3, 1, 1, 5, 1, 5] @test n.c == [1, 2, 9, 5, 5, 8, 5, 8] w = pweights([0.1, 0.25, 0.15, 0.25, 0.1, 0.15]) T = Sample(10_000, w, replace=true, rng=MersenneTwister(2)) n, c = apply(T, t) nrows = Tables.rowtable(n) @test isapprox(count(==(trows[1]), nrows) / 10_000, 0.10, atol=0.01) @test isapprox(count(==(trows[2]), nrows) / 10_000, 0.25, atol=0.01) @test isapprox(count(==(trows[3]), nrows) / 10_000, 0.15, atol=0.01) @test isapprox(count(==(trows[4]), nrows) / 10_000, 0.25, atol=0.01) @test isapprox(count(==(trows[5]), nrows) / 10_000, 0.10, atol=0.01) @test isapprox(count(==(trows[6]), nrows) / 10_000, 0.15, atol=0.01) w = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0] T = Sample(10_000, w, replace=true, rng=MersenneTwister(2)) n, c = apply(T, t) nrows = Tables.rowtable(n) @test isapprox(count(==(trows[1]), nrows) / 10_000, 1 / 21, atol=0.01) @test isapprox(count(==(trows[2]), nrows) / 10_000, 2 / 21, atol=0.01) @test isapprox(count(==(trows[3]), nrows) / 10_000, 3 / 21, atol=0.01) @test isapprox(count(==(trows[4]), nrows) / 10_000, 4 / 21, atol=0.01) @test isapprox(count(==(trows[5]), nrows) / 10_000, 5 / 21, atol=0.01) @test isapprox(count(==(trows[6]), nrows) / 10_000, 6 / 21, atol=0.01) # performance tests trng = MersenneTwister(2) # test rng x = rand(trng, 100_000) y = rand(trng, 100_000) c = CoDaArray((a=rand(trng, 100_000), b=rand(trng, 100_000), c=rand(trng, 100_000))) t = (; x, y, c) T = Sample(10_000) @test @elapsed(apply(T, t)) < 0.5 end
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
1509
@testset "Satisfies" begin @test !isrevertible(Satisfies(allunique)) a = [1, 2, 3, 4, 5, 6] b = [6, 5, 4, 3, 2, 1] c = [1, 2, 3, 4, 6, 6] d = [6, 6, 4, 3, 2, 1] t = Table(; a, b, c, d) T = Satisfies(allunique) n, c = apply(T, t) @test Tables.schema(n).names == (:a, :b) @test Tables.getcolumn(n, :a) == t.a @test Tables.getcolumn(n, :b) == t.b T = Satisfies(x -> sum(x) > 21) n, c = apply(T, t) @test Tables.schema(n).names == (:c, :d) @test Tables.getcolumn(n, :c) == t.c @test Tables.getcolumn(n, :d) == t.d end @testset "Only" begin a = rand(10) b = rand(Float32, 10) c = rand(1:9, 10) d = rand('a':'z', 10) t = Table(; a, b, c, d) T = Only(DST.Continuous) n, c = apply(T, t) @test Tables.schema(n).names == (:a, :b) @test Tables.getcolumn(n, :a) == t.a @test Tables.getcolumn(n, :b) == t.b T = Only(DST.Categorical) n, c = apply(T, t) @test Tables.schema(n).names == (:c, :d) @test Tables.getcolumn(n, :c) == t.c @test Tables.getcolumn(n, :d) == t.d end @testset "Except" begin a = rand(10) b = rand(Float32, 10) c = rand(1:9, 10) d = rand('a':'z', 10) t = Table(; a, b, c, d) T = Except(DST.Categorical) n, c = apply(T, t) @test Tables.schema(n).names == (:a, :b) @test Tables.getcolumn(n, :a) == t.a @test Tables.getcolumn(n, :b) == t.b T = Except(DST.Continuous) n, c = apply(T, t) @test Tables.schema(n).names == (:c, :d) @test Tables.getcolumn(n, :c) == t.c @test Tables.getcolumn(n, :d) == t.d end
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
8609
@testset "Select" begin @test !isrevertible(Select(:a, :b, :c)) a = rand(10) b = rand(10) c = rand(10) d = rand(10) e = rand(10) f = rand(10) t = Table(; a, b, c, d, e, f) T = Select(:f, :d) n, c = apply(T, t) @test Tables.columnnames(n) == [:f, :d] T = Select(:f, :d, :b) n, c = apply(T, t) @test Tables.columnnames(n) == [:f, :d, :b] T = Select(:d, :c, :b) n, c = apply(T, t) @test Tables.columnnames(n) == [:d, :c, :b] T = Select(:e, :c, :b, :a) n, c = apply(T, t) @test Tables.columnnames(n) == [:e, :c, :b, :a] # selection with tuples T = Select((:e, :c, :b, :a)) n, c = apply(T, t) @test Tables.columnnames(n) == [:e, :c, :b, :a] # selection with vectors T = Select([:e, :c, :b, :a]) n, c = apply(T, t) @test Tables.columnnames(n) == [:e, :c, :b, :a] # selection with strings T = Select("d", "c", "b") n, c = apply(T, t) @test Tables.columnnames(n) == [:d, :c, :b] # selection with tuple of strings T = Select(("d", "c", "b")) n, c = apply(T, t) @test Tables.columnnames(n) == [:d, :c, :b] # selection with vector of strings T = Select(["d", "c", "b"]) n, c = apply(T, t) @test Tables.columnnames(n) == [:d, :c, :b] # selection with integers T = Select(4, 3, 2) n, c = apply(T, t) @test Tables.columnnames(n) == [:d, :c, :b] # selection with tuple of integers T = Select((4, 3, 2)) n, c = apply(T, t) @test Tables.columnnames(n) == [:d, :c, :b] # selection with vector of integers T = Select([4, 3, 2]) n, c = apply(T, t) @test Tables.columnnames(n) == [:d, :c, :b] # reapply test T = Select(:b, :c, :d) n1, c1 = apply(T, t) n2 = reapply(T, t, c1) @test n1 == n2 # selection with renaming a = rand(10) b = rand(10) c = rand(10) d = rand(10) t = Table(; a, b, c, d) # integer => symbol T = Select(1 => :x, 3 => :y) n, c = apply(T, t) @test Tables.columnnames(n) == [:x, :y] @test Tables.getcolumn(n, :x) == t.a @test Tables.getcolumn(n, :y) == t.c # integer => string T = Select(2 => "x", 4 => "y") n, c = apply(T, t) @test Tables.columnnames(n) == [:x, :y] @test Tables.getcolumn(n, :x) == t.b @test Tables.getcolumn(n, :y) == t.d # symbol => symbol T = Select(:a => :x, :c => :y) n, c = apply(T, t) @test Tables.columnnames(n) == [:x, :y] @test Tables.getcolumn(n, :x) == t.a @test Tables.getcolumn(n, :y) == t.c # symbol => string T = Select(:b => "x", :d => "y") n, c = apply(T, t) @test Tables.columnnames(n) == [:x, :y] @test Tables.getcolumn(n, :x) == t.b @test Tables.getcolumn(n, :y) == t.d T = Select(:a => :x1, :b => :x2, :c => :x3, :d => :x4) n, c = apply(T, t) @test Tables.columnnames(n) == [:x1, :x2, :x3, :x4] @test Tables.getcolumn(n, :x1) == t.a @test Tables.getcolumn(n, :x2) == t.b @test Tables.getcolumn(n, :x3) == t.c @test Tables.getcolumn(n, :x4) == t.d # string => symbol T = Select("a" => :x, "c" => :y) n, c = apply(T, t) @test Tables.columnnames(n) == [:x, :y] @test Tables.getcolumn(n, :x) == t.a @test Tables.getcolumn(n, :y) == t.c # string => string T = Select("b" => "x", "d" => "y") n, c = apply(T, t) @test Tables.columnnames(n) == [:x, :y] @test Tables.getcolumn(n, :x) == t.b @test Tables.getcolumn(n, :y) == t.d T = Select("a" => "x1", "b" => "x2", "c" => "x3", "d" => "x4") n, c = apply(T, t) @test Tables.columnnames(n) == [:x1, :x2, :x3, :x4] @test Tables.getcolumn(n, :x1) == t.a @test Tables.getcolumn(n, :x2) == t.b @test Tables.getcolumn(n, :x3) == t.c @test Tables.getcolumn(n, :x4) == t.d # row table rt = Tables.rowtable(t) cols = Tables.columns(rt) T = Select(:a => :x, :c => :y) n, c = apply(T, rt) @test Tables.columnnames(n) == [:x, :y] @test Tables.getcolumn(n, :x) == Tables.getcolumn(cols, :a) @test Tables.getcolumn(n, :y) == Tables.getcolumn(cols, :c) # reapply test T = Select(:b => :x, :d => :y) n1, c1 = apply(T, t) n2 = reapply(T, t, c1) @test n1 == n2 # selection with Regex T = Select(r"[dcb]") n, c = apply(T, t) @test Tables.columnnames(n) == [:b, :c, :d] # the order of columns is preserved x1 = rand(10) x2 = rand(10) y1 = rand(10) y2 = rand(10) t = Table(; x1, x2, y1, y2) # select columns whose names contain the character x T = Select(r"x") n, c = apply(T, t) @test Tables.columnnames(n) == [:x1, :x2] # select columns whose names contain the character y T = Select(r"y") n, c = apply(T, t) @test Tables.columnnames(n) == [:y1, :y2] # row table rt = Tables.rowtable(t) T = Select(r"y") n, c = apply(T, rt) @test Tables.columnnames(n) == [:y1, :y2] # throws: Select without arguments @test_throws ArgumentError Select() # throws: empty selection @test_throws ArgumentError Select(()) @test_throws ArgumentError Select(Symbol[]) @test_throws ArgumentError Select(String[]) # throws: regex doesn't match any names in input table @test_throws AssertionError apply(Select(r"a"), t) # throws: columns that do not exist in the original table @test_throws AssertionError apply(Select(:x3, :y3), t) @test_throws AssertionError apply(Select([:x3, :y3]), t) @test_throws AssertionError apply(Select((:x3, :y3)), t) @test_throws AssertionError apply(Select("x3", "y3"), t) @test_throws AssertionError apply(Select(["x3", "y3"]), t) @test_throws AssertionError apply(Select(("x3", "y3")), t) end @testset "Reject" begin @test !isrevertible(Reject(:a, :b, :c)) a = rand(10) b = rand(10) c = rand(10) d = rand(10) e = rand(10) f = rand(10) t = Table(; a, b, c, d, e, f) T = Reject(:f, :d) n, c = apply(T, t) @test Tables.columnnames(n) == [:a, :b, :c, :e] T = Reject(:f, :d, :b) n, c = apply(T, t) @test Tables.columnnames(n) == [:a, :c, :e] T = Reject(:d, :c, :b) n, c = apply(T, t) @test Tables.columnnames(n) == [:a, :e, :f] T = Reject(:e, :c, :b, :a) n, c = apply(T, t) @test Tables.columnnames(n) == [:d, :f] # rejection with tuples T = Reject((:e, :c, :b, :a)) n, c = apply(T, t) @test Tables.columnnames(n) == [:d, :f] # rejection with vectors T = Reject([:e, :c, :b, :a]) n, c = apply(T, t) @test Tables.columnnames(n) == [:d, :f] # rejection with strings T = Reject("d", "c", "b") n, c = apply(T, t) @test Tables.columnnames(n) == [:a, :e, :f] # rejection with tuple of strings T = Reject(("d", "c", "b")) n, c = apply(T, t) @test Tables.columnnames(n) == [:a, :e, :f] # rejection with vector of strings T = Reject(["d", "c", "b"]) n, c = apply(T, t) @test Tables.columnnames(n) == [:a, :e, :f] # rejection with integers T = Reject(4, 3, 2) n, c = apply(T, t) @test Tables.columnnames(n) == [:a, :e, :f] # rejection with tuple of integers T = Reject((4, 3, 2)) n, c = apply(T, t) @test Tables.columnnames(n) == [:a, :e, :f] # rejection with vector of integers T = Reject([4, 3, 2]) n, c = apply(T, t) @test Tables.columnnames(n) == [:a, :e, :f] # reapply test T = Reject(:b, :c, :d) n1, c1 = apply(T, t) n2 = reapply(T, t, c1) @test n1 == n2 # rejection with Regex T = Reject(r"[dcb]") n, c = apply(T, t) @test Tables.columnnames(n) == [:a, :e, :f] # the order of columns is preserved x1 = rand(10) x2 = rand(10) y1 = rand(10) y2 = rand(10) t = Table(; x1, x2, y1, y2) # reject columns whose names contain the character x T = Reject(r"x") n, c = apply(T, t) @test Tables.columnnames(n) == [:y1, :y2] # reject columns whose names contain the character y T = Reject(r"y") n, c = apply(T, t) @test Tables.columnnames(n) == [:x1, :x2] # row table rt = Tables.rowtable(t) T = Reject(r"y") n, c = apply(T, rt) @test Tables.columnnames(n) == [:x1, :x2] # throws: Reject without arguments @test_throws ArgumentError Reject() # throws: empty rejection @test_throws ArgumentError Reject(()) @test_throws ArgumentError Reject(Symbol[]) @test_throws ArgumentError Reject(String[]) # throws: regex doesn't match any names in input table @test_throws AssertionError apply(Reject(r"a"), t) # throws: reject all columns @test_throws ArgumentError apply(Reject(r"[xy]"), t) @test_throws ArgumentError apply(Reject(:x1, :x2, :y1, :y2), t) @test_throws ArgumentError apply(Reject([:x1, :x2, :y1, :y2]), t) @test_throws ArgumentError apply(Reject((:x1, :x2, :y1, :y2)), t) @test_throws ArgumentError apply(Reject("x1", "x2", "y1", "y2"), t) @test_throws ArgumentError apply(Reject(["x1", "x2", "y1", "y2"]), t) @test_throws ArgumentError apply(Reject(["x1", "x2", "y1", "y2"]), t) end
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
677
@testset "Sequential" begin x = rand(Normal(0, 10), 1500) y = x + rand(Normal(0, 2), 1500) z = y + rand(Normal(0, 5), 1500) t = Table(; x, y, z) T = LowHigh(low=0.2, high=0.8) → EigenAnalysis(:VDV) n, c = apply(T, t) tₒ = revert(T, n, c) @test Tables.matrix(t) ≈ Tables.matrix(tₒ) # reapply with Sequential transform t = Table(x=rand(100)) T = ZScore() → Quantile() n1, c1 = apply(T, t) n2 = reapply(T, t, c1) @test n1 == n2 # row table rt = Tables.rowtable(t) T = LowHigh(low=0.2, high=0.8) → EigenAnalysis(:VDV) n, c = apply(T, rt) @test Tables.isrowtable(n) rtₒ = revert(T, n, c) @test Tables.matrix(rt) ≈ Tables.matrix(rtₒ) end
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
2174
@testset "Sort" begin @test !isrevertible(Sort(:a)) a = [5, 3, 1, 2] b = [2, 4, 8, 5] c = [3, 2, 1, 4] d = [4, 3, 7, 5] t = Table(; a, b, c, d) T = Sort(:a) n, c = apply(T, t) @test Tables.schema(t) == Tables.schema(n) @test n.a == [1, 2, 3, 5] @test n.b == [8, 5, 4, 2] @test n.c == [1, 4, 2, 3] @test n.d == [7, 5, 3, 4] # descending order test T = Sort(:b, rev=true) n, c = apply(T, t) @test Tables.schema(t) == Tables.schema(n) @test n.a == [1, 2, 3, 5] @test n.b == [8, 5, 4, 2] @test n.c == [1, 4, 2, 3] @test n.d == [7, 5, 3, 4] # random test a = rand(10) b = rand(10) c = rand(10) d = rand(10) t = Table(; a, b, c, d) T = Sort(:c) n, c = apply(T, t) @test Tables.schema(t) == Tables.schema(n) @test issetequal(Tables.rowtable(t), Tables.rowtable(n)) @test issorted(Tables.getcolumn(n, :c)) # sort by multiple columns a = [-2, -1, -2, 2, 1, -1, 1, 2] b = [-8, -4, 6, 9, 8, 2, 2, -8] c = [-3, 6, 5, 4, -8, -7, -1, -10] t = Table(; a, b, c) T = Sort(1, 2) n, c = apply(T, t) @test n.a == [-2, -2, -1, -1, 1, 1, 2, 2] @test n.b == [-8, 6, -4, 2, 2, 8, -8, 9] @test n.c == [-3, 5, 6, -7, -1, -8, -10, 4] T = Sort([:a, :c], rev=true) n, c = apply(T, t) @test n.a == [2, 2, 1, 1, -1, -1, -2, -2] @test n.b == [9, -8, 2, 8, -4, 2, 6, -8] @test n.c == [4, -10, -1, -8, 6, -7, 5, -3] T = Sort(("b", "c"), by=row -> abs.(row)) n, c = apply(T, t) @test n.a == [1, -1, -1, -2, -2, 1, 2, 2] @test n.b == [2, 2, -4, 6, -8, 8, -8, 9] @test n.c == [-1, -7, 6, 5, -3, -8, -10, 4] # throws: Sort without arguments @test_throws ArgumentError Sort() # throws: empty selection @test_throws ArgumentError Sort(()) @test_throws ArgumentError Sort(Symbol[]) @test_throws ArgumentError Sort(String[]) # throws: regex doesn't match any names in input table @test_throws AssertionError apply(Sort(r"x"), t) # throws: columns that do not exist in the original table @test_throws AssertionError apply(Sort([:d, :e]), t) @test_throws AssertionError apply(Sort(("d", "e")), t) # Invalid kwarg @test_throws MethodError apply(Sort(:a, :b, test=1), t) end
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
613
@testset "StdFeats" begin @test isrevertible(StdFeats()) a = rand(1:10, 100) b = rand(Normal(7, 10), 100) c = rand('a':'z', 100) d = rand(Normal(15, 2), 100) e = rand(["y", "n"], 100) t = Table(; a, b, c, d, e) T = StdFeats() n, c = apply(T, t) @test n.a == t.a @test isapprox(mean(n.b), 0; atol=1e-6) @test isapprox(std(n.b), 1; atol=1e-6) @test n.c == t.c @test isapprox(mean(n.d), 0; atol=1e-6) @test isapprox(std(n.d), 1; atol=1e-6) @test n.e == t.e tₒ = revert(T, n, c) @test tₒ.a == t.a @test tₒ.b ≈ t.b @test tₒ.c == t.c @test tₒ.d ≈ t.d @test tₒ.e == t.e end
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
4234
@testset "StdNames" begin names = Symbol.(["_apple tree_", " banana-fruit ", "-pear\tseed-"]) columns = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] t = Table(; zip(names, columns)...) T = StdNames(:uppersnake) n, c = apply(T, t) @test Tables.schema(n).names == (:APPLE_TREE, :BANANA_FRUIT, :PEAR_SEED) tₒ = revert(T, n, c) @test t == tₒ T = StdNames(:uppercamel) n, c = apply(T, t) @test Tables.schema(n).names == (:AppleTree, :BananaFruit, :PearSeed) tₒ = revert(T, n, c) @test t == tₒ T = StdNames(:upperflat) n, c = apply(T, t) @test Tables.schema(n).names == (:APPLETREE, :BANANAFRUIT, :PEARSEED) tₒ = revert(T, n, c) @test t == tₒ T = StdNames(:snake) n, c = apply(T, t) @test Tables.schema(n).names == (:apple_tree, :banana_fruit, :pear_seed) tₒ = revert(T, n, c) @test t == tₒ T = StdNames(:camel) n, c = apply(T, t) @test Tables.schema(n).names == (:appleTree, :bananaFruit, :pearSeed) tₒ = revert(T, n, c) @test t == tₒ T = StdNames(:flat) n, c = apply(T, t) @test Tables.schema(n).names == (:appletree, :bananafruit, :pearseed) tₒ = revert(T, n, c) @test t == tₒ # titlecase names = Symbol.(["_apPLe trEe_", " baNaNA-fRuIt ", "-peAR\tsEEd-"]) t = Table(; zip(names, columns)...) T = StdNames(:uppercamel) n, c = apply(T, t) @test Tables.schema(n).names == (:AppleTree, :BananaFruit, :PearSeed) tₒ = revert(T, n, c) @test t == tₒ T = StdNames(:camel) n, c = apply(T, t) @test Tables.schema(n).names == (:appleTree, :bananaFruit, :pearSeed) tₒ = revert(T, n, c) @test t == tₒ # internal functions names = ["apple banana", "apple\tbanana", "apple_banana", "apple-banana", "apple_Banana"] for name in names @test TT._uppersnake(name) == "APPLE_BANANA" @test TT._uppercamel(name) == "AppleBanana" @test TT._upperflat(name) == "APPLEBANANA" @test TT._snake(name) == "apple_banana" @test TT._camel(name) == "appleBanana" @test TT._flat(name) == "applebanana" end names = ["a", "A", "_a", "_A", "a ", "A "] for name in names @test TT._uppersnake(TT._clean(name)) == "A" @test TT._uppercamel(TT._clean(name)) == "A" @test TT._upperflat(TT._clean(name)) == "A" @test TT._snake(TT._clean(name)) == "a" @test TT._camel(TT._clean(name)) == "a" @test TT._flat(TT._clean(name)) == "a" end # special characters name = "a&B" @test TT._clean(name) == "aB" name = "apple#" @test TT._clean(name) == "apple" name = "apple-tree" @test TT._clean(name) == "apple-tree" # invariance test names = ["APPLE_TREE", "BANANA_FRUIT", "PEAR_SEED"] for name in names @test TT._isuppersnake(name) @test TT._uppersnake(name) == name end names = ["AppleTree", "BananaFruit", "PearSeed"] for name in names @test TT._isuppercamel(name) @test TT._uppercamel(name) == name end names = ["APPLETREE", "BANANAFRUIT", "PEARSEED"] for name in names @test TT._isupperflat(name) @test TT._upperflat(name) == name end names = ["apple_tree", "banana_fruit", "pear_seed"] for name in names @test TT._issnake(name) @test TT._snake(name) == name end names = ["appleTree", "bananaFruit", "pearSeed"] for name in names @test TT._iscamel(name) @test TT._camel(name) == name end names = ["appletree", "bananafruit", "pearseed"] for name in names @test TT._isflat(name) @test TT._flat(name) == name end # uniqueness test names = (Symbol("AppleTree"), Symbol("apple tree"), Symbol("apple_tree")) columns = ([1, 2, 3], [4, 5, 6], [7, 8, 9]) t = Table(; zip(names, columns)...) rt = Tables.rowtable(t) T = StdNames(:upperflat) n, c = apply(T, rt) @test Tables.schema(n).names == (:APPLETREE, :APPLETREE_, :APPLETREE__) # row table test names = (:a, Symbol("apple tree"), Symbol("banana tree")) columns = ([1, 2, 3], [4, 5, 6], [7, 8, 9]) t = Table(; zip(names, columns)...) rt = Tables.rowtable(t) T = StdNames() n, c = apply(T, rt) @test Tables.isrowtable(n) @test isrevertible(T) rtₒ = revert(T, n, c) @test rt == rtₒ # reapply test T = StdNames() n1, c1 = apply(T, rt) n2 = reapply(T, n1, c1) @test n1 == n2 # throws @test_throws ArgumentError StdNames(:test) end
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
4977
@testset "Unit" begin @test isrevertible(Unit(u"m")) a = [2.7, 2.9, 2.2, 1.4, 1.8, 3.3] * u"m" b = [300, 500, missing, 800, missing, 400] * u"cm" c = [8, 2, 5, 7, 9, 4] * u"km" d = [0.3, 0.1, 0.9, 0.2, 0.7, 0.4] e = ["no", "no", "yes", "yes", "no", "yes"] t = Table(; a, b, c, d, e) T = Unit(u"m") n, c = apply(T, t) @test unit(eltype(n.a)) == u"m" @test unit(eltype(n.b)) == u"m" @test unit(eltype(n.c)) == u"m" @test eltype(n.d) <: Float64 @test eltype(n.e) <: String tₒ = revert(T, n, c) @test unit(eltype(tₒ.a)) == u"m" @test unit(eltype(tₒ.b)) == u"cm" @test unit(eltype(tₒ.c)) == u"km" @test all(isapprox.(tₒ.a, t.a)) @test all(isapprox.(skipmissing(tₒ.b), skipmissing(t.b))) @test all(isapprox.(tₒ.c, t.c)) @test tₒ.d == t.d @test tₒ.e == t.e a = [2.7, 2.9, 2.2, 1.4, 1.8, 3.3] * u"m" b = [300, 500, missing, 800, missing, 400] * u"cm" c = [8, 2, 5, 7, 9, 4] * u"km" d = [29.1, missing, 29.2, missing, 28.4, 26.4] * u"°C" e = [0.9, 0.4, 0.5, 0.1, 0.3, 0.6] * u"kg" f = 0.5u"ppm" * e t = Table(; a, b, c, d, e, f) T = Unit(4 => u"K") n, c = apply(T, t) @test unit(eltype(n.a)) == u"m" @test unit(eltype(n.b)) == u"cm" @test unit(eltype(n.c)) == u"km" @test unit(eltype(n.d)) == u"K" @test unit(eltype(n.e)) == u"kg" @test unit(eltype(n.f)) == u"kg * ppm" tₒ = revert(T, n, c) @test unit(eltype(tₒ.d)) == u"°C" @test tₒ.a == t.a @test isequal(tₒ.b, t.b) @test tₒ.c == t.c @test all(isapprox.(skipmissing(tₒ.d), skipmissing(t.d))) @test tₒ.e == t.e @test tₒ.f == t.f T = Unit(:e => u"g") n, c = apply(T, t) @test unit(eltype(n.a)) == u"m" @test unit(eltype(n.b)) == u"cm" @test unit(eltype(n.c)) == u"km" @test unit(eltype(n.d)) == u"°C" @test unit(eltype(n.e)) == u"g" @test unit(eltype(n.f)) == u"kg * ppm" tₒ = revert(T, n, c) @test unit(eltype(tₒ.e)) == u"kg" @test tₒ.a == t.a @test isequal(tₒ.b, t.b) @test tₒ.c == t.c @test isequal(tₒ.d, t.d) @test all(isapprox.(tₒ.e, t.e)) @test tₒ.f == t.f T = Unit("f" => u"kg") n, c = apply(T, t) @test unit(eltype(n.a)) == u"m" @test unit(eltype(n.b)) == u"cm" @test unit(eltype(n.c)) == u"km" @test unit(eltype(n.d)) == u"°C" @test unit(eltype(n.e)) == u"kg" @test unit(eltype(n.f)) == u"kg" tₒ = revert(T, n, c) @test unit(eltype(tₒ.f)) == u"kg * ppm" @test tₒ.a == t.a @test isequal(tₒ.b, t.b) @test tₒ.c == t.c @test isequal(tₒ.d, t.d) @test tₒ.e == t.e @test all(isapprox.(tₒ.f, t.f)) T = Unit([1, 2, 3] => u"m") n, c = apply(T, t) @test unit(eltype(n.a)) == u"m" @test unit(eltype(n.b)) == u"m" @test unit(eltype(n.c)) == u"m" @test unit(eltype(n.d)) == u"°C" @test unit(eltype(n.e)) == u"kg" @test unit(eltype(n.f)) == u"kg * ppm" tₒ = revert(T, n, c) @test unit(eltype(tₒ.a)) == u"m" @test unit(eltype(tₒ.b)) == u"cm" @test unit(eltype(tₒ.c)) == u"km" @test all(isapprox.(tₒ.a, t.a)) @test all(isapprox.(skipmissing(tₒ.b), skipmissing(t.b))) @test all(isapprox.(tₒ.c, t.c)) @test isequal(tₒ.d, t.d) @test tₒ.e == t.e @test tₒ.f == t.f T = Unit([:a, :b, :c] => u"cm") n, c = apply(T, t) @test unit(eltype(n.a)) == u"cm" @test unit(eltype(n.b)) == u"cm" @test unit(eltype(n.c)) == u"cm" @test unit(eltype(n.d)) == u"°C" @test unit(eltype(n.e)) == u"kg" @test unit(eltype(n.f)) == u"kg * ppm" tₒ = revert(T, n, c) @test unit(eltype(tₒ.a)) == u"m" @test unit(eltype(tₒ.b)) == u"cm" @test unit(eltype(tₒ.c)) == u"km" @test all(isapprox.(tₒ.a, t.a)) @test all(isapprox.(skipmissing(tₒ.b), skipmissing(t.b))) @test all(isapprox.(tₒ.c, t.c)) @test isequal(tₒ.d, t.d) @test tₒ.e == t.e @test tₒ.f == t.f T = Unit(["a", "b", "c"] => u"km") n, c = apply(T, t) @test unit(eltype(n.a)) == u"km" @test unit(eltype(n.b)) == u"km" @test unit(eltype(n.c)) == u"km" @test unit(eltype(n.d)) == u"°C" @test unit(eltype(n.e)) == u"kg" @test unit(eltype(n.f)) == u"kg * ppm" tₒ = revert(T, n, c) @test unit(eltype(tₒ.a)) == u"m" @test unit(eltype(tₒ.b)) == u"cm" @test unit(eltype(tₒ.c)) == u"km" @test all(isapprox.(tₒ.a, t.a)) @test all(isapprox.(skipmissing(tₒ.b), skipmissing(t.b))) @test all(isapprox.(tₒ.c, t.c)) @test isequal(tₒ.d, t.d) @test tₒ.e == t.e @test tₒ.f == t.f T = Unit(r"[abc]" => u"m") n, c = apply(T, t) @test unit(eltype(n.a)) == u"m" @test unit(eltype(n.b)) == u"m" @test unit(eltype(n.c)) == u"m" @test unit(eltype(n.d)) == u"°C" @test unit(eltype(n.e)) == u"kg" @test unit(eltype(n.f)) == u"kg * ppm" tₒ = revert(T, n, c) @test unit(eltype(tₒ.a)) == u"m" @test unit(eltype(tₒ.b)) == u"cm" @test unit(eltype(tₒ.c)) == u"km" @test all(isapprox.(tₒ.a, t.a)) @test all(isapprox.(skipmissing(tₒ.b), skipmissing(t.b))) @test all(isapprox.(tₒ.c, t.c)) @test isequal(tₒ.d, t.d) @test tₒ.e == t.e @test tₒ.f == t.f # error: cannot create Unit transform without arguments @test_throws ArgumentError Unit() end
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
1524
@testset "Unitify" begin @test isrevertible(Unitify()) anm = Symbol("a [m]") bnm = :b cnm = Symbol("c [km/hr]") dnm = :d enm = Symbol("e [°C]") a = rand(10) b = rand(10) c = rand(10) d = rand(10) e = rand(10) t = Table(; anm => a, bnm => b, cnm => c, dnm => d, enm => e) T = Unitify() n, c = apply(T, t) @test Tables.schema(n).names == (:a, :b, :c, :d, :e) @test unit(eltype(n.a)) === u"m" @test unit(eltype(n.b)) === NoUnits @test unit(eltype(n.c)) === u"km/hr" @test unit(eltype(n.d)) === NoUnits @test unit(eltype(n.e)) === u"°C" tₒ = revert(T, n, c) @test tₒ == t # no units t = Table(; Symbol("a []") => rand(10), Symbol("b [NoUnits]") => rand(10)) T = Unitify() n, c = apply(T, t) @test Tables.schema(n).names == (:a, :b) @test unit(eltype(n.a)) === NoUnits @test unit(eltype(n.b)) === NoUnits tₒ = revert(T, n, c) @test tₒ == t # invalid unit name t = Table(; Symbol("a [test]") => rand(10)) T = Unitify() n, c = @test_logs (:warn, "The unit \"test\" is not valid") apply(T, t) @test Tables.schema(n).names == (:a,) @test unit(eltype(n.a)) === NoUnits tₒ = revert(T, n, c) @test tₒ == t # non-numeric columns t = Table(; anm => a, :b => rand('a':'z', 10), :c => categorical(rand(["yes", "no"], 10))) T = Unitify() n, c = apply(T, t) @test Tables.schema(n).names == (:a, :b, :c) @test unit(eltype(n.a)) === u"m" @test eltype(n.b) <: Char @test eltype(n.c) <: CategoricalValue tₒ = revert(T, n, c) @test tₒ == t end
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
code
2575
@testset "ZScore" begin x = rand(rng, Normal(7, 10), 4000) y = rand(rng, Normal(15, 2), 4000) t = Table(; x, y) T = ZScore() n, c = apply(T, t) μ = mean(Tables.matrix(n), dims=1) σ = std(Tables.matrix(n), dims=1) @test isapprox(μ[1], 0; atol=1e-6) @test isapprox(σ[1], 1; atol=1e-6) @test isapprox(μ[2], 0; atol=1e-6) @test isapprox(σ[2], 1; atol=1e-6) tₒ = revert(T, n, c) @test Tables.matrix(t) ≈ Tables.matrix(tₒ) # row table rt = Tables.rowtable(t) T = ZScore() n, c = apply(T, rt) @test Tables.isrowtable(n) rtₒ = revert(T, n, c) @test Tables.matrix(rt) ≈ Tables.matrix(rtₒ) # make sure transform works with single-column tables t = Table(x=rand(100)) n, c = apply(ZScore(), t) r = revert(ZScore(), n, c) @test isapprox(mean(n.x), 0.0, atol=1e-8) @test isapprox(std(n.x), 1.0, atol=1e-8) @test isapprox(mean(r.x), mean(t.x), atol=1e-8) @test isapprox(std(r.x), std(t.x), atol=1e-8) # colspec z = x + y t = Table(; x, y, z) T = ZScore(1, 2) n, c = apply(T, t) μ = mean(Tables.matrix(n), dims=1) σ = std(Tables.matrix(n), dims=1) @test isapprox(μ[1], 0; atol=1e-6) @test isapprox(σ[1], 1; atol=1e-6) @test isapprox(μ[2], 0; atol=1e-6) @test isapprox(σ[2], 1; atol=1e-6) tₒ = revert(T, n, c) @test Tables.matrix(t) ≈ Tables.matrix(tₒ) T = ZScore([:x, :y]) n, c = apply(T, t) μ = mean(Tables.matrix(n), dims=1) σ = std(Tables.matrix(n), dims=1) @test isapprox(μ[1], 0; atol=1e-6) @test isapprox(σ[1], 1; atol=1e-6) @test isapprox(μ[2], 0; atol=1e-6) @test isapprox(σ[2], 1; atol=1e-6) tₒ = revert(T, n, c) @test Tables.matrix(t) ≈ Tables.matrix(tₒ) T = ZScore(("x", "y")) n, c = apply(T, t) μ = mean(Tables.matrix(n), dims=1) σ = std(Tables.matrix(n), dims=1) @test isapprox(μ[1], 0; atol=1e-6) @test isapprox(σ[1], 1; atol=1e-6) @test isapprox(μ[2], 0; atol=1e-6) @test isapprox(σ[2], 1; atol=1e-6) tₒ = revert(T, n, c) @test Tables.matrix(t) ≈ Tables.matrix(tₒ) T = ZScore(r"[xy]") n, c = apply(T, t) μ = mean(Tables.matrix(n), dims=1) σ = std(Tables.matrix(n), dims=1) @test isapprox(μ[1], 0; atol=1e-6) @test isapprox(σ[1], 1; atol=1e-6) @test isapprox(μ[2], 0; atol=1e-6) @test isapprox(σ[2], 1; atol=1e-6) tₒ = revert(T, n, c) @test Tables.matrix(t) ≈ Tables.matrix(tₒ) a = rand(Int, 10) b = rand(10) t = Table(; a, b) T = ZScore(:b) n, c = apply(T, t) @test isapprox(mean(n.b), 0; atol=1e-6) @test isapprox(std(n.b), 1; atol=1e-6) tₒ = revert(T, n, c) @test Tables.matrix(t) ≈ Tables.matrix(tₒ) end
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
docs
1785
<p align="center"> <img src="docs/src/assets/logo.png" height="200"><br> <a href="https://github.com/JuliaML/TableTransforms.jl/actions"> <img src="https://img.shields.io/github/actions/workflow/status/JuliaML/TableTransforms.jl/CI.yml?branch=master&style=flat-square"> </a> <a href="https://codecov.io/gh/JuliaML/TableTransforms.jl"> <img src="https://img.shields.io/codecov/c/github/JuliaML/TableTransforms.jl?style=flat-square"> </a> <a href="https://JuliaML.github.io/TableTransforms.jl/stable"> <img src="https://img.shields.io/badge/docs-stable-blue?style=flat-square"> </a> <a href="https://JuliaML.github.io/TableTransforms.jl/dev"> <img src="https://img.shields.io/badge/docs-latest-blue?style=flat-square"> </a> <a href="LICENSE"> <img src="https://img.shields.io/badge/license-MIT-blue.svg?style=flat-square"> </a> </p> This package provides transforms that are commonly used in statistics and machine learning. It was developed to address specific needs in feature engineering and works with general [Tables.jl](https://github.com/JuliaData/Tables.jl) tables. ## Installation Get the latest stable release with Julia's package manager: ``` ] add TableTransforms ``` ## Documentation - [**STABLE**][docs-stable-url] &mdash; **most recently tagged version of the documentation.** - [**LATEST**][docs-latest-url] &mdash; *in-development version of the documentation.* ## Contributing Contributions are very welcome. Please [open an issue](https://github.com/JuliaML/TableTransforms.jl/issues) if you have questions. We have open issues with missing transforms that you can contribute. [docs-stable-url]: https://JuliaML.github.io/TableTransforms.jl/stable [docs-latest-url]: https://JuliaML.github.io/TableTransforms.jl/dev
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
docs
6430
# Developer guide A short guide for extending the interface as a developer. ## Motivation TableTransforms.jl currently supports over 25 different transforms that cover a wide variety of use cases ranging from ordinary table operations to complex statistical transformations, which can be arbitrarily composed with one another through elegant syntax. It is easy to leverage all this functionality as a developer of new transforms, and this is the motivation of this guide. ## Basic assumptions All the transforms in this package implement the transforms interface defined in the TransformsBase.jl package so this is really the only dependency needed. The interface assumes the following about new transforms: * Transforms operate on a single table * Transforms may be associated with some state that if computed while applying it for the first time and is then cached can help later reapply the transform on another table without recomputing the state * The transform may be revertible, meaning that a transformed table can be brought back to its original form, and it may need to use the cache for that * Your transform may be invertible in the mathematical sense !!! note "Revertible does not imply invertible" Reversibility assumes that the transform has been applied already and can be undone. On the other hand, invertibility implies that there is a one-to-one mapping between the input and output tables so a table can be inverted to a corresponding input even if it was not transformed a priori. ## Defining a new transform In the following we shall demonstrate the steps to define a new transform. ### 1. Declare a new type for your transform The type should subtype `TransformsBase.Transform` and it should have a named field for each parameter needed to apply the transform besides the input table. For instance, if you want to call your transform `Standardize` and it takes two boolean inputs `center` and `scale` , then you should declare: ```julia struct Standardize <: TransformsBase.Transform center::Bool scale::Bool end ``` You may implement keyword constructors as needed if some of the parameters are optional: ```julia Standardize(; center::Bool=true, scale::Bool=true) = Standardize(center, scale) ``` ### 2. Implement the `apply` method for your transform The `apply` method takes an instance of your transform type and a table and returns a new table and cache. Suppose that the `Standardize` transform should zero-mean each column if `center` is true and scale each column to unit variance if `scale` is true, then the `apply` method should be implemented as follows: ```julia using Statistics function TransformsBase.apply(transform::Standardize, X) # convert the table to a matrix and get col names Xm = Tables.matrix(X) names = Tables.columnnames(X) # compute the means and stds μ = transform.center ? mean(Xm, dims=1) : zeros(1, size(Xm, 2)) σ = transform.scale ? std(Xm, dims=1) : ones(1, size(Xm, 2)) # standardize the data Xm = (Xm .- μ) ./ σ # convert matrix to column table Xc = (; zip(names, eachcol(Xm))...) # convert back to original table type X = Xc |> Tables.materializer(X) # return the table and cache that may help reapply or revert later return X, (μ, σ) end ``` That's it really! Your transform now behaves like any table transform: ```julia using TableTransforms X = (A=[1, 2, 3], B=[4, 5, 6]) Xt = X |> Standardize() |> Identity() |> Select([:A]) ``` It holds, however, that in case your transform can be reapplied, is revertible, or is invertible then you should continue implementing the interface to support such functionality. ### 3. Optionally implement `reapply` We need this in case of the `Standarize` transform because after computing the mean and std for some training table we may want to apply the transform directly given a test table. Hence, we implement `reapply` which has the same signature as apply but it takes an extra argument for the cache and doesn't return it. ```julia function TransformsBase.reapply(transform::Standardize, X, cache) # convert the table to a matrix and get col names Xm = Tables.matrix(X) names = Tables.columnnames(X) # no need to recompute means and stds μ, σ = cache # standardize the data Xm = (Xm .- μ) ./ σ # convert matrix to column table Xc = (; zip(names, eachcol(Xm))...) # convert back to original table type X = Xc |> Tables.materializer(X) return X end ``` If not implemented, `reapply` simply falls back to `apply`. ### 4. Optionally specify that your transform is revertible and implement `revert` We can specify reversibility for an arbitrary transform `T` by setting `isrevertible(::Type{T})` to `true`. It's obvious that this should be supported by our transform so we do ```julia TransformsBase.isrevertible(::Type{Standardize}) = true ``` By default this falls back to `false` so users of the interface would be aware that revert is not implemented in that case. Now we follow up by implementing the `revert` method: ```julia function TransformsBase.revert(transform::Standardize, X, cache) # convert the table to a matrix and get col names Xm = Tables.matrix(X) names = Tables.columnnames(X) # extract the mean and std μ, σ = cache # revert the transform Xm = Xm .* σ .+ μ # convert matrix to column table Xc = (; zip(names, eachcol(Xm))...) # convert back to original table type X = Xc |> Tables.materializer(X) return X end ``` ### 5. Optionally specify that your transform is invertible and implement `Base.inv` Similar to reversibility, falls back to `false` by default. We can write that explicitly here since `Standardize` has no inverse if we are given nothing except for the table. ```julia TransformsBase.isinvertible(::Type{Standardize}) = false ``` If an arbitrary transform `T` is invertible we can rather specify that as `true` and follow up by implementing `Base.inv(::T)` which would be expected to return an instance of the inverse transform. For instance, for an identity transform we can do ```julia # interface struct struct Identity <: Transform end # specify that it is invertible TransformsBase.isinvertible(::Type{Identity}) = true # implement Base.inv Base.inv(::Identity) = Identity() ``` which implies that `inv(Identity())` would return an identity transform.
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
docs
5541
# TableTransforms.jl *Transforms and pipelines with tabular data.* ## Overview This package provides transforms that are commonly used in statistics and machine learning. It was developed to address specific needs in feature engineering and works with general [Tables.jl](https://github.com/JuliaData/Tables.jl) tables. Past attempts to model transforms in Julia such as [FeatureTransforms.jl](https://github.com/invenia/FeatureTransforms.jl) served as inspiration for this package. We are happy to absorb any missing transform, and contributions are very welcome. ## Features - Transforms are **revertible** meaning that one can apply a transform and undo the transformation without having to do all the manual work keeping constants around. - Pipelines can be easily constructed with clean syntax `(f1 → f2 → f3) ⊔ (f4 → f5)`, and they are automatically revertible when the individual transforms are revertible. - Branches of a pipeline and colwise transforms are run in parallel using multiple processes with the Distributed standard library. - Pipelines can be reapplied to unseen "test" data using the same cache (e.g. constants) fitted with "training" data. For example, a `ZScore` relies on "fitting" `μ` and `σ` once at training time. ## Rationale A common task in statistics and machine learning consists of transforming the variables of a problem to achieve better convergence or to apply methods that rely on multivariate Gaussian distributions. This process can be quite tedious to implement by hand and very error-prone. We provide a consistent and clean API to combine statistical transforms into pipelines. *Although most transforms discussed here come from the statistical domain, our long term vision is more ambitious. We aim to provide a complete user experience with fully-featured pipelines that include standardization of column names, imputation of missing data, and more.* ## Usage Consider the following table and its pairplot: ```@example usage using TableTransforms using CairoMakie, PairPlots using Random; Random.seed!(2) # hide # example table from PairPlots.jl N = 100_000 a = [2randn(N÷2) .+ 6; randn(N÷2)] b = [3randn(N÷2); 2randn(N÷2)] c = randn(N) d = c .+ 0.6randn(N) table = (; a, b, c, d) # pairplot of original table table |> pairplot ``` We can convert the columns to PCA scores: ```@example usage # convert to PCA scores table |> PCA() |> pairplot ``` or to any marginal distribution: ```@example usage using Distributions # convert to any Distributions.jl table |> Quantile(dist=Normal()) |> pairplot ``` Below is a more sophisticated example with a pipeline that has two parallel branches. The tables produced by these two branches are concatenated horizontally in the final table: ```@example usage # create a transform pipeline f1 = ZScore() f2 = LowHigh() f3 = Quantile() f4 = Functional(cos) f5 = Interquartile() pipeline = (f1 → f2 → f3) ⊔ (f4 → f5) # feed data into the pipeline table |> pipeline |> pairplot ``` Each branch is a sequence of transforms constructed with the `→` (`\to<tab>`) operator. The branches are placed in parallel with the `⊔` (`\sqcup<tab>`) operator. ```@docs → TransformsBase.SequentialTransform ⊔ TableTransforms.ParallelTableTransform ``` ### Reverting transforms To revert a pipeline or single transform, use the [`apply`](@ref) and [`revert`](@ref) functions instead. The function [`isrevertible`](@ref) can be used to check if a transform is revertible. ```@docs apply revert isrevertible ``` To exemplify the use of these functions, let's create a table: ```@example usage a = [-1.0, 4.0, 1.6, 3.4] b = [1.6, 3.4, -1.0, 4.0] c = [3.4, 2.0, 3.6, -1.0] table = (; a, b, c) ``` Now, let's choose a transform and check that it is revertible: ```@example usage transform = Center() isrevertible(transform) ``` We apply the transformation to the table and save the cache in a variable: ```@example usage newtable, cache = apply(transform, table) newtable ``` Using the cache we can revert the transform: ```@example usage original = revert(transform, newtable, cache) ``` ### Inverting transforms Some transforms have an inverse that can be created with the [`inverse`](@ref) function. The function [`isinvertible`](@ref) can be used to check if a transform is invertible. ```@docs inverse isinvertible ``` Let's exemplify this: ```@example usage a = [5.1, 1.5, 9.4, 2.4] b = [7.6, 6.2, 5.8, 3.0] c = [6.3, 7.9, 7.6, 8.4] table = (; a, b, c) ``` Choose a transform and check that it is invertible: ```@example usage transform = Functional(exp) isinvertible(transform) ``` Now, let's test the inverse transform: ```@example usage invtransform = inverse(transform) invtransform(transform(table)) ``` ### Reapplying transforms Finally, it is sometimes useful to [`reapply`](@ref) a transform that was "fitted" with training data to unseen test data. In this case, the cache from a previous [`apply`](@ref) call is used: ```@docs reapply ``` Consider the following example: ```@example usage traintable = (a = rand(3), b = rand(3), c = rand(3)) testtable = (a = rand(3), b = rand(3), c = rand(3)) transform = ZScore() # ZScore transform "fits" μ and σ using training data newtable, cache = apply(transform, traintable) # we can reuse the same values of μ and σ with test data newtable = reapply(transform, testtable, cache) ``` Note that this result is different from the result returned by the [`apply`](@ref) function: ```@example usage newtable, cache = apply(transform, testtable) newtable ```
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
docs
1876
# Related - [FeatureTransforms.jl](https://github.com/invenia/FeatureTransforms.jl) has transforms, but they are not fully revertible. Some of their transforms such as `MeanStdScaling` are constructed for a specific table and cannot be inserted in the middle of a pipeline for example. - [AutoMLPipeline.jl](https://github.com/IBM/AutoMLPipeline.jl) relies on the Python stack via [PyCall.jl](https://github.com/JuliaPy/PyCall.jl). They provide pipelines with Julia's pipe `|>` operator and follow a more "Pythonic" interface. They do not support general [Tables.jl](https://github.com/JuliaData/Tables.jl). - [Impute.jl](https://github.com/invenia/Impute.jl), [Cleaner.jl](https://github.com/TheRoniOne/Cleaner.jl), [DataConvenience.jl](https://github.com/xiaodaigh/DataConvenience.jl) all have a small set of transforms related to fixing column names as well as other basic transforms that we plan to absorb in the long term. - [DataFramesMeta.jl](https://github.com/jkrumbiegel/Chain.jl) is a package to manipulate [DataFrames.jl](https://github.com/JuliaData/DataFrames.jl) tables. It is not intended for statistical transforms such as `PCA`, `Quantile`, etc, which rely on complex interactions between the rows and columns of a table. The usage of macros in the package promotes one-shot scripts as opposed to general pipelines that can be passed around to different places in the program. - [Query.jl](https://github.com/queryverse/Query.jl) is a package to query [IterableTables.jl](https://github.com/queryverse/IterableTables.jl). Similar to other alternatives above, the package is not intended for advanced statistical transforms. - [MLJ.jl](https://alan-turing-institute.github.io/MLJ.jl/dev/) is a popular machine learning framework in Julia that adopts a different design for pipelines based on mutability of structs.
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.33.5
9635db5d125f39b6407e60ee895349a028c61aa6
docs
1735
# Transforms Below is the list of transforms that are are available in this package. # Assert ```@docs Assert ``` ## Select ```@docs Select ``` ## Reject ```@docs Reject ``` ## Satisfies ```@docs Satisfies ``` ## Only ```@docs Only ``` ## Except ```@docs Except ``` ## Rename ```@docs Rename ``` ## StdNames ```@docs StdNames ``` ## StdFeats ```@docs StdFeats ``` ## Sort ```@docs Sort ``` ## Sample ```@docs Sample ``` ## Filter ```@docs Filter ``` ## DropMissing ```@docs DropMissing ``` ## DropNaN ```@docs DropNaN ``` ## DropExtrema ```@docs DropExtrema ``` ## DropUnits ```@docs DropUnits ``` ## DropConstant ```@docs DropConstant ``` ## AbsoluteUnits ```@docs AbsoluteUnits ``` ## Unitify ```@docs Unitify ``` ## Unit ```@docs Unit ``` ## Map ```@docs Map ``` ## Replace ```@docs Replace ``` ## Coalesce ```@docs Coalesce ``` ## Coerce ```@docs Coerce ``` ## Levels ```@docs Levels ``` ## Indicator ```@docs Indicator ``` ## OneHot ```@docs OneHot ``` ## Identity ```@docs Identity ``` ## Center ```@docs Center ``` ## LowHigh ```@docs LowHigh ``` ## MinMax ```@docs MinMax ``` ## Interquartile ```@docs Interquartile ``` ## ZScore ```@docs ZScore ``` ## Quantile ```@docs Quantile ``` ## Functional ```@docs Functional ``` ## EigenAnalysis ```@docs EigenAnalysis ``` ## PCA ```@docs PCA ``` ## DRS ```@docs DRS ``` ## SDS ```@docs SDS ``` ## ProjectionPursuit ```@docs ProjectionPursuit ``` ## Closure ```@docs Closure ``` ## Remainder ```@docs Remainder ``` ## Compose ```@docs Compose ``` ## ALR ```@docs ALR ``` ## CLR ```@docs CLR ``` ## ILR ```@docs ILR ``` ## RowTable ```@docs RowTable ``` ## ColTable ```@docs ColTable ```
TableTransforms
https://github.com/JuliaML/TableTransforms.jl.git
[ "MIT" ]
1.0.0
e044808e0bffd6932140479d57d2ed7e8b565be2
code
798
using DiagnosisClassification using Documenter DocMeta.setdocmeta!(DiagnosisClassification, :DocTestSetup, :(using DiagnosisClassification); recursive=true) makedocs(; modules=[DiagnosisClassification], authors="Dilum Aluthge, Brown Center for Biomedical Informatics, and contributors", repo="https://github.com/JuliaHealth/DiagnosisClassification.jl/blob/{commit}{path}#{line}", sitename="DiagnosisClassification.jl", format=Documenter.HTML(; prettyurls=get(ENV, "CI", "false") == "true", canonical="https://JuliaHealth.github.io/DiagnosisClassification.jl", assets=String[], ), pages=[ "Home" => "index.md", ], strict=true, ) deploydocs(; repo="github.com/JuliaHealth/DiagnosisClassification.jl", devbranch="main", )
DiagnosisClassification
https://github.com/JuliaHealth/DiagnosisClassification.jl.git
[ "MIT" ]
1.0.0
e044808e0bffd6932140479d57d2ed7e8b565be2
code
357
module DiagnosisClassification import CSV import Downloads import Pkg import ProgressMeter import Scratch import TOML include("types.jl") include("dict_utils.jl") include("download.jl") include("convenience/icd9.jl") include("convenience/icd10.jl") include("dots/icd9.jl") include("dots/icd10.jl") include("init.jl") include("TODO.jl") end # module
DiagnosisClassification
https://github.com/JuliaHealth/DiagnosisClassification.jl.git
[ "MIT" ]
1.0.0
e044808e0bffd6932140479d57d2ed7e8b565be2
code
3456
function generate_ccs9_to_icd9(download_cache = ensure_downloaded_files()) ccs_filename = joinpath(download_cache, "ccs9.txt") ccs_filecontents = strip(read(ccs_filename, String)::String) elements = strip.(split(ccs_filecontents, "\n\n")) ccs9_to_icd9 = Dict{Class, Set{Class}}() ccs9_to_ccs_description = Dict{Class, String}() for element in elements if startswith(element, "Appendix A - ") continue end if startswith(element, "Revised ") continue end element2 = replace(element, '`' => ''') r = r"^(\d\d*?)\s\s*?([A-Za-z() :;,\-'\/]*?)\s*?\n([\S\s]*?)$" m = match(r, element2) (m === nothing) && @error("Could not parse element", element2) ccs_value = strip(m[1]) ccs_description = strip(m[2]) ccs_node = construct_ccs9(ccs_value) icd_values = strip.(split(strip(replace(m[3], '\n' => ' ')), ' ')) filter!(x -> !isempty(x), icd_values) icd_nodes = construct_icd9.(icd_values) icd_set = Set{Class}(icd_nodes) setindex_no_overwrite!( ccs9_to_icd9, ccs_node, icd_set, ) setindex_no_overwrite!( ccs9_to_ccs_description, ccs_node, ccs_description, ) end return (; ccs9_to_icd9, ccs9_to_ccs_description) end function generate_ccs10_to_icd10(download_cache = ensure_downloaded_files()) ccs_filename = joinpath(download_cache, "ccs10.csv") ccs_file = CSV.File(ccs_filename) all_column_names_str = String.(ccs_file.names) unique!(all_column_names_str) sort!(all_column_names_str) ccs_column_names_str = filter( x -> startswith(x, "'CCSR CATEGORY ") && !occursin("DESCRIPTION", x), all_column_names_str, ) unique!(ccs_column_names_str) sort!(ccs_column_names_str) remove_single_quotes = x -> begin r = r"^'(.*?)'$" m = match(r, x) (m === nothing) && @error("Could not parse", x) return convert(String, m[1])::String end ccscolname_to_ccsdesccolname = x -> begin return "'" * remove_single_quotes(x) * " DESCRIPTION'" end (length(ccs_column_names_str) < 1) && throw(ErrorException("Not enough CCS category columns")) ccs10_to_icd10 = Dict{Class, Set{Class}}() ccs10_to_ccs_description = Dict{Class, String}() for row in ccs_file icd_value = remove_single_quotes(row[Symbol("'ICD-10-CM CODE'")]) icd_node = construct_icd10(icd_value) for ccscolname in ccs_column_names_str ccs_value = row[Symbol(ccscolname)] |> remove_single_quotes |> strip if isempty(ccs_value) continue end ccs_node = construct_ccs10(ccs_value) if !haskey(ccs10_to_icd10, ccs_node) ccs10_to_icd10[ccs_node] = Set{Class}() end push!(ccs10_to_icd10[ccs_node], icd_node) ccsdesccolname = ccscolname_to_ccsdesccolname.(ccscolname) ccs_description = row[Symbol(ccsdesccolname)] |> strip ccs_description_string = convert(String, ccs_description)::String setindex_same_value!( ccs10_to_ccs_description, ccs_node, ccs_description_string, ) end end return (; ccs10_to_icd10, ccs10_to_ccs_description) end
DiagnosisClassification
https://github.com/JuliaHealth/DiagnosisClassification.jl.git
[ "MIT" ]
1.0.0
e044808e0bffd6932140479d57d2ed7e8b565be2
code
781
function setindex_no_overwrite!( dict::AbstractDict{<:K, <:V}, key::K, new_value, ) where {K, V} if !haskey(dict, key) dict[key] = new_value return nothing end old_value = dict[key] msg = "Duplicate key found" @error msg key old_value new_value throw(ErrorException(msg)) end function setindex_same_value!( dict::AbstractDict{<:K, <:V}, key::K, new_value, ) where {K, V} if !haskey(dict, key) dict[key] = new_value return nothing end old_value = dict[key] if old_value !== new_value # we require egality msg = "Duplicate key found" @error msg key old_value new_value throw(ErrorException(msg)) end return nothing end
DiagnosisClassification
https://github.com/JuliaHealth/DiagnosisClassification.jl.git
[ "MIT" ]
1.0.0
e044808e0bffd6932140479d57d2ed7e8b565be2
code
1831
function ensure_downloaded_files() global download_cache download_cache::String if isempty(readdir(download_cache)) force_download_files(download_cache) end return download_cache::String end function force_download_files(dest_directory::AbstractString) let url = "https://www.hcup-us.ahrq.gov/toolssoftware/ccs/AppendixASingleDX.txt" @info "Downloading files for CCS9" sleep(3) # Sleep for a bit, so that we can be compliant with any rate limits src = Downloads.download(url) dest_filename = "ccs9.txt" dest = joinpath( dest_directory, dest_filename, ) mv(src, dest; force = true) end let url = "https://www.hcup-us.ahrq.gov/toolssoftware/ccsr/DXCCSR_v2022-1.zip" @info "Downloading files for CCS10" sleep(3) # Sleep for a bit, so that we can be compliant with any rate limits downloaded_filename = Downloads.download(url) dest_filename = "ccs10.csv" dest = joinpath( dest_directory, dest_filename, ) _extract_zip_file(downloaded_filename) do extraction_output_dir src = joinpath(extraction_output_dir, "DXCCSR_v2022-1.CSV") mv(src, dest) end end return nothing end function _extract_zip_file( f::F, zip_file::AbstractString, ) where {F <: Function} mktempdir() do extraction_output_dir cd(extraction_output_dir) do extraction_cmd = `$(Pkg.PlatformEngines.exe7z())` push!(extraction_cmd.exec, "x") push!(extraction_cmd.exec, "$(zip_file)") push!(extraction_cmd.exec, "-o$(extraction_output_dir)") run(extraction_cmd) f(extraction_output_dir) end end return nothing end
DiagnosisClassification
https://github.com/JuliaHealth/DiagnosisClassification.jl.git