Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Simplify Imputor API #69

Merged
merged 19 commits into from
Oct 14, 2020
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
cdef813
Remove `context` to simplify imputation code.
rofinn Sep 29, 2020
f1c863f
Replace context limits with a threshold assertion type.
rofinn Sep 29, 2020
640e2cb
Introduce function interface for threshold.
rofinn Sep 29, 2020
1500ece
Initial work on improving support for `dims` and other cleanup.
rofinn Sep 30, 2020
4772961
Finished reworking dims changes.
rofinn Oct 1, 2020
6e6497e
Simplify dims code a bit more by explicitly using NamedDims.jl
rofinn Oct 1, 2020
43fc0fc
Chain is no longer an imputor.
rofinn Oct 1, 2020
c992d51
Added a Standardize imputor which handles replace user defined 'missi…
rofinn Oct 2, 2020
bc15b8f
Replaced Impute.Fill with Impute.Replace for constants and Impute.Sub…
rofinn Oct 3, 2020
10f3737
Update doctests and run documenter doctests in runtests.jl.
rofinn Oct 6, 2020
8ed73e4
Finish moving various imputor testsets into independent files.
rofinn Oct 6, 2020
850d119
Added more NamedDims and AxisKeys tests.
rofinn Oct 6, 2020
0bba5aa
Lots of documentation updates and minor bug fixes/improvements.
rofinn Oct 8, 2020
af45737
Run CI on julia 1.5 and move deprecated matrix block into jobs so doc…
rofinn Oct 8, 2020
8213ce3
Removed redundant/unreachable code and added more tests.
rofinn Oct 9, 2020
27dfb99
Minor changes from review comments.
rofinn Oct 11, 2020
701d85b
Use a ThresholdError for clearer error messages.
rofinn Oct 11, 2020
bb98aa9
Fix outdated imputor docstring.
rofinn Oct 11, 2020
6c3b6d8
Test Threshold showerror method.
rofinn Oct 14, 2020
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion docs/make.jl
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ makedocs(
pages=[
"Home" => "index.md",
"Impute" => "api/impute.md",
"Context" => "api/context.md",
"Imputors" => "api/imputors.md",
"Utilities" => "api/utils.md",
],
Expand Down
5 changes: 0 additions & 5 deletions docs/src/api/context.md

This file was deleted.

63 changes: 39 additions & 24 deletions src/Impute.jl
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,20 @@ using LinearAlgebra: Diagonal

import Base.Iterators: drop

#=
TODO List:
- [X] Drop Context
- [X] Introduce a separate Threshold type and `assert` function
- [X] Update old tests cases to use new type
- [ ] Add deprecations for old `context` calls
- [ ] Generalize the dimensionality behaviour using a `dims` keyword similar to the stats functions
https://github.com/JuliaLang/Statistics.jl/blob/master/src/Statistics.jl#L164
- [ ] Drop in-place calls
- [ ] Base imputors should dispatch on `impute(AbstractArray{Union{T, Missing}}, imp)`
- [ ] Replace `dropobs` and `dropvars` with `Impute.drop` and a `dims` keyword
- [ ] Make `Chain` not an imputor and have it work on `Assertions` and `Imputors`
- [ ] Add function for checking if a methods support some input data?
=#
"""
ImputeError{T} <: Exception

Expand All @@ -30,14 +44,15 @@ end

Base.showerror(io::IO, err::ImputeError) = println(io, "ImputeError: $(err.msg)")

include("context.jl")
include("utils.jl")
include("assertions.jl")
include("imputors.jl")

#=
These default methods are required because @auto_hash_equals doesn't
play nice with Base.@kwdef
=#
function Base.hash(imp::T, h::UInt) where T <: Union{Imputor, AbstractContext}
function Base.hash(imp::T, h::UInt) where T <: Imputor
h = hash(Symbol(T), h)

for f in fieldnames(T)
Expand All @@ -47,7 +62,7 @@ function Base.hash(imp::T, h::UInt) where T <: Union{Imputor, AbstractContext}
return h
end

function Base.:(==)(a::T, b::T) where T <: Union{Imputor, AbstractContext}
function Base.:(==)(a::T, b::T) where T <: Imputor
result = true

for f in fieldnames(T)
Expand Down Expand Up @@ -89,14 +104,14 @@ for (f, v) in pairs(imputation_methods)
end

@doc """
Impute.dropobs(data; dims=1, context=Context())
Impute.dropobs(data; dims=1)

Removes missing observations from the `AbstractArray` or `Tables.table` provided.
See [DropObs](@ref) for details.

# Example
```
julia> using DataFrames; using Impute: Impute, Context
julia> using DataFrames; using Impute: Impute

julia> df = DataFrame(:a => [1.0, 2.0, missing, missing, 5.0], :b => [1.1, 2.2, 3.3, missing, 5.5])
5×2 DataFrames.DataFrame
Expand All @@ -109,7 +124,7 @@ julia> df = DataFrame(:a => [1.0, 2.0, missing, missing, 5.0], :b => [1.1, 2.2,
│ 4 │ missing │ missing │
│ 5 │ 5.0 │ 5.5 │

julia> Impute.dropobs(df; dims=2, context=Context(; limit=1.0))
julia> Impute.dropobs(df; dims=2)
3×2 DataFrames.DataFrame
│ Row │ a │ b │
│ │ Float64 │ Float64 │
Expand All @@ -121,14 +136,14 @@ julia> Impute.dropobs(df; dims=2, context=Context(; limit=1.0))
""" dropobs

@doc """
Impute.dropvars(data; dims=1, context=Context())
Impute.dropvars(data; dims=1)

Finds variables with too many missing values in a `AbstractMatrix` or `Tables.table` and
removes them from the input data. See [DropVars](@ref) for details.

# Example
```jldoctest
julia> using DataFrames; using Impute: Impute, Context
julia> using DataFrames; using Impute: Impute

julia> df = DataFrame(:a => [1.0, 2.0, missing, missing, 5.0], :b => [1.1, 2.2, 3.3, missing, 5.5])
5×2 DataFrames.DataFrame
Expand All @@ -141,7 +156,7 @@ julia> df = DataFrame(:a => [1.0, 2.0, missing, missing, 5.0], :b => [1.1, 2.2,
│ 4 │ missing │ missing │
│ 5 │ 5.0 │ 5.5 │

julia> Impute.dropvars(df; context=Context(; limit=0.2))
julia> Impute.dropvars(df)
5×1 DataFrames.DataFrame
│ Row │ b │
│ │ Float64 │
Expand All @@ -155,14 +170,14 @@ julia> Impute.dropvars(df; context=Context(; limit=0.2))
""" dropvars

@doc """
Impute.interp(data; dims=1, context=Context())
Impute.interp(data; dims=1)

Performs linear interpolation between the nearest values in an vector.
See [Interpolate](@ref) for details.

# Example
```jldoctest
julia> using DataFrames; using Impute: Impute, Context
julia> using DataFrames; using Impute: Impute

julia> df = DataFrame(:a => [1.0, 2.0, missing, missing, 5.0], :b => [1.1, 2.2, 3.3, missing, 5.5])
5×2 DataFrames.DataFrame
Expand All @@ -175,7 +190,7 @@ julia> df = DataFrame(:a => [1.0, 2.0, missing, missing, 5.0], :b => [1.1, 2.2,
│ 4 │ missing │ missing │
│ 5 │ 5.0 │ 5.5 │

julia> Impute.interp(df; context=Context(; limit=1.0))
julia> Impute.interp(df)
5×2 DataFrames.DataFrame
│ Row │ a │ b │
│ │ Float64 │ Float64 │
Expand All @@ -189,13 +204,13 @@ julia> Impute.interp(df; context=Context(; limit=1.0))
""" interp

@doc """
Impute.fill(data; value=mean, dims=1, context=Context())
Impute.fill(data; value=mean, dims=1)

Fills in the missing data with a specific value. See [Fill](@ref) for details.

# Example
```jldoctest
julia> using DataFrames; using Impute: Impute, Context
julia> using DataFrames; using Impute: Impute

julia> df = DataFrame(:a => [1.0, 2.0, missing, missing, 5.0], :b => [1.1, 2.2, 3.3, missing, 5.5])
5×2 DataFrames.DataFrame
Expand All @@ -208,7 +223,7 @@ julia> df = DataFrame(:a => [1.0, 2.0, missing, missing, 5.0], :b => [1.1, 2.2,
│ 4 │ missing │ missing │
│ 5 │ 5.0 │ 5.5 │

julia> Impute.fill(df; value=-1.0, context=Context(; limit=1.0))
julia> Impute.fill(df; value=-1.0)
5×2 DataFrames.DataFrame
│ Row │ a │ b │
│ │ Float64 │ Float64 │
Expand All @@ -222,14 +237,14 @@ julia> Impute.fill(df; value=-1.0, context=Context(; limit=1.0))
""" fill

@doc """
Impute.locf(data; dims=1, context=Context())
Impute.locf(data; dims=1)

Iterates forwards through the `data` and fills missing data with the last existing
observation. See [LOCF](@ref) for details.

# Example
```jldoctest
julia> using DataFrames; using Impute: Impute, Context
julia> using DataFrames; using Impute: Impute

julia> df = DataFrame(:a => [1.0, 2.0, missing, missing, 5.0], :b => [1.1, 2.2, 3.3, missing, 5.5])
5×2 DataFrames.DataFrame
Expand All @@ -242,7 +257,7 @@ julia> df = DataFrame(:a => [1.0, 2.0, missing, missing, 5.0], :b => [1.1, 2.2,
│ 4 │ missing │ missing │
│ 5 │ 5.0 │ 5.5 │

julia> Impute.locf(df; context=Context(; limit=1.0))
julia> Impute.locf(df)
5×2 DataFrames.DataFrame
│ Row │ a │ b │
│ │ Float64 │ Float64 │
Expand All @@ -256,14 +271,14 @@ julia> Impute.locf(df; context=Context(; limit=1.0))
""" locf

@doc """
Impute.nocb(data; dims=1, context=Context())
Impute.nocb(data; dims=1)

Iterates backwards through the `data` and fills missing data with the next existing
observation. See [LOCF](@ref) for details.

# Example
```jldoctest
julia> using DataFrames; using Impute: Impute, Context
julia> using DataFrames; using Impute: Impute

julia> df = DataFrame(:a => [1.0, 2.0, missing, missing, 5.0], :b => [1.1, 2.2, 3.3, missing, 5.5])
5×2 DataFrames.DataFrame
Expand All @@ -276,7 +291,7 @@ julia> df = DataFrame(:a => [1.0, 2.0, missing, missing, 5.0], :b => [1.1, 2.2,
│ 4 │ missing │ missing │
│ 5 │ 5.0 │ 5.5 │

julia> Impute.nocb(df; context=Context(; limit=1.0))
julia> Impute.nocb(df)
5×2 DataFrames.DataFrame
│ Row │ a │ b │
│ │ Float64 │ Float64 │
Expand All @@ -290,15 +305,15 @@ julia> Impute.nocb(df; context=Context(; limit=1.0))
""" nocb

@doc """
Impute.srs(data; rng=Random.GLOBAL_RNG, context=Context())
Impute.srs(data; rng=Random.GLOBAL_RNG)

Simple Random Sampling (SRS) imputation is a method for imputing both continuous and
categorical variables. Furthermore, it completes imputation while preserving the
distributional properties of the variables (e.g., mean, standard deviation).

# Example
```jldoctest
julia> using DataFrames; using Random; using Impute: Impute, Context
julia> using DataFrames; using Random; using Impute: Impute

julia> df = DataFrame(:a => [1.0, 2.0, missing, missing, 5.0], :b => [1.1, 2.2, 3.3, missing, 5.5])
5×2 DataFrames.DataFrame
Expand All @@ -311,7 +326,7 @@ julia> df = DataFrame(:a => [1.0, 2.0, missing, missing, 5.0], :b => [1.1, 2.2,
│ 4 │ missing │ missing │
│ 5 │ 5.0 │ 5.5 │

julia> Impute.srs(df; rng=MersenneTwister(1234), context=Context(; limit=1.0))
julia> Impute.srs(df; rng=MersenneTwister(1234))
5×2 DataFrame
│ Row │ a │ b │
│ │ Float64 │ Float64 │
Expand Down
41 changes: 41 additions & 0 deletions src/assertions.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
"""
Assertion

An Assertion stores settings for checking the validity of a `AbstractArray` or `Tables.table` containing missing values.
New assertions are expected to subtype `Impute.Assertion` and, at minimum,
implement the `assert(data::AbstractVector{Union{T, Missing}}, ::<MyAssertion>)` method.
"""
abstract type Assertion end
rofinn marked this conversation as resolved.
Show resolved Hide resolved


"""
assert(data, a::Assertion; kwargs...)

If the assertion `a` fails then an `AssertionError` is thrown, otherwise the `data`
provided is returned without mutation.

rofinn marked this conversation as resolved.
Show resolved Hide resolved
# Keywords
* `dims`: The dimension to apply the assertion along (e.g., observations dim)
"""
rofinn marked this conversation as resolved.
Show resolved Hide resolved
assert

# A couple fallbacks for matrices and tables
function assert(data::AbstractMatrix, a::Assertion; dims=1)
for var in varwise(data; dims=dims)
assert(var, a)
rofinn marked this conversation as resolved.
Show resolved Hide resolved
end
return data
end

function assert(table, a::Assertion)
istable(table) || throw(MethodError(a, (table, a)))
columntable = Tables.columns(table)

for cname in propertynames(columntable)
assert(getproperty(columntable, cname), a)
end

return table
end

include("assertions/threshold.jl")
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would we want it here, or would it be nicer to put these all in the top file?
There isn't hundreds of files.

ChainRules puts them all in the top
https://github.com/JuliaDiff/ChainRules.jl/blob/e2cfd58b983a5023fd649b79fd980bd3428280b8/src/ChainRules.jl#L26-L45

as does ChainRulesCore
https://github.com/JuliaDiff/ChainRulesCore.jl/blob/43e2113ebf482b74ba292c17e5b3845be4f5faef/src/ChainRulesCore.jl#L15-L29

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess I prefer seeing the abstract type API first, but I don't have a strong opinion. What's the benefit to putting it earlier?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess marginally
easier to delete or rename the file if I know where it will be referenced.

Mostly just for constancy?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, n/m looks like julia doesn't like that because then the threshold code doesn't know about the Assertion type yet.

38 changes: 38 additions & 0 deletions src/assertions/threshold.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
"""
Threshold(ratio; weights=nothing)

Assert that the ratio of missing values in the provided dataset does not exceed to specified ratio.
If a weights array is provided then the ratio will be calculated as the
`sum(weights[ismissing.(data)]) / sum(weights)`
"""
struct Threshold <: Assertion
ratio::Float64
weights::Union{AbstractVector, Nothing}
rofinn marked this conversation as resolved.
Show resolved Hide resolved
end

Threshold(ratio::Float64; weights=nothing) = Threshold(ratio, weights)
rofinn marked this conversation as resolved.
Show resolved Hide resolved

function assert(data::AbstractVector{Union{T, Missing}}, t::Threshold) where T
if t.weights === nothing
mratio = count(ismissing, data) / length(data)
if mratio > t.ratio
throw(AssertionError("Ratio of missing values exceeded $(t.ratio) ($mratio)."))
rofinn marked this conversation as resolved.
Show resolved Hide resolved
end
else
if size(data) != size(t.weights)
throw(DimensionMismatch(string(
"Input has dimensions $(size(data)), but thresholds weights ",
"has dimensions $(size(t.weights))"
)))
end

mratio = sum(t.weights[ismissing.(data)]) / sum(t.weights)
if mratio > t.ratio
throw(AssertionError(
"Weighted ratio of missing values exceeded $(t.ratio) ($mratio)."
))
end
end

return data
end
Loading