licenses
sequencelengths 1
3
| version
stringclasses 677
values | tree_hash
stringlengths 40
40
| path
stringclasses 1
value | type
stringclasses 2
values | size
stringlengths 2
8
| text
stringlengths 25
67.1M
| package_name
stringlengths 2
41
| repo
stringlengths 33
86
|
---|---|---|---|---|---|---|---|---|
[
"MIT"
] | 0.1.3 | cf74064e00ff51978e436f2ccab83779503e7adf | code | 687 | @testset "Split + Join" begin
model = Chain(
Dense(10 => 5),
Split(Dense(5 => 1, tanh), Dense(5 => 3, tanh), Dense(5 => 2))
) |> gpu
@test model(gpu(rand(10))) isa Tuple{AbstractVector, AbstractVector, AbstractVector}
model2 = Chain(
Join(vcat,
Chain(Dense(1 => 5, relu), Dense(5 => 1)), # branch 1
Dense(1 => 2), # branch 2
Dense(1 => 1) # branch 3
),
Dense(4 => 1)
) |> gpu
xs = map(gpu, (rand(1), rand(1), rand(1)))
@test model2(xs) isa AbstractVector
end
| Fluxperimental | https://github.com/FluxML/Fluxperimental.jl.git |
|
[
"MIT"
] | 0.1.3 | cf74064e00ff51978e436f2ccab83779503e7adf | code | 878 | import Flux, Fluxperimental, Optimisers
@testset "shinkansen!" begin
X = repeat(hcat(digits.(0:3, base=2, pad=2)...), 1, 32)
Y = Flux.onehotbatch(xor.(eachrow(X)...), 0:1)
model = Flux.Chain(Flux.Dense(2 => 3, Flux.sigmoid), Flux.BatchNorm(3), Flux.Dense(3 => 2))
state = Optimisers.setup(Optimisers.Adam(0.1, (0.7, 0.95)), model)
Fluxperimental.shinkansen!(model, X, Y; state, epochs=100) do m, x, y
Flux.logitcrossentropy(m(x), y)
end
@test all((Flux.softmax(model(X)) .> 0.5) .== Y)
model = Flux.Chain(Flux.Dense(2 => 3, Flux.sigmoid), Flux.BatchNorm(3), Flux.Dense(3 => 2))
state = Optimisers.setup(Optimisers.Adam(0.1, (0.7, 0.95)), model)
Fluxperimental.shinkansen!(model, X, Y; state, epochs=100, batchsize=16, shuffle=true) do m, x, y
Flux.logitcrossentropy(m(x), y)
end
@test all((Flux.softmax(model(X)) .> 0.5) .== Y)
end
| Fluxperimental | https://github.com/FluxML/Fluxperimental.jl.git |
|
[
"MIT"
] | 0.1.3 | cf74064e00ff51978e436f2ccab83779503e7adf | docs | 1847 | <img align="right" width="200px" src="https://github.com/FluxML/Optimisers.jl/raw/master/docs/src/assets/logo.png">
# Fluxperimental.jl
[![][action-img]][action-url]
[![][coverage-img]][coverage-url]
[action-img]: https://github.com/FluxML/Fluxperimental.jl/workflows/CI/badge.svg
[action-url]: https://github.com/FluxML/Fluxperimental.jl/actions
[coverage-img]: https://codecov.io/gh/FluxML/Fluxperimental.jl/branch/master/graph/badge.svg
[coverage-url]: https://codecov.io/gh/FluxML/Fluxperimental.jl
The repository contains experimental features for [Flux.jl](https://github.com/FluxML/Flux.jl).
It needs to be loaded in addition to the main package:
```julia
using Flux, Fluxperimental
```
As an experiment, it only has discussion pages, not issues. Actual bugs reports are welcome,
as are comments that you think something is a great idea, or better ways achive the same goal,
or nice examples showing how it works.
Pull requests adding new features are also welcome. Ideally they should have at least some tests.
They should not alter existing functions (i.e. should not commit piracy)
to ensure that loading Fluxperimental won't affect other uses.
Prototypes for new versions of existing features should use a different name.
Features which break or are abandoned will be removed, in a minor (breaking) release.
As will any features which migrate to Flux itself.
## Current Features
* Layers [`Split` and `Join`](https://github.com/FluxML/Fluxperimental.jl/blob/master/src/split_join.jl)
* More advanced [`train!` function](https://github.com/FluxML/Fluxperimental.jl/blob/master/src/train.jl)
* Macro for [making custom layers](https://github.com/FluxML/Fluxperimental.jl/blob/master/src/compact.jl) quickly
* Experimental [`apply(c::Chain, x)`](https://github.com/FluxML/Fluxperimental.jl/blob/master/src/chain.jl) interface
| Fluxperimental | https://github.com/FluxML/Fluxperimental.jl.git |
|
[
"MIT"
] | 0.1.15 | f6bda01c117c93936dba48ddfe888f153f81d619 | code | 612 | # ------------------------------------------------------------------
# Licensed under the MIT License. See LICENCE in the project root.
# ------------------------------------------------------------------
module GeoStatsViz
using Meshes
using GeoStatsBase
using Variography
using Distances
using Reexport
import Makie
@reexport using MeshViz
# GeoStatsBase.jl recipes
include("base/weights.jl")
include("base/problems.jl")
include("base/histograms.jl")
# Variography.jl recipes
include("variography/empirical.jl")
include("variography/theoretical.jl")
# miscellaneous recipes
include("hscatter.jl")
end
| GeoStatsViz | https://github.com/juliohm/GeoStatsViz.jl.git |
|
[
"MIT"
] | 0.1.15 | f6bda01c117c93936dba48ddfe888f153f81d619 | code | 3667 | # ------------------------------------------------------------------
# Licensed under the MIT License. See LICENCE in the project root.
# ------------------------------------------------------------------
"""
hscatter(data, var₁, var₂)
H-scatter plot of geospatial `data` for pair of variables
`var₁` and `var₂` with additional options:
* `lag` - lag distance between points (default to `0.0`)
* `tol` - tolerance for lag distance (default to `1e-1`)
* `distance` - distance from Distances.jl (default to `Euclidean()`)
Aesthetics options:
* `size` - size of points in point set
* `color` - color of geometries or points
* `alpha` - transparency channel in [0,1]
* `colorscheme` - color scheme from ColorSchemes.jl
* `rcolor` - color of regression line
* `icolor` - color of identity line
* `ccolor` - color of center lines
## Examples
```
# h-scatter of Z vs. Z at lag 1.0
hscatter(data, :Z, :Z, lag=1.0)
# h-scatter of Z vs. W at lag 2.0
hscatter(data, :Z, :W, lag=2.0)
```
"""
@Makie.recipe(HScatter, data, var₁, var₂) do scene
Makie.Attributes(;
# h-scatter options
lag = 0.0,
tol = 1e-1,
distance = Euclidean(),
# aesthetics options
size = Makie.theme(scene, :markersize),
color = :slategray3,
alpha = 1.0,
colorscheme = :viridis,
rcolor = :brown,
icolor = :black,
ccolor = :green,
)
end
function Makie.plot!(plot::HScatter)
# retrieve data and variables
data = plot[:data][]
var₁ = plot[:var₁][]
var₂ = plot[:var₂][]
# retrieve h-scatter options
lag = plot[:lag][]
tol = plot[:tol][]
distance = plot[:distance][]
# retrieve aesthetics options
size = plot[:size][]
color = plot[:color][]
alpha = plot[:alpha][]
colorscheme = plot[:colorscheme][]
rcolor = plot[:rcolor][]
icolor = plot[:icolor][]
ccolor = plot[:ccolor][]
# process color spec into colorant
colorant = MeshViz.process(color, colorscheme, alpha)
# lookup valid data
I₁ = findall(!ismissing, getproperty(data, var₁))
I₂ = findall(!ismissing, getproperty(data, var₂))
𝒮₁ = view(data, I₁)
𝒮₂ = view(data, I₂)
𝒟₁ = domain(𝒮₁)
𝒟₂ = domain(𝒮₂)
X₁ = [coordinates(centroid(𝒟₁, i)) for i in 1:nelements(𝒟₁)]
X₂ = [coordinates(centroid(𝒟₂, i)) for i in 1:nelements(𝒟₂)]
z₁ = getproperty(𝒮₁, var₁)
z₂ = getproperty(𝒮₂, var₂)
# compute pairwise distance
m, n = length(z₁), length(z₂)
pairs = [(i,j) for j in 1:n for i in j:m]
ds = [evaluate(distance, X₁[i], X₂[j]) for (i,j) in pairs]
# find indices with given lag
match = findall(abs.(ds .- lag) .< tol)
if isempty(match)
throw(ErrorException("no points were found with lag = $lag, aborting..."))
end
# visualize h-scatter
mpairs = view(pairs, match)
x = z₁[first.(mpairs)]
y = z₂[last.(mpairs)]
Makie.scatter!(plot, x, y,
color = colorant,
markersize = size,
)
# visualize regression line
X = [x ones(length(x))]
ŷ = X * (X \ y)
Makie.lines!(plot, x, ŷ,
color = rcolor,
)
# visualize identity line
xmin, xmax = extrema(x)
ymin, ymax = extrema(y)
vmin = min(xmin, ymin)
vmax = max(xmax, ymax)
Makie.lines!(plot, [vmin, vmax], [vmin, vmax],
color = icolor,
)
# visualize center lines
x̄, ȳ = mean(x), mean(y)
Makie.lines!(plot, [x̄, x̄], [vmin, vmax],
color = ccolor,
)
Makie.lines!(plot, [vmin, vmax], [ȳ, ȳ],
color = ccolor,
)
Makie.scatter!(plot, [x̄], [ȳ],
color = ccolor,
marker = :rect,
markersize = 16,
)
end | GeoStatsViz | https://github.com/juliohm/GeoStatsViz.jl.git |
|
[
"MIT"
] | 0.1.15 | f6bda01c117c93936dba48ddfe888f153f81d619 | code | 672 | # ------------------------------------------------------------------
# Licensed under the MIT License. See LICENCE in the project root.
# ------------------------------------------------------------------
Makie.plottype(::EmpiricalHistogram) = Viz{<:Tuple{EmpiricalHistogram}}
function Makie.plot!(plot::Viz{<:Tuple{EmpiricalHistogram}})
# retrieve histogram object
hist = plot[:object]
# abscissa and ordinates
coords = Makie.@lift values($hist)
xs = Makie.@lift $coords[1]
ys = Makie.@lift $coords[2]
Makie.barplot!(plot, xs, ys,
color = plot[:color],
strokecolor = plot[:facetcolor],
strokewidth = 0.1,
gap = 0.0,
)
end | GeoStatsViz | https://github.com/juliohm/GeoStatsViz.jl.git |
|
[
"MIT"
] | 0.1.15 | f6bda01c117c93936dba48ddfe888f153f81d619 | code | 2842 | # ------------------------------------------------------------------
# Licensed under the MIT License. See LICENCE in the project root.
# ------------------------------------------------------------------
Makie.plottype(::EstimationProblem) = Viz{<:Tuple{EstimationProblem}}
function Makie.plot!(plot::Viz{<:Tuple{EstimationProblem}})
# retrieve problem object
problem = plot[:object]
# data and domain
dom1 = Makie.@lift domain($problem)
dom2 = Makie.@lift domain(data($problem))
# visualize estimation domain
viz!(plot, dom1,
color = plot[:color],
alpha = plot[:alpha],
colorscheme = plot[:colorscheme],
facetcolor = plot[:facetcolor],
showfacets = plot[:showfacets],
pointsize = plot[:pointsize],
segmentsize = plot[:segmentsize]
)
# visualize domain of data
viz!(plot, dom2,
color = :black,
alpha = plot[:alpha],
facetcolor = plot[:facetcolor],
showfacets = plot[:showfacets],
pointsize = plot[:pointsize],
segmentsize = plot[:segmentsize]
)
end
Makie.plottype(::SimulationProblem) = Viz{<:Tuple{SimulationProblem}}
function Makie.plot!(plot::Viz{<:Tuple{SimulationProblem}})
# retrieve problem object
problem = plot[:object]
# data and domain
dom1 = Makie.@lift domain($problem)
# visualize estimation domain
viz!(plot, dom1,
color = plot[:color],
alpha = plot[:alpha],
colorscheme = plot[:colorscheme],
facetcolor = plot[:facetcolor],
showfacets = plot[:showfacets],
pointsize = plot[:pointsize],
segmentsize = plot[:segmentsize]
)
# visualize domain of data
if hasdata(problem[])
dom2 = Makie.@lift domain(data($problem))
viz!(plot, dom2,
color = :black,
alpha = plot[:alpha],
facetcolor = plot[:facetcolor],
showfacets = plot[:showfacets],
pointsize = plot[:pointsize],
segmentsize = plot[:segmentsize]
)
end
end
Makie.plottype(::LearningProblem) = Viz{<:Tuple{LearningProblem}}
function Makie.plot!(plot::Viz{<:Tuple{LearningProblem}})
# retrieve problem object
problem = plot[:object]
# source and target domain
dom1 = Makie.@lift domain(sourcedata($problem))
dom2 = Makie.@lift domain(targetdata($problem))
# visualize estimation domain
viz!(plot, dom1,
color = plot[:color],
alpha = plot[:alpha],
colorscheme = plot[:colorscheme],
facetcolor = plot[:facetcolor],
showfacets = plot[:showfacets],
pointsize = plot[:pointsize],
segmentsize = plot[:segmentsize]
)
# visualize domain of data
viz!(plot, dom2,
color = :gray90,
alpha = plot[:alpha],
facetcolor = plot[:facetcolor],
showfacets = plot[:showfacets],
pointsize = plot[:pointsize],
segmentsize = plot[:segmentsize]
)
end | GeoStatsViz | https://github.com/juliohm/GeoStatsViz.jl.git |
|
[
"MIT"
] | 0.1.15 | f6bda01c117c93936dba48ddfe888f153f81d619 | code | 762 | # ------------------------------------------------------------------
# Licensed under the MIT License. See LICENCE in the project root.
# ------------------------------------------------------------------
Makie.plottype(::GeoWeights) = Viz{<:Tuple{GeoWeights}}
function Makie.plot!(plot::Viz{<:Tuple{GeoWeights}})
# retrieve weights object
weights = plot[:object]
# underlying domain and values
wdomain = Makie.@lift domain($weights)
wvalues = Makie.@lift collect($weights)
viz!(plot, wdomain,
color = wvalues,
alpha = plot[:alpha],
colorscheme = plot[:colorscheme],
facetcolor = plot[:facetcolor],
showfacets = plot[:showfacets],
pointsize = plot[:pointsize],
segmentsize = plot[:segmentsize]
)
end
| GeoStatsViz | https://github.com/juliohm/GeoStatsViz.jl.git |
|
[
"MIT"
] | 0.1.15 | f6bda01c117c93936dba48ddfe888f153f81d619 | code | 2112 | # ------------------------------------------------------------------
# Licensed under the MIT License. See LICENCE in the project root.
# ------------------------------------------------------------------
Makie.plottype(::EmpiricalVariogram) = Viz{<:Tuple{EmpiricalVariogram}}
function Makie.plot!(plot::Viz{<:Tuple{EmpiricalVariogram}})
# retrieve variogram object
γ = plot[:object]
# get the data
xyn = Makie.@lift values($γ)
x = Makie.@lift $xyn[1]
y = Makie.@lift $xyn[2]
n = Makie.@lift $xyn[3]
# discard empty bins
x = Makie.@lift $x[$n .> 0]
y = Makie.@lift $y[$n .> 0]
n = Makie.@lift $n[$n .> 0]
# visualize variogram
Makie.scatterlines!(plot, x, y,
color = plot[:color],
markersize = plot[:pointsize],
)
# visualize bin counts
bincounts = Makie.@lift string.($n)
positions = Makie.@lift collect(zip($x, $y))
Makie.text!(plot, bincounts,
position = positions,
textsize = plot[:pointsize],
)
# visualize frequencies as bars
f = Makie.@lift $n*(maximum($y) / maximum($n)) / 10
Makie.barplot!(plot, x, f,
color = plot[:color],
strokecolor = plot[:facetcolor],
strokewidth = 0.1,
gap = 0.0,
)
end
Makie.plottype(::EmpiricalVarioplane) = Viz{<:Tuple{EmpiricalVarioplane}}
function Makie.plot!(plot::Viz{<:Tuple{EmpiricalVarioplane}})
# retrieve varioplane object
v = plot[:object]
# underyling variograms
γs = Makie.@lift $v.γs
# polar angle
θs = Makie.@lift $v.θs
# polar radius
rs = Makie.@lift values($γs[1])[1]
# variogram values for all variograms
Z = Makie.@lift begin
zs = map($γs) do γ
_, zs, __ = values(γ)
# handle NaN values (i.e. empty bins)
isnan(zs[1]) && (zs[1] = 0)
for i in 2:length(zs)
isnan(zs[i]) && (zs[i] = zs[i-1])
end
zs
end
reduce(hcat, zs)
end
# exploit symmetry
θs = Makie.@lift range(0, 2π, length=2*length($θs))
Z = Makie.@lift [$Z $Z]
# hide hole at center
rs = Makie.@lift [0; $rs]
Z = Makie.@lift [$Z[1:1,:]; $Z]
Makie.surface!(plot, rs, θs, Z,
shading = false
)
end | GeoStatsViz | https://github.com/juliohm/GeoStatsViz.jl.git |
|
[
"MIT"
] | 0.1.15 | f6bda01c117c93936dba48ddfe888f153f81d619 | code | 718 | # ------------------------------------------------------------------
# Licensed under the MIT License. See LICENCE in the project root.
# ------------------------------------------------------------------
Makie.plottype(::Variogram) = Viz{<:Tuple{Variogram}}
function Makie.plot!(plot::Viz{<:Tuple{Variogram}})
# retrieve variogram object
γ = plot[:object]
# start at 1e-6 instead of 0 to avoid
# nugget artifact in visualization
x = Makie.@lift range(1e-6, stop=_maxlag($γ), length=100)
y = Makie.@lift $γ.($x)
# visualize variogram
Makie.lines!(plot, x, y,
color = plot[:color],
)
end
_maxlag(γ::Variogram) = 3range(γ)
_maxlag(γ::PowerVariogram) = 3.0
_maxlag(γ::NuggetEffect) = 3.0 | GeoStatsViz | https://github.com/juliohm/GeoStatsViz.jl.git |
|
[
"MIT"
] | 0.1.15 | f6bda01c117c93936dba48ddfe888f153f81d619 | code | 95 | using GeoStatsViz
using Test
@testset "GeoStatsViz.jl" begin
# Write your tests here.
end
| GeoStatsViz | https://github.com/juliohm/GeoStatsViz.jl.git |
|
[
"MIT"
] | 0.1.15 | f6bda01c117c93936dba48ddfe888f153f81d619 | docs | 801 | # GeoStatsViz.jl
[](https://github.com/JuliaEarth/GeoStatsViz.jl/actions/workflows/CI.yml?query=branch%3Amain)
[](https://codecov.io/gh/JuliaEarth/GeoStatsViz.jl)
Makie.jl recipes for visualization of [GeoStats.jl](https://github.com/JuliaEarth/GeoStats.jl) objects.
## Usage
Any object defined in the GeoStats.jl framework can be visualized with
the `viz` function. Additionally, we provide other recipes such as
`hscatter` with custom signatures described in their docstrings.
```julia
using GeoStats, GeoStatsViz
# choose a Makie backend
import GLMakie as Mke
g = GaussianVariogram()
viz(g)
``` | GeoStatsViz | https://github.com/juliohm/GeoStatsViz.jl.git |
|
[
"MIT"
] | 0.3.7 | db318813a5f07e3f93a1e530c8fd0e6bdc9cabac | code | 27531 | module MLJGLMInterface
# -------------------------------------------------------------------
# TODO
# - return feature importance curve to report using `features`
# - handle binomial case properly, needs MLJ API change for weighted
# samples (y/N ~ Be(p) with weights N)
# - handle levels properly (see GLM.jl/issues/240); if feed something
# with levels, the fit will fail.
# - revisit and test Poisson and Negbin regression once there's a clear
# example we can test on (requires handling levels which deps upon GLM)
# - test Logit, Probit etc on Binomial once binomial case is handled
# -------------------------------------------------------------------
export LinearRegressor, LinearBinaryClassifier, LinearCountRegressor
import MLJModelInterface
import MLJModelInterface: metadata_pkg, metadata_model, Table, Continuous, Count, Finite,
OrderedFactor, Multiclass, @mlj_model
using Distributions: Bernoulli, Distribution, Poisson
using StatsModels: ConstantTerm, Term, FormulaTerm, term, modelcols
using Tables
import GLM
const MMI = MLJModelInterface
const PKG = "MLJGLMInterface"
##
## DESCRIPTIONS
##
const LR_DESCR = "Linear regressor (OLS) with a Normal model."
const LBC_DESCR = "Linear binary classifier with "*
"specified link (e.g. logistic)."
const LCR_DESCR = "Linear count regressor with specified "*
"link and distribution (e.g. log link and poisson)."
####
#### REGRESSION TYPES
####
# LinearRegressor --> Probabilistic w Continuous Target
# LinearCountRegressor --> Probabilistic w Count Target
# LinearBinaryClassifier --> Probabilistic w Binary target // logit,cauchit,..
# MulticlassClassifier --> Probabilistic w Multiclass target
const VALID_KEYS = [
:deviance,
:dof_residual,
:stderror,
:vcov,
:coef_table,
:glm_model,
]
const VALID_KEYS_LIST = join(map(k-> "`:$k`", VALID_KEYS), ", ", " and ")
const DEFAULT_KEYS = setdiff(VALID_KEYS, [:glm_model,])
const KEYS_TYPE = Union{Nothing, AbstractVector{Symbol}}
@mlj_model mutable struct LinearRegressor <: MMI.Probabilistic
fit_intercept::Bool = true
dropcollinear::Bool = false
offsetcol::Union{Symbol, Nothing} = nothing
report_keys::KEYS_TYPE = DEFAULT_KEYS::(isnothing(_) || issubset(_, VALID_KEYS))
end
@mlj_model mutable struct LinearBinaryClassifier <: MMI.Probabilistic
fit_intercept::Bool = true
link::GLM.Link01 = GLM.LogitLink()
offsetcol::Union{Symbol, Nothing} = nothing
maxiter::Integer = 30
atol::Real = 1e-6
rtol::Real = 1e-6
minstepfac::Real = 0.001
report_keys::KEYS_TYPE = DEFAULT_KEYS::(isnothing(_) || issubset(_, VALID_KEYS))
end
@mlj_model mutable struct LinearCountRegressor <: MMI.Probabilistic
fit_intercept::Bool = true
distribution::Distribution = Poisson()
link::GLM.Link = GLM.LogLink()
offsetcol::Union{Symbol, Nothing} = nothing
maxiter::Integer = 30
atol::Real = 1e-6
rtol::Real = 1e-6
minstepfac::Real = 0.001
report_keys::KEYS_TYPE = DEFAULT_KEYS::(isnothing(_) || issubset(_, VALID_KEYS))
end
# Short names for convenience here
const GLM_MODELS = Union{
<:LinearRegressor, <:LinearBinaryClassifier, <:LinearCountRegressor
}
###
## Helper functions
###
_to_vector(v::Vector) = v
_to_vector(v) = collect(v)
_to_array(v::AbstractArray) = v
_to_array(v) = collect(v)
"""
split_X_offset(X, offsetcol::Nothing)
When no offset is specified, return `X` and an empty vector.
"""
split_X_offset(X, offsetcol::Nothing) = (X, Float64[])
"""
split_X_offset(X, offsetcol::Symbol)
Splits the input table X in:
- A new table not containing the original offset column
- The offset vector extracted from the table
"""
function split_X_offset(X, offsetcol::Symbol)
ct = Tables.columntable(X)
offset = Tables.getcolumn(ct, offsetcol)
newX = Base.structdiff(ct, NamedTuple{(offsetcol,)})
return newX, _to_vector(offset)
end
# If `estimates_dispersion_param` returns `false` then the dispersion
# parameter isn't estimated from data but known apriori to be `1`.
estimates_dispersion_param(::LinearRegressor) = true
estimates_dispersion_param(::LinearBinaryClassifier) = false
function estimates_dispersion_param(model::LinearCountRegressor)
return GLM.dispersion_parameter(model.distribution)
end
function _throw_sample_size_error(model, est_dispersion_param)
requires_info = _requires_info(model, est_dispersion_param)
if isnothing(model.offsetcol)
offset_info = " `offsetcol == nothing`"
else
offset_info = " `offsetcol !== nothing`"
end
modelname = nameof(typeof(model))
if model isa LinearCountRegressor
distribution_info = "and `distribution = $(nameof(typeof(model.distribution)))()`"
else
distribution_info = "\b"
end
throw(
ArgumentError(
" `$(modelname)` with `fit_intercept = $(model.fit_intercept)`,"*
"$(offset_info) $(distribution_info) requires $(requires_info)"
)
)
return nothing
end
"""
_requires_info(model, est_dispersion_param)
Returns one of the following strings
- "`n_samples >= n_features`", "`n_samples > n_features`"
- "`n_samples >= n_features - 1`", "`n_samples > n_features - 1`"
- "`n_samples >= n_features + 1`", "`n_samples > n_features + 1`"
"""
function _requires_info(model, est_dispersion_param)
inequality = est_dispersion_param ? ">" : ">="
int_num = model.fit_intercept - !isnothing(model.offsetcol)
if iszero(int_num)
int_num_string = "\b"
elseif int_num < 0
int_num_string = "- $(abs(int_num))"
else
int_num_string = "+ $(int_num)"
end
return "`n_samples $(inequality) n_features $(int_num_string)`."
end
function check_sample_size(model, n, p)
if estimates_dispersion_param(model)
n <= p + model.fit_intercept && _throw_sample_size_error(model, true)
else
n < p + model.fit_intercept && _throw_sample_size_error(model, false)
end
return nothing
end
"""
prepare_inputs(model, X; handle_intercept=false)
Handle `model.offsetcol` and `model.fit_intercept` if `handle_intercept=true`.
`handle_intercept` is disabled for fitting since the StatsModels.@formula handles the intercept.
"""
function prepare_inputs(model, X)
Xcols = Tables.columntable(X)
table_features = Base.keys(Xcols)
p = length(table_features)
p >= 1 || throw(
ArgumentError("`X` must contain at least one feature column.")
)
if !isnothing(model.offsetcol)
model.offsetcol in table_features || throw(
ArgumentError("offset column `$(model.offsetcol)` not found in table `X")
)
if p < 2 && !model.fit_intercept
throw(
ArgumentError(
"At least 2 feature columns are required for learning with"*
" `offsetcol !== nothing` and `fit_intercept == false`."
)
)
end
end
Xminoffset, offset = split_X_offset(Xcols, model.offsetcol)
features = Tables.columnnames(Xminoffset)
check_sample_size(model, length(first(Xminoffset)), p)
return Xminoffset, offset, _to_array(features)
end
"""
glm_report(glm_model, features, reportkeys)
Report based on a fitted `LinearModel/GeneralizedLinearModel`, `glm_model`
and keyed on `reportkeys`.
"""
glm_report
glm_report(glm_model, features, ::Nothing) = NamedTuple()
function glm_report(glm_model, features, reportkeys)
isempty(reportkeys) && return NamedTuple()
report_dict = Dict{Symbol, Any}()
if in(:deviance, reportkeys)
report_dict[:deviance] = GLM.deviance(glm_model)
end
if in(:dof_residual, reportkeys)
report_dict[:dof_residual] = GLM.dof_residual(glm_model)
end
if in(:stderror, reportkeys)
report_dict[:stderror] = GLM.stderror(glm_model)
end
if :vcov in reportkeys
report_dict[:vcov] = GLM.vcov(glm_model)
end
if :coef_table in reportkeys
coef_table = GLM.coeftable(glm_model)
report_dict[:coef_table] = coef_table
end
if :glm_model in reportkeys
report_dict[:glm_model] = glm_model
end
return NamedTuple{Tuple(keys(report_dict))}(values(report_dict))
end
"""
glm_formula(model, features::AbstractVector{Symbol}) -> FormulaTerm
Return formula which is ready to be passed to `fit(form, data, ...)`.
"""
function glm_formula(model, features::AbstractVector{Symbol})::FormulaTerm
# By default, using a JuliaStats formula will add an intercept.
# Adding a zero term explicitly disables the intercept.
# See the StatsModels.jl tests for more information.
intercept_term = model.fit_intercept ? 1 : 0
form = FormulaTerm(Term(:y), term(intercept_term) + sum(term.(features)))
return form
end
"""
check_weights(w, y)
Validate observation weights to be used in fitting `Linear/GeneralizedLinearModel` based
on target vector `y`.
Note:
Categorical targets have to be converted into a AbstractVector{<:Real} before
passing to this method.
"""
check_weights
check_weights(::Nothing, y::AbstractVector{<:Real}) = similar(y, 0)
function check_weights(w, y::AbstractVector{<:Real})
w isa AbstractVector{<:Real} || throw(
ArgumentError("Expected `weights === nothing` or `weights::AbstractVector{<:Real}")
)
length(y) == length(w) || throw(
ArgumentError("weights passed must have the same length as the target vector.")
)
return w
end
####
#### FIT FUNCTIONS
####
struct FitResult{F, V<:AbstractVector, T, R}
"Formula containing all coefficients and their types"
formula::F
"Vector containg coeficients of the predictors and intercept"
coefs::V
"An estimate of the dispersion parameter of the glm model. "
dispersion::T
"Other fitted parameters specific to a fitted model"
params::R
end
FitResult(fitted_glm, features) = FitResult(GLM.formula(fitted_glm), GLM.coef(fitted_glm), GLM.dispersion(fitted_glm.model), (features = features,))
dispersion(fr::FitResult) = fr.dispersion
params(fr::FitResult) = fr.params
coefs(fr::FitResult) = fr.coefs
function MMI.fit(model::LinearRegressor, verbosity::Int, X, y, w=nothing)
# apply the model
X_col_table, offset, features = prepare_inputs(model, X)
y_ = isempty(offset) ? y : y .- offset
wts = check_weights(w, y_)
data = merge(X_col_table, (; y = y_))
form = glm_formula(model, features)
fitted_lm = GLM.lm(form, data; model.dropcollinear, wts)
fitresult = FitResult(fitted_lm, features)
# form the report
report = glm_report(fitted_lm, features, model.report_keys)
cache = nothing
# return
return fitresult, cache, report
end
function MMI.fit(model::LinearCountRegressor, verbosity::Int, X, y, w=nothing)
# apply the model
X_col_table, offset, features = prepare_inputs(model, X)
data = merge(X_col_table, (; y))
wts = check_weights(w, y)
form = glm_formula(model, features)
fitted_glm = GLM.glm(
form, data, model.distribution, model.link;
offset,
model.maxiter,
model.atol,
model.rtol,
model.minstepfac,
wts
)
fitresult = FitResult(fitted_glm, features)
# form the report
report = glm_report(fitted_glm, features, model.report_keys)
cache = nothing
# return
return fitresult, cache, report
end
function MMI.fit(model::LinearBinaryClassifier, verbosity::Int, X, y, w=nothing)
# apply the model
decode = MMI.classes(y)
y_plain = MMI.int(y) .- 1 # 0, 1 of type Int
wts = check_weights(w, y_plain)
X_col_table, offset, features = prepare_inputs(model, X)
data = merge(X_col_table, (; y = y_plain))
form = glm_formula(model, features)
fitted_glm = GLM.glm(
form, data, Bernoulli(), model.link;
offset,
model.maxiter,
model.atol,
model.rtol,
model.minstepfac,
wts
)
fitresult = FitResult(fitted_glm, features)
# form the report
report = glm_report(fitted_glm, features, model.report_keys)
cache = nothing
# return
return (fitresult, decode), cache, report
end
glm_fitresult(::LinearRegressor, fitresult) = fitresult
glm_fitresult(::LinearCountRegressor, fitresult) = fitresult
glm_fitresult(::LinearBinaryClassifier, fitresult) = fitresult[1]
function MMI.fitted_params(model::GLM_MODELS, fitresult)
result = glm_fitresult(model, fitresult)
coef = coefs(result)
features = copy(params(result).features)
if model.fit_intercept
intercept = coef[1]
coef_ = coef[2:end]
else
intercept = zero(eltype(coef))
coef_ = copy(coef)
end
return (; features, coef=coef_, intercept)
end
####
#### PREDICT FUNCTIONS
####
glm_link(model) = model.link
glm_link(::LinearRegressor) = GLM.IdentityLink()
function glm_predict(link, terms, coef, offsetcol::Nothing, Xnew)
mm = modelcols(terms, Xnew)
η = mm * coef
μ = GLM.linkinv.(link, η)
return μ
end
function glm_predict(link, terms, coef, offsetcol::Symbol, Xnew)
mm = modelcols(terms, Xnew)
offset = Tables.getcolumn(Xnew, offsetcol)
η = mm * coef .+ offset
μ = GLM.linkinv.(link, η)
return μ
end
# More efficient fallback. predict_mean is not defined for LinearBinaryClassifier
function MMI.predict_mean(model::Union{LinearRegressor, LinearCountRegressor}, fitresult, Xnew)
p = glm_predict(glm_link(model), fitresult.formula.rhs, fitresult.coefs, model.offsetcol, Xnew)
return p
end
function MMI.predict(model::LinearRegressor, fitresult, Xnew)
μ = MMI.predict_mean(model, fitresult, Xnew)
σ̂ = dispersion(fitresult)
return [GLM.Normal(μᵢ, σ̂) for μᵢ ∈ μ]
end
function MMI.predict(model::LinearCountRegressor, fitresult, Xnew)
λ = MMI.predict_mean(model, fitresult, Xnew)
return [GLM.Poisson(λᵢ) for λᵢ ∈ λ]
end
function MMI.predict(model::LinearBinaryClassifier, (fitresult, decode), Xnew)
p = glm_predict(glm_link(model), fitresult.formula.rhs, fitresult.coefs, model.offsetcol, Xnew)
return MMI.UnivariateFinite(decode, p, augment=true)
end
# NOTE: predict_mode uses MLJBase's fallback
####
#### METADATA
####
# shared metadata
const GLM_REGS = Union{
Type{<:LinearRegressor}, Type{<:LinearBinaryClassifier}, Type{<:LinearCountRegressor}
}
metadata_pkg.(
(LinearRegressor, LinearBinaryClassifier, LinearCountRegressor),
name = "GLM",
uuid = "38e38edf-8417-5370-95a0-9cbb8c7f171a",
url = "https://github.com/JuliaStats/GLM.jl",
julia = true,
license = "MIT",
is_wrapper = false
)
metadata_model(
LinearRegressor,
input = Table(Continuous, Finite),
target = AbstractVector{Continuous},
supports_weights = true,
path = "$PKG.LinearRegressor"
)
metadata_model(
LinearBinaryClassifier,
input = Table(Continuous, Finite),
target = AbstractVector{<:Finite{2}},
supports_weights = true,
path = "$PKG.LinearBinaryClassifier"
)
metadata_model(
LinearCountRegressor,
input = Table(Continuous, Finite),
target = AbstractVector{Count},
supports_weights = true,
path = "$PKG.LinearCountRegressor"
)
"""
$(MMI.doc_header(LinearRegressor))
`LinearRegressor` assumes the target is a continuous variable
whose conditional distribution is normal with constant variance, and whose
expected value is a linear combination of the features (identity link function).
Options exist to specify an intercept or offset feature.
# Training data
In MLJ or MLJBase, bind an instance `model` to data with one of:
mach = machine(model, X, y)
mach = machine(model, X, y, w)
Here
- `X`: is any table of input features (eg, a `DataFrame`) whose columns
are of scitype `Continuous`; check the scitype with `schema(X)`
- `y`: is the target, which can be any `AbstractVector` whose element
scitype is `Continuous`; check the scitype with `scitype(y)`
- `w`: is a vector of `Real` per-observation weights
# Hyper-parameters
- `fit_intercept=true`: Whether to calculate the intercept for this model.
If set to false, no intercept will be calculated (e.g. the data is expected
to be centered)
- `dropcollinear=false`: Whether to drop features in the training data
to ensure linear independence. If true , only the first of each set
of linearly-dependent features is used. The coefficient for
redundant linearly dependent features is `0.0` and all associated
statistics are set to `NaN`.
- `offsetcol=nothing`: Name of the column to be used as an offset, if any.
An offset is a variable which is known to have a coefficient of 1.
- `report_keys`: `Vector` of keys for the report. Possible keys are: $VALID_KEYS_LIST. By
default only `:glm_model` is excluded.
Train the machine using `fit!(mach, rows=...)`.
# Operations
- `predict(mach, Xnew)`: return predictions of the target given new
features `Xnew` having the same Scitype as `X` above. Predictions are
probabilistic.
- `predict_mean(mach, Xnew)`: instead return the mean of
each prediction above
- `predict_median(mach, Xnew)`: instead return the median of
each prediction above.
# Fitted parameters
The fields of `fitted_params(mach)` are:
- `features`: The names of the features encountered during model fitting.
- `coef`: The linear coefficients determined by the model.
- `intercept`: The intercept determined by the model.
# Report
When all keys are enabled in `report_keys`, the following fields are available in
`report(mach)`:
- `deviance`: Measure of deviance of fitted model with respect to
a perfectly fitted model. For a linear model, this is the weighted
residual sum of squares
- `dof_residual`: The degrees of freedom for residuals, when meaningful.
- `stderror`: The standard errors of the coefficients.
- `vcov`: The estimated variance-covariance matrix of the coefficient estimates.
- `coef_table`: Table which displays coefficients and summarizes their significance
and confidence intervals.
- `glm_model`: The raw fitted model returned by `GLM.lm`. Note this points to training
data. Refer to the GLM.jl documentation for usage.
# Examples
```
using MLJ
LinearRegressor = @load LinearRegressor pkg=GLM
glm = LinearRegressor()
X, y = make_regression(100, 2) # synthetic data
mach = machine(glm, X, y) |> fit!
Xnew, _ = make_regression(3, 2)
yhat = predict(mach, Xnew) # new predictions
yhat_point = predict_mean(mach, Xnew) # new predictions
fitted_params(mach).features
fitted_params(mach).coef # x1, x2, intercept
fitted_params(mach).intercept
report(mach)
```
See also
[`LinearCountRegressor`](@ref), [`LinearBinaryClassifier`](@ref)
"""
LinearRegressor
"""
$(MMI.doc_header(LinearBinaryClassifier))
`LinearBinaryClassifier` is a [generalized linear
model](https://en.wikipedia.org/wiki/Generalized_linear_model#Variance_function),
specialised to the case of a binary target variable, with a user-specified link function.
Options exist to specify an intercept or offset feature.
# Training data
In MLJ or MLJBase, bind an instance `model` to data with one of:
mach = machine(model, X, y)
mach = machine(model, X, y, w)
Here
- `X`: is any table of input features (eg, a `DataFrame`) whose columns are of scitype
`Continuous`; check the scitype with `schema(X)`
- `y`: is the target, which can be any `AbstractVector` whose element scitype is
`<:OrderedFactor(2)` or `<:Multiclass(2)`; check the scitype with `schema(y)`
- `w`: is a vector of `Real` per-observation weights
Train the machine using `fit!(mach, rows=...)`.
# Hyper-parameters
- `fit_intercept=true`: Whether to calculate the intercept for this model. If set to false,
no intercept will be calculated (e.g. the data is expected to be centered)
- `link=GLM.LogitLink`: The function which links the linear prediction function to the
probability of a particular outcome or class. This must have type `GLM.Link01`. Options
include `GLM.LogitLink()`, `GLM.ProbitLink()`, `CloglogLink(), `CauchitLink()`.
- `offsetcol=nothing`: Name of the column to be used as an offset, if any. An offset is a
variable which is known to have a coefficient of 1.
- `maxiter::Integer=30`: The maximum number of iterations allowed to achieve convergence.
- `atol::Real=1e-6`: Absolute threshold for convergence. Convergence is achieved when the
relative change in deviance is less than `max(rtol*dev, atol). This term exists to avoid
failure when deviance is unchanged except for rounding errors.
- `rtol::Real=1e-6`: Relative threshold for convergence. Convergence is achieved when the
relative change in deviance is less than `max(rtol*dev, atol). This term exists to avoid
failure when deviance is unchanged except for rounding errors.
- `minstepfac::Real=0.001`: Minimum step fraction. Must be between 0 and 1. Lower bound for
the factor used to update the linear fit.
- `report_keys`: `Vector` of keys for the report. Possible keys are: $VALID_KEYS_LIST. By
default only `:glm_model` is excluded.
# Operations
- `predict(mach, Xnew)`: Return predictions of the target given features `Xnew` having the
same scitype as `X` above. Predictions are probabilistic.
- `predict_mode(mach, Xnew)`: Return the modes of the probabilistic predictions returned
above.
# Fitted parameters
The fields of `fitted_params(mach)` are:
- `features`: The names of the features used during model fitting.
- `coef`: The linear coefficients determined by the model.
- `intercept`: The intercept determined by the model.
# Report
The fields of `report(mach)` are:
- `deviance`: Measure of deviance of fitted model with respect to a perfectly fitted
model. For a linear model, this is the weighted residual sum of squares
- `dof_residual`: The degrees of freedom for residuals, when meaningful.
- `stderror`: The standard errors of the coefficients.
- `vcov`: The estimated variance-covariance matrix of the coefficient estimates.
- `coef_table`: Table which displays coefficients and summarizes their significance and
confidence intervals.
- `glm_model`: The raw fitted model returned by `GLM.lm`. Note this points to training
data. Refer to the GLM.jl documentation for usage.
# Examples
```
using MLJ
import GLM # namespace must be available
LinearBinaryClassifier = @load LinearBinaryClassifier pkg=GLM
clf = LinearBinaryClassifier(fit_intercept=false, link=GLM.ProbitLink())
X, y = @load_crabs
mach = machine(clf, X, y) |> fit!
Xnew = (;FL = [8.1, 24.8, 7.2],
RW = [5.1, 25.7, 6.4],
CL = [15.9, 46.7, 14.3],
CW = [18.7, 59.7, 12.2],
BD = [6.2, 23.6, 8.4],)
yhat = predict(mach, Xnew) # probabilistic predictions
pdf(yhat, levels(y)) # probability matrix
p_B = pdf.(yhat, "B")
class_labels = predict_mode(mach, Xnew)
fitted_params(mach).features
fitted_params(mach).coef
fitted_params(mach).intercept
report(mach)
```
See also
[`LinearRegressor`](@ref), [`LinearCountRegressor`](@ref)
"""
LinearBinaryClassifier
"""
$(MMI.doc_header(LinearCountRegressor))
`LinearCountRegressor` is a [generalized linear
model](https://en.wikipedia.org/wiki/Generalized_linear_model#Variance_function),
specialised to the case of a `Count` target variable (non-negative, unbounded integer) with
user-specified link function. Options exist to specify an intercept or offset feature.
# Training data
In MLJ or MLJBase, bind an instance `model` to data with one of:
mach = machine(model, X, y)
mach = machine(model, X, y, w)
Here
- `X`: is any table of input features (eg, a `DataFrame`) whose columns are of scitype
`Continuous`; check the scitype with `schema(X)`
- `y`: is the target, which can be any `AbstractVector` whose element scitype is `Count`;
check the scitype with `schema(y)`
- `w`: is a vector of `Real` per-observation weights
Train the machine using `fit!(mach, rows=...)`.
# Hyper-parameters
- `fit_intercept=true`: Whether to calculate the intercept for this model. If set to false,
no intercept will be calculated (e.g. the data is expected to be centered)
- `distribution=Distributions.Poisson()`: The distribution which the residuals/errors of the
model should fit.
- `link=GLM.LogLink()`: The function which links the linear prediction function to the
probability of a particular outcome or class. This should be one of the following:
`GLM.IdentityLink()`, `GLM.InverseLink()`, `GLM.InverseSquareLink()`, `GLM.LogLink()`,
`GLM.SqrtLink()`.
- `offsetcol=nothing`: Name of the column to be used as an offset, if any. An offset is a
variable which is known to have a coefficient of 1.
- `maxiter::Integer=30`: The maximum number of iterations allowed to achieve convergence.
- `atol::Real=1e-6`: Absolute threshold for convergence. Convergence is achieved when the
relative change in deviance is less than `max(rtol*dev, atol). This term exists to avoid
failure when deviance is unchanged except for rounding errors.
- `rtol::Real=1e-6`: Relative threshold for convergence. Convergence is achieved when the
relative change in deviance is less than `max(rtol*dev, atol). This term exists to avoid
failure when deviance is unchanged except for rounding errors.
- `minstepfac::Real=0.001`: Minimum step fraction. Must be between 0 and 1. Lower bound for
the factor used to update the linear fit.
- `report_keys`: `Vector` of keys for the report. Possible keys are: $VALID_KEYS_LIST. By
default only `:glm_model` is excluded.
# Operations
- `predict(mach, Xnew)`: return predictions of the target given new features `Xnew` having
the same Scitype as `X` above. Predictions are probabilistic.
- `predict_mean(mach, Xnew)`: instead return the mean of each prediction above
- `predict_median(mach, Xnew)`: instead return the median of each prediction above.
# Fitted parameters
The fields of `fitted_params(mach)` are:
- `features`: The names of the features encountered during model fitting.
- `coef`: The linear coefficients determined by the model.
- `intercept`: The intercept determined by the model.
# Report
The fields of `report(mach)` are:
- `deviance`: Measure of deviance of fitted model with respect to a perfectly fitted
model. For a linear model, this is the weighted residual sum of squares
- `dof_residual`: The degrees of freedom for residuals, when meaningful.
- `stderror`: The standard errors of the coefficients.
- `vcov`: The estimated variance-covariance matrix of the coefficient estimates.
- `coef_table`: Table which displays coefficients and summarizes their significance and
confidence intervals.
- `glm_model`: The raw fitted model returned by `GLM.lm`. Note this points to training
data. Refer to the GLM.jl documentation for usage.
# Examples
```
using MLJ
import MLJ.Distributions.Poisson
# Generate some data whose target y looks Poisson when conditioned on
# X:
N = 10_000
w = [1.0, -2.0, 3.0]
mu(x) = exp(w'x) # mean for a log link function
Xmat = rand(N, 3)
X = MLJ.table(Xmat)
y = map(1:N) do i
x = Xmat[i, :]
rand(Poisson(mu(x)))
end;
CountRegressor = @load LinearCountRegressor pkg=GLM
model = CountRegressor(fit_intercept=false)
mach = machine(model, X, y)
fit!(mach)
Xnew = MLJ.table(rand(3, 3))
yhat = predict(mach, Xnew)
yhat_point = predict_mean(mach, Xnew)
# get coefficients approximating `w`:
julia> fitted_params(mach).coef
3-element Vector{Float64}:
0.9969008753103842
-2.0255901752504775
3.014407534033522
report(mach)
```
See also
[`LinearRegressor`](@ref), [`LinearBinaryClassifier`](@ref)
"""
LinearCountRegressor
end # module
| MLJGLMInterface | https://github.com/JuliaAI/MLJGLMInterface.jl.git |
|
[
"MIT"
] | 0.3.7 | db318813a5f07e3f93a1e530c8fd0e6bdc9cabac | code | 13792 | using Test
using MLJBase
using StatisticalMeasures
using LinearAlgebra
using Statistics
using MLJGLMInterface
using GLM: coeftable
import GLM
import MLJTestInterface
using Distributions: Normal, Poisson, Uniform
import StableRNGs
using Tables
expit(X) = 1 ./ (1 .+ exp.(-X))
# TODO: Add more datasets to the following generic interface tests after #45 is merged
@testset "generic interface tests" begin
@testset "LinearRegressor" begin
for data in [
MLJTestInterface.make_regression(),
]
failures, summary = MLJTestInterface.test(
[LinearRegressor,],
data...;
mod=@__MODULE__,
verbosity=0, # bump to debug
throw=false, # set to true to debug
)
@test isempty(failures)
end
end
@testset "LinearCountRegressor" begin
for data in [
MLJTestInterface.make_count(),
]
failures, summary = MLJTestInterface.test(
[LinearCountRegressor,],
data...;
mod=@__MODULE__,
verbosity=0, # bump to debug
throw=false, # set to true to debug
)
@test isempty(failures)
end
end
@testset "LinearBinaryClassifier" begin
for data in [
MLJTestInterface.make_binary(),
]
failures, summary = MLJTestInterface.test(
[LinearBinaryClassifier,],
data...;
mod=@__MODULE__,
verbosity=0, # bump to debug
throw=false, # set to true to debug
)
end
end
end
###
### OLSREGRESSOR
###
@testset "OLSREGRESSOR" begin
X, y = @load_boston
w = ones(eltype(y), length(y))
train, test = partition(eachindex(y), 0.7)
atom_ols = LinearRegressor()
Xtrain = selectrows(X, train)
ytrain = selectrows(y, train)
wtrain = selectrows(w, train)
Xtest = selectrows(X, test)
fitresult, _, _ = fit(atom_ols, 1, Xtrain, ytrain)
θ = MLJBase.fitted_params(atom_ols, fitresult)
p = predict_mean(atom_ols, fitresult, Xtest)
fitresultw, _, _ = fit(atom_ols, 1, Xtrain, ytrain, wtrain)
θw = MLJBase.fitted_params(atom_ols, fitresult)
pw = predict_mean(atom_ols, fitresultw, Xtest)
Xa = MLJBase.matrix(X) # convert(Matrix{Float64}, X)
Xa1 = hcat(Xa, ones(size(Xa, 1)))
coefs = Xa1[train, :] \ y[train]
p2 = Xa1[test, :] * coefs
@test p ≈ p2
@test pw ≈ p2
# test `predict` object
p_distr = predict(atom_ols, fitresult, selectrows(X, test))
dispersion = MLJGLMInterface.dispersion(fitresult)
@test p_distr[1] == Normal(p[1], dispersion)
# test metadata
model = atom_ols
@test name(model) == "LinearRegressor"
@test package_name(model) == "GLM"
@test supports_weights(model)
@test is_pure_julia(model)
@test is_supervised(model)
@test package_license(model) == "MIT"
@test prediction_type(model) == :probabilistic
@test hyperparameters(model) == (:fit_intercept, :dropcollinear, :offsetcol, :report_keys)
hyp_types = hyperparameter_types(model)
@test hyp_types[1] == "Bool"
@test hyp_types[2] == "Bool"
@test hyp_types[3] == "Union{Nothing, Symbol}"
@test hyp_types[4] == "Union{Nothing, AbstractVector{Symbol}}"
end
###
### Logistic regression
###
@testset "Logistic regression" begin
rng = StableRNGs.StableRNG(0)
N = 100
X = MLJBase.table(rand(rng, N, 4));
ycont = 2*X.x1 - X.x3 + 0.6*rand(rng, N)
y = categorical(ycont .> mean(ycont))
w = ones(length(y))
lr = LinearBinaryClassifier()
pr = LinearBinaryClassifier(link=GLM.ProbitLink())
fitresult, _, report = fit(lr, 1, X, y)
yhat = predict(lr, fitresult, X)
@test cross_entropy(yhat, y) < 0.25
fitresult1, _, report1 = fit(pr, 1, X, y)
yhat1 = predict(pr, fitresult1, X)
@test cross_entropy(yhat1, y) < 0.25
fitresultw, _, reportw = fit(lr, 1, X, y, w)
yhatw = predict(lr, fitresultw, X)
@test cross_entropy(yhatw, y) < 0.25
@test yhatw ≈ yhat
fitresultw1, _, reportw1 = fit(pr, 1, X, y, w)
yhatw1 = predict(pr, fitresultw1, X)
@test cross_entropy(yhatw1, y) < 0.25
@test yhatw1 ≈ yhat1
# check predict on `Xnew` with wrong dims
Xnew = MLJBase.table(Tables.matrix(X)[:, 1:3], names=Tables.columnnames(X)[1:3])
@test_throws ErrorException predict(lr, fitresult, Xnew)
fitted_params(pr, fitresult)
# Test metadata
model = lr
@test name(model) == "LinearBinaryClassifier"
@test package_name(model) == "GLM"
@test supports_weights(model)
@test is_pure_julia(model)
@test is_supervised(model)
@test package_license(model) == "MIT"
@test prediction_type(model) == :probabilistic
hyper_params = hyperparameters(model)
@test hyper_params[1] == :fit_intercept
@test hyper_params[2] == :link
@test hyper_params[3] == :offsetcol
@test hyper_params[4] == :maxiter
@test hyper_params[5] == :atol
@test hyper_params[6] == :rtol
@test hyper_params[7] == :minstepfac
@test hyper_params[8] == :report_keys
end
###
### Count regression
###
@testset "Count regression" begin
rng = StableRNGs.StableRNG(123)
X = randn(rng, 500, 5)
θ = randn(rng, 5)
y = map(exp.(X*θ)) do mu
rand(rng, Poisson(mu))
end
w = ones(eltype(y), length(y))
XTable = MLJBase.table(X)
lcr = LinearCountRegressor(fit_intercept=false)
fitresult, _, _ = fit(lcr, 1, XTable, y)
θ̂ = fitted_params(lcr, fitresult).coef
@test norm(θ̂ .- θ)/norm(θ) ≤ 0.03
fitresultw, _, _ = fit(lcr, 1, XTable, y, w)
θ̂w = fitted_params(lcr, fitresultw).coef
@test norm(θ̂w .- θ)/norm(θ) ≤ 0.03
@test θ̂w ≈ θ̂
# check predict on `Xnew` with wrong dims
Xnew = MLJBase.table(
Tables.matrix(XTable)[:, 1:3], names=Tables.columnnames(XTable)[1:3]
)
@test_throws ErrorException predict(lcr, fitresult, Xnew)
# Test metadata
model = lcr
@test name(model) == "LinearCountRegressor"
@test package_name(model) == "GLM"
@test supports_weights(model)
@test is_pure_julia(model)
@test is_supervised(model)
@test package_license(model) == "MIT"
@test prediction_type(model) == :probabilistic
hyper_params = hyperparameters(model)
@test hyper_params[1] == :fit_intercept
@test hyper_params[2] == :distribution
@test hyper_params[3] == :link
@test hyper_params[4] == :offsetcol
@test hyper_params[5] == :maxiter
@test hyper_params[6] == :atol
@test hyper_params[7] == :rtol
@test hyper_params[8] == :minstepfac
end
modeltypes = [LinearRegressor, LinearBinaryClassifier, LinearCountRegressor]
@testset "Test prepare_inputs" begin
@testset "check sample size" for fit_intercept in [true, false]
lin_reg = LinearRegressor(; fit_intercept)
X_lin_reg = MLJBase.table(rand(3, 3 + fit_intercept))
log_reg = LinearBinaryClassifier(; fit_intercept)
X_log_reg = MLJBase.table(rand(2, 3 + fit_intercept))
lcr = LinearCountRegressor(; distribution=Poisson(), fit_intercept)
X_lcr = X_log_reg
for (m, X) in [(lin_reg, X_lin_reg), (log_reg, X_log_reg), (lcr, X_lcr)]
@test_throws ArgumentError MLJGLMInterface.prepare_inputs(m, X)
end
end
@testset "no intercept/no offsetcol" for mt in modeltypes
X = (x1=[1,2,3], x2=[4,5,6])
m = mt(fit_intercept=false)
r = MLJGLMInterface.prepare_inputs(m, X)
Xcols, offset, features = r
@test offset == []
@test Xcols == (x1 = [1, 2, 3], x2 = [4, 5, 6])
@test features == [:x1, :x2]
X1 = NamedTuple()
@test_throws ArgumentError MLJGLMInterface.prepare_inputs(m, X1)
end
@testset "offsetcol but no intercept" for mt in modeltypes
X = (x1=[1,2,3], x2=[4,5,6])
m = mt(offsetcol=:x1, fit_intercept=false)
Xcols, offset, features = MLJGLMInterface.prepare_inputs(m, X)
@test offset == [1, 2, 3]
@test Xcols == (x2 = [4, 5, 6],)
@test features == [:x2]
# throw error for tables with just one column.
# Since for `offsetcol !== nothing` and `fit_intercept == false`
# the table must have at least two columns.
X1 = (x1=[1,2,3],)
@test_throws ArgumentError MLJGLMInterface.prepare_inputs(m, X1)
end
end
@testset "Test offsetting models" begin
@testset "Test split_X_offset" begin
X = (x1=[1,2,3], x2=[4,5,6])
@test MLJGLMInterface.split_X_offset(X, nothing) == (X, Float64[])
@test MLJGLMInterface.split_X_offset(X, :x1) == ((x2=[4,5,6],), [1,2,3])
lr = LinearRegressor(fit_intercept = false, offsetcol = :x1)
fitresult, _, report = fit(lr, 1, X, [5, 7, 9])
yhat = predict_mean(lr, fitresult, (x1 = [2, 3, 4], x2 = [5, 6, 7]))
@test yhat == [7.0, 9.0, 11.0]
rng = StableRNGs.StableRNG(123)
N = 100
X = MLJBase.table(rand(rng, N, 3))
Xnew, offset = MLJGLMInterface.split_X_offset(X, :x2)
@test offset isa Vector
@test length(Xnew) == 2
end
# In the following:
# The second column is taken as an offset by the model
# This is equivalent to assuming the coef is 1 and known
@testset "Test Logistic regression with offset" begin
N = 1000
rng = StableRNGs.StableRNG(0)
X = MLJBase.table(rand(rng, N, 3))
y = rand(rng, Uniform(0,1), N) .< expit(2*X.x1 + X.x2 - X.x3)
y = categorical(y)
lr = LinearBinaryClassifier(fit_intercept=false, offsetcol=:x2)
fitresult, _, report = fit(lr, 1, X, y)
fp = fitted_params(lr, fitresult)
@test fp.coef ≈ [2, -1] atol=0.03
@test iszero(fp.intercept)
end
@testset "Test Linear regression with offset" begin
N = 1000
rng = StableRNGs.StableRNG(0)
X = MLJBase.table(rand(rng, N, 3))
y = 2*X.x1 + X.x2 - X.x3 + rand(rng, Normal(0,1), N)
lr = LinearRegressor(fit_intercept=false, offsetcol=:x2)
fitresult, _, report = fit(lr, 1, X, y)
fp = fitted_params(lr, fitresult)
@test fp.coef ≈ [2, -1] atol=0.07
end
@testset "Test Count regression with offset" begin
N = 1000
rng = StableRNGs.StableRNG(0)
X = MLJBase.table(rand(rng, N, 3))
y = map(exp.(2*X.x1 + X.x2 - X.x3)) do mu
rand(rng, Poisson(mu))
end
lcr = LinearCountRegressor(fit_intercept=false, offsetcol=:x2)
fitresult, _, _ = fit(lcr, 1, X, y)
fp = fitted_params(lcr, fitresult)
@test fp.coef ≈ [2, -1] atol=0.04
end
end
@testset "Param names in fitresult" begin
X = (a=[1, 9, 4, 2], b=[1, 2, 1, 4], c=[9, 1, 5, 3])
y = categorical([true, true, false, false])
lr = LinearBinaryClassifier(fit_intercept=true)
fitresult, _, report = fit(lr, 1, X, y)
ctable = last(report)
parameters = ctable.rownms # Row names.
@test parameters == ["(Intercept)", "a", "b", "c"]
intercept = ctable.cols[1][1]
yhat = predict(lr, fitresult, X)
@test cross_entropy(yhat, y) < 0.6
fp = fitted_params(lr, fitresult)
@test fp.features == [:a, :b, :c]
@test :intercept in keys(fp)
@test intercept == fp.intercept
end
@testset "Param names in report" begin
X = (a=[1, 4, 3, 1], b=[2, 0, 1, 4], c=[7, 1, 7, 3])
y = categorical([true, false, true, false])
# check that by default all possible keys are added in the report,
# except glm_model:
lr = LinearBinaryClassifier()
_, _, report = fit(lr, 1, X, y)
@test :deviance in keys(report)
@test :dof_residual in keys(report)
@test :stderror in keys(report)
@test :vcov in keys(report)
@test :coef_table in keys(report)
@test :glm_model ∉ keys(report)
# check that report is valid if only some keys are specified
lr = LinearBinaryClassifier(report_keys = [:stderror, :glm_model])
_, _, report = fit(lr, 1, X, y)
@test :deviance ∉ keys(report)
@test :stderror in keys(report)
@test :dof_residual ∉ keys(report)
@test :glm_model in keys(report)
@test report.glm_model.model isa GLM.GeneralizedLinearModel
# check that an empty `NamedTuple` is outputed for
# `report_params === nothing`
lr = LinearBinaryClassifier(report_keys=nothing)
_, _, report = fit(lr, 1, X, y)
@test report === NamedTuple()
end
@testset "Categorical predictors" begin
X = (x1=[1.,2.,3.,4.], x2 = categorical([0,1,0,0]), x3 = categorical([1, 0, 1,0], ordered=true))
y = categorical([false, false, true, true])
mach = machine(LinearBinaryClassifier(), X, y)
fit!(mach)
fp = fitted_params(mach)
@test fp.features == [:x1, :x2, :x3]
@test_throws KeyError predict(mach, (x1 = [2,3,4], x2 = categorical([0,1,2]), x3 = categorical([1,0,1], ordered=true)))
@test all(isapprox.(pdf.(predict(mach, X), true), [0,0,1,1], atol = 1e-3))
# only a categorical variable, with and without intercept
X2 = (; x = X.x2)
y2 = [0., 2., 1., 2.]
fitresult, _, report = fit(LinearRegressor(), 1, X2, y2)
pred = predict_mean(LinearRegressor(), fitresult, X2)
fitresult_nointercept, _, report = fit(LinearRegressor(fit_intercept = false), 1, X2, y2)
@test all(isapprox.(fitresult.coefs, [1.0, 1.0]))
@test all(isapprox.(fitresult_nointercept.coefs, [1.0, 2.0]))
end
@testset "Issue 27" begin
n, p = (100, 2)
Xmat = rand(p, n)' # note using adjoint
X = MLJBase.table(Xmat)
y = rand(n)
lr = LinearRegressor()
# Smoke test whether it crashes on an LinearAlgebra.Adjoint.
fit(lr, 1, X, y)
end
| MLJGLMInterface | https://github.com/JuliaAI/MLJGLMInterface.jl.git |
|
[
"MIT"
] | 0.3.7 | db318813a5f07e3f93a1e530c8fd0e6bdc9cabac | docs | 619 | # MLJGLMInterface.jl
Repository implementing [MLJ](https://alan-turing-institute.github.io/MLJ.jl/dev/) interface for
[GLM](https://github.com/JuliaStats/GLM.jl) models.
[](https://github.com/JuliaAI/MLJGLMInterface.jl/actions)
[](hhttps://codecov.io/github/JuliaAI/MLJGLMInterface.jl?branch=master)
[](https://github.com/invenia/BlueStyle)
| MLJGLMInterface | https://github.com/JuliaAI/MLJGLMInterface.jl.git |
|
[
"MIT"
] | 1.1.1 | 87d51a3ee9a4b0d2fe054bdd3fc2436258db2603 | code | 503 | using Static
using Documenter
makedocs(;
modules = [Static],
authors = "chriselrod, ChrisRackauckas, Tokazama",
repo = "https://github.com/SciML/Static.jl/blob/{commit}{path}#L{line}",
sitename = "Static.jl",
format = Documenter.HTML(;
prettyurls = get(ENV, "CI", "false") == "true",
canonical = "https://SciML.github.io/Static.jl",
assets = String[]),
pages = [
"Home" => "index.md"
])
deploydocs(;
repo = "github.com/SciML/Static.jl")
| Static | https://github.com/SciML/Static.jl.git |
|
[
"MIT"
] | 1.1.1 | 87d51a3ee9a4b0d2fe054bdd3fc2436258db2603 | code | 33279 | module Static
import IfElse: ifelse
export StaticInt, StaticFloat64, StaticSymbol, True, False, StaticBool, NDIndex
export dynamic, is_static, known, static, static_promote
import PrecompileTools: @recompile_invalidations
@recompile_invalidations begin
import CommonWorldInvalidations
end
"""
StaticSymbol
A statically typed `Symbol`.
"""
struct StaticSymbol{s}
StaticSymbol{s}() where {s} = new{s::Symbol}()
StaticSymbol(s::Symbol) = new{s}()
StaticSymbol(@nospecialize x::StaticSymbol) = x
StaticSymbol(x) = StaticSymbol(Symbol(x))
StaticSymbol(x, y) = StaticSymbol(Symbol(x, y))
@generated function StaticSymbol(::StaticSymbol{X}, ::StaticSymbol{Y}) where {X, Y}
StaticSymbol(Symbol(X, Y))
end
StaticSymbol(x, y, z...) = StaticSymbol(StaticSymbol(x, y), z...)
end
Base.Symbol(@nospecialize(s::StaticSymbol)) = known(s)
abstract type StaticInteger{N} <: Number end
"""
StaticBool(x::Bool) -> True/False
A statically typed `Bool`.
"""
abstract type StaticBool{bool} <: StaticInteger{bool} end
struct True <: StaticBool{true} end
struct False <: StaticBool{false} end
StaticBool{true}() = True()
StaticBool{false}() = False()
StaticBool(x::StaticBool) = x
function StaticBool(x::Bool)
if x
return True()
else
return False()
end
end
"""
StaticInt(N::Int) -> StaticInt{N}()
A statically sized `Int`.
Use `StaticInt(N)` instead of `Val(N)` when you want it to behave like a number.
"""
struct StaticInt{N} <: StaticInteger{N}
StaticInt{N}() where {N} = new{N::Int}()
StaticInt(N::Int) = new{N}()
StaticInt(@nospecialize N::StaticInt) = N
StaticInt(::Val{N}) where {N} = StaticInt(N)
end
"""
IntType(x::Integer) -> Union{Int,StaticInt}
`IntType` is a union of `Int` and `StaticInt`. As a function, it ensures that `x` one of the
two.
"""
const IntType = Union{StaticInt, Int}
IntType(x::Integer) = Int(x)
IntType(@nospecialize x::Union{Int, StaticInt}) = x
Base.isinteger(@nospecialize x::StaticInteger) = true
include("float.jl")
const StaticNumber{N} = Union{StaticInt{N}, StaticBool{N}, StaticFloat64{N}}
Base.promote_rule(::Type{Bool}, T::Type{<:StaticNumber}) = promote_rule(Bool, eltype(T))
Base.getindex(x::Tuple, ::StaticInt{N}) where {N} = getfield(x, N)
Base.getindex(x::NamedTuple, ::StaticSymbol{N}) where {N} = getfield(x, N)
function Base.getindex(x::NamedTuple, symbols::Tuple{StaticSymbol, Vararg{StaticSymbol}})
return x[map(known, symbols)]
end
Base.zero(@nospecialize(::StaticInt)) = StaticInt{0}()
Base.to_index(x::StaticInt) = known(x)
function Base.checkindex(::Type{Bool}, inds::AbstractUnitRange, ::StaticNumber{N}) where {N}
checkindex(Bool, inds, N)
end
function Base.checkindex(::Type{Bool}, inds::Base.IdentityUnitRange,
::StaticFloat64{N}) where {N}
checkindex(Bool, inds.indices, N)
end
ifelse(::True, @nospecialize(x), @nospecialize(y)) = x
ifelse(::False, @nospecialize(x), @nospecialize(y)) = y
const Zero = StaticInt{0}
const One = StaticInt{1}
const FloatOne = StaticFloat64{one(Float64)}
const FloatZero = StaticFloat64{zero(Float64)}
const StaticType{T} = Union{StaticNumber{T}, StaticSymbol{T}}
StaticInt(x::False) = Zero()
StaticInt(x::True) = One()
Base.Bool(::True) = true
Base.Bool(::False) = false
Base.eltype(@nospecialize(T::Type{<:StaticFloat64})) = Float64
Base.eltype(@nospecialize(T::Type{<:StaticInt})) = Int
Base.eltype(@nospecialize(T::Type{<:StaticBool})) = Bool
"""
NDIndex(i, j, k...) -> I
NDIndex((i, j, k...)) -> I
A multidimensional index that refers to a single element. Each dimension is represented by
a single `Int` or `StaticInt`.
```julia
julia> using Static
julia> i = NDIndex(static(1), 2, static(3))
NDIndex(static(1), 2, static(3))
julia> i[static(1)]
static(1)
julia> i[1]
1
```
"""
struct NDIndex{N, I <: Tuple{Vararg{Union{StaticInt, Int}, N}}} <:
Base.AbstractCartesianIndex{N}
index::I
NDIndex{N}(i::Tuple{Vararg{Union{StaticInt, Int}, N}}) where {N} = new{N, typeof(i)}(i)
NDIndex{N}(index::Tuple) where {N} = _ndindex(static(N), _flatten(index...))
NDIndex{N}(index...) where {N} = NDIndex{N}(index)
NDIndex{0}(::Tuple{}) = new{0, Tuple{}}(())
NDIndex{0}() = NDIndex{0}(())
NDIndex(i::Tuple{Vararg{Union{StaticInt, Int}, N}}) where {N} = new{N, typeof(i)}(i)
NDIndex(i::Vararg{Union{StaticInt, Int}, N}) where {N} = NDIndex(i)
NDIndex(index::Tuple) = NDIndex(_flatten(index...))
NDIndex(index...) = NDIndex(index)
end
_ndindex(n::StaticInt{N}, i::Tuple{Vararg{Union{Int, StaticInt}, N}}) where {N} = NDIndex(i)
function _ndindex(n::StaticInt{N}, i::Tuple{Vararg{Any, M}}) where {N, M}
M > N && throw(ArgumentError("input tuple of length $M, requested $N"))
return NDIndex(_fill_to_length(i, n))
end
_fill_to_length(x::Tuple{Vararg{Any, N}}, n::StaticInt{N}) where {N} = x
@inline function _fill_to_length(x::Tuple{Vararg{Any, M}}, n::StaticInt{N}) where {M, N}
return _fill_to_length((x..., static(1)), n)
end
_flatten(i::StaticInt{N}) where {N} = (i,)
_flatten(i::Integer) = (Int(i),)
_flatten(i::Base.AbstractCartesianIndex) = _flatten(Tuple(i)...)
@inline _flatten(i::StaticInt, I...) = (i, _flatten(I...)...)
@inline _flatten(i::Integer, I...) = (Int(i), _flatten(I...)...)
@inline function _flatten(i::Base.AbstractCartesianIndex, I...)
return (_flatten(Tuple(i)...)..., _flatten(I...)...)
end
Base.Tuple(@nospecialize(x::NDIndex)) = getfield(x, :index)
"""
known(T::Type)
Returns the known value corresponding to a static type `T`. If `T` is not a static type then
`nothing` is returned.
`known` ensures that the type of the returned value is always inferred, even if the
compiler fails to infer the exact value.
See also: [`static`](@ref), [`is_static`](@ref), [`dynamic`](@ref)
# Examples
```julia
julia> known(StaticInt{1})
1
julia> known(Int)
```
"""
known(@nospecialize(x)) = known(typeof(x))
_get_known(::Type{T}, dim::StaticInt{D}) where {T, D} = known(field_type(T, dim))
known(@nospecialize(T::Type{<:Tuple})) = eachop(_get_known, nstatic(Val(fieldcount(T))), T)
known(T::DataType) = nothing
known(@nospecialize(T::Type{<:NDIndex})) = known(T.parameters[2])
known(::Union{True, Type{True}}) = true
known(::Union{False, Type{False}}) = false
known(::Union{Val{V}, Type{Val{V}}}) where {V} = V
known(::Union{StaticInt{N}, Type{StaticInt{N}}}) where {N} = _return_int(N)
_return_int(x::Int) = x
known(::Union{StaticSymbol{S}, Type{StaticSymbol{S}}}) where {S} = _return_symbol(S)
_return_symbol(x::Symbol) = x
known(::Union{StaticFloat64{F}, Type{StaticFloat64{F}}}) where {F} = _return_float(F)
_return_float(x::Float64) = x
"""
static(x)
Returns a static form of `x`. If `x` is already in a static form then `x` is returned. If
there is no static alternative for `x` then an error is thrown.
See also: [`is_static`](@ref), [`known`](@ref)
# Examples
```julia
julia> using Static
julia> static(1)
static(1)
julia> static(true)
True()
julia> static(:x)
static(:x)
```
"""
static(@nospecialize(x::Union{StaticSymbol, StaticNumber})) = x
static(x::Integer) = StaticInt(x)
function static(x::Union{AbstractFloat, Complex, Rational, AbstractIrrational})
StaticFloat64(Float64(x))
end
static(x::Bool) = StaticBool(x)
static(x::Union{Symbol, AbstractChar, AbstractString}) = StaticSymbol(x)
static(x::Tuple{Vararg{Any}}) = map(static, x)
static(::Val{V}) where {V} = static(V)
static(x::CartesianIndex) = NDIndex(static(Tuple(x)))
function static(x::X) where {X}
Base.issingletontype(X) && return x
error("There is no static alternative for type $(typeof(x)).")
end
"""
is_static(::Type{T}) -> StaticBool
Returns `True` if `T` is a static type.
See also: [`static`](@ref), [`known`](@ref)
"""
is_static(@nospecialize(x)) = is_static(typeof(x))
is_static(@nospecialize(x::Type{<:StaticType})) = True()
is_static(@nospecialize(x::Type{<:Val})) = True()
_tuple_static(::Type{T}, i) where {T} = is_static(field_type(T, i))
@inline function is_static(@nospecialize(T::Type{<:Tuple}))
if all(eachop(_tuple_static, nstatic(Val(fieldcount(T))), T))
return True()
else
return False()
end
end
is_static(T::DataType) = False()
"""
dynamic(x)
Returns the "dynamic" or non-static form of `x`. If `x` is not a static type, then it is
returned unchanged.
`dynamic` ensures that the type of the returned value is always inferred, even if the
compiler fails to infer the exact value.
See also: [`known`](@ref)
# Examples
```julia
julia> dynamic(static(1))
1
julia> dynamic(1)
1
```
"""
@inline dynamic(@nospecialize x::StaticInt) = known(x)
@inline dynamic(@nospecialize x::StaticFloat64) = known(x)
@inline dynamic(@nospecialize x::StaticSymbol) = known(x)
@inline dynamic(@nospecialize x::Union{True, False}) = known(x)
@inline dynamic(@nospecialize x::Tuple) = map(dynamic, x)
dynamic(@nospecialize(x::NDIndex)) = CartesianIndex(dynamic(Tuple(x)))
dynamic(@nospecialize x) = x
"""
static_promote(x, y)
Throws an error if `x` and `y` are not equal, preferentially returning the one that is known
at compile time.
"""
@inline static_promote(x::StaticType{X}, ::StaticType{X}) where {X} = x
@noinline function static_promote(::StaticType{X}, ::StaticType{Y}) where {X, Y}
error("$X and $Y are not equal")
end
Base.@propagate_inbounds function static_promote(::StaticType{N}, x) where {N}
static(static_promote(N, x))
end
Base.@propagate_inbounds function static_promote(x, ::StaticType{N}) where {N}
static(static_promote(N, x))
end
Base.@propagate_inbounds static_promote(x, y) = _static_promote(x, y)
Base.@propagate_inbounds function _static_promote(x, y)
@boundscheck x === y || error("$x and $y are not equal")
x
end
_static_promote(::Nothing, ::Nothing) = nothing
_static_promote(x, ::Nothing) = x
_static_promote(::Nothing, y) = y
"""
static_promote(x::AbstractRange{<:Integer}, y::AbstractRange{<:Integer})
A type stable method for combining two equal ranges into a new range that preserves static
parameters. Throws an error if `x != y`.
# Examples
```julia
julia> static_promote(static(1):10, 1:static(10))
static(1):static(10)
julia> static_promote(1:2:9, static(1):static(2):static(9))
static(1):static(2):static(9)
```
"""
Base.@propagate_inbounds @inline function static_promote(x::AbstractUnitRange{<:Integer},
y::AbstractUnitRange{<:Integer})
fst = static_promote(static_first(x), static_first(y))
lst = static_promote(static_last(x), static_last(y))
return OptionallyStaticUnitRange(fst, lst)
end
Base.@propagate_inbounds @inline function static_promote(x::AbstractRange{<:Integer},
y::AbstractRange{<:Integer})
fst = static_promote(static_first(x), static_first(y))
stp = static_promote(static_step(x), static_step(y))
lst = static_promote(static_last(x), static_last(y))
return _OptionallyStaticStepRange(fst, stp, lst)
end
function static_promote(x::Base.Slice, y::Base.Slice)
Base.Slice(static_promote(x.indices, y.indices))
end
Base.@propagate_inbounds function _promote_shape(a::Tuple{A, Vararg{Any}},
b::Tuple{B, Vararg{Any}}) where {A, B}
(static_promote(getfield(a, 1), getfield(b, 1)),
_promote_shape(Base.tail(a), Base.tail(b))...)
end
_promote_shape(::Tuple{}, ::Tuple{}) = ()
Base.@propagate_inbounds function _promote_shape(::Tuple{}, b::Tuple{B}) where {B}
(static_promote(static(1), getfield(b, 1)),)
end
Base.@propagate_inbounds function _promote_shape(a::Tuple{A}, ::Tuple{}) where {A}
(static_promote(static(1), getfield(a, 1)),)
end
Base.@propagate_inbounds function Base.promote_shape(
a::Tuple{
Vararg{Union{Int, StaticInt}},
},
b::Tuple{Vararg{Union{Int, StaticInt}}
})
_promote_shape(a, b)
end
function Base.promote_rule(@nospecialize(T1::Type{<:StaticNumber}),
@nospecialize(T2::Type{<:StaticNumber}))
promote_rule(eltype(T1), eltype(T2))
end
function Base.promote_rule(::Type{<:Base.TwicePrecision{R}},
@nospecialize(T::Type{<:StaticNumber})) where {R <: Number}
promote_rule(Base.TwicePrecision{R}, eltype(T))
end
function Base.promote_rule(@nospecialize(T1::Type{<:StaticNumber}),
T2::Type{<:Union{Rational, AbstractFloat, Signed}})
promote_rule(T2, eltype(T1))
end
Base.:(~)(::StaticInteger{N}) where {N} = static(~N)
Base.inv(x::StaticInteger{N}) where {N} = one(x) / x
Base.zero(@nospecialize T::Type{<:StaticInt}) = StaticInt(0)
Base.zero(@nospecialize T::Type{<:StaticBool}) = False()
Base.one(@nospecialize T::Type{<:StaticBool}) = True()
Base.one(@nospecialize T::Type{<:StaticInt}) = StaticInt(1)
@inline Base.iszero(::Union{StaticInt{0}, StaticFloat64{0.0}, False}) = true
@inline Base.iszero(@nospecialize x::Union{StaticInt, True, StaticFloat64}) = false
@inline Base.isone(::Union{One, True, StaticFloat64{1.0}}) = true
@inline Base.isone(@nospecialize x::Union{StaticInt, False, StaticFloat64}) = false
@inline Base.iseven(@nospecialize x::StaticNumber) = iseven(known(x))
@inline Base.isodd(@nospecialize x::StaticNumber) = isodd(known(x))
Base.AbstractFloat(x::StaticNumber) = StaticFloat64(x)
Base.abs(::StaticNumber{N}) where {N} = static(abs(N))
Base.abs2(::StaticNumber{N}) where {N} = static(abs2(N))
Base.sign(::StaticNumber{N}) where {N} = static(sign(N))
Base.widen(@nospecialize(x::StaticNumber)) = widen(known(x))
function Base.convert(::Type{T}, @nospecialize(N::StaticNumber)) where {T <: Number}
convert(T, known(N))
end
#Base.Bool(::StaticInt{N}) where {N} = Bool(N)
Base.Integer(@nospecialize(x::StaticInt)) = x
(::Type{T})(x::StaticInteger) where {T <: Real} = T(known(x))
function (@nospecialize(T::Type{<:StaticNumber}))(x::Union{AbstractFloat,
AbstractIrrational, Integer,
Rational})
static(convert(eltype(T), x))
end
@inline Base.:(-)(::StaticNumber{N}) where {N} = static(-N)
Base.:(*)(::Union{AbstractFloat, AbstractIrrational, Integer, Rational}, y::Zero) = y
Base.:(*)(x::Zero, ::Union{AbstractFloat, AbstractIrrational, Integer, Rational}) = x
Base.:(*)(::StaticInteger{X}, ::StaticInteger{Y}) where {X, Y} = static(X * Y)
Base.:(/)(::StaticInteger{X}, ::StaticInteger{Y}) where {X, Y} = static(X / Y)
Base.:(-)(::StaticInteger{X}, ::StaticInteger{Y}) where {X, Y} = static(X - Y)
Base.:(+)(::StaticInteger{X}, ::StaticInteger{Y}) where {X, Y} = static(X + Y)
@generated Base.sqrt(::StaticNumber{N}) where {N} = :($(static(sqrt(N))))
function Base.div(::StaticNumber{X}, ::StaticNumber{Y}, m::RoundingMode) where {X, Y}
static(div(X, Y, m))
end
Base.div(x::Real, ::StaticInteger{Y}, m::RoundingMode) where {Y} = div(x, Y, m)
Base.div(::StaticNumber{X}, y::Real, m::RoundingMode) where {X} = div(X, y, m)
Base.div(x::StaticBool, y::False) = throw(DivideError())
Base.div(x::StaticBool, y::True) = x
Base.rem(@nospecialize(x::StaticNumber), T::Type{<:Integer}) = rem(known(x), T)
Base.rem(::StaticNumber{X}, ::StaticNumber{Y}) where {X, Y} = static(rem(X, Y))
Base.rem(x::Real, ::StaticInteger{Y}) where {Y} = rem(x, Y)
Base.rem(::StaticInteger{X}, y::Real) where {X} = rem(X, y)
Base.mod(::StaticNumber{X}, ::StaticNumber{Y}) where {X, Y} = static(mod(X, Y))
Base.mod(x::Real, ::StaticNumber{Y}) where {Y} = mod(x, Y)
Base.mod(::StaticNumber{X}, y::Real) where {X} = mod(X, y)
Base.:(==)(::StaticNumber{X}, ::StaticNumber{Y}) where {X, Y} = ==(X, Y)
Base.:(<)(::StaticNumber{X}, ::StaticNumber{Y}) where {X, Y} = <(X, Y)
Base.isless(::StaticInteger{X}, ::StaticInteger{Y}) where {X, Y} = isless(X, Y)
Base.isless(::StaticInteger{X}, y::Real) where {X} = isless(X, y)
Base.isless(x::Real, ::StaticInteger{Y}) where {Y} = isless(x, Y)
Base.min(::StaticInteger{X}, ::StaticInteger{Y}) where {X, Y} = static(min(X, Y))
Base.min(::StaticInteger{X}, y::Number) where {X} = min(X, y)
Base.min(x::Number, ::StaticInteger{Y}) where {Y} = min(x, Y)
Base.max(::StaticInteger{X}, ::StaticInteger{Y}) where {X, Y} = static(max(X, Y))
Base.max(::StaticInteger{X}, y::Number) where {X} = max(X, y)
Base.max(x::Number, ::StaticInteger{Y}) where {Y} = max(x, Y)
Base.minmax(::StaticNumber{X}, ::StaticNumber{Y}) where {X, Y} = static(minmax(X, Y))
Base.:(<<)(::StaticInteger{X}, ::StaticInteger{Y}) where {X, Y} = static(<<(X, Y))
Base.:(<<)(::StaticInteger{X}, n::Integer) where {X} = <<(X, n)
Base.:(<<)(x::Integer, ::StaticInteger{N}) where {N} = <<(x, N)
Base.:(>>)(::StaticInteger{X}, ::StaticInteger{Y}) where {X, Y} = static(>>(X, Y))
Base.:(>>)(::StaticInteger{X}, n::Integer) where {X} = >>(X, n)
Base.:(>>)(x::Integer, ::StaticInteger{N}) where {N} = >>(x, N)
Base.:(>>>)(::StaticInteger{X}, ::StaticInteger{Y}) where {X, Y} = static(>>>(X, Y))
Base.:(>>>)(::StaticInteger{X}, n::Integer) where {X} = >>>(X, n)
Base.:(>>>)(x::Integer, ::StaticInteger{N}) where {N} = >>>(x, N)
Base.:(&)(::StaticInteger{X}, ::StaticInteger{Y}) where {X, Y} = static(X & Y)
Base.:(&)(::StaticInteger{X}, y::Union{Integer, Missing}) where {X} = X & y
Base.:(&)(x::Union{Integer, Missing}, ::StaticInteger{Y}) where {Y} = x & Y
Base.:(&)(x::Bool, y::True) = x
Base.:(&)(x::Bool, y::False) = y
Base.:(&)(x::True, y::Bool) = y
Base.:(&)(x::False, y::Bool) = x
Base.:(|)(::StaticInteger{X}, ::StaticInteger{Y}) where {X, Y} = static(|(X, Y))
Base.:(|)(::StaticInteger{X}, y::Union{Integer, Missing}) where {X} = X | y
Base.:(|)(x::Union{Integer, Missing}, ::StaticInteger{Y}) where {Y} = x | Y
Base.:(|)(x::Bool, y::True) = y
Base.:(|)(x::Bool, y::False) = x
Base.:(|)(x::True, y::Bool) = x
Base.:(|)(x::False, y::Bool) = y
Base.xor(::StaticInteger{X}, ::StaticInteger{Y}) where {X, Y} = static(xor(X, Y))
Base.xor(::StaticInteger{X}, y::Union{Integer, Missing}) where {X} = xor(X, y)
Base.xor(x::Union{Integer, Missing}, ::StaticInteger{Y}) where {Y} = xor(x, Y)
Base.:(!)(::True) = False()
Base.:(!)(::False) = True()
Base.all(::Tuple{Vararg{True}}) = true
Base.all(::Tuple{Vararg{Union{True, False}}}) = false
Base.all(::Tuple{Vararg{False}}) = false
Base.any(::Tuple{Vararg{True}}) = true
Base.any(::Tuple{Vararg{Union{True, False}}}) = true
Base.any(::Tuple{Vararg{False}}) = false
Base.real(@nospecialize(x::StaticNumber)) = x
Base.real(@nospecialize(T::Type{<:StaticNumber})) = eltype(T)
Base.imag(@nospecialize(x::StaticNumber)) = zero(x)
"""
field_type(::Type{T}, f)
Functionally equivalent to `fieldtype(T, f)` except `f` may be a static type.
"""
@inline field_type(T::Type, f::Union{Int, Symbol}) = fieldtype(T, f)
@inline field_type(::Type{T}, ::StaticInt{N}) where {T, N} = fieldtype(T, N)
@inline field_type(::Type{T}, ::StaticSymbol{S}) where {T, S} = fieldtype(T, S)
@inline Base.exponent(::StaticNumber{M}) where {M} = static(exponent(M))
Base.:(^)(::StaticFloat64{x}, y::Float64) where {x} = exp2(log2(x) * y)
Base.:(+)(x::True) = One()
Base.:(+)(x::False) = Zero()
# from `^(x::Bool, y::Bool) = x | !y`
Base.:(^)(x::StaticBool, y::False) = True()
Base.:(^)(x::StaticBool, y::True) = x
Base.:(^)(x::Integer, y::False) = one(x)
Base.:(^)(x::Integer, y::True) = x
Base.:(^)(x::BigInt, y::False) = one(x)
Base.:(^)(x::BigInt, y::True) = x
@inline function Base.ntuple(f::F, ::StaticInt{N}) where {F, N}
(N >= 0) || throw(ArgumentError(string("tuple length should be ≥ 0, got ", N)))
if @generated
quote
Base.Cartesian.@ntuple $N i->f(i)
end
else
Tuple(f(i) for i in 1:N)
end
end
@inline function invariant_permutation(@nospecialize(x::Tuple), @nospecialize(y::Tuple))
if y === x === ntuple(static, StaticInt(nfields(x)))
return True()
else
return False()
end
end
@inline nstatic(::Val{N}) where {N} = ntuple(StaticInt, Val(N))
permute(@nospecialize(x::Tuple), @nospecialize(perm::Val)) = permute(x, static(perm))
@inline function permute(@nospecialize(x::Tuple), @nospecialize(perm::Tuple))
if invariant_permutation(nstatic(Val(nfields(x))), perm) === False()
return eachop(getindex, perm, x)
else
return x
end
end
"""
eachop(op, args...; iterator::Tuple{Vararg{StaticInt}}) -> Tuple
Produces a tuple of `(op(args..., iterator[1]), op(args..., iterator[2]),...)`.
"""
@inline function eachop(op::F, itr::Tuple{T, Vararg{Any}}, args::Vararg{Any}) where {F, T}
(op(args..., first(itr)), eachop(op, Base.tail(itr), args...)...)
end
eachop(::F, ::Tuple{}, args::Vararg{Any}) where {F} = ()
"""
eachop_tuple(op, arg, args...; iterator::Tuple{Vararg{StaticInt}}) -> Type{Tuple}
Produces a tuple type of `Tuple{op(arg, args..., iterator[1]), op(arg, args..., iterator[2]),...}`.
Note that if one of the arguments passed to `op` is a `Tuple` type then it should be the first argument
instead of one of the trailing arguments, ensuring type inference of each element of the tuple.
"""
eachop_tuple(op, itr, arg, args...) = _eachop_tuple(op, itr, arg, args)
@generated function _eachop_tuple(op, ::I, arg, args::A) where {A, I}
t = Expr(:curly, Tuple)
narg = length(A.parameters)
for p in I.parameters
call_expr = Expr(:call, :op, :arg)
if narg > 0
for i in 1:narg
push!(call_expr.args, :(getfield(args, $i)))
end
end
push!(call_expr.args, :(StaticInt{$(p.parameters[1])}()))
push!(t.args, call_expr)
end
Expr(:block, Expr(:meta, :inline), t)
end
#=
find_first_eq(x, collection::Tuple)
Finds the position in the tuple `collection` that is exactly equal (i.e. `===`) to `x`.
If `x` and `collection` are static (`is_static`) and `x` is in `collection` then the return
value is a `StaticInt`.
=#
@generated function find_first_eq(x::X, itr::I) where {X, N, I <: Tuple{Vararg{Any, N}}}
# we avoid incidental code gen when evaluated a tuple of known values by iterating
# through `I.parameters` instead of `known(I)`.
index = known(X) === nothing ? nothing : findfirst(==(X), I.parameters)
if index === nothing
:(Base.Cartesian.@nif $(N + 1) d->(dynamic(x) == dynamic(getfield(itr, d))) d->(d) d->(nothing))
else
:($(static(index)))
end
end
function Base.invperm(p::Tuple{StaticInt, Vararg{StaticInt, N}}) where {N}
map(Base.Fix2(find_first_eq, p), ntuple(static, StaticInt(N + 1)))
end
"""
reduce_tup(f::F, inds::Tuple{Vararg{Any,N}}) where {F,N}
An optimized `reduce` for tuples. `Base.reduce`'s `afoldl` will often not inline.
Additionally, `reduce_tup` attempts to order the reduction in an optimal manner.
```julia
julia> using StaticArrays, Static, BenchmarkTools
julia> rsum(v::SVector) = Static.reduce_tup(+, v.data)
rsum (generic function with 2 methods)
julia> for n ∈ 2:16
@show n
v = @SVector rand(n)
s1 = @btime sum(\$(Ref(v))[])
s2 = @btime rsum(\$(Ref(v))[])
end
n = 2
0.863 ns (0 allocations: 0 bytes)
0.863 ns (0 allocations: 0 bytes)
n = 3
0.862 ns (0 allocations: 0 bytes)
0.863 ns (0 allocations: 0 bytes)
n = 4
0.862 ns (0 allocations: 0 bytes)
0.862 ns (0 allocations: 0 bytes)
n = 5
1.074 ns (0 allocations: 0 bytes)
0.864 ns (0 allocations: 0 bytes)
n = 6
0.864 ns (0 allocations: 0 bytes)
0.862 ns (0 allocations: 0 bytes)
n = 7
1.075 ns (0 allocations: 0 bytes)
0.864 ns (0 allocations: 0 bytes)
n = 8
1.077 ns (0 allocations: 0 bytes)
0.865 ns (0 allocations: 0 bytes)
n = 9
1.081 ns (0 allocations: 0 bytes)
0.865 ns (0 allocations: 0 bytes)
n = 10
1.195 ns (0 allocations: 0 bytes)
0.867 ns (0 allocations: 0 bytes)
n = 11
1.357 ns (0 allocations: 0 bytes)
1.400 ns (0 allocations: 0 bytes)
n = 12
1.543 ns (0 allocations: 0 bytes)
1.074 ns (0 allocations: 0 bytes)
n = 13
1.702 ns (0 allocations: 0 bytes)
1.077 ns (0 allocations: 0 bytes)
n = 14
1.913 ns (0 allocations: 0 bytes)
0.867 ns (0 allocations: 0 bytes)
n = 15
2.076 ns (0 allocations: 0 bytes)
1.077 ns (0 allocations: 0 bytes)
n = 16
2.273 ns (0 allocations: 0 bytes)
1.078 ns (0 allocations: 0 bytes)
```
More importantly, `reduce_tup(_pick_range, inds)` often performs better than `reduce(_pick_range, inds)`.
```julia
julia> using ArrayInterface, BenchmarkTools, Static
julia> inds = (Base.OneTo(100), 1:100, 1:static(100))
(Base.OneTo(100), 1:100, 1:static(100))
julia> @btime reduce(ArrayInterface._pick_range, \$(Ref(inds))[])
6.405 ns (0 allocations: 0 bytes)
Base.Slice(static(1):static(100))
julia> @btime Static.reduce_tup(ArrayInterface._pick_range, \$(Ref(inds))[])
2.570 ns (0 allocations: 0 bytes)
Base.Slice(static(1):static(100))
julia> inds = (Base.OneTo(100), 1:100, 1:UInt(100))
(Base.OneTo(100), 1:100, 0x0000000000000001:0x0000000000000064)
julia> @btime reduce(ArrayInterface._pick_range, \$(Ref(inds))[])
6.411 ns (0 allocations: 0 bytes)
Base.Slice(static(1):100)
julia> @btime Static.reduce_tup(ArrayInterface._pick_range, \$(Ref(inds))[])
2.592 ns (0 allocations: 0 bytes)
Base.Slice(static(1):100)
julia> inds = (Base.OneTo(100), 1:100, 1:UInt(100), Int32(1):Int32(100))
(Base.OneTo(100), 1:100, 0x0000000000000001:0x0000000000000064, 1:100)
julia> @btime reduce(ArrayInterface._pick_range, \$(Ref(inds))[])
9.048 ns (0 allocations: 0 bytes)
Base.Slice(static(1):100)
julia> @btime Static.reduce_tup(ArrayInterface._pick_range, \$(Ref(inds))[])
2.569 ns (0 allocations: 0 bytes)
Base.Slice(static(1):100)
```
"""
@generated function reduce_tup(f::F, inds::Tuple{Vararg{Any, N}}) where {F, N}
q = Expr(:block, Expr(:meta, :inline, :propagate_inbounds))
if N == 1
push!(q.args, :(inds[1]))
return q
end
syms = Vector{Symbol}(undef, N)
i = 0
for n in 1:N
syms[n] = iₙ = Symbol(:i_, (i += 1))
push!(q.args, Expr(:(=), iₙ, Expr(:ref, :inds, n)))
end
W = 1 << (8sizeof(N) - 2 - leading_zeros(N))
while W > 0
_N = length(syms)
for _ in (2W):W:_N
for w in 1:W
new_sym = Symbol(:i_, (i += 1))
push!(q.args, Expr(:(=), new_sym, Expr(:call, :f, syms[w], syms[w + W])))
syms[w] = new_sym
end
deleteat!(syms, (1 + W):(2W))
end
W >>>= 1
end
q
end
# This method assumes that `f` uetrieves compile time information and `g` is the fall back
# for the corresponding dynamic method. If the `f(x)` doesn't return `nothing` that means
# the value is known and compile time and returns `static(f(x))`.
@inline function maybe_static(f::F, g::G, x) where {F, G}
L = f(x)
if L === nothing
return g(x)
else
return static(L)
end
end
"""
eq(x, y)
Equivalent to `!=` but if `x` and `y` are both static returns a `StaticBool.
"""
eq(x::X, y::Y) where {X, Y} = ifelse(is_static(X) & is_static(Y), static, identity)(x == y)
eq(x) = Base.Fix2(eq, x)
"""
ne(x, y)
Equivalent to `!=` but if `x` and `y` are both static returns a `StaticBool.
"""
ne(x::X, y::Y) where {X, Y} = !eq(x, y)
ne(x) = Base.Fix2(ne, x)
"""
gt(x, y)
Equivalent to `>` but if `x` and `y` are both static returns a `StaticBool.
"""
gt(x::X, y::Y) where {X, Y} = ifelse(is_static(X) & is_static(Y), static, identity)(x > y)
gt(x) = Base.Fix2(gt, x)
"""
ge(x, y)
Equivalent to `>=` but if `x` and `y` are both static returns a `StaticBool.
"""
ge(x::X, y::Y) where {X, Y} = ifelse(is_static(X) & is_static(Y), static, identity)(x >= y)
ge(x) = Base.Fix2(ge, x)
"""
le(x, y)
Equivalent to `<=` but if `x` and `y` are both static returns a `StaticBool.
"""
le(x::X, y::Y) where {X, Y} = ifelse(is_static(X) & is_static(Y), static, identity)(x <= y)
le(x) = Base.Fix2(le, x)
"""
lt(x, y)
Equivalent to `<` but if `x` and `y` are both static returns a `StaticBool.
"""
lt(x::X, y::Y) where {X, Y} = ifelse(is_static(X) & is_static(Y), static, identity)(x < y)
lt(x) = Base.Fix2(lt, x)
"""
mul(x) -> Base.Fix2(*, x)
mul(x, y) ->
Equivalent to `*` but allows for lazy multiplication when passing functions.
"""
mul(x) = Base.Fix2(*, x)
"""
add(x) -> Base.Fix2(+, x)
add(x, y) ->
Equivalent to `+` but allows for lazy addition when passing functions.
"""
add(x) = Base.Fix2(+, x)
const Mul{X} = Base.Fix2{typeof(*), X}
const Add{X} = Base.Fix2{typeof(+), X}
Base.:∘(::Add{StaticInt{X}}, ::Add{StaticInt{Y}}) where {X, Y} = Base.Fix2(+, static(X + Y))
Base.:∘(x::Mul{Int}, ::Add{StaticInt{0}}) = x
Base.:∘(x::Mul{StaticInt{X}}, ::Add{StaticInt{0}}) where {X} = x
Base.:∘(x::Mul{StaticInt{0}}, ::Add{StaticInt{0}}) = x
Base.:∘(x::Mul{StaticInt{1}}, ::Add{StaticInt{0}}) = x
Base.:∘(x::Mul{StaticInt{0}}, y::Add{StaticInt{Y}}) where {Y} = x
Base.:∘(::Mul{StaticInt{1}}, y::Add{StaticInt{Y}}) where {Y} = y
Base.:∘(x::Mul{StaticInt{0}}, y::Add{Int}) = x
Base.:∘(::Mul{StaticInt{1}}, y::Add{Int}) = y
Base.:∘(::Mul{StaticInt{X}}, ::Mul{StaticInt{Y}}) where {X, Y} = Base.Fix2(*, static(X * Y))
Base.:∘(x::Mul{StaticInt{0}}, y::Mul{Int}) = x
Base.:∘(::Mul{Int}, y::Mul{StaticInt{0}}) = y
Base.:∘(::Mul{StaticInt{1}}, y::Mul{Int}) = y
Base.:∘(x::Mul{Int}, ::Mul{StaticInt{1}}) = x
# length
Base.length(@nospecialize(x::NDIndex))::Int = length(Tuple(x))
Base.length(::Type{<:NDIndex{N}}) where {N} = N
# indexing
Base.@propagate_inbounds function Base.getindex(x::NDIndex{N, T}, i::Int)::Int where {N, T}
return Int(getfield(Tuple(x), i))
end
Base.@propagate_inbounds function Base.getindex(x::NDIndex{N, T},
i::StaticInt{I}) where {N, T, I}
return getfield(Tuple(x), I)
end
# Base.get(A::AbstractArray, I::CartesianIndex, default) = get(A, I.I, default)
# eltype(::Type{T}) where {T<:CartesianIndex} = eltype(fieldtype(T, :I))
Base.setindex(x::NDIndex, i, j) = NDIndex(Base.setindex(Tuple(x), i, j))
# equality
Base.:(==)(@nospecialize(x::NDIndex), @nospecialize(y::NDIndex)) = ==(Tuple(x), Tuple(y))
# zeros and ones
Base.zero(@nospecialize(x::NDIndex)) = zero(typeof(x))
function Base.zero(@nospecialize(T::Type{<:NDIndex}))
NDIndex(ntuple(_ -> static(0), Val(length(T))))
end
Base.oneunit(@nospecialize(x::NDIndex)) = oneunit(typeof(x))
function Base.oneunit(@nospecialize(T::Type{<:NDIndex}))
NDIndex(ntuple(_ -> static(1), Val(length(T))))
end
@inline function Base.IteratorsMD.split(i::NDIndex, V::Val)
i, j = Base.IteratorsMD.split(Tuple(i), V)
return NDIndex(i), NDIndex(j)
end
# arithmetic, min/max
@inline Base.:(-)(@nospecialize(i::NDIndex)) = NDIndex(map(-, Tuple(i)))
@inline function Base.:(+)(@nospecialize(i1::NDIndex), @nospecialize(i2::NDIndex))
NDIndex(map(+, Tuple(i1), Tuple(i2)))
end
@inline function Base.:(-)(@nospecialize(i1::NDIndex), @nospecialize(i2::NDIndex))
NDIndex(map(-, Tuple(i1), Tuple(i2)))
end
@inline function Base.min(@nospecialize(i1::NDIndex), @nospecialize(i2::NDIndex))
NDIndex(map(min, Tuple(i1), Tuple(i2)))
end
@inline function Base.max(@nospecialize(i1::NDIndex), @nospecialize(i2::NDIndex))
NDIndex(map(max, Tuple(i1), Tuple(i2)))
end
@inline function Base.:(*)(a::Integer, @nospecialize(i::NDIndex))
NDIndex(map(x -> a * x, Tuple(i)))
end
@inline Base.:(*)(@nospecialize(i::NDIndex), a::Integer) = *(a, i)
Base.CartesianIndex(@nospecialize(x::NDIndex)) = dynamic(x)
# comparison
@inline function Base.isless(@nospecialize(x::NDIndex), @nospecialize(y::NDIndex))
Bool(_isless(static(0), Tuple(x), Tuple(y)))
end
function lt(@nospecialize(x::NDIndex), @nospecialize(y::NDIndex))
_isless(static(0), Tuple(x), Tuple(y))
end
_final_isless(c::Int) = c === 1
_final_isless(::StaticInt{N}) where {N} = static(false)
_final_isless(::StaticInt{1}) = static(true)
_isless(c::C, x::Tuple{}, y::Tuple{}) where {C} = _final_isless(c)
function _isless(c::C, x::Tuple, y::Tuple) where {C}
_isless(icmp(c, x, y), Base.front(x), Base.front(y))
end
icmp(::StaticInt{0}, x::Tuple, y::Tuple) = icmp(last(x), last(y))
icmp(::StaticInt{N}, x::Tuple, y::Tuple) where {N} = static(N)
function icmp(cmp::Int, x::Tuple, y::Tuple)
if cmp === 0
return icmp(Int(last(x)), Int(last(y)))
else
return cmp
end
end
icmp(a, b) = _icmp(lt(a, b), a, b)
_icmp(x::StaticBool, a, b) = ifelse(x, static(1), __icmp(eq(a, b)))
_icmp(x::Bool, a, b) = ifelse(x, 1, __icmp(a == b))
__icmp(x::StaticBool) = ifelse(x, static(0), static(-1))
__icmp(x::Bool) = ifelse(x, 0, -1)
# Necessary for compatibility with Base
# In simple cases, we know that we don't need to use axes(A). Optimize those
# until Julia gets smart enough to elide the call on its own:
@inline function Base.to_indices(A, inds, I::Tuple{NDIndex, Vararg{Any}})
to_indices(A, inds, (Tuple(I[1])..., Base.tail(I)...))
end
# But for arrays of CartesianIndex, we just skip the appropriate number of inds
@inline function Base.to_indices(A, inds,
I::Tuple{AbstractArray{NDIndex{N, J}}, Vararg{Any}}) where {
N,
J
}
_, indstail = Base.IteratorsMD.split(inds, Val(N))
return (Base.to_index(A, I[1]), to_indices(A, indstail, Base.tail(I))...)
end
function Base.show(io::IO, @nospecialize(x::Union{StaticNumber, StaticSymbol, NDIndex}))
show(io, MIME"text/plain"(), x)
end
function Base.show(io::IO, ::MIME"text/plain",
@nospecialize(x::Union{StaticNumber, StaticSymbol}))
print(io, "static(" * repr(known(typeof(x))) * ")")
nothing
end
function Base.show(io::IO, m::MIME"text/plain", @nospecialize(x::NDIndex))
print(io, "NDIndex")
show(io, m, Tuple(x))
nothing
end
include("ranges.jl")
end
| Static | https://github.com/SciML/Static.jl.git |
|
[
"MIT"
] | 1.1.1 | 87d51a3ee9a4b0d2fe054bdd3fc2436258db2603 | code | 5623 |
"""
StaticFloat64{N}
A statically sized `Float64`.
Use `StaticInt(N)` instead of `Val(N)` when you want it to behave like a number.
"""
struct StaticFloat64{N} <: Real
StaticFloat64{N}() where {N} = new{N::Float64}()
StaticFloat64(x::Float64) = new{x}()
StaticFloat64(x::Int) = new{Base.sitofp(Float64, x)::Float64}()
StaticFloat64(x::StaticInt{N}) where {N} = StaticFloat64(convert(Float64, N))
StaticFloat64(x::Complex) = StaticFloat64(convert(Float64, x))
StaticFloat64(@nospecialize x::StaticFloat64) = x
end
Base.zero(@nospecialize T::Type{<:StaticFloat64}) = Float64(0.0)
Base.one(@nospecialize T::Type{<:StaticFloat64}) = Float64(1.0)
Base.round(::StaticFloat64{M}) where {M} = StaticFloat64(round(M))
roundtostaticint(::StaticFloat64{M}) where {M} = StaticInt(round(Int, M))
roundtostaticint(x::AbstractFloat) = round(Int, x)
floortostaticint(::StaticFloat64{M}) where {M} = StaticInt(Base.fptosi(Int, M))
floortostaticint(x::AbstractFloat) = Base.fptosi(Int, x)
Base.rad2deg(::StaticFloat64{M}) where {M} = StaticFloat64(rad2deg(M))
Base.deg2rad(::StaticFloat64{M}) where {M} = StaticFloat64(deg2rad(M))
@generated Base.cbrt(::StaticFloat64{M}) where {M} = StaticFloat64(cbrt(M))
Base.mod2pi(::StaticFloat64{M}) where {M} = StaticFloat64(mod2pi(M))
@generated Base.sinpi(::StaticFloat64{M}) where {M} = StaticFloat64(sinpi(M))
@generated Base.cospi(::StaticFloat64{M}) where {M} = StaticFloat64(cospi(M))
Base.exp(::StaticFloat64{M}) where {M} = StaticFloat64(exp(M))
Base.exp2(::StaticFloat64{M}) where {M} = StaticFloat64(exp2(M))
Base.exp10(::StaticFloat64{M}) where {M} = StaticFloat64(exp10(M))
@generated Base.expm1(::StaticFloat64{M}) where {M} = StaticFloat64(expm1(M))
@generated Base.log(::StaticFloat64{M}) where {M} = StaticFloat64(log(M))
@generated Base.log2(::StaticFloat64{M}) where {M} = StaticFloat64(log2(M))
@generated Base.log10(::StaticFloat64{M}) where {M} = StaticFloat64(log10(M))
@generated Base.log1p(::StaticFloat64{M}) where {M} = StaticFloat64(log1p(M))
@generated Base.sin(::StaticFloat64{M}) where {M} = StaticFloat64(sin(M))
@generated Base.cos(::StaticFloat64{M}) where {M} = StaticFloat64(cos(M))
@generated Base.tan(::StaticFloat64{M}) where {M} = StaticFloat64(tan(M))
Base.sec(x::StaticFloat64{M}) where {M} = inv(cos(x))
Base.csc(x::StaticFloat64{M}) where {M} = inv(sin(x))
Base.cot(x::StaticFloat64{M}) where {M} = inv(tan(x))
@generated Base.asin(::StaticFloat64{M}) where {M} = StaticFloat64(asin(M))
@generated Base.acos(::StaticFloat64{M}) where {M} = StaticFloat64(acos(M))
@generated Base.atan(::StaticFloat64{M}) where {M} = StaticFloat64(atan(M))
@generated Base.sind(::StaticFloat64{M}) where {M} = StaticFloat64(sind(M))
@generated Base.cosd(::StaticFloat64{M}) where {M} = StaticFloat64(cosd(M))
Base.tand(x::StaticFloat64{M}) where {M} = sind(x) / cosd(x)
Base.secd(x::StaticFloat64{M}) where {M} = inv(cosd(x))
Base.cscd(x::StaticFloat64{M}) where {M} = inv(sind(x))
Base.cotd(x::StaticFloat64{M}) where {M} = inv(tand(x))
Base.asind(x::StaticFloat64{M}) where {M} = rad2deg(asin(x))
Base.acosd(x::StaticFloat64{M}) where {M} = rad2deg(acos(x))
Base.asecd(x::StaticFloat64{M}) where {M} = rad2deg(asec(x))
Base.acscd(x::StaticFloat64{M}) where {M} = rad2deg(acsc(x))
Base.acotd(x::StaticFloat64{M}) where {M} = rad2deg(acot(x))
Base.atand(x::StaticFloat64{M}) where {M} = rad2deg(atan(x))
@generated Base.sinh(::StaticFloat64{M}) where {M} = StaticFloat64(sinh(M))
Base.cosh(::StaticFloat64{M}) where {M} = StaticFloat64(cosh(M))
Base.tanh(x::StaticFloat64{M}) where {M} = StaticFloat64(tanh(M))
Base.sech(x::StaticFloat64{M}) where {M} = inv(cosh(x))
Base.csch(x::StaticFloat64{M}) where {M} = inv(sinh(x))
Base.coth(x::StaticFloat64{M}) where {M} = inv(tanh(x))
@generated Base.asinh(::StaticFloat64{M}) where {M} = StaticFloat64(asinh(M))
@generated Base.acosh(::StaticFloat64{M}) where {M} = StaticFloat64(acosh(M))
@generated Base.atanh(::StaticFloat64{M}) where {M} = StaticFloat64(atanh(M))
Base.asech(x::StaticFloat64{M}) where {M} = acosh(inv(x))
Base.acsch(x::StaticFloat64{M}) where {M} = asinh(inv(x))
Base.acoth(x::StaticFloat64{M}) where {M} = atanh(inv(x))
Base.asec(x::StaticFloat64{M}) where {M} = acos(inv(x))
Base.acsc(x::StaticFloat64{M}) where {M} = asin(inv(x))
Base.acot(x::StaticFloat64{M}) where {M} = atan(inv(x))
Base.rem(x::Real, ::StaticFloat64{Y}) where {Y} = rem(x, Y)
Base.rem(::StaticFloat64{X}, y::Real) where {X} = rem(X, y)
Base.rem(::StaticFloat64{X}, ::StaticFloat64{Y}) where {X, Y} = StaticFloat64(rem(X, Y))
Base.min(x::StaticFloat64{X}, y::StaticFloat64{Y}) where {X, Y} = X > Y ? y : x
Base.min(x::Real, ::StaticFloat64{Y}) where {Y} = min(x, Y)
Base.min(::StaticFloat64{X}, y::Real) where {X} = min(X, y)
Base.max(x::StaticFloat64{X}, y::StaticFloat64{Y}) where {X, Y} = X > Y ? x : y
Base.max(x::Real, ::StaticFloat64{Y}) where {Y} = max(x, Y)
Base.max(::StaticFloat64{X}, y::Real) where {X} = max(X, y)
Base.isless(::StaticFloat64{X}, ::StaticFloat64{Y}) where {X, Y} = isless(X, Y)
Base.isless(x::AbstractFloat, ::StaticFloat64{Y}) where {Y} = isless(x, Y)
Base.isless(::StaticFloat64{X}, y::AbstractFloat) where {X} = isless(X, y)
Base.inv(::StaticFloat64{N}) where {N} = StaticFloat64(1.0 / N)
Base.:(*)(::StaticFloat64{X}, ::StaticFloat64{Y}) where {X, Y} = static(X * Y)
Base.:(/)(::StaticFloat64{X}, ::StaticFloat64{Y}) where {X, Y} = static(X / Y)
Base.:(-)(::StaticFloat64{X}, ::StaticFloat64{Y}) where {X, Y} = static(X - Y)
Base.:(+)(::StaticFloat64{X}, ::StaticFloat64{Y}) where {X, Y} = static(X + Y)
Base.isinteger(x::StaticFloat64{X}) where {X} = isinteger(X)
| Static | https://github.com/SciML/Static.jl.git |
|
[
"MIT"
] | 1.1.1 | 87d51a3ee9a4b0d2fe054bdd3fc2436258db2603 | code | 14880 |
"""
OptionallyStaticUnitRange(start, stop) <: AbstractUnitRange{Int}
Similar to `UnitRange` except each field may be an `Int` or `StaticInt`. An
`OptionallyStaticUnitRange` is intended to be constructed internally from other valid
indices. Therefore, users should not expect the same checks are used to ensure construction
of a valid `OptionallyStaticUnitRange` as a `UnitRange`.
"""
struct OptionallyStaticUnitRange{F <: IntType, L <: IntType} <:
AbstractUnitRange{Int}
start::F
stop::L
function OptionallyStaticUnitRange(start::IntType,
stop::IntType)
new{typeof(start), typeof(stop)}(start, stop)
end
function OptionallyStaticUnitRange(start, stop)
OptionallyStaticUnitRange(IntType(start), IntType(stop))
end
OptionallyStaticUnitRange(@nospecialize x::OptionallyStaticUnitRange) = x
function OptionallyStaticUnitRange(x::AbstractRange)
step(x) == 1 && return OptionallyStaticUnitRange(static_first(x), static_last(x))
errmsg(x) = throw(ArgumentError("step must be 1, got $(step(x))")) # avoid GC frame
errmsg(x)
end
function OptionallyStaticUnitRange{F, L}(x::AbstractRange) where {F, L}
OptionallyStaticUnitRange(x)
end
function OptionallyStaticUnitRange{StaticInt{F}, StaticInt{L}}() where {F, L}
new{StaticInt{F}, StaticInt{L}}()
end
end
"""
OptionallyStaticStepRange(start, step, stop) <: OrdinalRange{Int,Int}
Similarly to [`OptionallyStaticUnitRange`](@ref), `OptionallyStaticStepRange` permits
a combination of static and standard primitive `Int`s to construct a range. It
specifically enables the use of ranges without a step size of 1. It may be constructed
through the use of `OptionallyStaticStepRange` directly or using static integers with
the range operator (i.e., `:`).
```julia
julia> using Static
julia> x = static(2);
julia> x:x:10
static(2):static(2):10
julia> Static.OptionallyStaticStepRange(x, x, 10)
static(2):static(2):10
```
"""
struct OptionallyStaticStepRange{F <: IntType, S <: IntType,
L <: IntType} <: OrdinalRange{Int, Int}
start::F
step::S
stop::L
global function _OptionallyStaticStepRange(@nospecialize(start::IntType),
@nospecialize(step::IntType),
@nospecialize(stop::IntType))
new{typeof(start), typeof(step), typeof(stop)}(start, step, stop)
end
end
@noinline function OptionallyStaticStepRange(@nospecialize(start::IntType),
::StaticInt{0},
@nospecialize(stop::IntType))
throw(ArgumentError("step cannot be zero"))
end
# we don't need to check the `stop` if we know it acts like a unit range
function OptionallyStaticStepRange(@nospecialize(start::IntType),
step::StaticInt{1},
@nospecialize(stop::IntType))
_OptionallyStaticStepRange(start, step, stop)
end
function OptionallyStaticStepRange(@nospecialize(start::IntType),
@nospecialize(step::StaticInt),
@nospecialize(stop::IntType))
_OptionallyStaticStepRange(start, step, _steprange_last(start, step, stop))
end
function OptionallyStaticStepRange(start, step, stop)
OptionallyStaticStepRange(IntType(start), IntType(step), IntType(stop))
end
function OptionallyStaticStepRange(@nospecialize(start::IntType),
step::Int,
@nospecialize(stop::IntType))
if step === 0
throw(ArgumentError("step cannot be zero"))
else
_OptionallyStaticStepRange(start, step, _steprange_last(start, step, stop))
end
end
OptionallyStaticStepRange(@nospecialize x::OptionallyStaticStepRange) = x
function OptionallyStaticStepRange(x::AbstractRange)
_OptionallyStaticStepRange(IntType(static_first(x)), IntType(static_step(x)),
IntType(static_last(x)))
end
# to make StepRange constructor inlineable, so optimizer can see `step` value
@inline function _steprange_last(start::StaticInt, step::StaticInt, stop::StaticInt)
StaticInt(_steprange_last(Int(start), Int(step), Int(stop)))
end
@inline function _steprange_last(start::Union{StaticInt, Int},
step::Union{StaticInt, Int},
stop::Union{StaticInt, Int})
_steprange_last(Int(start), Int(step), Int(stop))
end
@inline function _steprange_last(start::Int, step::Int, stop::Int)
if stop === start
return stop
elseif step > 0
if stop > start
return stop - rem(stop - start, step)
else
return start - 1
end
else
if stop > start
return start + 1
else
return stop + rem(start - stop, -step)
end
end
end
"""
SUnitRange(start::Int, stop::Int)
An alias for `OptionallyStaticUnitRange` where both the start and stop are known statically.
"""
const SUnitRange{F, L} = OptionallyStaticUnitRange{StaticInt{F}, StaticInt{L}}
SUnitRange(start::Int, stop::Int) = SUnitRange{start, stop}()
"""
SOneTo(n::Int)
An alias for `OptionallyStaticUnitRange` usfeul for statically sized axes.
"""
const SOneTo{L} = SUnitRange{1, L}
SOneTo(n::Int) = SOneTo{n}()
Base.oneto(::StaticInt{N}) where {N} = SOneTo{N}()
const OptionallyStaticRange{F, L} = Union{OptionallyStaticUnitRange{F, L},
OptionallyStaticStepRange{F, <:Any, L}}
# these probide a generic method for extracting potentially static values.
static_first(x::Base.OneTo) = StaticInt(1)
static_first(x::Union{Base.Slice, Base.IdentityUnitRange}) = static_first(x.indices)
static_first(x::OptionallyStaticRange) = getfield(x, :start)
static_first(x) = first(x)
static_step(@nospecialize x::AbstractUnitRange) = StaticInt(1)
static_step(x::OptionallyStaticStepRange) = getfield(x, :step)
static_step(x) = step(x)
static_last(x::OptionallyStaticRange) = getfield(x, :stop)
static_last(x) = last(x)
static_last(x::Union{Base.Slice, Base.IdentityUnitRange}) = static_last(x.indices)
Base.first(x::OptionallyStaticRange{Int}) = getfield(x, :start)
Base.first(::OptionallyStaticRange{StaticInt{F}}) where {F} = F
Base.step(x::OptionallyStaticStepRange{<:Any, Int}) = getfield(x, :step)
Base.step(::OptionallyStaticStepRange{<:Any, StaticInt{S}}) where {S} = S
Base.last(x::OptionallyStaticRange{<:Any, Int}) = getfield(x, :stop)
Base.last(::OptionallyStaticRange{<:Any, StaticInt{L}}) where {L} = L
# FIXME this line causes invalidations
Base.:(:)(L::Integer, ::StaticInt{U}) where {U} = OptionallyStaticUnitRange(L, StaticInt(U))
Base.:(:)(::StaticInt{L}, U::Integer) where {L} = OptionallyStaticUnitRange(StaticInt(L), U)
function Base.:(:)(::StaticInt{L}, ::StaticInt{U}) where {L, U}
OptionallyStaticUnitRange(StaticInt(L), StaticInt(U))
end
function Base.:(:)(::StaticInt{F}, ::StaticInt{S}, ::StaticInt{L}) where {F, S, L}
OptionallyStaticStepRange(StaticInt(F), StaticInt(S), StaticInt(L))
end
function Base.:(:)(start::Integer, ::StaticInt{S}, ::StaticInt{L}) where {S, L}
OptionallyStaticStepRange(start, StaticInt(S), StaticInt(L))
end
function Base.:(:)(::StaticInt{F}, ::StaticInt{S}, stop::Integer) where {F, S}
OptionallyStaticStepRange(StaticInt(F), StaticInt(S), stop)
end
function Base.:(:)(::StaticInt{F}, step::Integer, ::StaticInt{L}) where {F, L}
OptionallyStaticStepRange(StaticInt(F), step, StaticInt(L))
end
function Base.:(:)(start::Integer, step::Integer, ::StaticInt{L}) where {L}
OptionallyStaticStepRange(start, step, StaticInt(L))
end
function Base.:(:)(start::Integer, ::StaticInt{S}, stop::Integer) where {S}
OptionallyStaticStepRange(start, StaticInt(S), stop)
end
function Base.:(:)(::StaticInt{F}, step::Integer, stop::Integer) where {F}
OptionallyStaticStepRange(StaticInt(F), step, stop)
end
Base.:(:)(start::StaticInt{F}, ::StaticInt{1}, stop::StaticInt{L}) where {F, L} = start:stop
Base.:(:)(start::Integer, ::StaticInt{1}, stop::StaticInt{L}) where {L} = start:stop
Base.:(:)(start::StaticInt{F}, ::StaticInt{1}, stop::Integer) where {F} = start:stop
function Base.:(:)(start::Integer, ::StaticInt{1}, stop::Integer)
OptionallyStaticUnitRange(start, stop)
end
Base.isempty(r::OptionallyStaticUnitRange) = first(r) > last(r)
@inline function Base.isempty(x::OptionallyStaticStepRange)
start = first(x)
stop = last(x)
if start === stop
return false
else
s = step(x)
s > 0 ? start > stop : start < stop
end
end
function Base.checkindex(::Type{Bool},
::SUnitRange{F1, L1},
::SUnitRange{F2, L2}) where {F1, L1, F2, L2}
(F1::Int <= F2::Int) && (L1::Int >= L2::Int)
end
function Base.getindex(r::OptionallyStaticUnitRange,
s::AbstractUnitRange{<:Integer})
@boundscheck checkbounds(r, s)
f = static_first(r)
fnew = f - one(f)
return (fnew + static_first(s)):(fnew + static_last(s))
end
function Base.getindex(x::OptionallyStaticUnitRange{StaticInt{1}}, i::Int)
@boundscheck checkbounds(x, i)
i
end
function Base.getindex(x::OptionallyStaticUnitRange, i::Int)
val = first(x) + (i - 1)
@boundscheck ((i < 1) || val > last(x)) && throw(BoundsError(x, i))
val::Int
end
## length
@inline function Base.length(x::OptionallyStaticUnitRange)
start = first(x)
stop = last(x)
start > stop ? 0 : stop - start + 1
end
Base.length(r::OptionallyStaticStepRange) = _range_length(first(r), step(r), last(r))
@inline function _range_length(start::Int, s::Int, stop::Int)
if s > 0
stop < start ? 0 : div(stop - start, s) + 1
else
stop > start ? 0 : div(start - stop, -s) + 1
end
end
Base.AbstractUnitRange{Int}(r::OptionallyStaticUnitRange) = r
function Base.AbstractUnitRange{T}(r::OptionallyStaticUnitRange) where {T}
start = static_first(r)
if isa(start, StaticInt{1}) && T <: Integer
return Base.OneTo{T}(T(static_last(r)))
else
return UnitRange{T}(T(static_first(r)), T(static_last(r)))
end
end
Base.isdone(x::OptionallyStaticRange, state::Int) = state === last(x)
function _next(x::OptionallyStaticRange)
new_state = first(x)
(new_state, new_state)
end
@inline function _next(@nospecialize(x::OptionallyStaticUnitRange), state::Int)
new_state = state + 1
(new_state, new_state)
end
@inline function _next(x::OptionallyStaticStepRange, state::Int)
new_state = state + step(x)
(new_state, new_state)
end
@inline Base.iterate(x::OptionallyStaticRange) = isempty(x) ? nothing : _next(x)
@inline function Base.iterate(x::OptionallyStaticRange, s::Int)
Base.isdone(x, s) ? nothing : _next(x, s)
end
Base.to_shape(x::OptionallyStaticRange) = length(x)
Base.to_shape(x::Base.Slice{T}) where {T <: OptionallyStaticRange} = length(x)
Base.axes(S::Base.Slice{<:OptionallyStaticUnitRange{StaticInt{1}}}) = (S.indices,)
Base.axes(S::Base.Slice{<:OptionallyStaticRange}) = (Base.IdentityUnitRange(S.indices),)
Base.axes(x::OptionallyStaticRange) = (Base.axes1(x),)
function Base.axes1(x::OptionallyStaticUnitRange)
OptionallyStaticUnitRange(StaticInt(1), length(x))
end
Base.axes1(x::OptionallyStaticUnitRange{StaticInt{1}}) = x
function Base.axes1(x::OptionallyStaticUnitRange{StaticInt{F}, StaticInt{L}}) where {F, L}
OptionallyStaticUnitRange(StaticInt(1), StaticInt(L - F + 1))
end
function Base.axes1(x::OptionallyStaticStepRange)
OptionallyStaticUnitRange(StaticInt(1), length(x))
end
function Base.axes1(x::OptionallyStaticStepRange{
StaticInt{F}, StaticInt{S}, StaticInt{L}}) where {
F,
S,
L
}
OptionallyStaticUnitRange(StaticInt(1), StaticInt(_range_length(F, S, L)))
end
Base.axes1(x::Base.Slice{<:OptionallyStaticUnitRange{One}}) = x.indices
Base.axes1(x::Base.Slice{<:OptionallyStaticRange}) = Base.IdentityUnitRange(x.indices)
Base.:(-)(r::OptionallyStaticRange) = (-static_first(r)):(-static_step(r)):(-static_last(r))
function Base.reverse(x::OptionallyStaticUnitRange)
_OptionallyStaticStepRange(getfield(x, :stop), StaticInt(-1), getfield(x, :start))
end
function Base.reverse(x::OptionallyStaticStepRange)
_OptionallyStaticStepRange(getfield(x, :stop), -getfield(x, :step), getfield(x, :start))
end
Base.show(io::IO, @nospecialize(x::OptionallyStaticRange)) = show(io, MIME"text/plain"(), x)
function Base.show(io::IO, ::MIME"text/plain", @nospecialize(r::OptionallyStaticUnitRange))
print(io, "$(getfield(r, :start)):$(getfield(r, :stop))")
end
function Base.show(io::IO, ::MIME"text/plain", @nospecialize(r::OptionallyStaticStepRange))
print(io, "$(getfield(r, :start)):$(getfield(r, :step)):$(getfield(r, :stop))")
end
# we overload properties because occasionally Base assumes that abstract range types have
# the same exact same set up as native types where `x.start === first(x)`
@inline function Base.getproperty(x::OptionallyStaticRange, s::Symbol)
if s === :start
return first(x)
elseif s === :step
return step(x)
elseif s === :stop
return last(x)
else
error("$x has no property $s")
end
end
function Base.Broadcast.axistype(r::OptionallyStaticUnitRange{StaticInt{1}}, _)
Base.OneTo(last(r))
end
function Base.Broadcast.axistype(_, r::OptionallyStaticUnitRange{StaticInt{1}})
Base.OneTo(last(r))
end
function Base.Broadcast.axistype(r::OptionallyStaticUnitRange{StaticInt{1}},
::OptionallyStaticUnitRange{StaticInt{1}})
Base.OneTo(last(r))
end
function Base.similar(::Type{<:Array{T}},
axes::Tuple{OptionallyStaticUnitRange{StaticInt{1}},
Vararg{
Union{Base.OneTo,
OptionallyStaticUnitRange{StaticInt{1}}}}}) where {
T
}
Array{T}(undef, map(last, axes))
end
function Base.similar(::Type{<:Array{T}},
axes::Tuple{Base.OneTo, OptionallyStaticUnitRange{StaticInt{1}},
Vararg{
Union{Base.OneTo,
OptionallyStaticUnitRange{StaticInt{1}}}}}) where {
T
}
Array{T}(undef, map(last, axes))
end
function Base.first(x::OptionallyStaticUnitRange, n::IntType)
n < 0 && throw(ArgumentError("Number of elements must be nonnegative"))
start = static_first(x)
OptionallyStaticUnitRange(start, min(start - one(start) + n, static_last(x)))
end
function Base.first(x::OptionallyStaticStepRange, n::IntType)
n < 0 && throw(ArgumentError("Number of elements must be nonnegative"))
start = static_first(x)
s = static_step(x)
stop = min(((n - one(n)) * s) + static_first(x), static_last(x))
OptionallyStaticStepRange(start, s, stop)
end
function Base.last(x::OptionallyStaticUnitRange, n::IntType)
n < 0 && throw(ArgumentError("Number of elements must be nonnegative"))
stop = static_last(x)
OptionallyStaticUnitRange(max(stop + one(stop) - n, static_first(x)), stop)
end
function Base.last(x::OptionallyStaticStepRange, n::IntType)
n < 0 && throw(ArgumentError("Number of elements must be nonnegative"))
start = static_first(x)
s = static_step(x)
stop = static_last(x)
OptionallyStaticStepRange(max(stop + one(stop) - (n * s), start), s, stop)
end
| Static | https://github.com/SciML/Static.jl.git |
|
[
"MIT"
] | 1.1.1 | 87d51a3ee9a4b0d2fe054bdd3fc2436258db2603 | code | 7894 |
@testset "Range Constructors" begin
@test @inferred(static(1):static(10)) == 1:10
@test @inferred(Static.SUnitRange{1, 10}()) == 1:10
@test @inferred(static(1):static(2):static(10)) == 1:2:10
@test @inferred(1:static(2):static(10)) == 1:2:10
@test @inferred(static(1):static(2):10) == 1:2:10
@test @inferred(static(1):2:static(10)) == 1:2:10
@test @inferred(1:2:static(10)) == 1:2:10
@test @inferred(1:static(2):10) == 1:2:10
@test @inferred(static(1):2:10) == 1:2:10
@test @inferred(static(1):UInt(10)) === static(1):10
@test @inferred(UInt(1):static(1):static(10)) === 1:static(10)
@test Static.SUnitRange(1, 10) == 1:10
@test @inferred(Static.OptionallyStaticUnitRange{Int, Int}(1:10)) == 1:10
@test @inferred(Static.OptionallyStaticUnitRange(1:10)) == 1:10 ==
@inferred(Static.OptionallyStaticUnitRange(Static.OptionallyStaticUnitRange(1:10)))
sr = Static.OptionallyStaticStepRange(static(1), static(1), static(1))
@test @inferred(Static.OptionallyStaticStepRange(sr)) == sr == 1:1:1
@test @inferred(Static.OptionallyStaticStepRange(static(1), 1, UInt(10))) ==
static(1):1:10 == Static.SOneTo(10)
@test @inferred(Static.OptionallyStaticStepRange(UInt(1), 1, static(10))) ==
static(1):1:10
@test @inferred(Static.OptionallyStaticStepRange(1:10)) == 1:1:10
@test_throws ArgumentError Static.OptionallyStaticUnitRange(1:2:10)
@test_throws ArgumentError Static.OptionallyStaticUnitRange{Int, Int}(1:2:10)
@test_throws ArgumentError Static.OptionallyStaticStepRange(1, 0, 10)
@test_throws ArgumentError Static.OptionallyStaticStepRange(1, StaticInt(0), 10)
@test @inferred(static(1):static(1):static(10)) ===
Static.OptionallyStaticUnitRange(static(1), static(10))
@test @inferred(static(1):static(1):10) ===
Static.OptionallyStaticUnitRange(static(1), 10)
@test @inferred(1:static(1):10) === Static.OptionallyStaticUnitRange(1, 10)
@test length(static(-1):static(-1):static(-10)) == 10 ==
lastindex(static(-1):static(-1):static(-10))
@test UnitRange(Static.OptionallyStaticUnitRange(static(1), static(10))) ===
UnitRange(1, 10)
@test UnitRange{Int}(Static.OptionallyStaticUnitRange(static(1), static(10))) ===
UnitRange(1, 10)
@test AbstractUnitRange{Int}(Static.OptionallyStaticUnitRange(
static(1), static(10))) isa
Static.OptionallyStaticUnitRange
@test AbstractUnitRange{UInt}(Static.OptionallyStaticUnitRange(
static(1), static(10))) isa
Base.OneTo
@test AbstractUnitRange{UInt}(Static.OptionallyStaticUnitRange(
static(2), static(10))) isa
UnitRange
@test @inferred((static(1):static(10))[static(2):static(3)]) === static(2):static(3)
@test @inferred((static(1):static(10))[static(2):3]) === static(2):3
@test @inferred((static(1):static(10))[2:3]) === 2:3
@test @inferred((1:static(10))[static(2):static(3)]) === 2:3
@test Base.checkindex(Bool, static(1):static(10), static(1):static(5))
@test -(static(1):static(10)) === static(-1):static(-1):static(-10)
@test reverse(static(1):static(10)) === static(10):static(-1):static(1)
@test reverse(static(1):static(2):static(9)) === static(9):static(-2):static(1)
end
@testset "range properties" begin
x = static(1):static(2):static(9)
@test getproperty(x, :start) === first(x)
@test getproperty(x, :step) === step(x)
@test getproperty(x, :stop) === last(x)
@test_throws ErrorException getproperty(x, :foo)
end
@testset "iterate" begin
@test iterate(static(1):static(5)) === (1, 1)
@test iterate(static(1):static(5), 1) === (2, 2)
@test iterate(static(1):static(5), 5) === nothing
@test iterate(static(2):static(5), 5) === nothing
@test iterate(static(1):static(2):static(9), 1) === (3, 3)
@test iterate(static(1):static(2):static(9), 9) === nothing
# make sure single length ranges work correctly
@test iterate(static(2):static(3):static(2))[1] === 2 ===
(static(2):static(3):static(2))[1]
@test iterate(static(2):static(3):static(2), 2) === nothing
end
# CartesianIndices
CI = CartesianIndices((static(1):static(2), static(1):static(2)))
@testset "length" begin
@test @inferred(length(Static.OptionallyStaticUnitRange(1, 0))) == 0
@test @inferred(length(Static.OptionallyStaticUnitRange(1, 10))) == 10
@test @inferred(length(Static.OptionallyStaticUnitRange(static(1), 10))) == 10
@test @inferred(length(Static.OptionallyStaticUnitRange(static(0), 10))) == 11
@test @inferred(length(Static.OptionallyStaticUnitRange(static(1), static(10)))) == 10
@test @inferred(length(Static.OptionallyStaticUnitRange(static(0), static(10)))) == 11
@test @inferred(length(static(1):static(2):static(0))) == 0
@test @inferred(length(static(0):static(-2):static(1))) == 0
@test @inferred(length(Static.OptionallyStaticStepRange(static(1), 2, 10))) == 5
@test @inferred(length(Static.OptionallyStaticStepRange(static(1), static(1),
static(10)))) == 10
@test @inferred(length(Static.OptionallyStaticStepRange(static(2), static(1),
static(10)))) == 9
@test @inferred(length(Static.OptionallyStaticStepRange(static(2), static(2),
static(10)))) == 5
end
@test @inferred(getindex(static(1):10, Base.Slice(static(1):10))) === static(1):10
@test @inferred(getindex(Static.OptionallyStaticUnitRange(static(1), 10), 1)) == 1
@test @inferred(getindex(Static.OptionallyStaticUnitRange(static(0), 10), 1)) == 0
@test_throws BoundsError getindex(Static.OptionallyStaticUnitRange(static(1), 10), 0)
@test_throws BoundsError getindex(Static.OptionallyStaticStepRange(static(1), 2, 10), 0)
@test_throws BoundsError getindex(Static.OptionallyStaticUnitRange(static(1), 10), 11)
@test_throws BoundsError getindex(Static.OptionallyStaticStepRange(static(1), 2, 10), 11)
@test Static.static_first(Base.OneTo(one(UInt))) === static(1)
@test Static.static_step(Base.OneTo(one(UInt))) === static(1)
@test @inferred(eachindex(static(-7):static(7))) === static(1):static(15)
@test @inferred((static(-7):static(7))[first(eachindex(static(-7):static(7)))]) == -7
@test @inferred(firstindex(128:static(-1):1)) == 1
@test identity.(static(1):5) isa Vector{Int}
@test (static(1):5) .+ (1:3)' isa Matrix{Int}
@test similar(Array{Int}, (static(1):(4),)) isa Vector{Int}
@test similar(Array{Int}, (static(1):(4), Base.OneTo(4))) isa Matrix{Int}
@test similar(Array{Int}, (Base.OneTo(4), static(1):(4))) isa Matrix{Int}
@test Base.to_shape(static(1):10) == 10
@test Base.to_shape(Base.Slice(static(1):10)) == 10
@test Base.axes1(Base.Slice(static(1):10)) === static(1):10
@test axes(Base.Slice(static(1):10)) === (static(1):10,)
@test isa(axes(Base.Slice(static(0):static(1):10))[1], Base.IdentityUnitRange)
@test isa(Base.axes1(Base.Slice(static(0):static(1):10)), Base.IdentityUnitRange)
@test Base.Broadcast.axistype(static(1):10, static(1):10) === Base.OneTo(10)
@test Base.Broadcast.axistype(Base.OneTo(10), static(1):10) === Base.OneTo(10)
@testset "static_promote(::AbstractRange, ::AbstractRange)" begin
ur1 = static(1):10
ur2 = 1:static(10)
@test @inferred(static_promote(ur1, ur2)) === static(1):static(10)
@test static_promote(Base.Slice(ur1), Base.Slice(ur2)) ===
Base.Slice(static(1):static(10))
sr1 = static(1):2:10
sr2 = static(1):static(2):static(10)
@test @inferred(static_promote(sr1, sr2)) === sr2
end
@testset "n-last/first" begin
ur = static(2):static(10)
sr = static(2):static(2):static(10)
n3 = static(3)
@test @inferred(first(ur, n3)) === static(2):static(4)
@test @inferred(last(ur, n3)) === static(8):static(10)
@test @inferred(first(sr, n3)) === static(2):static(2):static(6)
@test @inferred(last(sr, n3)) === static(5):static(2):static(9)
end
| Static | https://github.com/SciML/Static.jl.git |
|
[
"MIT"
] | 1.1.1 | 87d51a3ee9a4b0d2fe054bdd3fc2436258db2603 | code | 22356 | using Static, Aqua
using Static: Zero
using Test
@testset "Aqua" begin
Aqua.find_persistent_tasks_deps(Static)
Aqua.test_ambiguities(Static, recursive = false)
Aqua.test_deps_compat(Static)
Aqua.test_piracies(Static, broken = true)
Aqua.test_project_extras(Static)
Aqua.test_stale_deps(Static)
Aqua.test_unbound_args(Static)
Aqua.test_undefined_exports(Static)
end
@testset "StaticSymbol" begin
x = StaticSymbol(:x)
y = StaticSymbol("y")
z = StaticSymbol(1)
@test y === StaticSymbol(:y)
@test z === StaticSymbol(Symbol(1))
@test z == StaticSymbol(Symbol(1))
@test @inferred(StaticSymbol(x)) === x
@test @inferred(StaticSymbol(x, y)) === StaticSymbol(:x, :y)
@test @inferred(StaticSymbol(x, y, z)) === static(:xy1)
@test @inferred(static(nothing)) === nothing
nt = (x = :x, y = "y", z = 1)
@test @inferred(getindex(nt, x)) == :x
@test @inferred(getindex(nt, (x, y))) == (x = :x, y = "y")
@test_throws ErrorException static([])
end
@testset "StaticInt" begin
@test static(UInt(8)) === StaticInt(UInt(8)) === StaticInt{8}()
@test iszero(StaticInt(0))
@test !iszero(StaticInt(1))
@test !isone(StaticInt(0))
@test isone(StaticInt(1))
@test @inferred(one(StaticInt(1))) === StaticInt(1)
@test @inferred(zero(StaticInt(1))) === StaticInt(0)
@test @inferred(one(StaticInt)) === StaticInt(1)
@test @inferred(zero(StaticInt)) === StaticInt(0) === StaticInt(StaticInt(Val(0)))
@test eltype(one(StaticInt)) <: Int
@test @inferred(isodd(one(StaticInt)))
@test @inferred(iseven(zero(StaticInt)))
x = StaticInt(1)
y = static(3)
@test isinteger(y)
@test @inferred(minmax(x, y)) == @inferred(minmax(y, x)) == minmax(1, 3)
@test @inferred(Bool(x)) isa Bool
@test @inferred(BigInt(x)) isa BigInt
@test @inferred(Integer(x)) === x
@test @inferred(%(x, Integer)) === 1
# test for ambiguities and correctness
for i in Any[StaticInt(0), StaticInt(1), StaticInt(2), 3]
for j in Any[StaticInt(0), StaticInt(1), StaticInt(2), 3]
i === j === 3 && continue
for f in [+, -, *, ÷, %, <<, >>, >>>, &, |, ⊻, ==, ≤, ≥, min, max]
(iszero(j) && ((f === ÷) || (f === %))) && continue # integer division error
@test convert(Int, @inferred(f(i, j))) ==
f(convert(Int, i), convert(Int, j))
end
end
i == 3 && break
for f in [+, -, *, /, ÷, %, ==, ≤, ≥]
w = f(convert(Int, i), 1.4)
x = f(1.4, convert(Int, i))
@test convert(typeof(w), @inferred(f(i, 1.4))) === w
@test convert(typeof(x), @inferred(f(1.4, i))) === x # if f is division and i === StaticInt(0), returns `NaN`; hence use of ==== in check.
(((f === ÷) || (f === %)) && (i === StaticInt(0))) && continue
y = f(convert(Int, i), 2 // 7)
z = f(2 // 7, convert(Int, i))
@test convert(typeof(y), @inferred(f(i, 2 // 7))) === y
@test convert(typeof(z), @inferred(f(2 // 7, i))) === z
end
end
@test @inferred(*(Zero(), 3)) === @inferred(*(3, Zero())) === *(Zero(), Zero())
@test float(StaticInt(8)) === static(8.0)
@test @inferred(cld(40, static(4))) === cld(40, 4)
@test @inferred(fld(40, static(4))) === fld(40, 4)
@test @inferred(cld(static(40), static(4))) === static(cld(40, 4))
@test @inferred(fld(static(40), static(4))) === static(fld(40, 4))
# test specific promote rules to ensure we don't cause ambiguities
SI = StaticInt{1}
IR = typeof(1 // 1)
PI = typeof(pi)
@test @inferred(convert(SI, SI())) === SI()
@test @inferred(promote_type(SI, PI)) <: promote_type(Int, PI)
@test @inferred(promote_type(SI, IR)) <: promote_type(Int, IR)
@test @inferred(promote_rule(SI, SI)) <: Int
@test @inferred(promote_type(Base.TwicePrecision{Int}, StaticInt{1})) <:
Base.TwicePrecision{Int}
@test static(Int8(-18)) === static(-18)
@test static(0xef) === static(239)
@test static(Int16(-18)) === static(-18)
@test static(0xffef) === static(65519)
if sizeof(Int) == 8
@test static(Int32(-18)) === static(-18)
@test static(0xffffffef) === static(4294967279)
end
@test @inferred(getindex([1], static(1))) == 1
@test @inferred(Base.checkindex(Bool, 1:10, static(1)))
@test widen(static(1)) isa Int128
@test isless(static(1), static(2))
v = rand(3)
@test real(static(3)) === static(3)
@test imag(static(3)) === static(0)
@test mod(static(3), static(3)) === static(0)
@test mod(static(3), 3) == 0
@test mod(3, static(3)) == 0
@test mod(static(3), static(2)) === static(1)
@test mod(static(3), 2) == 1
@test mod(3, static(2)) == 1
end
@testset "StaticBool" begin
t = static(static(true))
f = StaticBool(static(false))
@test @inferred(dynamic(t)) === @inferred(known(t)) === true
@test StaticBool{true}() === t
@test StaticBool{false}() === f
@test @inferred(StaticInt(t)) === StaticInt(1)
@test @inferred(StaticInt(f)) === StaticInt(0)
@test isinteger(static(true))
@test @inferred(~t) === f
@test @inferred(~f) === t
@test @inferred(!t) === f
@test @inferred(!f) === t
@test @inferred(+t) === StaticInt(1)
@test @inferred(+f) === StaticInt(0)
@test @inferred(-t) === StaticInt(-1)
@test @inferred(-f) === StaticInt(0)
@test @inferred(sign(t)) === t
@test @inferred(abs(t)) === t
@test @inferred(abs2(t)) === t
@test @inferred(iszero(zero(True)))
@test @inferred(isone(one(True)))
@test !@inferred(iszero(t))
@test @inferred(isone(t))
@test @inferred(iszero(f))
@test !@inferred(isone(f))
@test @inferred(xor(true, f))
@test @inferred(xor(f, true))
@test @inferred(xor(f, f)) === f
@test @inferred(xor(f, t)) === t
@test @inferred(xor(t, f)) === t
@test @inferred(xor(t, t)) === f
@test @inferred(|(true, f))
@test @inferred(|(true, t)) === t
@test @inferred(|(f, true))
@test @inferred(|(t, true)) === t
@test @inferred(|(f, f)) === f
@test @inferred(|(f, t)) === t
@test @inferred(|(t, f)) === t
@test @inferred(|(t, t)) === t
@test @inferred(Base.:(&)(true, f)) === f
@test @inferred(Base.:(&)(true, t))
@test @inferred(Base.:(&)(f, true)) === f
@test @inferred(Base.:(&)(t, true))
@test @inferred(Base.:(&)(f, f)) === f
@test @inferred(Base.:(&)(f, t)) === f
@test @inferred(Base.:(&)(t, f)) === f
@test @inferred(Base.:(&)(t, t)) === t
@test @inferred(<(f, f)) === false
@test @inferred(<(f, t)) === true
@test @inferred(<(t, f)) === false
@test @inferred(<(t, t)) === false
@test @inferred(<=(f, f)) === true
@test @inferred(<=(f, t)) === true
@test @inferred(<=(t, f)) === false
@test @inferred(<=(t, t)) === true
@test @inferred(==(f, f)) === true
@test @inferred(==(f, t)) === false
@test @inferred(==(t, f)) === false
@test @inferred(==(t, t)) === true
@test @inferred(*(f, t)) === t & f
@test @inferred(-(f, t)) === StaticInt(f) - StaticInt(t)
@test @inferred(+(f, t)) === StaticInt(f) + StaticInt(t)
@test @inferred(^(t, f)) == ^(true, false)
@test @inferred(^(t, t)) == ^(true, true)
@test @inferred(^(2, f)) == 1
@test @inferred(^(2, t)) == 2
@test @inferred(^(BigInt(2), f)) == 1
@test @inferred(^(BigInt(2), t)) == 2
@test @inferred(div(t, t)) === t
@test_throws DivideError div(t, f)
@test @inferred(rem(t, t)) === f
@test_throws DivideError rem(t, f)
@test @inferred(mod(t, t)) === f
@test @inferred(all((t, t, t)))
@test !@inferred(all((t, f, t)))
@test !@inferred(all((f, f, f)))
@test @inferred(any((t, t, t)))
@test @inferred(any((t, f, t)))
@test !@inferred(any((f, f, f)))
@test static(true) == true
@test static(false) != true
@test static(true) != false
@test static(false) == false
@test !(static(true) != true)
@test !(static(false) == true)
@test !(static(true) == false)
@test !(static(false) != false)
@test true == static(true)
@test false != static(true)
@test true != static(false)
@test false == static(false)
@test !(true != static(true))
@test !(false == static(true))
@test !(true == static(false))
@test !(false != static(false))
end
@testset "operators" begin
f = static(false)
t = static(true)
x = StaticInt(1)
y = StaticInt(0)
z = StaticInt(-1)
@test @inferred(Static.eq(y)(x)) === f
@test @inferred(Static.eq(x, x)) === t
@test @inferred(Static.ne(y)(x)) === t
@test @inferred(Static.ne(x, x)) === f
@test @inferred(Static.gt(y)(x)) === t
@test @inferred(Static.gt(y, x)) === f
@test @inferred(Static.ge(y)(x)) === t
@test @inferred(Static.ge(y, x)) === f
@test @inferred(Static.lt(x)(y)) === t
@test @inferred(Static.lt(x, y)) === f
@test @inferred(Static.le(x)(y)) === t
@test @inferred(Static.le(x, y)) === f
@test @inferred(Static.ifelse(t, x, y)) === x
@test @inferred(Static.ifelse(f, x, y)) === y
sa1 = Static.add(x)
sa0 = Static.add(y)
saz = Static.add(z)
da = Static.add(dynamic(x))
sm1 = Static.mul(x)
sm0 = Static.mul(y)
smz = Static.mul(z)
dm = Static.mul(dynamic(x))
@test (sa1 ∘ sa1) === Static.add(static(2))
@test (sm1 ∘ sa0) === sm1
@test (sm0 ∘ sa0) === sm0
@test (smz ∘ sa0) === smz
@test (dm ∘ sa0) === dm
@test (sm1 ∘ saz) === saz
@test (sm0 ∘ saz) === sm0
@test (sm1 ∘ da) === da
@test (sm0 ∘ da) === sm0
@test (sm1 ∘ smz) === smz # 1 * -1
@test (sm0 ∘ dm) === sm0
@test (dm ∘ sm0) === sm0
@test (sm1 ∘ dm) === dm
@test (dm ∘ sm1) === dm
end
@testset "static interface" begin
v = Val((:a, 1, true))
@test static(1) === StaticInt(1)
@test static(true) === True()
@test static(:a) === StaticSymbol{:a}() === static("a") === static('a')
@test Symbol(static(:a)) === :a
@test static((:a, 1, true)) === (static(:a), static(1), static(true))
@test @inferred(static(v)) === (static(:a), static(1), static(true))
@test @inferred(Static.is_static(v)) === True()
@test @inferred(Static.is_static(typeof(v))) === True()
@test @inferred(Static.is_static(typeof(static(true)))) === True()
@test @inferred(Static.is_static(typeof(static(1)))) === True()
@test @inferred(Static.is_static(typeof(static(:x)))) === True()
@test @inferred(Static.is_static(typeof(1))) === False()
@test @inferred(Static.is_static(typeof((static(:x), static(:x))))) === True()
@test @inferred(Static.is_static(typeof((static(:x), :x)))) === False()
@test @inferred(Static.is_static(typeof(static(1.0)))) === True()
@test @inferred(Static.known(v)) === (:a, 1, true)
@test @inferred(Static.known(typeof(v))) === (:a, 1, true)
@test @inferred(Static.known(typeof(static(true))))
@test @inferred(Static.known(typeof(static(false)))) === false
@test @inferred(Static.known(typeof(static(1.0)))) === 1.0
@test @inferred(Static.known(typeof(static(1)))) === 1
@test @inferred(Static.known(typeof(static(:x)))) === :x
@test @inferred(Static.known(typeof(1))) === nothing
@test @inferred(Static.known(typeof((static(:x), static(:x))))) === (:x, :x)
@test @inferred(Static.known(typeof((static(:x), :x)))) === (:x, nothing)
@test @inferred(Static.dynamic((static(:a), static(1), true))) === (:a, 1, true)
end
@testset "promote_shape" begin
x = (static(1), 1)
y = (1, static(1), 1)
@test @inferred(Base.promote_shape(x, x)) === (static(1), 1)
@test @inferred(Base.promote_shape(x, y)) === (static(1), static(1), static(1))
@test @inferred(Base.promote_shape(y, x)) === (static(1), static(1), static(1))
@test static_promote(1, nothing) === 1
@test static_promote(nothing, 1) === 1
@test static_promote(nothing, nothing) === nothing
@test_throws ErrorException Base.promote_shape((static(1),), (static(2),))
end
@testset "tuple utilities" begin
x = (static(1), static(2), static(3))
y = (static(3), static(2), static(1))
z = (static(1), static(2), static(3), static(4))
T = Tuple{Int, Float64, String}
@test @inferred(Static.invariant_permutation(x, x)) === True()
@test @inferred(Static.invariant_permutation(x, y)) === False()
@test @inferred(Static.invariant_permutation(x, z)) === False()
@test @inferred(Static.permute(x, Val(x))) === x
@test @inferred(Static.permute(x, (static(1), static(2)))) === (static(1), static(2))
@test @inferred(Static.permute(x, x)) === x
@test @inferred(Static.permute(x, y)) === y
@test @inferred(Static.eachop(getindex, x)) === x
@test Static.field_type(typeof((x = 1, y = 2)), :x) <: Int
@test Static.field_type(typeof((x = 1, y = 2)), static(:x)) <: Int
function get_tuple_add(::Type{T}, ::Type{X}, dim::StaticInt) where {T, X}
Tuple{Static.field_type(T, dim), X}
end
@test @inferred(Static.eachop_tuple(Static.field_type, y, T)) ===
Tuple{String, Float64, Int}
@test @inferred(Static.eachop_tuple(get_tuple_add, y, T, String)) ===
Tuple{Tuple{String, String}, Tuple{Float64, String}, Tuple{Int, String}}
@test @inferred(Static.find_first_eq(static(1), y)) === static(3)
@test @inferred(Static.find_first_eq(static(2), (1, static(2)))) === static(2)
@test @inferred(Static.find_first_eq(static(2), (1, static(2), 3))) === static(2)
# inferred is Union{Int,Nothing}
@test Static.find_first_eq(1, map(Int, y)) === 3
@testset "reduce_tup" begin
for n in 2:16
x = ntuple(
_ -> rand(Bool) ? rand() : (rand(Bool) ? rand(0x00:0x1f) : rand(0:31)),
n)
@test @inferred(Static.reduce_tup(+, x)) ≈ reduce(+, x)
end
end
end
@testset "invperm" begin
perm = static((10, 3, 4, 5, 6, 2, 9, 7, 8, 1))
invp = static((10, 6, 2, 3, 4, 5, 8, 9, 7, 1))
@test @inferred(invperm(perm)) === invp
end
@testset "NDIndex" begin
x = NDIndex((1, 2, 3))
y = NDIndex((1, static(2), 3))
z = NDIndex(static(3), static(3), static(3))
@testset "constructors" begin
@test static(CartesianIndex(3, 3, 3)) === z ==
Base.setindex(Base.setindex(x, 3, 1), 3, 2)
@test @inferred(CartesianIndex(z)) === @inferred(Static.dynamic(z)) ===
CartesianIndex(3, 3, 3)
@test @inferred(Static.known(z)) === (3, 3, 3)
@test Tuple(@inferred(NDIndex{0}())) === ()
@test @inferred(NDIndex{3}(1, static(2), 3)) === y
@test @inferred(NDIndex{3}((1, static(2), 3))) === y
@test @inferred(NDIndex{3}((1, static(2)))) === NDIndex(1, static(2), static(1))
@test @inferred(NDIndex(x, y)) === NDIndex(1, 2, 3, 1, static(2), 3)
end
@test @inferred(Base.IteratorsMD.split(x, Val(2))) === (NDIndex(1, 2), NDIndex(3))
@test @inferred(length(x)) === 3
@test @inferred(length(typeof(x))) === 3
NDIndex2{I <: Tuple{Vararg{Union{StaticInt, Int}, 2}}} = NDIndex{2, I}
@test length(NDIndex2) === 2
@test @inferred(y[2]) === 2
@test @inferred(y[static(2)]) === static(2)
@test @inferred(-y) === NDIndex((-1, -static(2), -3))
@test @inferred(y+y) === NDIndex((2, static(4), 6))
@test @inferred(y-y) === NDIndex((0, static(0), 0))
@test @inferred(zero(x)) === NDIndex(static(0), static(0), static(0))
@test @inferred(oneunit(x)) === NDIndex(static(1), static(1), static(1))
@test @inferred(x*3) === NDIndex((3, 6, 9))
@test @inferred(3*x) === NDIndex((3, 6, 9))
@test @inferred(min(x, z)) === x
@test @inferred(max(x, z)) === NDIndex(3, 3, 3)
@test !@inferred(isless(y, x))
@test @inferred(isless(x, z))
@test @inferred(Static.lt(oneunit(z), z)) === static(true)
A = rand(3, 3, 3)
@test @inferred(to_indices(A, axes(A), (x,))) === (1, 2, 3)
@test @inferred(to_indices(A, axes(A), ([y, y],))) == ([y, y],)
# issue #44
@test deleteat!(Union{}[], Union{}[]) == Union{}[]
end
# for some reason this can't be inferred when in the "Static.jl" test set
known_length(x) = known_length(typeof(x))
known_length(::Type{T}) where {N, T <: Tuple{Vararg{Any, N}}} = N
known_length(::Type{T}) where {T} = nothing
maybe_static_length(x) = Static.maybe_static(known_length, length, x)
x = ntuple(+, 10)
y = 1:10
@test @inferred(maybe_static_length(x)) === StaticInt(10)
@test @inferred(maybe_static_length(y)) === 10
@testset "StaticFloat64" begin
f = static(1.0)
@test @inferred(dynamic(f)) === @inferred(known(f)) === 1.0
for i in -10:10
for j in -10:10
@test i + j == @inferred(Static.StaticInt(i)+Static.StaticFloat64(j)) ==
@inferred(i+Static.StaticFloat64(Static.StaticFloat64(j))) ==
@inferred(Static.StaticFloat64(i)+j) ==
@inferred(Static.StaticFloat64(i)+Static.StaticInt(j)) ==
@inferred(Static.StaticFloat64(i)+Static.StaticFloat64(j))
@test i - j == @inferred(Static.StaticInt(i)-Static.StaticFloat64(j)) ==
@inferred(i-Static.StaticFloat64(j)) ==
@inferred(Static.StaticFloat64(i)-Static.StaticInt(j)) ==
@inferred(Static.StaticFloat64(i)-j) ==
@inferred(Static.StaticFloat64(i)-Static.StaticFloat64(j))
@test i * j == @inferred(Static.StaticInt(i)*Static.StaticFloat64(j)) ==
@inferred(i*Static.StaticFloat64(j)) ==
@inferred(Static.StaticFloat64(i)*Static.StaticInt(j)) ==
@inferred(Static.StaticFloat64(i)*j) ==
@inferred(Static.StaticFloat64(i)*Static.StaticFloat64(j))
i == j == 0 && continue
@test i / j == @inferred(Static.StaticInt(i)/Static.StaticFloat64(j)) ==
@inferred(i/Static.StaticFloat64(j)) ==
@inferred(Static.StaticFloat64(i)/Static.StaticInt(j)) ==
@inferred(Static.StaticFloat64(i)/j) ==
@inferred(Static.StaticFloat64(i)/Static.StaticFloat64(j))
end
if i ≥ 0
@test sqrt(i) == @inferred(sqrt(Static.StaticInt(i))) ==
@inferred(sqrt(Static.StaticFloat64(i))) ==
@inferred(sqrt(Static.StaticFloat64(Float64(i))))
end
end
@test Static.floortostaticint(1.0) === 1
@test Static.floortostaticint(prevfloat(2.0)) === 1
@test @inferred(Static.floortostaticint(Static.StaticFloat64(1.0))) ===
Static.StaticInt(1)
@test @inferred(Static.floortostaticint(Static.StaticFloat64(prevfloat(2.0)))) ===
Static.StaticInt(1)
@test Static.roundtostaticint(1.0) === 1
@test Static.roundtostaticint(prevfloat(2.0)) === 2
@test @inferred(Static.roundtostaticint(Static.StaticFloat64(1.0))) ===
Static.StaticInt(1)
@test @inferred(Static.roundtostaticint(Static.StaticFloat64(prevfloat(2.0)))) ===
Static.StaticInt(2)
@test @inferred(round(Static.StaticFloat64{1.0}())) === Static.StaticFloat64(1)
@test @inferred(round(Static.StaticFloat64(prevfloat(2.0)))) ===
Static.StaticFloat64(ComplexF64(2))
x = static(5.0)
y = static(10.0)
@test @inferred(rem(x, y)) === x
@test @inferred(rem(x, 10.0)) === 5.0
@test @inferred(rem(5.0, y)) === 5.0
@test @inferred(min(x, y)) === x
@test @inferred(min(x, 10.0)) === 5.0
@test @inferred(min(5.0, y)) === 5.0
@test @inferred(max(x, y)) === y
@test @inferred(max(x, 10.0)) === 10.0
@test @inferred(max(5.0, y)) === 10.0
@test @inferred(isless(x, y))
@test @inferred(isless(x, 10.0))
@test @inferred(isless(5.0, y))
fone = static(1.0)
fzero = static(0.0)
@test @inferred(isone(fone))
@test @inferred(isone(one(fzero)))
@test @inferred(isone(fzero)) === false
@test @inferred(iszero(fone)) === false
@test @inferred(iszero(fzero))
@test @inferred(iszero(zero(typeof(fzero))))
@test typeof(fone)(1) isa Static.StaticFloat64
@test typeof(fone)(1.0) isa Static.StaticFloat64
@test @inferred(eltype(Static.StaticFloat64(static(1)))) <: Float64
@test @inferred(promote_rule(typeof(fone), Int)) <: promote_type(Float64, Int)
@test @inferred(promote_rule(typeof(fone), Float64)) <: Float64
@test @inferred(promote_rule(typeof(fone), Float32)) <: Float32
@test @inferred(promote_rule(typeof(fone), Float16)) <: Float16
@test @inferred(inv(static(2.0))) === static(inv(2.0)) === inv(static(2))
@test @inferred(static(2.0)^2.0) === 2.0^2.0
@testset "trig" begin
for f in [sin, cos, tan, asin, atan, acos, sinh, cosh, tanh,
asinh, atanh, exp, exp2,
exp10, expm1, log, log2, log10, log1p, exponent, sqrt, cbrt, sec, csc, cot, sech,
secd, csch, cscd, cotd, cosd, tand, asind, acosd, atand, acotd, sech, coth, asech,
acsch, deg2rad, mod2pi, sinpi, cospi]
@info "Testing $f(0.5)"
@test @inferred(f(static(0.5))) === static(f(0.5))
end
end
@test @inferred(asec(static(2.0))) === static(asec(2.0))
@test @inferred(acsc(static(2.0))) === static(acsc(2.0))
@test @inferred(acot(static(2.0))) === static(acot(2.0))
@test @inferred(asecd(static(2.0))) === static(asecd(2.0))
@test @inferred(acscd(static(2.0))) === static(acscd(2.0))
@test @inferred(acoth(static(2.0))) === static(acoth(2.0))
@info "Testing acosh(1.5)"
@inferred acosh(static(1.5))
@test @inferred(isinteger(static(1.0)))
@test @inferred(!isinteger(static(1.5)))
end
@testset "string/print/show" begin
f = static(float(2))
repr(f)
@test repr(static(float(1))) == "static($(float(1)))"
@test repr(static(1)) == "static(1)"
@test repr(static(:x)) == "static(:x)"
@test repr(static(true)) == "static(true)"
@test repr(static(CartesianIndex(1, 1))) == "NDIndex(static(1), static(1))"
@test string(static(true)) == "static(true)" == "$(static(true))"
@test repr(static(1):static(10)) == "static(1):static(10)"
@test repr(static(1):static(2):static(9)) == "static(1):static(2):static(9)"
end
include("ranges.jl")
| Static | https://github.com/SciML/Static.jl.git |
|
[
"MIT"
] | 1.1.1 | 87d51a3ee9a4b0d2fe054bdd3fc2436258db2603 | docs | 2113 | # Static
[](https://sciml.github.io/Static.jl/stable)
[](https://sciml.github.io/Static.jl/dev)
[](https://github.com/SciML/Static.jl/actions)
[](https://codecov.io/gh/SciML/Static.jl)
`Static` defines a set of types (`True`, `False`, `StaticInt{value::Int}`, `StaticFloat64{value::Float64}`, `StaticSymbol{value::Symbol}`) that may be dispatched on (similar to `Base.Val{value}`). Unlike `Base.Val`, instances of these types provide "static" values (meaning known at compile time) that in many cases work interchangeably with dynamic values (meaning the value is known at runtime but not compile time). This is particularly useful when designing types whose fields may be dynamically or statically known, such as a range whose size may be dynamic or statically known.
Generic conversion to static values, dynamic values, and compile time known values is accomplished with the methods `static`, `dynamic`, and `known`, respectively.
```julia
julia> using Static
julia> static(1)
static(1)
julia> dynamic(static(1))
1
julia> dynamic(1)
1
julia> typeof(static(1))
StaticInt{1}
julia> known(typeof(static(1)))
1
julia> known(typeof(1)) === nothing # `Int` has no compile time known value
true
```
## Types, Dispatch, Compile-Time, and StaticNumbers.jl
Static.jl does not subtype the Base number types. For example, `!(StaticInt <: Integer)`. The reason for this is that it
invalidates all downstream compilation caches. This has a major effect, for example, causing LoopVectorization.jl to
not precompile and ultimately giving the ODE solvers >20 second extra compile times. To avoid these invalidations, the
dispatches were removed. An alternative library [StaticNumbers.jl](https://github.com/perrutquist/StaticNumbers.jl) is
more ergonomic but has these invalidations. Use the library that is more appropriate for your use case.
| Static | https://github.com/SciML/Static.jl.git |
|
[
"MIT"
] | 1.1.1 | 87d51a3ee9a4b0d2fe054bdd3fc2436258db2603 | docs | 98 | ```@meta
CurrentModule = Static
```
# Static
```@index
```
```@autodocs
Modules = [Static]
```
| Static | https://github.com/SciML/Static.jl.git |
|
[
"MIT"
] | 4.0.0 | 98a5b8742c045c30af566c5046e2e7a9b44481c3 | code | 672 | using EquationsOfState
using Documenter
DocMeta.setdocmeta!(EquationsOfState, :DocTestSetup, :(using EquationsOfState); recursive=true)
makedocs(;
modules=[EquationsOfState],
authors="Qi Zhang <singularitti@outlook.com>",
repo="https://github.com/MineralsCloud/EquationsOfState.jl/blob/{commit}{path}#{line}",
sitename="EquationsOfState.jl",
format=Documenter.HTML(;
prettyurls=get(ENV, "CI", "false") == "true",
canonical="https://MineralsCloud.github.io/EquationsOfState.jl",
assets=String[],
),
pages=[
"Home" => "index.md",
],
)
deploydocs(;
repo="github.com/MineralsCloud/EquationsOfState.jl",
)
| EquationsOfState | https://github.com/MineralsCloud/EquationsOfState.jl.git |
|
[
"MIT"
] | 4.0.0 | 98a5b8742c045c30af566c5046e2e7a9b44481c3 | code | 188 | module EquationsOfState
abstract type EquationOfStateOfSolidsParameters{T} end
const Parameters = EquationOfStateOfSolidsParameters
abstract type EquationOfState{T<:Parameters} end
end
| EquationsOfState | https://github.com/MineralsCloud/EquationsOfState.jl.git |
|
[
"MIT"
] | 4.0.0 | 98a5b8742c045c30af566c5046e2e7a9b44481c3 | code | 105 | using EquationsOfState
using Test
@testset "EquationsOfState.jl" begin
# Write your tests here.
end
| EquationsOfState | https://github.com/MineralsCloud/EquationsOfState.jl.git |
|
[
"MIT"
] | 4.0.0 | 98a5b8742c045c30af566c5046e2e7a9b44481c3 | docs | 1421 | # EquationsOfState
[](https://MineralsCloud.github.io/EquationsOfState.jl/stable)
[](https://MineralsCloud.github.io/EquationsOfState.jl/dev)
[](https://github.com/MineralsCloud/EquationsOfState.jl/actions)
[](https://ci.appveyor.com/project/singularitti/EquationsOfState-jl)
[](https://cloud.drone.io/MineralsCloud/EquationsOfState.jl)
[](https://cirrus-ci.com/github/MineralsCloud/EquationsOfState.jl)
[](https://codecov.io/gh/MineralsCloud/EquationsOfState.jl)
Note: starting from version `v4.0.0`, we will move all the past functionalities to package
[`EquationsOfStateOfSolids.jl`](https://github.com/MineralsCloud/EquationsOfStateOfSolids.jl).
This package is only served as a "base" package or a high-level package for similar packages.
To use the previous functionalities, please use `EquationsOfStateOfSolids.jl`.
| EquationsOfState | https://github.com/MineralsCloud/EquationsOfState.jl.git |
|
[
"MIT"
] | 4.0.0 | 98a5b8742c045c30af566c5046e2e7a9b44481c3 | docs | 221 | ```@meta
CurrentModule = EquationsOfState
```
# EquationsOfState
Documentation for [EquationsOfState](https://github.com/MineralsCloud/EquationsOfState.jl).
```@index
```
```@autodocs
Modules = [EquationsOfState]
```
| EquationsOfState | https://github.com/MineralsCloud/EquationsOfState.jl.git |
|
[
"MIT"
] | 1.3.6 | d126c3731d9c9d21ab25b26f0ab7809dc39a5543 | code | 3306 | using Distributed
using ArgParse
procs_id = addprocs(4)
@everywhere using Distributions
@everywhere using Cumulants
@everywhere using SymmetricTensors
using JLD2
using FileIO
using Random
@everywhere import CumulantsFeatures: reduceband
@everywhere using DatagenCopulaBased
@everywhere using CumulantsFeatures
@everywhere using HypothesisTests
@everywhere cut_order(x) = (x->x[3]).(x)
@everywhere function gmarg2t(X::Matrix{T}, nu::Int) where T <: AbstractFloat
Y = copy(X)
for i = 1:size(X, 2)
x = X[:,i]
s = var(x)
mu = mean(x)
d = Normal(mu, s)
u = cdf.(d, x)
pvalue(ExactOneSampleKSTest(u,Uniform(0,1)))>0.0001 || throw(AssertionError("$i marg. not unif."))
Y[:,i] = quantile.(TDist(nu), u)
end
return Y
end
function main(args)
s = ArgParseSettings("description")
@add_arg_table! s begin
"--nu", "-n"
default = 4
help = "the number of degrees of freedom for the t-Student copula"
arg_type = Int
"--nuu", "-u"
default = 25
help = "the number of degrees of freedom for the t-Student marginals"
arg_type = Int
end
parsed_args = parse_args(s)
ν = parsed_args["nu"]
νu = parsed_args["nuu"]
println(ν)
@everywhere t = 100_000
@everywhere n = 50
@everywhere malf_size = 10
data_dir = "."
test_number = 10
filename = "tstudent_$(ν)_marg_$(νu)-t_size-$(n)_malfsize-$malf_size-t_$t.jld2"
data = Dict{String, Any}("variables_no" => n,
"sample_number" => t,
"ν" => ν,
"test_number" => test_number,
"malf_size" => malf_size,
"data" => Dict{String, Dict{String,Any}}())
known_data_size = 0
if isfile("$data_dir/$filename")
data["data"] = load("$data_dir/$filename")["data"]
known_data_size += length(data["data"])
println("Already have $known_data_size samples \n Will generate $(test_number-known_data_size) more")
end
#true calculations
println("Calculation started")
for m=(known_data_size+1):test_number
@time begin
println(" > $m ($ν)")
malf = randperm(n)[1:malf_size]
Σ = cormatgen_rand(n)
samples_orig = Array(rand(MvNormal(Σ), t)')
versions = [(x->gmarg2t(x, νu), "original"),
(x->gmarg2t(gcop2tstudent(x, malf, ν), νu), "malf")]
cur_dict = Dict{String, Any}("malf" => malf,
"cor_source" => Σ)
data_dict = @distributed (merge) for (sampler, label)=versions
println(label)
samples = Array(sampler(samples_orig))
Σ_malf = SymmetricTensor(cov(samples))
cum = cumulants(samples, 4)
bands2 = cut_order(cumfsel(Σ_malf))
bands3 = cut_order(cumfsel(cum[2], cum[3], "hosvd"))
bands4 = cut_order(cumfsel(cum[2], cum[4], "hosvd"))
bands4n = cut_order(cumfsel(cum[2], cum[4], "norm", n-1))
bands4n = vcat(bands4n, setdiff(collect(1:n), bands4n))
Dict("cor_$label" => Σ_malf,
"bands_MEV_$label" => bands2,
"bands_JSBS_$label" => bands3,
"bands_JKFS_$label" => bands4,
"bands_JKN_$label" => bands4n)
end
data["data"]["$m"] = merge(cur_dict, data_dict)
save("$data_dir/$filename", data)
end
end
end
main(ARGS)
| CumulantsFeatures | https://github.com/iitis/CumulantsFeatures.jl.git |
|
[
"MIT"
] | 1.3.6 | d126c3731d9c9d21ab25b26f0ab7809dc39a5543 | code | 2981 | #!/usr/bin/env julia
using JLD2
using FileIO
using ArgParse
using PyCall
using SymmetricTensors
mpl = pyimport("matplotlib")
mc = pyimport("matplotlib.colors")
mpl.rc("text", usetex=true)
mpl.use("Agg")
using PyPlot
function union_size(list1::Vector, list2::Vector)
return length(list1 ∩ list2)
end
function features_selection_results(data::Dict, d::Int = 0)
malf_size = data["malf_size"]
check_size = malf_size
labels = ["malf"]
algorithms = ["MEV", "JKN", "JSBS", "JKFS"]
data_parts_label = sort([ "bands_$(alg)_$l" for l=labels for alg=algorithms])
plot_data = Dict()
for label = data_parts_label
plot_data[label] = zeros(Int, malf_size+1)
end
for m=1:length(data["data"]), label = data_parts_label
list1 = data["data"]["$m"][label][end-check_size+1-d:end]
list2 = data["data"]["$m"]["malf"]
no_common = union_size(list1, list2)
plot_data[label][no_common+1] += 1
end
plot_data, data_parts_label
end
function theoretical(sizedata::Int, malfsize::Int, found::Int)
binomial(malfsize, found)*binomial(sizedata-malfsize, malfsize-found)/binomial(sizedata,malfsize)
end
function los(n, ksize, p, r = 500_000)
ret = []
for s in 1:r
b = []
x = collect(1:n)
for a in 1:p
y = rand(x)
push!(b, y)
filter!(i -> i != y, x)
end
push!(ret, (count(b .<= ksize)))
end
[count(ret .== i) for i in 0:ksize]./r, collect(0:ksize)
end
function plotdata(plot_data, data_parts_label, ν, malf_size, var_number, repeating, δ::Int = 0)
mpl.rc("font", family="serif", size = 7)
fig, ax = subplots(figsize = (2.5, 2.))
cols = ["red", "green", "blue", "brown", "grey"]
p = ["--d", "--o", "--^", "--<", "--v"]
cla()
i = 0
for data_label = data_parts_label
i += 1
data_y = plot_data[data_label]
data_x = collect(0:(length(data_y)-1))
println(data_y)
d = replace(data_label, "bands_"=>"")
plot(data_x, data_y/repeating, p[i], label=replace(d, "_malf"=>""), color = cols[i], linewidth = 0.8, markersize = 3.)
end
data_x = 0:malf_size
data_y = los(var_number, malf_size, malf_size+δ)[1]
plot(data_x, data_y, "--x", label="rand choice", color = "black", linewidth = 1., markersize = 3.)
if true
ax.legend(fontsize = 4.5, loc = 2, ncol = 2)
end
subplots_adjust(left = 0.15, bottom = 0.16)
xlabel("no. selected features", labelpad = 0.)
ylabel("selection probability", labelpad = 0.)
savefig("$(ν)_$(δ)jkfs.pdf")
end
function main(args)
s = ArgParseSettings("description")
@add_arg_table! s begin
"file"
help = "the file name"
arg_type = String
"--delta", "-d"
help = "no. additiona features"
default = 0
arg_type = Int
end
parsed_args = parse_args(s)
data = load(parsed_args["file"])
d = parsed_args["delta"]
plot_data, data_parts_label = features_selection_results(data, d)
plotdata(plot_data, data_parts_label, data["ν"], data["malf_size"], data["variables_no"], data["test_number"], d)
end
main(ARGS)
| CumulantsFeatures | https://github.com/iitis/CumulantsFeatures.jl.git |
|
[
"MIT"
] | 1.3.6 | d126c3731d9c9d21ab25b26f0ab7809dc39a5543 | code | 6283 | #!/usr/bin/env julia
using Distributed
using JLD2
using FileIO
using ArgParse
using Distributions
using CumulantsFeatures
using LinearAlgebra
using Cumulants
addprocs(3)
@everywhere using CumulantsFeatures
@everywhere using Cumulants
using PyCall
mpl = pyimport("matplotlib")
mc = pyimport("matplotlib.colors")
mpl.rc("text", usetex=true)
mpl.use("Agg")
using PyPlot
"""
rand_withour_return(s::Int, b::Int)
out of numbers 1,2,3 , ... s returns no_pools random iterms without replacements
"""
function rand_withour_return(s::Int, no_pools::Int)
data = collect(1:s)
ret = []
for i in 1:no_pools
temp = rand(data)
data = filter!(i -> i != temp, data)
ret = vcat(ret, temp)
end
ret
end
"""
random_choice(data::Dict, β::Int)
Given data Dict and the parameter no_pools
returns a vector of random choice detections: [TruePositive, FalsePosotiveRate]
FalsePosotiveRate is the probability of type 1 error.
"""
function random_choice(data::Dict, no_pools::Int)
no_cases = length(data["data"])
ret = zeros(no_cases, 2)
println("random_choice detector")
for c=1:no_cases
println("case n. = ", c)
s = size(data["data"]["$c"]["x_malf"],1)
detected = rand_withour_return(s, no_pools)
no_positive = data["a"]
# it is assumed by the random data generation
#that outliers are at the beginning of data set
theshold = no_positive
no_true_detected = count(detected .<= theshold)
no_false_detercted = count(detected .> theshold)
sample_size = size(data["data"]["$c"]["x_malf"], 1)
no_negative = sample_size-no_positive
truePositiveRate = no_true_detected/no_positive
#type 1 error
flasePositiveRate = no_false_detercted/no_negative
ret[c,:] = [truePositiveRate, flasePositiveRate]
end
ret
end
"""
detection_hosvd(data::Dict, β::Float64, r::Int = 3)
Given data Dict and the parameter β (threshold) and r (number of direction data
are projected) returns a vector of hosvd detection:
[TruePositive, FalsePosotiveRate]
"""
function detection_hosvd(data::Dict, β::Float64, r::Int = 3)
no_cases = length(data["data"])
ret = zeros(no_cases, 2)
println("4th cumulant detector")
for c=1:no_cases
println("case no = ", c)
detected = hosvdc4detect(data["data"]["$c"]["x_malf"], β, r)
no_positive = data["a"]
# it is assumed by the random data generation
#that outliers are at the beginning of data set
theshold = no_positive
no_true_detected = count(findall(detected) .<= theshold)
no_false_detected = count(findall(detected) .> theshold)
sample_size = size(data["data"]["$c"]["x_malf"], 1)
no_negative = sample_size-no_positive
truePositiveRate = no_true_detected/no_positive
#type 1 error
flasePositiveRate = no_false_detected/no_negative
ret[c,:] = [truePositiveRate, flasePositiveRate]
end
ret
end
"""
detection_rx(data::Dict, α::Float64 = 0.99)
Given data Dict and the parameter α ("probability" threshold)
returns a vector of RX detection:
[TruePositive, FalsePosotiveRate]
"""
function detection_rx(data::Dict, α::Float64 = 0.99)
no_cases = length(data["data"])
ret = zeros(no_cases, 2)
print("rx detector")
for c=1:no_cases
println("case no = ", c)
detected = rxdetect(data["data"]["$c"]["x_malf"], α)
no_positive = data["a"]
# it is assumed by the random data generation
#that outliers are at the beginning of data set
theshold = no_positive
no_true_detected = count(findall(detected) .<= theshold)
no_false_detected = count(findall(detected) .> theshold)
sample_size = size(data["data"]["$c"]["x_malf"], 1)
no_negative = sample_size-no_positive
truePositiveRate = no_true_detected/no_positive
#type 1 error
flasePositiveRate = no_false_detected/no_negative
ret[c,:] = [truePositiveRate, flasePositiveRate]
end
ret
end
"""
plotdet(hosvd, rx, rand, nu::Int = 6)
plot results of detection
"""
function plotdet(hosvd, rx, rand, nu::Int = 6)
mpl.rc("font", family="serif", size = 7)
fig, ax = subplots(figsize = (2.5, 2.))
# raking each data case
for i in 1:size(hosvd[1],1)
xh = [k[i,2] for k in hosvd]
yh = [k[i,1] for k in hosvd]
# excluding [0., 0.] case where the parameter is out of range
j = (xh .> 0.) .* (yh .> 0.)
xh = xh[j]
yh = yh[j]
xrx = [k[i,2] for k in rx]
yrx = [k[i,1] for k in rx]
xrand = [k[i,2] for k in rand]
yrand = [k[i,1] for k in rand]
plt.plot(xh, yh, "o-", label = "4th cumulant", color = "blue")
plt.plot(xrx, yrx, "d-", label = "RX", color = "red")
plt.plot(xrand, yrand, "x-", label = "random", color = "gray")
ax.legend(fontsize = 6., loc = 2, ncol = 2)
subplots_adjust(left = 0.15, bottom = 0.16)
xlabel("False Positive Rate (type 1 error rate)", labelpad = -1.0)
ylabel("True Positive Rate", labelpad = 0.)
savefig("./pics/$(nu)_$(i)detect.pdf")
PyPlot.clf()
end
end
function main(args)
s = ArgParseSettings("description")
@add_arg_table! s begin
"file"
help = "the file name"
arg_type = String
end
parsed_args = parse_args(s)
str = parsed_args["file"]
data = load(str)
# copulas parameter for outliers
ν = data["ν"]
if !isfile("./data/roc_rand"*str)
no_pools = [1000, 900, 800, 700, 600, 500, 400, 300, 200, 100, 50, 10]
print("number random= ", size(no_pools))
roc = [random_choice(data, k) for k in no_pools]
save("./data/roc_rand"*str, "roc", roc, "ks", no_pools)
print(roc)
end
if !isfile("./data/roc"*str)
threshold = [8., 6., 5., 4., 3., 2.5, 2., 1.8, 1.6, 1.40, 1.30, 1.28]
print("number hosvd= ", size(threshold))
roc = [detection_hosvd(data, k) for k in threshold]
print(threshold)
print(roc)
save("./data/roc"*str, "roc", roc, "ks", threshold)
end
if !isfile("./data/rocrx"*str)
as = vcat([0.0005, 0.002, 0.01], collect(0.02:0.1:0.85), [0.9, 0.99, 0.999, 0.9999, 0.99999])
print("number rx= ", size(as))
rocrx = [detection_rx(data, k) for k in as]
print(as)
print(rocrx)
save("./data/rocrx"*str, "roc", rocrx, "alpha", as)
end
r = load("./data/roc"*str)["roc"]
rx = load("./data/rocrx"*str)["roc"]
rr = load("./data/roc_rand"*str)["roc"]
plotdet(r, rx, rr, ν)
end
main(ARGS)
| CumulantsFeatures | https://github.com/iitis/CumulantsFeatures.jl.git |
|
[
"MIT"
] | 1.3.6 | d126c3731d9c9d21ab25b26f0ab7809dc39a5543 | code | 3566 | #!/usr/bin/env julia
using Distributed
using Random
using LinearAlgebra
procs_id = addprocs(4)
using DatagenCopulaBased
@everywhere using Distributions
@everywhere using Cumulants
@everywhere using SymmetricTensors
using CumulantsFeatures
using JLD2
using FileIO
using ArgParse
@everywhere import CumulantsFeatures: reduceband
@everywhere using DatagenCopulaBased
@everywhere using CumulantsFeatures
@everywhere using HypothesisTests
Random.seed!(1234)
@everywhere function gmarg2t(X::Matrix{T}, nu::Int) where T <: AbstractFloat
# transform univariate gasussian marginals into t-Student with nu degrees of freedom
Y = copy(X)
for i = 1:size(X, 2)
x = X[:,i]
s = var(x)
mu = mean(x)
d = Normal(mu, s)
u = cdf.(d, x)
pvalue(ExactOneSampleKSTest(u,Uniform(0,1)))>0.0001 || throw(AssertionError("$i marg. not unif."))
Y[:,i] = quantile.(TDist(nu), u)
end
return Y
end
function main(args)
s = ArgParseSettings("description")
@add_arg_table! s begin
"--nu", "-n"
default = 6
help = "the number of degrees of freedom for the t-Student copula"
arg_type = Int
"--nuu", "-u"
default = 6
help = "the number of degrees of freedom for the t-Student marginal"
arg_type = Int
"--reals", "-N"
default = 5
help = "number of tests realisations"
arg_type = Int
end
parsed_args = parse_args(s)
ν = parsed_args["nu"]
νu = parsed_args["nuu"]
# number of generated data sets
test_number = parsed_args["reals"]
println("copula's degreen of freedom = ", ν)
println("matginal's degree of freedom = ", νu)
# parameters, data sie
@everywhere t = 1000
# no of marginals
@everywhere n = 30
# no of marginals with t-Student copula
@everywhere malf_size = 15
# outliers places on the beginning of data
@everywhere a = 100
data_dir = "."
filename = "tstudent_$(ν)_marg$(νu)-t_size-$(n)_malfsize-$malf_size-t_$(t)_$a.jld2"
data = Dict{String, Any}("variables_no" => n,
"sample_number" => t,
"ν" => ν,
"test_number" => test_number,
"malf_size" => malf_size,
"a" => a,
"data" => Dict{String, Dict{String,Any}}())
known_data_size = 0
if isfile("./$filename")
data["data"] = load("./$filename")["data"]
known_data_size += length(data["data"])
println("Already have $known_data_size samples \n Will generate $(test_number-known_data_size) more")
end
println("Calculation started")
for m=(known_data_size+1):test_number
@time begin
println(" > $m ($ν)")
malf = randperm(n)[1:malf_size]
Σ = cormatgen_rand(n)
samples_orig = rand(MvNormal(Σ), t)'
# gcop2tstudent(x[1:a, :], malf, ν) - outliers, given gaussian multivariate copula is changed for Gaussian
# x[a+1:end, :] - ordinary data
# gmarg2t( ..., νu) - univariate marginals are changed to t-Student
# "malf" - dict key
versions = [(x->gmarg2t(vcat(gcop2tstudent(x[1:a, :], malf, ν), x[a+1:end, :]), νu), "malf")]
cur_dict = Dict{String, Any}("malf" => malf,
"cor_source" => Σ)
data_dict = @distributed (merge) for (sampler, label)=versions
println(label)
samples = sampler(samples_orig)
Σ_malf = cov(samples)
Dict("cor_$label" => Σ_malf,
"x_$label" => samples)
end
data["data"]["$m"] = merge(cur_dict, data_dict)
save("./$filename", data)
end
end
end
main(ARGS)
| CumulantsFeatures | https://github.com/iitis/CumulantsFeatures.jl.git |
|
[
"MIT"
] | 1.3.6 | d126c3731d9c9d21ab25b26f0ab7809dc39a5543 | code | 505 | module CumulantsFeatures
using Distributions
using SymmetricTensors
using Cumulants
using Distributed
using StatsBase
using LinearAlgebra
using SharedArrays
using CumulantsUpdates
#using DistributedArrays
if VERSION >= v"1.3"
using CompilerSupportLibraries_jll
end
import SymmetricTensors: issymetric, getblock, pyramidindices
include("optimizationalgorithms.jl")
include("detectors.jl")
include("symten2mat.jl")
export cumfsel, rxdetect, hosvdc4detect, cum2mat
end
| CumulantsFeatures | https://github.com/iitis/CumulantsFeatures.jl.git |
|
[
"MIT"
] | 1.3.6 | d126c3731d9c9d21ab25b26f0ab7809dc39a5543 | code | 4104 | """
function rxdetect(X::Matrix{T}, alpha::Float64 = 0.99)
Takes data in the form of matrix where first index correspond to realisations and
second to feratures (marginals).
Using the RX (Reed-Xiaoli) Anomaly Detection returns the array of Bool that
correspond to outlier realisations. alpha is the sensitivity parameter of the RX detector
```jldoctest
julia> Random.seed!(42);
julia> x = vcat(rand(8,2), 20*rand(2,2))
10×2 Array{Float64,2}:
0.533183 0.956916
0.454029 0.584284
0.0176868 0.937466
0.172933 0.160006
0.958926 0.422956
0.973566 0.602298
0.30387 0.363458
0.176909 0.383491
11.8582 5.25618
14.9036 10.059
julia> rxdetect(x, 0.95)
10-element Array{Bool,1}:
false
false
false
false
false
false
false
false
true
true
```
"""
function rxdetect(X::Matrix{T}, alpha::Float64 = 0.99) where T <: AbstractFloat
t = size(X,1)
outliers = fill(false, t)
mu = mean(X,dims=1)[1,:]
Kinv = inv(cov(X))
d = Chisq(size(X,2))
for i in 1:t
if (X[i,:] - mu)'*Kinv*(X[i,:] - mu) > quantile(d, alpha)
outliers[i] = true
end
end
outliers
end
"""
hosvdstep(X::Matrix{T}, ls::Vector{Bool}, β::Float64, r::Int, cc::SymmetricTensor{T,4}) where T <: AbstractFloat
Returns Vector{Bool} - outliers form an itteration step of th hosvd algorithm
and Vector{Float64} vector of univariate kurtosis for data projected on specific
directions
"""
function hosvdstep(X::Matrix{T}, ls::Vector{Bool}, β::Float64, r::Int, cc::SymmetricTensor{T,4}) where T <: AbstractFloat
bestls = copy(ls)
M = Array(cum2mat(cc))
# sorting eigenvalues for highest to lowest
p = sortperm(eigvals(M), rev = true)
W = eigvecs(M)[:,p[1:r]]
Z = X*W
mm = [mad(Z[ls,i]; center=median(Z[ls,i]), normalize=true) for i in 1:r]
me = [median(Z[ls,i]) for i in 1:r]
for i in findall(ls)
if maximum(abs.(Z[i,:].-me)./mm) .> β
bestls[i] = false
end
end
bestls, norm([kurtosis(Z[bestls,i]) for i in 1:r])
end
"""
function hosvdc4detect(X::Matrix{T}, β::Float64 = 4.1, r::Int = 3; b::Int = 4)
Takes data in the form of matrix where first index correspond to realisations and
second to feratures (marginals).
Using the HOSVD of the 4'th cumulant's tensor of data returns the array of Bool that
correspond to outlier realisations. β is the sensitivity parameter while r a
number of specific directions, data are projected onto. Parameter b is a size of
blocks in a SymmetricTensors structure
```jldoctest
julia> Random.seed!(42);
julia> x = vcat(rand(8,2), 20*rand(2,2))
10×2 Array{Float64,2}:
0.533183 0.956916
0.454029 0.584284
0.0176868 0.937466
0.172933 0.160006
0.958926 0.422956
0.973566 0.602298
0.30387 0.363458
0.176909 0.383491
11.8582 5.25618
14.9036 10.059
julia> rxdetect(x, 0.95)
10-element Array{Bool,1}:
false
false
false
false
false
false
false
false
true
true
```
"""
function hosvdc4detect(X::Matrix{T}, β::Float64 = 4.1, r::Int = 3; b::Int = 4) where T <: AbstractFloat
X = X.-mean(X,dims=1)
s = cov(X)
X = X*Real.(sqrt(inv(s)))
ls = fill(true, size(X,1))
lsold = copy(ls)
aold = 1000000000.
ma = momentarray(X, 4, b)
t = size(X,1)
while count(ls) > div(size(X,1)+r+1, 2)
ma, t = updatemoments(ma, t, X, ls, lsold)
lsold = copy(ls)
c = copy(ma)
moms2cums!(c)
ls, a = hosvdstep(X, lsold, β, r, c[4])
if (aold-a)/a < 0.0001
return .!lsold
end
aold = a
end
.!lsold
end
"""
updatemoments(ma::Vector{SymmetricTensor{Float64,N} where N}, t::Int, X::Matix{T}, ls::Vector{Bool}, lsold::Vector{Bool})
Returns Array{SymmetricTensor} - an array of updated moments (after outliers removal)
and t - number of realisations of data after outliers removal
"""
function updatemoments(ma::Vector{SymmetricTensor{Float64,N} where N}, t::Int, X::Matrix{T}, ls::Vector{Bool}, lsold::Vector{Bool}) where T <: AbstractFloat
lstemp = (lsold.+ls) .== 1
if true in lstemp
dt = count(lstemp)
ma = t/(t-dt).*ma .- dt/(t-dt).*momentarray(X[lstemp,:], 4, ma[1].bls)
t = t - dt
end
ma, t
end
| CumulantsFeatures | https://github.com/iitis/CumulantsFeatures.jl.git |
|
[
"MIT"
] | 1.3.6 | d126c3731d9c9d21ab25b26f0ab7809dc39a5543 | code | 5694 | mev(Σ::Matrix{T}, c, ls::Vector{Bool}) where T <: AbstractFloat = det(reduceband(Σ, ls))
function mormbased(Σ::Matrix{T}, c::Array{T, N}, ls::Vector{Bool}) where {T <: AbstractFloat, N}
norm(reduceband(c, ls))/norm(reduceband(Σ, ls))^(N/2)
end
"""
detoverdetfitfunction(a::Array{N}, b::Array{N})
computes the maximizing function det(C_n)/det(C_2)^(n/2). It assumes, that product
of singular values from HOSVD of tensor is a good approximation of hyperdeterminant
of the tensor (whatever that means).
Returns the value of the maximizin function
"""
function hosvdapprox(Σ::Matrix{T}, c::Array{T,N}, fibres::Vector{Bool} = [fill(true, size(Σ, 1))...]) where {T <: AbstractFloat, N}
c = reduceband(c, fibres)
Σ = reduceband(Σ, fibres)
cunf = unfoldsym(c)
eigc = abs.(eigvals(cunf*cunf'))
eigΣ = abs.(eigvals(Σ*Σ'))
sum(log.(eigc)-N/2*log.(eigΣ))/2
end
"""
reduceband(ar::Array{N}, k::Vector{Bool})
Returns n-array without values at indices in ind
```jldoctest
julia> reshape(collect(1.:27.),(3,3,3))
3×3×3 Array{Float64,3}:
[:, :, 1] =
1.0 4.0 7.0
2.0 5.0 8.0
3.0 6.0 9.0
[:, :, 2] =
10.0 13.0 16.0
11.0 14.0 17.0
12.0 15.0 18.0
[:, :, 3] =
19.0 22.0 25.0
20.0 23.0 26.0
21.0 24.0 27.0
julia> reduceband(reshape(collect(1.:27.),(3,3,3)), [true, false, false])
1×1×1 Array{Float64,3}:
[:, :, 1] =
1.0
```
TODO reimplement in blocks
"""
reduceband(ar::Array{T,N}, fibres::Vector{Bool}) where {T <: AbstractFloat, N} =
ar[fill(fibres, N)...]
"""
function unfoldsym{T <: Real, N}(ar::Array{T,N})
Returns a matrix of size (i, k^(N-1)) that is an unfold of symmetric array ar
"""
function unfoldsym(ar::Array{T,N}) where {T <: AbstractFloat, N}
i = size(ar, 1)
return reshape(ar, i, i^(N-1))
end
"""
TODO reimplement in blocks
"""
function unfoldsym(t::SymmetricTensor{T, N}) where {T <: AbstractFloat, N}
t = unfoldsym(Array(t))
t*t'
end
#greedy algorithm
"""
greedestep(c::Vector{Array{Float}}, maxfunction::Function, ls::Vector{Bool})
Returns vector of bools that determines bands that maximise a function. True means include
a band, false exclude a band. It changes one true to false in input ls
```jldoctest
julia> a = reshape(collect(1.:9.), 3,3);
julia> b = reshape(collect(1.: 27.), 3,3,3);
julia> testf(ar,bool)= det(ar[1][bool,bool])
julia> greedestep(ar, testf, [true, true, true])
3-element Array{Bool,1}:
true
true
false
```
"""
function greedestep(Σ::Matrix{T}, c::Array{T, N}, maxfunction::Function,
ls::Vector{Bool}) where {T <: AbstractFloat, N}
inds = findall(ls)
bestval = SharedArray{T}(length(ls))
bestval .= -Inf
bestls = copy(ls)
@sync @distributed for i in inds
templs = copy(ls)
templs[i] = false
bestval[i] = maxfunction(Σ, c, templs)
end
v, i = findmax(bestval)
bestls[i] = false
return bestls, v, i
end
"""
greedesearchdata(Σ::SymmetricTensor{T,2}, c::SymmetricTensor{T, N}, maxfunction::Function, k::Int)
returns array of bools that are non-outliers features
"""
function greedesearchdata(Σ::SymmetricTensor{T,2}, c::SymmetricTensor{T, N}, maxfunction::Function, k::Int) where {T <: AbstractFloat, N}
ls = [true for i=1:Σ.dats]
Σ = Array(Σ)
c = Array(c)
result = []
for i = 1:k
ls, value, j = greedestep(Σ, c, maxfunction, ls)
push!(result, (ls,value,j))
value != -Inf || throw(AssertionError(" for k = $(k) optimisation does not work"))
end
result
end
"""
function cumfsel(Σ::SymmetricTensor{T,2}, c::SymmetricTensor{T, N}, f::String, k::Int = Σ.dats) where {T <: AbstractFloat, N}
Returns an Array of tuples (ind::Array{Bool}, fval::Float64, i::Int). Given
k-th Array ind are marginals removed after k -steps as those with low N'th order
dependency, fval, the value of the target function at step k and i, a feature removed
at step k.
Uses Σ - the covariance matrix and c - the N'th cumulant tensor to measure the
N'th order dependencies between marginals.
Function f is the optimization function, ["hosvd", "norm", "mev"] are supported.
```jldoctest
julia> Random.seed!(42);
julia> x = rand(12,10);
julia> c = cumulants(x, 4);
julia> cumfsel(c[2], c[4], "hosvd")
10-element Array{Any,1}:
(Bool[true, true, true, false, true, true, true, true, true, true], 27.2519, 4)
(Bool[true, true, false, false, true, true, true, true, true, true], 22.6659, 3)
(Bool[true, true, false, false, false, true, true, true, true, true], 18.1387, 5)
(Bool[false, true, false, false, false, true, true, true, true, true], 14.4492, 1)
(Bool[false, true, false, false, false, true, true, false, true, true], 11.2086, 8)
(Bool[false, true, false, false, false, true, true, false, true, false], 7.84083, 10)
(Bool[false, false, false, false, false, true, true, false, true, false], 5.15192, 2)
(Bool[false, false, false, false, false, false, true, false, true, false], 2.56748, 6)
(Bool[false, false, false, false, false, false, true, false, false, false], 0.30936, 9)
(Bool[false, false, false, false, false, false, false, false, false, false], 0.0, 7)
```
"""
function cumfsel(Σ::SymmetricTensor{T,2}, c::SymmetricTensor{T, N}, f::String, k::Int = Σ.dats) where {T <: AbstractFloat, N}
if f == "hosvd"
return greedesearchdata(Σ, c, hosvdapprox, k)
elseif f == "norm"
return greedesearchdata(Σ, c, mormbased, k)
elseif f == "mev"
return greedesearchdata(Σ, c ,mev, k)
end
throw(AssertionError("$(f) not supported use hosvd, norm or mev"))
end
"""
cumfsel(Σ::Matrix{T}, k::Int = size(Σ, 1))
cumfsel that uses as default the mev method
"""
cumfsel(Σ::SymmetricTensor{T,2}, k::Int = Σ.dats) where T <: AbstractFloat = cumfsel(Σ, SymmetricTensor(convert(Array{T}, ones(2,2,2))), "mev", k)
| CumulantsFeatures | https://github.com/iitis/CumulantsFeatures.jl.git |
|
[
"MIT"
] | 1.3.6 | d126c3731d9c9d21ab25b26f0ab7809dc39a5543 | code | 2803 | """
makeblocksize(bm::SymmetricTensor{T, N}, i::Tuple{Int, Int}) where {T <: AbstractFloat, N}
Returns Tuple{Int, Int} of the size ob the block in the output matrix
"""
function makeblocksize(bm::SymmetricTensor{T, N}, i::Tuple{Int, Int}) where {T <: AbstractFloat, N}
a = bm.bls
b = bm.bls
if !bm.sqr
if i[1] == bm.bln
a = bm.dats - (bm.bln-1)*bm.bls
end
if i[2] == bm.bln
b = bm.dats - (bm.bln-1)*bm.bls
end
end
a,b
end
"""
computeblock(bm::SymmetricTensor{T, N}, i::Tuple{Int, Int}, dims::Tuple) where {T <: AbstractFloat, N}
Returns Matrix{T}, the single block of the output higher correlation matrix
"""
function computeblock(bm::SymmetricTensor{T, N}, i::Tuple{Int, Int}, dims::Tuple) where {T <: AbstractFloat, N}
x = bm.bln^(N-2)
R = zeros(T, makeblocksize(bm, i))
for j in 1:x
@inbounds k = Tuple(CartesianIndices(dims)[j])
for k1 in 1:bm.bln
@inbounds M1 = unfold(getblock(bm, (i[1],k1, k...)),1)
@inbounds M2 = unfold(getblock(bm, (k1,i[2],k...)),2)
@inbounds R += M1*transpose(M2)
end
end
return R
end
"""
computeblock_p(bm::SymmetricTensor{T, N}, i::Tuple{Int, Int}, dims::Tuple) where {T <: AbstractFloat, N}
Returns Matrix{T}, the single block of the output higher correlation matrix
Parallel implementation
"""
function computeblock_p(bm::SymmetricTensor{T, N}, i::Tuple{Int, Int}, dims::Tuple) where {T <: AbstractFloat, N}
x = bm.bln^(N-2)
@inbounds R = SharedArray(zeros(T, (makeblocksize(bm, i)..., x)))
@sync @distributed for j in 1:x
@inbounds k = Tuple(CartesianIndices(dims)[j])
for k1 in 1:bm.bln
@inbounds M1 = unfold(getblock(bm, (i[1],k1, k...)),1)
@inbounds M2 = unfold(getblock(bm, (k1,i[2],k...)),2)
@inbounds R[:,:,j] += M1*transpose(M2)
end
end
@inbounds R = Array(R)
return mapreduce(i -> R[:,:,i], +, 1:size(R,3))
end
"""
cum2mat(bm::SymmetricTensor{T, N}) where {T <: AbstractFloat, N}
Returns higher order correlation matrix in the form of bm::SymmetricTensor{T, 2}
```jldoctest
julia> Random.seed!(42);
julia> t = rand(SymmetricTensor{Float64, 3}, 4);
julia> cum2mat(t)
SymmetricTensor{Float64,2}(Union{Nothing, Array{Float64,2}}[[7.69432 4.9757; 4.9757 5.72935] [6.09424 4.92375; 5.05157 3.17723]; nothing [7.33094 4.93128; 4.93128 4.7921]], 2, 2, 4, true)
```
"""
function cum2mat(bm::SymmetricTensor{T, N}) where {T <: AbstractFloat, N}
ret = arraynarrays(T, bm.bln, bm.bln)
ds = (fill(bm.bln, N-2)...,)
if nworkers() == 1
for i in pyramidindices(2, bm.bln)
@inbounds ret[i...] = computeblock(bm, i, ds)
end
else
for i in pyramidindices(2, bm.bln)
@inbounds ret[i...] = computeblock_p(bm, i, ds)
end
end
SymmetricTensor(ret; testdatstruct = false)
end
| CumulantsFeatures | https://github.com/iitis/CumulantsFeatures.jl.git |
|
[
"MIT"
] | 1.3.6 | d126c3731d9c9d21ab25b26f0ab7809dc39a5543 | code | 2715 | Random.seed!(42)
a = rand(SymmetricTensor{Float64, 2}, 3)
b = rand(SymmetricTensor{Float64, 3}, 3)
@everywhere using LinearAlgebra
@everywhere testf(a,b,bool)= det(a[bool,bool])
println("nworkers()")
println(nworkers())
@testset "greedesearch parallel implementation" begin
g = greedesearchdata(a,b, testf, 3)
if VERSION <= v"1.7"
@test g[1][1] == [true, false, true]
@test g[2][1] == [false, false, true]
@test g[3][1] == [false, false, false]
@test g[1][2] ≈ 0.48918301293211774
@test g[2][2] ≈ 0.9735659798036858
@test g[3][2] == 1.0
@test g[1][3] == 2
@test g[2][3] == 1
@test g[3][3] == 3
else
@test g[1][1] == [true, true, false]
@test g[2][1] == [true, false, false]
@test g[3][1] == [false, false, false]
@test g[1][2] ≈ 0.09764869605558585
@test g[2][2] ≈ 0.6293451231426089
@test g[3][2] == 1.0
@test g[1][3] == 3
@test g[2][3] == 2
@test g[3][3] == 1
end
end
Random.seed!(42)
@testset "cum2mat parallel tests on cumulants" begin
@testset "small data sie" begin
x = rand(200,12)
c = cumulants(x,5,2)
s = cum2mat(c[3])
X = unfold(Array(c[3]), 1)
M = X*transpose(X)
@test maximum(abs.(M - Array(s))) ≈ 0 atol = 10^(-10)
s = cum2mat(c[4])
X = unfold(Array(c[4]), 1)
M = X*transpose(X)
@test maximum(abs.(M - Array(s))) ≈ 0 atol = 10^(-10)
s = cum2mat(c[5])
X = unfold(Array(c[5]), 1)
M = X*transpose(X)
@test maximum(abs.(M - Array(s))) ≈ 0 atol = 10^(-10)
end
@testset "larger data size" begin
x = rand(200,27)
c = cumulants(x,5,5)
s = cum2mat(c[3])
X = unfold(Array(c[3]), 1)
M = X*transpose(X)
@test maximum(abs.(M - Array(s))) ≈ 0 atol = 10^(-10)
s = cum2mat(c[4])
X = unfold(Array(c[4]), 1)
M = X*transpose(X)
@test maximum(abs.(M - Array(s))) ≈ 0 atol = 10^(-10)
s = cum2mat(c[5])
X = unfold(Array(c[5]), 1)
M = X*transpose(X)
@test maximum(abs.(M - Array(s))) ≈ 0 atol = 10^(-10)
end
end
@testset "cum2mat parallel tests on random tensors" begin
@testset "m = 5, n = 24, d = 4" begin
Random.seed!(42)
t = rand(SymmetricTensor{Float64, 5}, 24, 4)
s = cum2mat(t)
X = unfold(Array(t), 1)
M = X*transpose(X)
@test maximum(abs.(M - Array(s))) ≈ 0 atol = 10^(-8)
end
@testset "m = 5, n = 37, d = 6" begin
t = rand(SymmetricTensor{Float64, 5}, 37, 6)
s = cum2mat(t)
X = unfold(Array(t), 1)
M = X*transpose(X)
@test maximum(abs.(M - Array(s))) ≈ 0 atol = 10^(-8)
end
end
| CumulantsFeatures | https://github.com/iitis/CumulantsFeatures.jl.git |
|
[
"MIT"
] | 1.3.6 | d126c3731d9c9d21ab25b26f0ab7809dc39a5543 | code | 617 | using Test
using Distributed
using LinearAlgebra
using SymmetricTensors
using Cumulants
using CumulantsFeatures
using Combinatorics
using Distributions
using Random
using CumulantsUpdates
import CumulantsFeatures: reduceband, greedestep, unfoldsym, hosvdstep, greedesearchdata, mev, mormbased, hosvdapprox
import CumulantsFeatures: updatemoments
include("test_select.jl")
include("test_detectors.jl")
include("symten2mattest.jl")
addprocs(3)
@everywhere using CumulantsFeatures
@everywhere using SymmetricTensors
@everywhere using Cumulants
@everywhere import SymmetricTensors: getblock
include("paralleltests.jl")
| CumulantsFeatures | https://github.com/iitis/CumulantsFeatures.jl.git |
|
[
"MIT"
] | 1.3.6 | d126c3731d9c9d21ab25b26f0ab7809dc39a5543 | code | 3268 | import CumulantsFeatures: makeblocksize, computeblock
@testset "axiliary for cum2mat" begin
Random.seed!(42)
t = rand(SymmetricTensor{Float64, 3}, 9, 4)
@test makeblocksize(t, (1,1)) == (4,4)
@test makeblocksize(t, (1,3)) == (4,1)
@test makeblocksize(t, (3,1)) == (1,4)
t1 = rand(SymmetricTensor{Float64, 3}, 9, 3)
@test makeblocksize(t1, (1,1)) == (3,3)
dims = (fill(t.bln, 1)...,)
if VERSION <= v"1.7"
@test computeblock(t, (1,1), dims)[1,1] ≈ 21.8503 atol = 0.01
else
@test computeblock(t, (1,1), dims)[1,1] ≈ 19.1174 atol = 0.01
end
end
@testset "cum2mat tests on cumulants" begin
x = rand(20,13)
c = cumulants(x,5,2)
s = cum2mat(c[3])
X = unfold(Array(c[3]), 1)
M = X*transpose(X)
@test maximum(abs.(M - Array(s))) ≈ 0 atol = 10^(-10)
s = cum2mat(c[4])
X = unfold(Array(c[4]), 1)
M = X*transpose(X)
@test maximum(abs.(M - Array(s))) ≈ 0 atol = 10^(-10)
s = cum2mat(c[5])
X = unfold(Array(c[5]), 1)
M = X*transpose(X)
@test maximum(abs.(M - Array(s))) ≈ 0 atol = 10^(-10)
end
@testset "cum2mat tests on random tensor one core" begin
@testset "order 3" begin
Random.seed!(42)
t = rand(SymmetricTensor{Float64, 3}, 12, 4)
s = cum2mat(t)
X = unfold(Array(t), 1)
M = X*transpose(X)
@test maximum(abs.(M - Array(s))) ≈ 0 atol = 10^(-10)
end
@testset "order 4" begin
t = rand(SymmetricTensor{Float64, 4}, 12, 3)
s = cum2mat(t)
X = unfold(Array(t), 1)
M = X*transpose(X)
@test maximum(abs.(M - Array(s))) ≈ 0 atol = 10^(-10)
end
@testset "order 5" begin
t = rand(SymmetricTensor{Float64, 5}, 10, 2)
s = cum2mat(t)
X = unfold(Array(t), 1)
M = X*transpose(X)
@test maximum(abs.(M - Array(s))) ≈ 0 atol = 10^(-10)
end
@testset "order 5 not squared" begin
t = rand(SymmetricTensor{Float64, 5}, 11, 3)
s = cum2mat(t)
X = unfold(Array(t), 1)
M = X*transpose(X)
@test maximum(abs.(M - Array(s))) ≈ 0 atol = 10^(-10)
end
@testset "order 6" begin
t = rand(SymmetricTensor{Float64, 6}, 9, 3)
s = cum2mat(t)
X = unfold(Array(t), 1)
M = X*transpose(X)
@test maximum(abs.(M - Array(s))) ≈ 0 atol = 10^(-10)
end
@testset "order 6 not squared" begin
t = rand(SymmetricTensor{Float64, 6}, 7, 3)
s = cum2mat(t)
X = unfold(Array(t), 1)
M = X*transpose(X)
@test maximum(abs.(M - Array(s))) ≈ 0 atol = 10^(-10)
end
@testset "larger data set" begin
t = rand(SymmetricTensor{Float64, 5}, 26, 4)
s = cum2mat(t)
X = unfold(Array(t), 1)
M = X*transpose(X)
@test maximum(abs.(M - Array(s))) ≈ 0 atol = 10^(-8)
end
end
@testset "test on Gaussian data" begin
Random.seed!(1234)
s = 0.5*(ones(4,4)+1*Matrix(I, 4, 4))
x = Array(rand(MvNormal(s), 1_000_000)');
c = cumulants(x, 5)
M3 = cum2mat(c[3])
M4 = cum2mat(c[4])
M5 = cum2mat(c[5])
@test norm(c[2]) ≈ 2.64 atol = 10^(-2)
@test norm(M3) ≈ 0. atol = 2*10^(-4)
@test norm(M4)≈ 0. atol = 4*10^(-3)
@test norm(M5)≈ 0. atol = 7*10^(-2)
end
| CumulantsFeatures | https://github.com/iitis/CumulantsFeatures.jl.git |
|
[
"MIT"
] | 1.3.6 | d126c3731d9c9d21ab25b26f0ab7809dc39a5543 | code | 818 | @testset "detectors" begin
Random.seed!(42)
x = vcat(rand(8,2), 5*rand(1,2), 30*rand(1,2))
x1 = vcat(rand(20,3), 5*rand(1,3), 30*rand(1,3))
@test rxdetect(x, 0.8) == [false, false, false, false, false, false, false, false, true, true]
@test hosvdc4detect(x, 4., 2; b=2) == [false, false, false, false, false, false, false, false, true, true]
@test hosvdc4detect(x1, 3.9, 1; b=1) == vcat(fill(false, 20), [true, true])
x2 = [[0. 0.]; [1. 2.]; [1. 1.]]
@test hosvdc4detect(x2, .1, 2; b=2) == [false, false, false]
@test rxdetect(x1, 0.9) == vcat(fill(false, 20), [true, true])
ls = fill(true, 10)
ls1 = [true, true, true, true, true, true, true, true, false, false]
c = cumulants(x, 4)
@test hosvdstep(x, ls, 4., 2, c[4])[1] == ls1
@test hosvdstep(x, ls, 3., 1, c[4])[2] ≈ 1.15 atol= 0.1
end
| CumulantsFeatures | https://github.com/iitis/CumulantsFeatures.jl.git |
|
[
"MIT"
] | 1.3.6 | d126c3731d9c9d21ab25b26f0ab7809dc39a5543 | code | 5066 |
te = [-0.112639 0.124715 0.124715 0.268717 0.124715 0.268717 0.268717 0.046154]
st = (reshape(te, (2,2,2)))
mat = reshape(te[1:4], (2,2))
ar = reshape(collect(1.:27.),(3,3,3))
@testset "unfoldsym reduce" begin
@test unfoldsym(st) == reshape(te, (2,4))
stt = SymmetricTensor(st)
@test unfoldsym(stt) == reshape(te, (2,4))*reshape(te, (2,4))'
@test reduceband(ar, [true, false, false]) ≈ ones(Float64, (1,1,1))
@test reduceband(ar, [true, true, true]) ≈ ar
end
Random.seed!(42)
a = rand(SymmetricTensor{Float64, 2}, 3)
b = rand(SymmetricTensor{Float64, 3}, 3)
testf(a,b,bool)= det(a[bool,bool])
@testset "optimisation" begin
@testset "greedestep" begin
g = greedestep(Array(a), Array(b), testf, [true, true, true])
if VERSION <= v"1.7"
@test g[1] == [true, false, true]
@test g[3] == 2
@test g[2] ≈ 0.48918301293211774
else
@test g[1] == [true, true, false]
@test g[3] == 3
@test g[2] ≈ 0.09764869605558585
end
end
@testset "greedesearch" begin
g = greedesearchdata(a,b, testf, 3)
if VERSION <= v"1.7"
@test g[1][1] == [true, false, true]
@test g[2][1] == [false, false, true]
@test g[3][1] == [false, false, false]
@test g[1][2] ≈ 0.48918301293211774
@test g[2][2] ≈ 0.9735659798036858
@test g[3][2] == 1.0
@test g[1][3] == 2
@test g[2][3] == 1
@test g[3][3] == 3
else
@test g[1][1] == [true, true, false]
@test g[2][1] == [true, false, false]
@test g[3][1] == [false, false, false]
@test g[1][2] ≈ 0.09764869605558585
@test g[2][2] ≈ 0.6293451231426089
@test g[3][2] == 1.0
@test g[1][3] == 3
@test g[2][3] == 2
@test g[3][3] == 1
end
end
end
@testset "target functions" begin
Σ = [1. 0.5 0.5; 0.5 1. 0.5; 0.5 0.5 1.]
@test mev(Σ, ones(2,2,2), [true, true, true]) == 0.5
c3 = ones(3,3,3)
#@test hosvdapprox(Σ,c3, [true, true, true]) ≈ -33.905320329609154
c4 = ones(3,3,3,3)
#@test hosvdapprox(Σ,c4, [true, true, true]) ≈ -30.23685187275532
@test mormbased(Σ,c4, [true, true, true]) ≈ 2.
c5 = ones(3,3,3,3,3)
#@test hosvdapprox(Σ,c5, [true, true, true]) ≈ -29.34097213814129
end
@testset "hosvdapprox additional tests" begin
Random.seed!(44)
c3 = rand(SymmetricTensor{Float64, 3}, 5)
Σ = rand(SymmetricTensor{Float64, 2}, 5)
m3 = unfoldsym(c3)
@test size(m3) == (5,5)
Σ = Array(Σ)
@test hosvdapprox(Σ, Array(c3)) ≈ log(det(m3)^(1/2)/det(Σ)^(3/2))
c4 = rand(SymmetricTensor{Float64, 4}, 5)
m4 = unfoldsym(c4)
@test size(m4) == (5,5)
@test hosvdapprox(Σ, Array(c4)) ≈ log(det(m4)^(1/2)/det(Σ)^(4/2))
c5 = rand(SymmetricTensor{Float64, 5}, 5)
m5 = unfoldsym(c5)
@test size(m5) == (5,5)
@test hosvdapprox(Σ, Array(c5)) ≈ log(det(m5)^(1/2)/det(Σ)^(5/2))
end
@testset "cumfsel tests" begin
Random.seed!(43)
Σ = rand(SymmetricTensor{Float64, 2}, 5)
c = 0.1*ones(5,5,5)
c[1,1,1] = 20.
c[2,2,2] = 10.
c[3,3,3] = 10.
for j in permutations([1,2,3])
c[j...] = 20.
end
for j in permutations([1,2,2])
c[j...] = 20.
end
for j in permutations([2,2,3])
c[j...] = 10.
end
for j in permutations([1,3,3])
c[j...] = 20.
end
c = SymmetricTensor(c)
ret = cumfsel(Σ, c, "hosvd", 5)
retn = cumfsel(Σ, c, "norm", 4)
if VERSION <= v"1.7"
@test ret[3][1] == [true, true, false, false, false]
@test ret[3][2] ≈ 7.943479150509705
@test (x->x[3]).(ret) == [4, 5, 3, 2, 1] #from lest important to most important"
@test retn[3][1] == [true, true, false, false, false]
@test retn[3][2] ≈ 24.285620999564703
@test (x->x[3]).(retn) == [4, 5, 3, 2]
@test cumfsel(Σ, c, "mev", 5)[1][3] == 5
@test cumfsel(Σ, 5)[1][3] == 5
@test_throws AssertionError cumfsel(Σ, c, "mov", 5)
@test_throws AssertionError cumfsel(Σ, c, "hosvd", 7)
else
@test ret[3][1] == [false, true, true, false, false]
@test ret[3][2] ≈ 10.943399558215603
@test (x->x[3]).(ret) == [4, 5, 1, 3, 2] #from lest important to most important"
@test retn[3][1] == [true, false, true, false, false]
@test retn[3][2] ≈ 46.617412130431866
@test (x->x[3]).(retn) == [4, 5, 2, 3]
@test cumfsel(Σ, c, "mev", 5)[1][3] == 5
@test cumfsel(Σ, 5)[1][3] == 5
@test_throws AssertionError cumfsel(Σ, c, "mov", 5)
@test_throws AssertionError cumfsel(Σ, c, "hosvd", 7)
end
Random.seed!(42)
x = rand(12,10);
c = cumulants(x,4);
f = cumfsel(c[2], c[4], "hosvd")
if VERSION <= v"1.7"
@test f[9][1] == [false, false, false, false, false, false, true, false, false, false]
@test f[9][3] == 9
@test f[10][3] == 7
else
@test f[9][1] == [false, false, false, false, false, false, false, false, true, false]
@test f[9][3] == 6
@test f[10][3] == 9
end
end
@testset "cumfsel tests on Float32" begin
Random.seed!(42)
x = rand(Float32, 12,10);
c = cumulants(x,4);
f = cumfsel(c[2], c[4], "hosvd")
if VERSION <= v"1.7"
@test f[9][3] == 6
@test f[10][3] == 5
else
@test f[9][3] == 2
@test f[10][3] == 6
end
end
| CumulantsFeatures | https://github.com/iitis/CumulantsFeatures.jl.git |
|
[
"MIT"
] | 1.3.6 | d126c3731d9c9d21ab25b26f0ab7809dc39a5543 | docs | 9453 | # CumulantsFeatures.jl
[](https://coveralls.io/github/iitis/CumulantsFeatures.jl?branch=master)
[](https://doi.org/10.5281/zenodo.7716695)
CumulantsFeatures.jl uses multivariate cumulants to provide the algorithms for the outliers detection and the features selection given the multivariate data represented in the form of `t x n` matrix of Floats, `t` numerates the realisations, while `n` numerates the marginals.
Requires SymmetricTensors.jl Cumulants.jl and CumulantsUpdates.jl to compute and update multivariate cumulants of data.
As of 24/09/2018 [@kdomino](https://github.com/kdomino) is the lead maintainer of this package.
## Installation
Within Julia, run
```julia
pkg> add CumulantsFeatures
```
Parallel computation is supported
## Features selection
Given `n`-variate data, iteratively determines its `k`-marginals that are little informative.
Uses `C2`- the covariance matrix, and `CN` - the `N`th cumulant's tensor, both in the `SymmetricTensor` type, see SymmetricTensors.jl. Uses one of the following optimisation functions
`f`: `["hosvd", "norm", "mev"].
```julia
julia> function cumfsel(C2::SymmetricTensor{T,2}, CN::SymmetricTensor{T, N}, f::String, k::Int = n) where {T <: AbstractFloat, N}
```
The "norm" uses the norm of the higher-order cumulant tensor, this is a benchmark method for comparison.
The "mev" uses only the corrlelation matrix, see: C. Sheffield, 'Selecting band combinations from multispectral data', Photogrammetric Engineering and Remote Sensing, vol. 51 (1985)
The "hosvd" uses the Higher Order Singular Value decomposition of cumulant's tensor to extract information. For the `N=3` case, the Joint Skewness Band Selection (JSBS), see X. Geng, K. Sun, L. Ji, H. Tang & Y. Zhao 'Joint Skewness and Its Application in Unsupervised Band Selection for Small Target Detection Sci Rep. vol.5 (2015) (https://www.nature.com/articles/srep09915). For the JSBS application in biomedical data analysis see: M. Domino, K. Domino, Z. Gajewski, 'An application of higher order multivariate cumulants in modelling of myoelectrical activity of porcine uterus during early pregnancy', Biosystems (2018), (https://doi.org/10.1016/j.biosystems.2018.10.019). For `N = 4` and `N = 5` see also P. Głomb, K. Domino, M. Romaszewski, M. Cholewa 'Band selection with Higher Order Multivariate Cumulants for small target detection in hyperspectral images' (2018) (https://arxiv.org/abs/1808.03513).
```julia
julia> Random.seed!(42);
julia> using Cumulants
julia> using SymmetricTensors
julia> x = rand(12,10);
julia> c = cumulants(x, 4);
julia> cumfsel(c[2], c[4], "hosvd")
10-element Array{Any,1}:
(Bool[true, true, true, false, true, true, true, true, true, true], 27.2519, 4)
(Bool[true, true, false, false, true, true, true, true, true, true], 22.6659, 3)
(Bool[true, true, false, false, false, true, true, true, true, true], 18.1387, 5)
(Bool[false, true, false, false, false, true, true, true, true, true], 14.4492, 1)
(Bool[false, true, false, false, false, true, true, false, true, true], 11.2086, 8)
(Bool[false, true, false, false, false, true, true, false, true, false], 7.84083, 10)
(Bool[false, false, false, false, false, true, true, false, true, false], 5.15192, 2)
(Bool[false, false, false, false, false, false, true, false, true, false], 2.56748, 6)
(Bool[false, false, false, false, false, false, true, false, false, false], 0.30936, 9)
(Bool[false, false, false, false, false, false, false, false, false, false], 0.0, 7)
```
The output is the Array of tuples `(ind::Array{Bool}, fval::Float64, i::Int)`, each tuple corresponds to the one step
of the features selection. Marginals are removed in the information hierarchy, starting from the least informatve and ending on the most infomrative.
The vector `ind` consist of `false` that determines the removed marginal, and `true` that determines the left marginal.
The `fval` is the value of the target function.
The `i` numerates the marginal removed at the given step.
To limit number of steps use the default parameter `k`:
```julia
julia> cumfsel(Array(c[2]), Array(c[4]), "hosvd", 2)
2-element Array{Any,1}:
(Bool[true, true, true, false, true, true, true, true, true, true], 27.2519, 4)
(Bool[true, true, false, false, true, true, true, true, true, true], 22.6659, 3)
```
For the mev optimization run:
```julia
julia> cumfsel(Σ::SymmetricTensor{T,2}, k::Int = Σ.dats)
```
## The higher-order cross-correlation matrix
```julia
cum2mat(c::SymmetricTensor{T, N}) where {T <: AbstractFloat, N}
```
Returns the higher-order cross-correlation matrix in the form of `SymmetricTensor{T, 2}`. Such matrix is the contraction of the corresponding higher-order cumulant tensor `c::SymmetricTensor{T, N}`
with itself in all modes but one.
```julia
julia> Random.seed!(42);
julia> t = rand(SymmetricTensor{Float64, 3}, 4);
julia> cum2mat(t)
SymmetricTensor{Float64,2}(Union{Nothing, Array{Float64,2}}[[7.69432 4.9757; 4.9757 5.72935] [6.09424 4.92375; 5.05157 3.17723]; nothing [7.33094 4.93128; 4.93128 4.7921]], 2, 2, 4, true)
```
## Outliers detection
Let `X` be the multivariate data represented in the form of `t x n` matrix of Floats, `t` numerates the realisations, while `n` numerates the marginals.
### RX detector
```julia
rxdetect(X::Matrix{T}, α::Float64 = 0.99)
```
The RX (Reed-Xiaoli) Anomaly Detection returns the array of Bool, where `true`
corresponds to the outlier realisations while `false` corresponds to the ordinary data. The parameter `α` is the sensitivity (threshold) parameter of the RX detector.
```julia
julia> Random.seed!(42);
julia> x = vcat(rand(8,2), 20*rand(2,2))
10×2 Array{Float64,2}:
0.533183 0.956916
0.454029 0.584284
0.0176868 0.937466
0.172933 0.160006
0.958926 0.422956
0.973566 0.602298
0.30387 0.363458
0.176909 0.383491
11.8582 5.25618
14.9036 10.059
julia> rxdetect(x, 0.95)
10-element Array{Bool,1}:
false
false
false
false
false
false
false
false
true
true
```
### The 4th order multivariate cumulant outlier detector
```julia
function hosvdc4detect(X::Matrix{T}, β::Float64 = 4.1, r::Int = 3)
```
The 4th order multivariate cumulant outlier detector returns the array of Bool, where `true`
corresponds to the outlier realisations while `false` corresponds to the ordinary data. The parameter `β` is the sensitivity parameter, the parameter `r` is the number of specific directions (with high `4`th order cumulant) on which data are projected. See K. Domino: 'Multivariate cumulants in outlier detection for financial data analysis', [arXiv:1804.00541] (https://arxiv.org/abs/1804.00541).
```julia
julia> Random.seed!(42);
julia> x = vcat(rand(8,2), 20*rand(2,2))
10×2 Array{Float64,2}:
0.533183 0.956916
0.454029 0.584284
0.0176868 0.937466
0.172933 0.160006
0.958926 0.422956
0.973566 0.602298
0.30387 0.363458
0.176909 0.383491
11.8582 5.25618
14.9036 10.059
julia> rxdetect(x, 0.95)
10-element Array{Bool,1}:
false
false
false
false
false
false
false
false
true
true
```
## Tests on artificial data.
In folder `benchmarks/outliers_detect` and `benchmarks/features_select` there are the Julia executable files for testing features selection and outliers detection on artificial data.
### Features selection
In `./benchmarks/features_select` the executable file `gendat4selection.jl` generates multivariate data where the subset of `infomrative` margianls is modelled by the t-Student copula with `--nu` degrees of freedom (by defalt `4`). All univariate marginal distributions are t-Student with `-nuu` degrees of freedom (by defalt `25`).
The `gendat4selection.jl` returns a `.jld2` file with data. Run `jkfs_selection.jl` on this file to display the characteristics of features selection plotted in `./benchmarks/features_select/pics/`
### Outlier detection
In `./benchmarks/outliers_detect/` the executable file `gendat4detection.jl` generates multivariate data with outliers modelled by the t-Student copula with `--nu` degrees of freedom (by defalt `6`). All univariate marginal distributions are t-Student with `--nuu` degrees of freedom (by defalt `6`). The number of test realisations is `--reals` (by default `5`).
The `gendat4detection.jl` returns a `.jld2` file with data. Run `detect_outliers.jl` on this file to display the characteristics of outlier detection plotted in `./benchmarks/outliers_detect/pics/'
`
# Citing this work
This project was partially financed by the National Science Centre, Poland – project number 2014/15/B/ST6/05204.
While using `hosvdc4detect()` - please cite: K. Domino: 'Multivariate cumulants in outlier detection for financial data analysis', Physica A: Statistical Mechanics and its Applications Volume 558, 15 November 2020, 124995 (https://doi.org/10.1016/j.physa.2020.124995).
While using `cumfsel()` - please cite: P. Głomb, K. Domino, M. Romaszewski, M. Cholewa, 'Band selection with Higher Order Multivariate Cumulants for small target detection in hyperspectral images', Wroclaw University of Science and Technology, Conference Proceedings: PP-RAI'2019 (2019), ISBN: 978-83-943803-2-8; [arxiv: 1808.03513] (https://arxiv.org/abs/1808.03513).
| CumulantsFeatures | https://github.com/iitis/CumulantsFeatures.jl.git |
|
[
"MIT"
] | 0.4.4 | b45738c2e3d0d402dffa32b2c1654759a2ac35a4 | code | 598 | using MLUtils
using Documenter
# Copy the README to the home page in docs, to avoid duplication.
readme = readlines(joinpath(@__DIR__, "..", "README.md"))
open(joinpath(@__DIR__, "src/index.md"), "w") do f
for l in readme
println(f, l)
end
end
DocMeta.setdocmeta!(MLUtils, :DocTestSetup, :(using MLUtils); recursive=true)
makedocs(;
modules=[MLUtils],
doctest=true,
clean=true,
sitename = "MLUtils.jl",
pages = ["Home" => "index.md",
"API" => "api.md"],
)
deploydocs(repo="github.com/JuliaML/MLUtils.jl.git",
devbranch="main")
| MLUtils | https://github.com/JuliaML/MLUtils.jl.git |
|
[
"MIT"
] | 0.4.4 | b45738c2e3d0d402dffa32b2c1654759a2ac35a4 | code | 1608 | module MLUtils
using Random
using Statistics
using ShowCases: ShowLimit
using FLoops: @floop
using FLoops.Transducers: Executor, ThreadedEx
import StatsBase: sample
using Transducers
using Tables
using DataAPI
using Base: @propagate_inbounds
using Random: AbstractRNG, shuffle!, GLOBAL_RNG, rand!, randn!
import ChainRulesCore: rrule
using ChainRulesCore: @non_differentiable, unthunk, AbstractZero,
NoTangent, ZeroTangent, ProjectTo
using SimpleTraits
import NNlib
@traitdef IsTable{X}
@traitimpl IsTable{X} <- Tables.istable(X)
using Compat: stack
include("observation.jl")
export numobs,
getobs,
getobs!
include("obstransform.jl")
export mapobs,
filterobs,
groupobs,
joinobs,
shuffleobs
include("batchview.jl")
export batchsize,
BatchView
include("eachobs.jl")
export eachobs, DataLoader
include("parallel.jl")
include("folds.jl")
export kfolds,
leavepout
include("obsview.jl")
export obsview,
ObsView
include("randobs.jl")
export randobs
include("resample.jl")
export oversample,
undersample
include("splitobs.jl")
export splitobs
include("utils.jl")
export batch,
batchseq,
chunk,
fill_like,
flatten,
group_counts,
group_indices,
normalise,
ones_like,
rand_like,
randn_like,
rpad_constant,
stack, # in Base since julia v1.9
unbatch,
unsqueeze,
unstack,
zeros_like
include("Datasets/Datasets.jl")
using .Datasets
export Datasets,
load_iris
include("deprecations.jl")
end
| MLUtils | https://github.com/JuliaML/MLUtils.jl.git |
|
[
"MIT"
] | 0.4.4 | b45738c2e3d0d402dffa32b2c1654759a2ac35a4 | code | 6254 | """
BatchView(data, batchsize; partial=true, collate=nothing)
BatchView(data; batchsize=1, partial=true, collate=nothing)
Create a view of the given `data` that represents it as a vector
of batches. Each batch will contain an equal amount of
observations in them. The batch-size
can be specified using the parameter `batchsize`.
In the case that the size of the dataset is not dividable by the
specified `batchsize`, the remaining observations will
be ignored if `partial=false`. If `partial=true` instead
the last batch-size can be slightly smaller.
Note that any data access is delayed until `getindex` is called.
If used as an iterator, the object will iterate over the dataset
once, effectively denoting an epoch.
For `BatchView` to work on some data structure, the type of the
given variable `data` must implement the data container
interface. See [`ObsView`](@ref) for more info.
# Arguments
- **`data`** : The object describing the dataset. Can be of any
type as long as it implements [`getobs`](@ref) and
[`numobs`](@ref) (see Details for more information).
- **`batchsize`** : The batch-size of each batch.
It is the number of observations that each batch must contain
(except possibly for the last one).
- **`partial`** : If `partial=false` and the number of observations is
not divisible by the batch-size, then the last mini-batch is dropped.
- **`collate`**: Batching behavior. If `nothing` (default), a batch
is `getobs(data, indices)`. If `false`, each batch is
`[getobs(data, i) for i in indices]`. When `true`, applies [`batch`](@ref)
to the vector of observations in a batch, recursively collating
arrays in the last dimensions. See [`batch`](@ref) for more information
and examples.
# Examples
```julia
using MLUtils
X, Y = MLUtils.load_iris()
A = BatchView(X, batchsize=30)
@assert typeof(A) <: BatchView <: AbstractVector
@assert eltype(A) <: SubArray{Float64,2}
@assert length(A) == 5 # Iris has 150 observations
@assert size(A[1]) == (4,30) # Iris has 4 features
# 5 batches of size 30 observations
for x in BatchView(X, batchsize=30)
@assert typeof(x) <: SubArray{Float64,2}
@assert numobs(x) === 30
end
# 7 batches of size 20 observations
# Note that the iris dataset has 150 observations,
# which means that with a batchsize of 20, the last
# 10 observations will be ignored
for (x, y) in BatchView((X, Y), batchsize=20, partial=false)
@assert typeof(x) <: SubArray{Float64,2}
@assert typeof(y) <: SubArray{String,1}
@assert numobs(x) == numobs(y) == 20
end
# collate tuple observations
for (x, y) in BatchView((rand(10, 3), ["a", "b", "c"]), batchsize=2, collate=true, partial=false)
@assert size(x) == (10, 2)
@assert size(y) == (2,)
end
# randomly assign observations to one and only one batch.
for (x, y) in BatchView(shuffleobs((X, Y)), batchsize=20)
@assert typeof(x) <: SubArray{Float64,2}
@assert typeof(y) <: SubArray{String,1}
end
```
"""
struct BatchView{TElem,TData,TCollate} <: AbstractDataContainer
data::TData
batchsize::Int
count::Int
partial::Bool
end
function BatchView(data::T; batchsize::Int=1, partial::Bool=true, collate=Val(nothing)) where {T}
n = numobs(data)
if n < batchsize
@warn "Number of observations less than batch-size, decreasing the batch-size to $n"
batchsize = n
end
collate = collate isa Val ? collate : Val(collate)
if !(collate ∈ (Val(nothing), Val(true), Val(false)))
throw(ArgumentError("`collate` must be one of `nothing`, `true` or `false`."))
end
E = _batchviewelemtype(data, collate)
count = partial ? cld(n, batchsize) : fld(n, batchsize)
BatchView{E,T,typeof(collate)}(data, batchsize, count, partial)
end
_batchviewelemtype(::TData, ::Val{nothing}) where TData =
Core.Compiler.return_type(getobs, Tuple{TData, UnitRange{Int}})
_batchviewelemtype(::TData, ::Val{false}) where TData =
Vector{Core.Compiler.return_type(getobs, Tuple{TData, Int})}
_batchviewelemtype(data, ::Val{true}) =
Core.Compiler.return_type(batch, Tuple{_batchviewelemtype(data, Val(false))})
"""
batchsize(data::BatchView) -> Int
Return the fixed size of each batch in `data`.
# Examples
```julia
using MLUtils
X, Y = MLUtils.load_iris()
A = BatchView(X, batchsize=30)
@assert batchsize(A) == 30
```
"""
batchsize(A::BatchView) = A.batchsize
Base.length(A::BatchView) = A.count
Base.@propagate_inbounds function getobs(A::BatchView)
return _getbatch(A, 1:numobs(A.data))
end
Base.@propagate_inbounds function Base.getindex(A::BatchView, i::Int)
obsindices = _batchrange(A, i)
_getbatch(A, obsindices)
end
Base.@propagate_inbounds function Base.getindex(A::BatchView, is::AbstractVector)
obsindices = union((_batchrange(A, i) for i in is)...)::Vector{Int}
_getbatch(A, obsindices)
end
function _getbatch(A::BatchView{TElem, TData, Val{true}}, obsindices) where {TElem, TData}
batch([getobs(A.data, i) for i in obsindices])
end
function _getbatch(A::BatchView{TElem, TData, Val{false}}, obsindices) where {TElem, TData}
return [getobs(A.data, i) for i in obsindices]
end
function _getbatch(A::BatchView{TElem, TData, Val{nothing}}, obsindices) where {TElem, TData}
getobs(A.data, obsindices)
end
Base.parent(A::BatchView) = A.data
Base.eltype(::BatchView{Tel}) where Tel = Tel
# override AbstractDataContainer default
Base.iterate(A::BatchView, state = 1) =
(state > numobs(A)) ? nothing : (A[state], state + 1)
# Helper function to translate a batch-index into a range of observations.
@inline function _batchrange(A::BatchView, batchindex::Int)
@boundscheck (batchindex > A.count || batchindex < 0) && throw(BoundsError())
startidx = (batchindex - 1) * A.batchsize + 1
endidx = min(numobs(parent(A)), startidx + A.batchsize -1)
return startidx:endidx
end
function Base.showarg(io::IO, A::BatchView, toplevel)
print(io, "BatchView(")
Base.showarg(io, parent(A), false)
print(io, ", ")
print(io, "batchsize=$(A.batchsize), ")
print(io, "partial=$(A.partial)")
print(io, ')')
toplevel && print(io, " with eltype ", nameof(eltype(A))) # simplify
end
# --------------------------------------------------------------------
| MLUtils | https://github.com/JuliaML/MLUtils.jl.git |
|
[
"MIT"
] | 0.4.4 | b45738c2e3d0d402dffa32b2c1654759a2ac35a4 | code | 663 | # Deprecated in v0.2
@deprecate unstack(x, dims) unstack(x; dims=dims)
@deprecate unsqueeze(x::AbstractArray, dims::Int) unsqueeze(x; dims=dims)
@deprecate unsqueeze(dims::Int) unsqueeze(dims=dims)
@deprecate labelmap(x) group_indices(x)
@deprecate frequencies(x) group_counts(x)
@deprecate eachbatch(data, batchsize; kws...) eachobs(data; batchsize, kws...)
@deprecate eachbatch(data; size=1, kws...) eachobs(data; batchsize=size, kws...)
# Deprecated in v0.3
import Base: rpad
@deprecate rpad(v::AbstractVector, n::Integer, p) rpad_constant(v, n, p)
@deprecate rpad(v::AbstractVector, n::Integer, p::Union{AbstractChar, AbstractString}) rpad_constant(v, n, p)
| MLUtils | https://github.com/JuliaML/MLUtils.jl.git |
|
[
"MIT"
] | 0.4.4 | b45738c2e3d0d402dffa32b2c1654759a2ac35a4 | code | 9362 | """
eachobs(data; kws...)
Return an iterator over `data`.
Supports the same arguments as [`DataLoader`](@ref).
The `batchsize` default is `-1` here while
it is `1` for `DataLoader`.
# Examples
```julia
X = rand(4,100)
for x in eachobs(X)
# loop entered 100 times
@assert typeof(x) <: Vector{Float64}
@assert size(x) == (4,)
end
# mini-batch iterations
for x in eachobs(X, batchsize=10)
# loop entered 10 times
@assert typeof(x) <: Matrix{Float64}
@assert size(x) == (4,10)
end
# support for tuples, named tuples, dicts
for (x, y) in eachobs((X, Y))
# ...
end
```
"""
function eachobs(data; batchsize=-1, kws...)
DataLoader(data; batchsize, kws...)
end
"""
DataLoader(data; [batchsize, buffer, collate, parallel, partial, rng, shuffle])
An object that iterates over mini-batches of `data`,
each mini-batch containing `batchsize` observations
(except possibly the last one).
Takes as input a single data array, a tuple (or a named tuple) of arrays,
or in general any `data` object that implements the [`numobs`](@ref) and [`getobs`](@ref)
methods.
The last dimension in each array is the observation dimension, i.e. the one
divided into mini-batches.
The original data is preserved in the `data` field of the DataLoader.
# Arguments
- `data`: The data to be iterated over. The data type has to be supported by
[`numobs`](@ref) and [`getobs`](@ref).
- `batchsize`: If less than 0, iterates over individual observations.
Otherwise, each iteration (except possibly the last) yields a mini-batch
containing `batchsize` observations. Default `1`.
- `buffer`: If `buffer=true` and supported by the type of `data`,
a buffer will be allocated and reused for memory efficiency.
You can also pass a preallocated object to `buffer`. Default `false`.
- `collate`: Batching behavior. If `nothing` (default), a batch is `getobs(data, indices)`. If `false`, each batch is
`[getobs(data, i) for i in indices]`. When `true`, applies [`batch`](@ref) to the vector of observations in a batch,
recursively collating arrays in the last dimensions. See [`batch`](@ref) for more information and examples.
- `parallel`: Whether to use load data in parallel using worker threads. Greatly
speeds up data loading by factor of available threads. Requires starting
Julia with multiple threads. Check `Threads.nthreads()` to see the number of
available threads. **Passing `parallel = true` breaks ordering guarantees**.
Default `false`.
- `partial`: This argument is used only when `batchsize > 0`.
If `partial=false` and the number of observations is not divisible by the batchsize,
then the last mini-batch is dropped. Default `true`.
- `rng`: A random number generator. Default `Random.GLOBAL_RNG`.
- `shuffle`: Whether to shuffle the observations before iterating. Unlike
wrapping the data container with `shuffleobs(data)`, `shuffle=true` ensures
that the observations are shuffled anew every time you start iterating over
`eachobs`. Default `false`.
# Examples
```jldoctest
julia> Xtrain = rand(10, 100);
julia> array_loader = DataLoader(Xtrain, batchsize=2);
julia> for x in array_loader
@assert size(x) == (10, 2)
# do something with x, 50 times
end
julia> array_loader.data === Xtrain
true
julia> tuple_loader = DataLoader((Xtrain,), batchsize=2); # similar, but yielding 1-element tuples
julia> for x in tuple_loader
@assert x isa Tuple{Matrix}
@assert size(x[1]) == (10, 2)
end
julia> Ytrain = rand('a':'z', 100); # now make a DataLoader yielding 2-element named tuples
julia> train_loader = DataLoader((data=Xtrain, label=Ytrain), batchsize=5, shuffle=true);
julia> for epoch in 1:100
for (x, y) in train_loader # access via tuple destructuring
@assert size(x) == (10, 5)
@assert size(y) == (5,)
# loss += f(x, y) # etc, runs 100 * 20 times
end
end
julia> first(train_loader).label isa Vector{Char} # access via property name
true
julia> first(train_loader).label == Ytrain[1:5] # because of shuffle=true
false
julia> foreach(println∘summary, DataLoader(rand(Int8, 10, 64), batchsize=30)) # partial=false would omit last
10×30 Matrix{Int8}
10×30 Matrix{Int8}
10×4 Matrix{Int8}
```
"""
struct DataLoader{T, R<:AbstractRNG, C<:Val}
data::T
batchsize::Int
buffer::Bool
partial::Bool
shuffle::Bool
parallel::Bool
collate::C
rng::R
end
function DataLoader(
data;
buffer = false,
parallel = false,
shuffle = false,
batchsize::Int = 1,
partial::Bool = true,
collate = Val(nothing),
rng::AbstractRNG = Random.GLOBAL_RNG)
buffer = buffer isa Bool ? buffer : true
collate = collate isa Val ? collate : Val(collate)
if !(collate ∈ (Val(nothing), Val(true), Val(false)))
throw(ArgumentError("`collate` must be one of `nothing`, `true` or `false`."))
end
return DataLoader(data, batchsize, buffer, partial, shuffle, parallel, collate, rng)
end
function Base.iterate(e::DataLoader)
# Wrapping with ObsView in order to work around
# issue https://github.com/FluxML/Flux.jl/issues/1935
data = ObsView(e.data)
data = e.shuffle ? shuffleobs(e.rng, data) : data
data = e.batchsize > 0 ? BatchView(data; e.batchsize, e.partial, e.collate) : data
iter = if e.parallel
eachobsparallel(data; e.buffer)
else
if e.buffer
buf = getobs(data, 1)
(getobs!(buf, data, i) for i in 1:numobs(data))
else
(getobs(data, i) for i in 1:numobs(data))
end
end
obs, state = iterate(iter)
return obs, (iter, state)
end
function Base.iterate(::DataLoader, (iter, state))
ret = iterate(iter, state)
isnothing(ret) && return
obs, state = ret
return obs, (iter, state)
end
function Base.length(e::DataLoader)
numobs(if e.batchsize > 0
# Wrapping with ObsView in order to work around
# issue https://github.com/FluxML/Flux.jl/issues/1935
data = ObsView(e.data)
BatchView(data; e.batchsize, e.partial)
else
e.data
end)
end
Base.IteratorEltype(::DataLoader) = Base.EltypeUnknown()
## This causes error in some cases of `collect(loader)`
# function Base.eltype(e::DataLoader)
# eltype(if e.batchsize > 0
# BatchView(e.data; e.batchsize, e.partial)
# else
# e.data
# end)
# end
@inline function _dataloader_foldl1(rf, val, e::DataLoader, data)
if e.shuffle
_dataloader_foldl2(rf, val, e, shuffleobs(e.rng, data))
else
_dataloader_foldl2(rf, val, e, data)
end
end
@inline function _dataloader_foldl2(rf, val, e::DataLoader, data)
if e.batchsize > 0
_dataloader_foldl3(rf, val, e, BatchView(data; e.batchsize, e.partial))
else
_dataloader_foldl3(rf, val, e, data)
end
end
@inline function _dataloader_foldl3(rf, val, e::DataLoader, data)
if e.buffer > 0
_dataloader_foldl4_buffered(rf, val, data)
else
_dataloader_foldl4(rf, val, data)
end
end
@inline function _dataloader_foldl4(rf, val, data)
for i in 1:numobs(data)
@inbounds x = getobs(data, i)
# TODO: in 1.8 we could @inline this at the callsite,
# optimizer seems to be very sensitive to inlining and
# quite brittle in its capacity to keep this type stable
val = Transducers.@next(rf, val, x)
end
Transducers.complete(rf, val)
end
@inline function _dataloader_foldl4_buffered(rf, val, data)
buf = getobs(data, 1)
for i in 1:numobs(data)
@inbounds x = getobs!(buf, data, i)
val = Transducers.@next(rf, val, x)
end
Transducers.complete(rf, val)
end
@inline function Transducers.__foldl__(rf, val, e::DataLoader)
e.parallel && throw(ArgumentError("Transducer fold protocol not supported on parallel data loads"))
_dataloader_foldl1(rf, val, e, ObsView(e.data))
end
# Base uses this function for composable array printing, e.g. adjoint(view(::Matrix)))
function Base.showarg(io::IO, e::DataLoader, toplevel)
print(io, "DataLoader(")
Base.showarg(io, e.data, false)
e.buffer == false || print(io, ", buffer=", e.buffer)
e.parallel == false || print(io, ", parallel=", e.parallel)
e.shuffle == false || print(io, ", shuffle=", e.shuffle)
e.batchsize == 1 || print(io, ", batchsize=", e.batchsize)
e.partial == true || print(io, ", partial=", e.partial)
e.collate == Val(nothing) || print(io, ", collate=", e.collate)
e.rng == Random.GLOBAL_RNG || print(io, ", rng=", e.rng)
print(io, ")")
end
Base.show(io::IO, e::DataLoader) = Base.showarg(io, e, false)
function Base.show(io::IO, m::MIME"text/plain", e::DataLoader)
if Base.haslength(e)
print(io, length(e), "-element ")
else
print(io, "Unknown-length ")
end
Base.showarg(io, e, false)
print(io, "\n with first element:")
print(io, "\n ", _expanded_summary(first(e)))
end
_expanded_summary(x) = summary(x)
function _expanded_summary(xs::Tuple)
parts = [_expanded_summary(x) for x in xs]
"(" * join(parts, ", ") * ",)"
end
function _expanded_summary(xs::NamedTuple)
parts = ["$k = "*_expanded_summary(x) for (k,x) in zip(keys(xs), xs)]
"(; " * join(parts, ", ") * ")"
end
| MLUtils | https://github.com/JuliaML/MLUtils.jl.git |
|
[
"MIT"
] | 0.4.4 | b45738c2e3d0d402dffa32b2c1654759a2ac35a4 | code | 5754 |
"""
kfolds(n::Integer, k = 5) -> Tuple
Compute the train/validation assignments for `k` repartitions of
`n` observations, and return them in the form of two vectors. The
first vector contains the index-vectors for the training subsets,
and the second vector the index-vectors for the validation subsets
respectively. A general rule of thumb is to use either `k = 5` or
`k = 10`. The following code snippet generates the indices
assignments for `k = 5`
```julia
julia> train_idx, val_idx = kfolds(10, 5);
```
Each observation is assigned to the validation subset once (and
only once). Thus, a union over all validation index-vectors
reproduces the full range `1:n`. Note that there is no random
assignment of observations to subsets, which means that adjacent
observations are likely to be part of the same validation subset.
```julia
julia> train_idx
5-element Array{Array{Int64,1},1}:
[3,4,5,6,7,8,9,10]
[1,2,5,6,7,8,9,10]
[1,2,3,4,7,8,9,10]
[1,2,3,4,5,6,9,10]
[1,2,3,4,5,6,7,8]
julia> val_idx
5-element Array{UnitRange{Int64},1}:
1:2
3:4
5:6
7:8
9:10
```
"""
function kfolds(n::Integer, k::Integer = 5)
2 <= k <= n || throw(ArgumentError("n must be positive and k must to be within 2:$(max(2,n))"))
# Compute the size of each fold. This is important because
# in general the number of total observations might not be
# divideable by k. In such cases it is custom that the remaining
# observations are divided among the folds. Thus some folds
# have one more observation than others.
sizes = fill(floor(Int, n/k), k)
for i = 1:(n % k)
sizes[i] = sizes[i] + 1
end
# Compute start offset for each fold
offsets = cumsum(sizes) .- sizes .+ 1
# Compute the validation indices using the offsets and sizes
val_indices = map((o,s)->(o:o+s-1), offsets, sizes)
# The train indices are then the indicies not in validation
train_indices = map(idx->setdiff(1:n,idx), val_indices)
# We return a tuple of arrays
train_indices, val_indices
end
"""
kfolds(data, [k = 5])
Repartition a `data` container `k` times using a `k` folds
strategy and return the sequence of folds as a lazy iterator.
Only data subsets are created, which means that no actual data is copied until
[`getobs`](@ref) is invoked.
Conceptually, a k-folds repartitioning strategy divides the given
`data` into `k` roughly equal-sized parts. Each part will serve
as validation set once, while the remaining parts are used for
training. This results in `k` different partitions of `data`.
In the case that the size of the dataset is not dividable by the
specified `k`, the remaining observations will be evenly
distributed among the parts.
```julia
for (x_train, x_val) in kfolds(X, k=10)
# code called 10 times
# nobs(x_val) may differ up to ±1 over iterations
end
```
Multiple variables are supported (e.g. for labeled data)
```julia
for ((x_train, y_train), val) in kfolds((X, Y), k=10)
# ...
end
```
By default the folds are created using static splits. Use
[`shuffleobs`](@ref) to randomly assign observations to the
folds.
```julia
for (x_train, x_val) in kfolds(shuffleobs(X), k = 10)
# ...
end
```
See [`leavepout`](@ref) for a related function.
"""
function kfolds(data, k::Integer)
n = numobs(data)
train_indices, val_indices = kfolds(n, k)
((obsview(data, itrain), obsview(data, ival))
for (itrain, ival) in zip(train_indices, val_indices))
end
kfolds(data; k) = kfolds(data, k)
"""
leavepout(n::Integer, [size = 1]) -> Tuple
Compute the train/validation assignments for `k ≈ n/size`
repartitions of `n` observations, and return them in the form of
two vectors. The first vector contains the index-vectors for the
training subsets, and the second vector the index-vectors for the
validation subsets respectively. Each validation subset will have
either `size` or `size+1` observations assigned to it. The
following code snippet generates the index-vectors for `size = 2`.
```julia
julia> train_idx, val_idx = leavepout(10, 2);
```
Each observation is assigned to the validation subset once (and
only once). Thus, a union over all validation index-vectors
reproduces the full range `1:n`. Note that there is no random
assignment of observations to subsets, which means that adjacent
observations are likely to be part of the same validation subset.
```julia
julia> train_idx
5-element Array{Array{Int64,1},1}:
[3,4,5,6,7,8,9,10]
[1,2,5,6,7,8,9,10]
[1,2,3,4,7,8,9,10]
[1,2,3,4,5,6,9,10]
[1,2,3,4,5,6,7,8]
julia> val_idx
5-element Array{UnitRange{Int64},1}:
1:2
3:4
5:6
7:8
9:10
```
"""
function leavepout(n::Integer, p::Integer = 1)
1 <= p <= floor(n/2) || throw(ArgumentError("p must to be within 1:$(floor(Int,n/2))"))
k = floor(Int, n / p)
kfolds(n, k)
end
"""
leavepout(data, p = 1)
Repartition a `data` container using a k-fold strategy, where `k`
is chosen in such a way, that each validation subset of the
resulting folds contains roughly `p` observations. Defaults to
`p = 1`, which is also known as "leave-one-out" partitioning.
The resulting sequence of folds is returned as a lazy
iterator. Only data subsets are created. That means no actual
data is copied until [`getobs`](@ref) is invoked.
```julia
for (train, val) in leavepout(X, p=2)
# if nobs(X) is dividable by 2,
# then numobs(val) will be 2 for each iteraton,
# otherwise it may be 3 for the first few iterations.
end
```
See[`kfolds`](@ref) for a related function.
"""
function leavepout(data, p::Integer)
n = numobs(data)
1 <= p <= floor(n/2) || throw(ArgumentError("p must to be within 1:$(floor(Int,n/2))"))
k = floor(Int, n / p)
kfolds(data, k)
end
leavepout(data; p::Integer=1) = leavepout(data, p) | MLUtils | https://github.com/JuliaML/MLUtils.jl.git |
|
[
"MIT"
] | 0.4.4 | b45738c2e3d0d402dffa32b2c1654759a2ac35a4 | code | 6731 | """
numobs(data)
Return the total number of observations contained in `data`.
If `data` does not have `numobs` defined,
then in the case of `Tables.table(data) == true`
returns the number of rows, otherwise returns `length(data)`.
Authors of custom data containers should implement
`Base.length` for their type instead of `numobs`.
`numobs` should only be implemented for types where there is a
difference between `numobs` and `Base.length`
(such as multi-dimensional arrays).
`getobs` supports by default nested combinations of array, tuple,
named tuples, and dictionaries.
See also [`getobs`](@ref).
# Examples
```jldoctest
# named tuples
x = (a = [1, 2, 3], b = rand(6, 3))
numobs(x) == 3
# dictionaries
x = Dict(:a => [1, 2, 3], :b => rand(6, 3))
numobs(x) == 3
```
All internal containers must have the same number of observations:
```juliarepl
julia> x = (a = [1, 2, 3, 4], b = rand(6, 3));
julia> numobs(x)
ERROR: DimensionMismatch: All data containers must have the same number of observations.
Stacktrace:
[1] _check_numobs_error()
@ MLUtils ~/.julia/dev/MLUtils/src/observation.jl:163
[2] _check_numobs
@ ~/.julia/dev/MLUtils/src/observation.jl:130 [inlined]
[3] numobs(data::NamedTuple{(:a, :b), Tuple{Vector{Int64}, Matrix{Float64}}})
@ MLUtils ~/.julia/dev/MLUtils/src/observation.jl:177
[4] top-level scope
@ REPL[35]:1
```
"""
function numobs end
# Generic Fallbacks
@traitfn numobs(data::X) where {X; IsTable{X}} = DataAPI.nrow(data)
@traitfn numobs(data::X) where {X; !IsTable{X}} = length(data)
"""
getobs(data, [idx])
Return the observations corresponding to the observation index `idx`.
Note that `idx` can be any type as long as `data` has defined
`getobs` for that type. If `idx` is not provided, then materialize
all observations in `data`.
If `data` does not have `getobs` defined,
then in the case of `Tables.table(data) == true`
returns the row(s) in position `idx`, otherwise returns `data[idx]`.
Authors of custom data containers should implement
`Base.getindex` for their type instead of `getobs`.
`getobs` should only be implemented for types where there is a
difference between `getobs` and `Base.getindex`
(such as multi-dimensional arrays).
The returned observation(s) should be in the form intended to
be passed as-is to some learning algorithm. There is no strict
interface requirement on how this "actual data" must look like.
Every author behind some custom data container can make this
decision themselves.
The output should be consistent when `idx` is a scalar vs vector.
`getobs` supports by default nested combinations of array, tuple,
named tuples, and dictionaries.
See also [`getobs!`](@ref) and [`numobs`](@ref).
# Examples
```jldoctest
# named tuples
x = (a = [1, 2, 3], b = rand(6, 3))
getobs(x, 2) == (a = 2, b = x.b[:, 2])
getobs(x, [1, 3]) == (a = [1, 3], b = x.b[:, [1, 3]])
# dictionaries
x = Dict(:a => [1, 2, 3], :b => rand(6, 3))
getobs(x, 2) == Dict(:a => 2, :b => x[:b][:, 2])
getobs(x, [1, 3]) == Dict(:a => [1, 3], :b => x[:b][:, [1, 3]])
```
"""
function getobs end
# Generic Fallbacks
getobs(data) = data
@traitfn getobs(data::X, idx) where {X; IsTable{X}} = Tables.subset(data, idx, viewhint=false)
@traitfn getobs(data::X, idx) where {X; !IsTable{X}} = data[idx]
"""
getobs!(buffer, data, idx)
Inplace version of `getobs(data, idx)`. If this method
is defined for the type of `data`, then `buffer` should be used
to store the result, instead of allocating a dedicated object.
Implementing this function is optional. In the case no such
method is provided for the type of `data`, then `buffer` will be
*ignored* and the result of [`getobs`](@ref) returned. This could be
because the type of `data` may not lend itself to the concept
of `copy!`. Thus, supporting a custom `getobs!` is optional
and not required.
See also [`getobs`](@ref) and [`numobs`](@ref).
"""
function getobs! end
# getobs!(buffer, data) = getobs(data)
getobs!(buffer, data, idx) = getobs(data, idx)
# --------------------------------------------------------------------
# AbstractDataContainer
# Having an AbstractDataContainer allows to define sensible defaults
# for Base (or other) interfaces based on our interface.
# This makes it easier for developers by reducing boilerplate.
abstract type AbstractDataContainer end
Base.size(x::AbstractDataContainer) = (numobs(x),)
Base.iterate(x::AbstractDataContainer, state = 1) =
(state > numobs(x)) ? nothing : (getobs(x, state), state + 1)
Base.lastindex(x::AbstractDataContainer) = numobs(x)
Base.firstindex(::AbstractDataContainer) = 1
# --------------------------------------------------------------------
# Arrays
# We are very opinionated with arrays: the observation dimension
# is th last dimension. For different behavior wrap the array in
# a custom type, e.g. with Tables.table.
numobs(A::AbstractArray{<:Any, N}) where {N} = size(A, N)
# 0-dim arrays
numobs(A::AbstractArray{<:Any, 0}) = 1
function getobs(A::AbstractArray{<:Any, N}, idx) where N
I = ntuple(_ -> :, N-1)
return A[I..., idx]
end
getobs(A::AbstractArray{<:Any, 0}, idx) = A[idx]
function getobs!(buffer::AbstractArray, A::AbstractArray{<:Any, N}, idx) where N
I = ntuple(_ -> :, N-1)
buffer .= view(A, I..., idx)
return buffer
end
function getobs!(buffer::AbstractArray, A::AbstractArray)
buffer .= A
return buffer
end
# --------------------------------------------------------------------
# Tuples and NamedTuples
_check_numobs_error() =
throw(DimensionMismatch("All data containers must have the same number of observations."))
function _check_numobs(data::Union{Tuple, NamedTuple, Dict})
length(data) == 0 && return 0
n = numobs(data[first(keys(data))])
for i in keys(data)
ni = numobs(data[i])
n == ni || _check_numobs_error()
end
return n
end
numobs(data::Union{Tuple, NamedTuple}) = _check_numobs(data)
getobs(tup::Union{Tuple, NamedTuple}) = map(x -> getobs(x), tup)
Base.@propagate_inbounds function getobs(tup::Union{Tuple, NamedTuple}, indices)
@boundscheck _check_numobs(tup)
return map(x -> getobs(x, indices), tup)
end
function getobs!(buffers::Union{Tuple, NamedTuple},
tup::Union{Tuple, NamedTuple},
indices)
_check_numobs(tup)
return map(buffers, tup) do buffer, x
getobs!(buffer, x, indices)
end
end
## Dict
numobs(data::Dict) = _check_numobs(data)
getobs(data::Dict, i) = Dict(k => getobs(v, i) for (k, v) in pairs(data))
getobs(data::Dict) = Dict(k => getobs(v) for (k, v) in pairs(data))
function getobs!(buffers, data::Dict, i)
for (k, v) in pairs(data)
getobs!(buffers[k], v, i)
end
return buffers
end
| MLUtils | https://github.com/JuliaML/MLUtils.jl.git |
|
[
"MIT"
] | 0.4.4 | b45738c2e3d0d402dffa32b2c1654759a2ac35a4 | code | 6308 |
# mapobs
struct MappedData{batched, F, D} <: AbstractDataContainer
f::F
data::D
end
function Base.show(io::IO, data::MappedData{batched}) where {batched}
print(io, "mapobs(")
print(IOContext(io, :compact=>true), data.f)
print(io, ", ")
print(IOContext(io, :compact=>true), data.data)
print(io, "; batched=:$(batched))")
end
Base.length(data::MappedData) = numobs(data.data)
Base.getindex(data::MappedData, ::Colon) = data[1:length(data)]
Base.getindex(data::MappedData{:auto}, idx::Int) = data.f(getobs(data.data, idx))
Base.getindex(data::MappedData{:auto}, idxs::AbstractVector) = data.f(getobs(data.data, idxs))
Base.getindex(data::MappedData{:never}, idx::Int) = data.f(getobs(data.data, idx))
Base.getindex(data::MappedData{:never}, idxs::AbstractVector) = [data.f(getobs(data.data, idx)) for idx in idxs]
Base.getindex(data::MappedData{:always}, idx::Int) = getobs(data.f(getobs(data.data, [idx])), 1)
Base.getindex(data::MappedData{:always}, idxs::AbstractVector) = data.f(getobs(data.data, idxs))
"""
mapobs(f, data; batched=:auto)
Lazily map `f` over the observations in a data container `data`.
Returns a new data container `mdata` that can be indexed and has a length.
Indexing triggers the transformation `f`.
The batched keyword argument controls the behavior of `mdata[idx]` and `mdata[idxs]`
where `idx` is an integer and `idxs` is a vector of integers:
- `batched=:auto` (default). Let `f` handle the two cases.
Calls `f(getobs(data, idx))` and `f(getobs(data, idxs))`.
- `batched=:never`. The function `f` is always called on a single observation.
Calls `f(getobs(data, idx))` and `[f(getobs(data, idx)) for idx in idxs]`.
- `batched=:always`. The function `f` is always called on a batch of observations.
Calls `getobs(f(getobs(data, [idx])), 1)` and `f(getobs(data, idxs))`.
# Examples
```julia
julia> data = (a=[1,2,3], b=[1,2,3]);
julia> mdata = mapobs(data) do x
(c = x.a .+ x.b, d = x.a .- x.b)
end
mapobs(#25, (a = [1, 2, 3], b = [1, 2, 3]); batched=:auto))
julia> mdata[1]
(c = 2, d = 0)
julia> mdata[1:2]
(c = [2, 4], d = [0, 0])
```
"""
mapobs(f::F, data::D; batched=:auto) where {F,D} = MappedData{batched, F, D}(f, data)
"""
mapobs(fs, data)
Lazily map each function in tuple `fs` over the observations in data container `data`.
Returns a tuple of transformed data containers.
"""
mapobs(fs::Tuple, data) = Tuple(mapobs(f, data) for f in fs)
struct NamedTupleData{TData,F} <: AbstractDataContainer
data::TData
namedfs::NamedTuple{F}
end
Base.length(data::NamedTupleData) = numobs(getfield(data, :data))
function Base.getindex(data::NamedTupleData{TData,F}, idx::Int) where {TData,F}
obs = getobs(getfield(data, :data), idx)
namedfs = getfield(data, :namedfs)
return NamedTuple{F}(f(obs) for f in namedfs)
end
Base.getproperty(data::NamedTupleData, field::Symbol) =
mapobs(getproperty(getfield(data, :namedfs), field), getfield(data, :data))
Base.show(io::IO, data::NamedTupleData) =
print(io, "mapobs($(getfield(data, :namedfs)), $(getfield(data, :data)))")
"""
mapobs(namedfs::NamedTuple, data)
Map a `NamedTuple` of functions over `data`, turning it into a data container
of `NamedTuple`s. Field syntax can be used to select a column of the resulting
data container.
```julia
data = 1:10
nameddata = mapobs((x = sqrt, y = log), data)
getobs(nameddata, 10) == (x = sqrt(10), y = log(10))
getobs(nameddata.x, 10) == sqrt(10)
```
"""
function mapobs(namedfs::NamedTuple, data)
return NamedTupleData(data, namedfs)
end
# filterobs
"""
filterobs(f, data)
Return a subset of data container `data` including all indices `i` for
which `f(getobs(data, i)) === true`.
```julia
data = 1:10
numobs(data) == 10
fdata = filterobs(>(5), data)
numobs(fdata) == 5
```
"""
function filterobs(f, data; iterfn = _iterobs)
return obsview(data, [i for (i, obs) in enumerate(iterfn(data)) if f(obs)])
end
_iterobs(data) = [getobs(data, i) for i = 1:numobs(data)]
# groupobs
"""
groupobs(f, data)
Split data container data `data` into different data containers, grouping
observations by `f(obs)`.
```julia
data = -10:10
datas = groupobs(>(0), data)
length(datas) == 2
```
"""
function groupobs(f, data)
groups = Dict{Any,Vector{Int}}()
for i = 1:numobs(data)
group = f(getobs(data, i))
if !haskey(groups, group)
groups[group] = [i]
else
push!(groups[group], i)
end
end
return Dict(group => obsview(data, idxs) for (group, idxs) in groups)
end
# joinumobs
struct JoinedData{T,N} <: AbstractDataContainer
datas::NTuple{N,T}
ns::NTuple{N,Int}
end
JoinedData(datas) = JoinedData(datas, numobs.(datas))
Base.length(data::JoinedData) = sum(data.ns)
function Base.getindex(data::JoinedData, idx)
for (i, n) in enumerate(data.ns)
if idx <= n
return getobs(data.datas[i], idx)
else
idx -= n
end
end
end
"""
joinobs(datas...)
Concatenate data containers `datas`.
```julia
data1, data2 = 1:10, 11:20
jdata = joinumobs(data1, data2)
getobs(jdata, 15) == 15
```
"""
joinobs(datas...) = JoinedData(datas)
"""
shuffleobs([rng], data)
Return a "subset" of `data` that spans all observations, but
has the order of the observations shuffled.
The values of `data` itself are not copied. Instead only the
indices are shuffled. This function calls [`obsview`](@ref) to
accomplish that, which means that the return value is likely of a
different type than `data`.
```julia
# For Arrays the subset will be of type SubArray
@assert typeof(shuffleobs(rand(4,10))) <: SubArray
# Iterate through all observations in random order
for x in eachobs(shuffleobs(X))
...
end
```
The optional parameter `rng` allows one to specify the
random number generator used for shuffling. This is useful when
reproducible results are desired. By default, uses the global RNG.
See `Random` in Julia's standard library for more info.
For this function to work, the type of `data` must implement
[`numobs`](@ref) and [`getobs`](@ref). See [`ObsView`](@ref)
for more information.
"""
shuffleobs(data) = shuffleobs(Random.GLOBAL_RNG, data)
function shuffleobs(rng::AbstractRNG, data)
obsview(data, randperm(rng, numobs(data)))
end
| MLUtils | https://github.com/JuliaML/MLUtils.jl.git |
|
[
"MIT"
] | 0.4.4 | b45738c2e3d0d402dffa32b2c1654759a2ac35a4 | code | 7591 | """
ObsView(data, [indices])
Used to represent a subset of some `data` of arbitrary type by
storing which observation-indices the subset spans. Furthermore,
subsequent subsettings are accumulated without needing to access
actual data.
The main purpose for the existence of `ObsView` is to delay
data access and movement until an actual batch of data (or single
observation) is needed for some computation. This is particularily
useful when the data is not located in memory, but on the hard
drive or some remote location. In such a scenario one wants to
load the required data only when needed.
Any data access is delayed until `getindex` is called,
and even `getindex` returns the result of
[`obsview`](@ref) which in general avoids data movement until
[`getobs`](@ref) is called.
If used as an iterator, the view will iterate over the dataset
once, effectively denoting an epoch. Each iteration will return a
lazy subset to the current observation.
# Arguments
- **`data`** : The object describing the dataset. Can be of any
type as long as it implements [`getobs`](@ref) and
[`numobs`](@ref) (see Details for more information).
- **`indices`** : Optional. The index or indices of the
observation(s) in `data` that the subset should represent.
Can be of type `Int` or some subtype of `AbstractVector`.
# Methods
- **`getindex`** : Returns the observation(s) of the given
index/indices. No data is copied aside
from the required indices.
- **`numobs`** : Returns the total number observations in the subset.
- **`getobs`** : Returns the underlying data that the
`ObsView` represents at the given relative indices. Note
that these indices are in "subset space", and in general will
not directly correspond to the same indices in the underlying
data set.
# Details
For `ObsView` to work on some data structure, the desired type
`MyType` must implement the following interface:
- `getobs(data::MyType, idx)` :
Should return the observation(s) indexed by `idx`.
In what form is up to the user.
Note that `idx` can be of type `Int` or `AbstractVector`.
- `numobs(data::MyType)` :
Should return the total number of observations in `data`
The following methods can also be provided and are optional:
- `getobs(data::MyType)` :
By default this function is the identity function.
If that is not the behaviour that you want for your type,
you need to provide this method as well.
- `obsview(data::MyType, idx)` :
If your custom type has its own kind of subset type, you can
return it here. An example for such a case are `SubArray` for
representing a subset of some `AbstractArray`.
- `getobs!(buffer, data::MyType, [idx])` :
Inplace version of `getobs(data, idx)`. If this method
is provided for `MyType`, then `eachobs` can preallocate a buffer that is then reused
every iteration. Note: `buffer` should be equivalent to the
return value of `getobs(::MyType, ...)`, since this is how
`buffer` is preallocated by default.
# Examples
```julia
X, Y = MLUtils.load_iris()
# The iris set has 150 observations and 4 features
@assert size(X) == (4,150)
# Represents the 80 observations as a ObsView
v = ObsView(X, 21:100)
@assert numobs(v) == 80
@assert typeof(v) <: ObsView
# getobs indexes into v
@assert getobs(v, 1:10) == X[:, 21:30]
# Use `obsview` to avoid boxing into ObsView
# for types that provide a custom "subset", such as arrays.
# Here it instead creates a native SubArray.
v = obsview(X, 1:100)
@assert numobs(v) == 100
@assert typeof(v) <: SubArray
# Also works for tuples of arbitrary length
subset = obsview((X, Y), 1:100)
@assert numobs(subset) == 100
@assert typeof(subset) <: Tuple # tuple of SubArray
# Use as iterator
for x in ObsView(X)
@assert typeof(x) <: SubArray{Float64,1}
end
# iterate over each individual labeled observation
for (x, y) in ObsView((X, Y))
@assert typeof(x) <: SubArray{Float64,1}
@assert typeof(y) <: String
end
# same but in random order
for (x, y) in ObsView(shuffleobs((X, Y)))
@assert typeof(x) <: SubArray{Float64,1}
@assert typeof(y) <: String
end
# Indexing: take first 10 observations
x, y = ObsView((X, Y))[1:10]
```
# See also
[`obsview`](@ref), [`getobs`](@ref), [`numobs`](@ref),
[`splitobs`](@ref), [`shuffleobs`](@ref),
[`kfolds`](@ref).
"""
struct ObsView{Tdata, I<:Union{Int,AbstractVector}} <: AbstractDataContainer
data::Tdata
indices::I
function ObsView(data::T, indices::I) where {T,I}
1 <= minimum(indices) || throw(BoundsError(data, indices))
maximum(indices) <= numobs(data) || throw(BoundsError(data, indices))
new{T,I}(data, indices)
end
end
ObsView(data) = ObsView(data, 1:numobs(data))
# # don't nest subsets
ObsView(subset::ObsView) = subset
function ObsView(subset::ObsView, indices::Union{Int,AbstractVector})
ObsView(subset.data, subset.indices[indices])
end
function Base.show(io::IO, subset::ObsView)
if get(io, :compact, false)
print(io, "ObsView{", typeof(subset.data), "} with " , numobs(subset), " observations")
else
print(io, summary(subset), "\n ", numobs(subset), " observations")
end
end
function Base.summary(subset::ObsView)
io = IOBuffer()
print(io, typeof(subset).name.name, "(")
Base.showarg(io, subset.data, false)
print(io, ", ")
Base.showarg(io, subset.indices, false)
print(io, ')')
first(readlines(seek(io,0)))
end
# compare if both subsets cover the same observations of the same data
# we don't care how the indices are stored, just that they match
# in order and values
function Base.:(==)(s1::ObsView, s2::ObsView)
s1.data == s2.data && s1.indices == s2.indices
end
Base.IteratorEltype(::Type{<:ObsView}) = Base.EltypeUnknown()
@propagate_inbounds Base.getindex(subset::ObsView, idx) =
obsview(subset.data, subset.indices[idx])
Base.length(subset::ObsView) = length(subset.indices)
getobs(subset::ObsView) = getobs(subset.data, subset.indices)
@propagate_inbounds getobs(subset::ObsView, idx) = getobs(subset.data, subset.indices[idx])
getobs!(buffer, subset::ObsView) = getobs!(buffer, subset.data, subset.indices)
@propagate_inbounds getobs!(buffer, subset::ObsView, idx) = getobs!(buffer, subset.data, subset.indices[idx])
Base.parent(x::ObsView) = x.data
# --------------------------------------------------------------------
"""
obsview(data, [indices])
Returns a lazy view of the observations in `data` that
correspond to the given `indices`. No data will be copied except
of the indices. It is similar to constructing an [`ObsView`](@ref),
but returns a `SubArray` if the type of
`data` is `Array` or `SubArray`. Furthermore, this function may
be extended for custom types of `data` that also want to provide
their own subset-type.
In case `data` is a tuple, the constructor will be mapped
over its elements. That means that the constructor returns a
tuple of `ObsView` instead of a `ObsView` of tuples.
If instead you want to get the subset of observations
corresponding to the given `indices` in their native type, use
`getobs`.
See [`ObsView`](@ref) for more information.
"""
obsview(data, indices=1:numobs(data)) = ObsView(data, indices)
##### Arrays / SubArrays
obsview(A::SubArray) = A
function obsview(A::AbstractArray{T,N}, idx) where {T,N}
I = ntuple(_ -> :, N-1)
return view(A, I..., idx)
end
getobs(a::SubArray) = getobs(a.parent, last(a.indices))
##### Tuples / NamedTuples
function obsview(tup::Union{Tuple, NamedTuple}, indices)
map(data -> obsview(data, indices), tup)
end
| MLUtils | https://github.com/JuliaML/MLUtils.jl.git |
|
[
"MIT"
] | 0.4.4 | b45738c2e3d0d402dffa32b2c1654759a2ac35a4 | code | 6398 | """
eachobsparallel(data; buffer, executor, channelsize)
Construct a data iterator over observations in container `data`.
It uses available threads as workers to load observations in
parallel, leading to large speedups when threads are available.
To ensure that the active Julia session has multiple threads
available, check that `Threads.nthreads() > 1`. You can start
Julia with multiple threads with the `-t n` option. If your data
loading is bottlenecked by the CPU, it is recommended to set `n`
to the number of physical CPU cores.
## Arguments
- `data`: a data container that implements `getindex/getobs` and `length/numobs`
- `buffer = false`: whether to use inplace data loading with `getobs!`. Only use
this if you need the additional performance and `getobs!` is implemented for
`data`. Setting `buffer = true` means that when using the iterator, an
observation is only valid for the current loop iteration.
You can also pass in a preallocated `buffer = getobs(data, 1)`.
- `executor = Folds.ThreadedEx()`: task scheduler
You may specify a different task scheduler which can
be any `Folds.Executor`.
- `channelsize = Threads.nthreads()`: the number of observations that are prefetched.
Increasing `channelsize` can lead to speedups when per-observation processing
time is irregular but will cause higher memory usage.
"""
function eachobsparallel(
data;
executor::Executor = _default_executor(),
buffer = false,
channelsize = Threads.nthreads())
if buffer
return _eachobsparallel_buffered(data, executor; channelsize)
else
return _eachobsparallel_unbuffered(data, executor; channelsize)
end
end
function _eachobsparallel_buffered(
data,
executor;
buffer = getobs(data, 1),
channelsize=Threads.nthreads())
buffers = [buffer]
foreach(_ -> push!(buffers, deepcopy(buffer)), 1:channelsize)
# This ensures the `Loader` will take from the `RingBuffer`s result
# channel, and that a new results channel is created on repeated
# iteration. (Since `Loader`) closes the previous at the end of
# each iteration.
setup_channel(sz) = RingBuffer(buffers)
return Loader(1:numobs(data); executor, channelsize, setup_channel) do ringbuffer, i
# Internally, `RingBuffer` will `put!` the result in the results channel
put!(ringbuffer) do buf
getobs!(buf, data, i)
end
end
end
function _eachobsparallel_unbuffered(data, executor; channelsize=Threads.nthreads())
return Loader(1:numobs(data); executor, channelsize) do ch, i
obs = getobs(data, i)
put!(ch, obs)
end
end
# Unlike DataLoaders.jl, this currently does not use task pools
# since `ThreadedEx` has shown to be more performant. This may
# change in the future.
# See PR 33 https://github.com/JuliaML/MLUtils.jl/pull/33
_default_executor() = ThreadedEx()
# ## Internals
# The `Loader` handles the asynchronous iteration and fills
# a result channel.
"""
Loader(f, args; executor, channelsize, setup_channel)
Create a threaded iterator that iterates over `(f(arg) for arg in args)`
using threads that prefill a channel of length `channelsize`.
Note: results may not be returned in the correct order, depending on
`executor`.
"""
struct Loader
f
argiter::AbstractVector
executor::Executor
channelsize::Int
setup_channel
end
function Loader(
f,
argiter;
executor=_default_executor(),
channelsize=Threads.nthreads(),
setup_channel = sz -> Channel(sz))
Loader(f, argiter, executor, channelsize, setup_channel)
end
Base.length(loader::Loader) = length(loader.argiter)
struct LoaderState
spawnertask::Any
channel::Any
remaining::Any
end
function Base.iterate(loader::Loader)
ch = loader.setup_channel(loader.channelsize)
task = @async begin
@floop loader.executor for arg in loader.argiter
try
loader.f(ch, arg)
catch e
close(ch, e)
rethrow()
end
end
end
return Base.iterate(loader, LoaderState(task, ch, length(loader.argiter)))
end
function Base.iterate(::Loader, state::LoaderState)
if state.remaining == 0
close(state.channel)
return nothing
else
result = take!(state.channel)
return result, LoaderState(state.spawnertask, state.channel, state.remaining - 1)
end
end
# The `RingBuffer` ensures that the same buffers are reused
# and the loading works asynchronously.
"""
RingBuffer(size, buffer)
RingBuffer(buffers)
A `Channel`-like data structure that rotates through
`size` buffers. You can either pass in a vector of `buffers`, or
a single `buffer` that is copied `size` times.
`put!`s work by mutating one of the buffers:
```
put!(ringbuffer) do buf
rand!(buf)
end
```
The result can then be `take!`n:
```
res = take!(ringbuffer)
```
!!! warning "Invalidation"
Only one result is valid at a time! On the next `take!`, the previous
result will be reused as a buffer and be mutated by a `put!`
"""
mutable struct RingBuffer{T}
buffers::Channel{T}
results::Channel{T}
current::T
end
function RingBuffer(bufs::Vector{T}) where T
size = length(bufs) - 1
ch_buffers = Channel{T}(size + 1)
ch_results = Channel{T}(size)
foreach(bufs[begin+1:end]) do buf
put!(ch_buffers, buf)
end
return RingBuffer{T}(ch_buffers, ch_results, bufs[begin])
end
function Base.take!(ringbuffer::RingBuffer)
put!(ringbuffer.buffers, ringbuffer.current)
ringbuffer.current = take!(ringbuffer.results)
return ringbuffer.current
end
"""
put!(f!, ringbuffer::RingBuffer)
Apply f! to a buffer in `ringbuffer` and put into the results
channel.
```julia
x = rand(10, 10)
ringbuffer = RingBuffer(1, x)
put!(ringbuffer) do buf
@test x == buf
copy!(buf, rand(10, 10))
end
x_ = take!(ringbuffer)
@test !(x ≈ x_)
```
"""
function Base.put!(f!, ringbuffer::RingBuffer)
buf = take!(ringbuffer.buffers)
buf_ = f!(buf)
put!(ringbuffer.results, buf_)
return buf_
end
Base.put!(c::Channel, b::MLUtils.RingBuffer) = throw(MethodError(put!, (c, b)))
function Base.close(ringbuffer::RingBuffer, args...)
close(ringbuffer.results, args...)
close(ringbuffer.buffers, args...)
end
| MLUtils | https://github.com/JuliaML/MLUtils.jl.git |
|
[
"MIT"
] | 0.4.4 | b45738c2e3d0d402dffa32b2c1654759a2ac35a4 | code | 364 | # TODO: allow passing a rng as first parameter
"""
randobs(data, [n])
Pick a random observation or a batch of `n` random observations
from `data`.
For this function to work, the type of `data` must implement
[`numobs`](@ref) and [`getobs`](@ref).
"""
randobs(data) = getobs(data, rand(1:numobs(data)))
randobs(data, n) = getobs(data, rand(1:numobs(data), n)) | MLUtils | https://github.com/JuliaML/MLUtils.jl.git |
|
[
"MIT"
] | 0.4.4 | b45738c2e3d0d402dffa32b2c1654759a2ac35a4 | code | 6343 | """
oversample(data, classes; fraction=1, shuffle=true)
oversample(data::Tuple; fraction=1, shuffle=true)
Generate a re-balanced version of `data` by repeatedly sampling
existing observations in such a way that every class will have at
least `fraction` times the number observations of the largest
class in `classes`. This way, all classes will have a minimum number of
observations in the resulting data set relative to what largest
class has in the given (original) `data`.
As an example, by default (i.e. with `fraction = 1`) the
resulting dataset will be near perfectly balanced. On the other
hand, with `fraction = 0.5` every class in the resulting data
with have at least 50% as many observations as the largest class.
The `classes` input is an array with the same length as `numobs(data)`.
The convenience parameter `shuffle` determines if the
resulting data will be shuffled after its creation; if it is not
shuffled then all the repeated samples will be together at the
end, sorted by class. Defaults to `true`.
The output will contain both the resampled data and classes.
```julia
# 6 observations with 3 features each
X = rand(3, 6)
# 2 classes, severely imbalanced
Y = ["a", "b", "b", "b", "b", "a"]
# oversample the class "a" to match "b"
X_bal, Y_bal = oversample(X, Y)
# this results in a bigger dataset with repeated data
@assert size(X_bal) == (3,8)
@assert length(Y_bal) == 8
# now both "a", and "b" have 4 observations each
@assert sum(Y_bal .== "a") == 4
@assert sum(Y_bal .== "b") == 4
```
For this function to work, the type of `data` must implement
[`numobs`](@ref) and [`getobs`](@ref).
Note that if `data` is a tuple and `classes` is not given,
then it will be assumed that the last element of the tuple contains the classes.
```julia
julia> data = DataFrame(X1=rand(6), X2=rand(6), Y=[:a,:b,:b,:b,:b,:a])
6×3 DataFrames.DataFrame
│ Row │ X1 │ X2 │ Y │
├─────┼───────────┼─────────────┼───┤
│ 1 │ 0.226582 │ 0.0443222 │ a │
│ 2 │ 0.504629 │ 0.722906 │ b │
│ 3 │ 0.933372 │ 0.812814 │ b │
│ 4 │ 0.522172 │ 0.245457 │ b │
│ 5 │ 0.505208 │ 0.11202 │ b │
│ 6 │ 0.0997825 │ 0.000341996 │ a │
julia> getobs(oversample(data, data.Y))
8×3 DataFrame
Row │ X1 X2 Y
│ Float64 Float64 Symbol
─────┼─────────────────────────────
1 │ 0.376304 0.100022 a
2 │ 0.467095 0.185437 b
3 │ 0.481957 0.319906 b
4 │ 0.336762 0.390811 b
5 │ 0.376304 0.100022 a
6 │ 0.427064 0.0648339 a
7 │ 0.427064 0.0648339 a
8 │ 0.457043 0.490688 b
```
See [`ObsView`](@ref) for more information on data subsets.
See also [`undersample`](@ref).
"""
function oversample(data, classes; fraction=1, shuffle::Bool=true)
lm = group_indices(classes)
maxcount = maximum(length, values(lm))
fraccount = round(Int, fraction * maxcount)
# firstly we will start by keeping everything
inds = collect(1:numobs(data))
for (lbl, inds_for_lbl) in lm
num_extra_needed = fraccount - length(inds_for_lbl)
while num_extra_needed > length(inds_for_lbl)
num_extra_needed -= length(inds_for_lbl)
append!(inds, inds_for_lbl)
end
if num_extra_needed > 0
if shuffle
append!(inds, sample(inds_for_lbl, num_extra_needed; replace=false))
else
append!(inds, inds_for_lbl[1:num_extra_needed])
end
end
end
shuffle && shuffle!(inds)
return obsview(data, inds), obsview(classes, inds)
end
function oversample(data::Tuple; kws...)
d, c = oversample(data[1:end-1], data[end]; kws...)
return (d..., c)
end
"""
undersample(data, classes; shuffle=true)
Generate a class-balanced version of `data` by subsampling its
observations in such a way that the resulting number of
observations will be the same number for every class. This way,
all classes will have as many observations in the resulting data
set as the smallest class has in the given (original) `data`.
The convenience parameter `shuffle` determines if the
resulting data will be shuffled after its creation; if it is not
shuffled then all the observations will be in their original
order. Defaults to `false`.
The output will contain both the resampled data and classes.
```julia
# 6 observations with 3 features each
X = rand(3, 6)
# 2 classes, severely imbalanced
Y = ["a", "b", "b", "b", "b", "a"]
# subsample the class "b" to match "a"
X_bal, Y_bal = undersample(X, Y)
# this results in a smaller dataset
@assert size(X_bal) == (3,4)
@assert length(Y_bal) == 4
# now both "a", and "b" have 2 observations each
@assert sum(Y_bal .== "a") == 2
@assert sum(Y_bal .== "b") == 2
```
For this function to work, the type of `data` must implement
[`numobs`](@ref) and [`getobs`](@ref).
Note that if `data` is a tuple, then it will be assumed that the
last element of the tuple contains the targets.
```julia
julia> data = DataFrame(X1=rand(6), X2=rand(6), Y=[:a,:b,:b,:b,:b,:a])
6×3 DataFrames.DataFrame
│ Row │ X1 │ X2 │ Y │
├─────┼───────────┼─────────────┼───┤
│ 1 │ 0.226582 │ 0.0443222 │ a │
│ 2 │ 0.504629 │ 0.722906 │ b │
│ 3 │ 0.933372 │ 0.812814 │ b │
│ 4 │ 0.522172 │ 0.245457 │ b │
│ 5 │ 0.505208 │ 0.11202 │ b │
│ 6 │ 0.0997825 │ 0.000341996 │ a │
julia> getobs(undersample(data, data.Y))
4×3 DataFrame
Row │ X1 X2 Y
│ Float64 Float64 Symbol
─────┼─────────────────────────────
1 │ 0.427064 0.0648339 a
2 │ 0.376304 0.100022 a
3 │ 0.467095 0.185437 b
4 │ 0.457043 0.490688 b
```
See [`ObsView`](@ref) for more information on data subsets.
See also [`oversample`](@ref).
"""
function undersample(data, classes; shuffle::Bool=true)
lm = group_indices(classes)
mincount = minimum(length, values(lm))
inds = Int[]
for (lbl, inds_for_lbl) in lm
if shuffle
append!(inds, sample(inds_for_lbl, mincount; replace=false))
else
append!(inds, inds_for_lbl[1:mincount])
end
end
shuffle ? shuffle!(inds) : sort!(inds)
return obsview(data, inds), obsview(classes, inds)
end
function undersample(data::Tuple; kws...)
d, c = undersample(data[1:end-1], data[end]; kws...)
return (d..., c)
end
| MLUtils | https://github.com/JuliaML/MLUtils.jl.git |
|
[
"MIT"
] | 0.4.4 | b45738c2e3d0d402dffa32b2c1654759a2ac35a4 | code | 2381 | """
splitobs(n::Int; at) -> Tuple
Compute the indices for two or more disjoint subsets of
the range `1:n` with splits given by `at`.
# Examples
```julia
julia> splitobs(100, at=0.7)
(1:70, 71:100)
julia> splitobs(100, at=(0.1, 0.4))
(1:10, 11:50, 51:100)
```
"""
splitobs(n::Int; at) = _splitobs(n, at)
_splitobs(n::Int, at::Integer) = _splitobs(n::Int, at / n)
_splitobs(n::Int, at::NTuple{N, <:Integer}) where {N} = _splitobs(n::Int, at ./ n)
_splitobs(n::Int, at::Tuple{}) = (1:n,)
function _splitobs(n::Int, at::AbstractFloat)
0 <= at <= 1 || throw(ArgumentError("the parameter \"at\" must be in interval (0, 1)"))
n1 = clamp(round(Int, at*n), 0, n)
(1:n1, n1+1:n)
end
function _splitobs(n::Int, at::NTuple{N,<:AbstractFloat}) where N
at1 = first(at)
a, b = _splitobs(n::Int, at1)
n1 = a.stop
n2 = b.stop
at2 = Base.tail(at) .* n ./ (n2 - n1)
rest = map(x -> n1 .+ x, _splitobs(n2-n1, at2))
return (a, rest...)
end
"""
splitobs(data; at, shuffle=false) -> Tuple
Partition the `data` into two or more subsets.
When `at` is a number (between 0 and 1) this specifies the proportion in the first subset.
When `at` is a tuple, each entry specifies the proportion an a subset,
with the last having `1-sum(at)`. In all there are `length(at)+1` subsets returned.
If `shuffle=true`, randomly permute the observations before splitting.
Supports any datatype implementing the [`numobs`](@ref) and
[`getobs`](@ref) interfaces -- including arrays, tuples & NamedTuples of arrays.
# Examples
```jldoctest
julia> splitobs(permutedims(1:100); at=0.7) # simple 70%-30% split, of a matrix
([1 2 … 69 70], [71 72 … 99 100])
julia> data = (x=ones(2,10), n=1:10) # a NamedTuple, consistent last dimension
(x = [1.0 1.0 … 1.0 1.0; 1.0 1.0 … 1.0 1.0], n = 1:10)
julia> splitobs(data, at=(0.5, 0.3)) # a 50%-30%-20% split, e.g. train/test/validation
((x = [1.0 1.0 … 1.0 1.0; 1.0 1.0 … 1.0 1.0], n = 1:5), (x = [1.0 1.0 1.0; 1.0 1.0 1.0], n = 6:8), (x = [1.0 1.0; 1.0 1.0], n = 9:10))
julia> train, test = splitobs((permutedims(1.0:100.0), 101:200), at=0.7, shuffle=true); # split a Tuple
julia> vec(test[1]) .+ 100 == test[2]
true
```
"""
function splitobs(data; at, shuffle::Bool=false)
if shuffle
data = shuffleobs(data)
end
n = numobs(data)
return map(idx -> obsview(data, idx), splitobs(n; at))
end
| MLUtils | https://github.com/JuliaML/MLUtils.jl.git |
|
[
"MIT"
] | 0.4.4 | b45738c2e3d0d402dffa32b2c1654759a2ac35a4 | code | 19936 | # Some general utility functions. Many of them were part of Flux.jl
"""
unsqueeze(x; dims)
Return `x` reshaped into an array one dimensionality higher than `x`,
where `dims` indicates in which dimension `x` is extended.
`dims` can be an integer between 1 and `ndims(x)+1`.
See also [`flatten`](@ref), [`stack`](@ref).
# Examples
```jldoctest
julia> unsqueeze([1 2; 3 4], dims=2)
2×1×2 Array{Int64, 3}:
[:, :, 1] =
1
3
[:, :, 2] =
2
4
julia> xs = [[1, 2], [3, 4], [5, 6]]
3-element Vector{Vector{Int64}}:
[1, 2]
[3, 4]
[5, 6]
julia> unsqueeze(xs, dims=1)
1×3 Matrix{Vector{Int64}}:
[1, 2] [3, 4] [5, 6]
```
"""
function unsqueeze(x::AbstractArray{T,N}; dims::Int) where {T, N}
@assert 1 <= dims <= N + 1
sz = ntuple(i -> i < dims ? size(x, i) : i == dims ? 1 : size(x, i - 1), N + 1)
return reshape(x, sz)
end
"""
unsqueeze(; dims)
Returns a function which, acting on an array, inserts a dimension of size 1 at `dims`.
# Examples
```jldoctest
julia> rand(21, 22, 23) |> unsqueeze(dims=2) |> size
(21, 1, 22, 23)
```
"""
unsqueeze(; dims::Int) = Base.Fix2(_unsqueeze, dims)
_unsqueeze(x, dims) = unsqueeze(x; dims)
Base.show_function(io::IO, u::Base.Fix2{typeof(_unsqueeze)}, ::Bool) = print(io, "unsqueeze(dims=", u.x, ")")
"""
unstack(xs; dims)
Unroll the given `xs` into an array of arrays along the given dimension `dims`.
See also [`stack`](@ref), [`unbatch`](@ref),
and [`chunk`](@ref).
# Examples
```jldoctest
julia> unstack([1 3 5 7; 2 4 6 8], dims=2)
4-element Vector{Vector{Int64}}:
[1, 2]
[3, 4]
[5, 6]
[7, 8]
```
"""
unstack(xs; dims) = _unstack(dims, xs)
dims2unstack(::Val{dims}) where dims = dims2unstack(dims)
dims2unstack(dims::Integer) = dims
@inline _unstack(dims, xs) = [copy(selectdim(xs, dims2unstack(dims), i)) for i in axes(xs, dims2unstack(dims))]
"""
chunk(x, n; [dims])
chunk(x; [size, dims])
Split `x` into `n` parts or alternatively, if `size` is an integer, into equal chunks of size `size`.
The parts contain the same number of elements except possibly for the last one that can be smaller.
In case `size` is a collection of integers instead, the elements of `x` are split into chunks of
the given sizes.
If `x` is an array, `dims` can be used to specify along which dimension to
split (defaults to the last dimension).
# Examples
```jldoctest
julia> chunk(1:10, 3)
3-element Vector{UnitRange{Int64}}:
1:4
5:8
9:10
julia> chunk(1:10; size = 2)
5-element Vector{UnitRange{Int64}}:
1:2
3:4
5:6
7:8
9:10
julia> x = reshape(collect(1:20), (5, 4))
5×4 Matrix{Int64}:
1 6 11 16
2 7 12 17
3 8 13 18
4 9 14 19
5 10 15 20
julia> xs = chunk(x, 2, dims=1)
2-element Vector{SubArray{Int64, 2, Matrix{Int64}, Tuple{UnitRange{Int64}, Base.Slice{Base.OneTo{Int64}}}, false}}:
[1 6 11 16; 2 7 12 17; 3 8 13 18]
[4 9 14 19; 5 10 15 20]
julia> xs[1]
3×4 view(::Matrix{Int64}, 1:3, :) with eltype Int64:
1 6 11 16
2 7 12 17
3 8 13 18
julia> xes = chunk(x; size = 2, dims = 2)
2-element Vector{SubArray{Int64, 2, Matrix{Int64}, Tuple{Base.Slice{Base.OneTo{Int64}}, UnitRange{Int64}}, true}}:
[1 6; 2 7; … ; 4 9; 5 10]
[11 16; 12 17; … ; 14 19; 15 20]
julia> xes[2]
5×2 view(::Matrix{Int64}, :, 3:4) with eltype Int64:
11 16
12 17
13 18
14 19
15 20
julia> chunk(1:6; size = [2, 4])
2-element Vector{UnitRange{Int64}}:
1:2
3:6
```
"""
chunk(x; size::Int) = collect(Iterators.partition(x, size))
chunk(x, n::Int) = chunk(x; size = cld(length(x), n))
chunk(x::AbstractArray, n::Int; dims::Int=ndims(x)) = chunk(x; size = cld(size(x, dims), n), dims)
function chunk(x::AbstractArray; size, dims::Int=ndims(x))
idxs = _partition_idxs(x, size, dims)
return [_selectdim(x, dims, i) for i in idxs]
end
"""
chunk(x, partition_idxs; [npartitions, dims])
Partition the array `x` along the dimension `dims` according to the indexes
in `partition_idxs`.
`partition_idxs` must be sorted and contain only positive integers
between 1 and the number of partitions.
If the number of partition `npartitions` is not provided,
it is inferred from `partition_idxs`.
If `dims` is not provided, it defaults to the last dimension.
See also [`unbatch`](@ref).
# Examples
```jldoctest
julia> x = reshape([1:10;], 2, 5)
2×5 Matrix{Int64}:
1 3 5 7 9
2 4 6 8 10
julia> chunk(x, [1, 2, 2, 3, 3])
3-element Vector{SubArray{Int64, 2, Matrix{Int64}, Tuple{Base.Slice{Base.OneTo{Int64}}, UnitRange{Int64}}, true}}:
[1; 2;;]
[3 5; 4 6]
[7 9; 8 10]
```
"""
function chunk(x::AbstractArray{T,N}, partition_idxs::AbstractVector;
npartitions=nothing, dims=ndims(x)) where {T, N}
@assert issorted(partition_idxs) "partition_idxs must be sorted"
m = npartitions === nothing ? maximum(partition_idxs) : npartitions
degrees = NNlib.scatter(+, ones_like(partition_idxs), partition_idxs, dstsize=(m,))
return chunk(x; size=degrees, dims)
end
# work around https://github.com/JuliaML/MLUtils.jl/issues/103
_selectdim(x::AbstractArray, dims::Int, i) = selectdim(x, dims, i)
_selectdim(x::AbstractArray, dims::Int, i::UnitRange) = _selectdim(x, Val(dims), i)
function _selectdim(x::AbstractArray{T,N}, ::Val{dims}, i::UnitRange) where {T,N,dims}
return view(x, ntuple(_ -> Colon(), dims-1)..., i, ntuple(_ -> Colon(), N-dims)...)
end
function rrule(::typeof(chunk), x::AbstractArray; size, dims::Int=ndims(x))
# This is the implementation of chunk
idxs = _partition_idxs(x, size, dims)
y = [_selectdim(x, dims, i) for i in idxs]
valdims = Val(dims)
# TODO avoid capturing x in the pullback
chunk_pullback(dy) = (NoTangent(), ∇chunk(unthunk(dy), x, idxs, valdims))
return y, chunk_pullback
end
_partition_idxs(x, size::Int, dims::Int) = Iterators.partition(axes(x, dims), size)
_partition_idxs(x, size, dims::Int) = _partition_idxs(x, collect(size), dims)
function _partition_idxs(x, size::AbstractVector{<:Integer}, dims::Int)
n = length(axes(x, dims))
cumsz = cumsum(size)
if cumsz[end] != n
throw(ArgumentError("The sum of the sizes must be equal to $n, the length of the dimension."))
end
return [(i==1 ? 1 : cumsz[i-1]+1):cumsz[i] for i=1:length(cumsz)]
end
@non_differentiable _partition_idxs(::Any...)
# Similar to ∇eachslice https://github.com/JuliaDiff/ChainRules.jl/blob/8108a77a96af5d4b0c460aac393e44f8943f3c5e/src/rulesets/Base/indexing.jl#L77
function ∇chunk(dys, x, idxs, vd::Val{dim}) where {dim}
i1 = findfirst(dy -> !(dy isa AbstractZero), dys)
if i1 === nothing # all slices are Zero!
return _zero_fill!(similar(x, float(eltype(x))))
end
T = promote_type(eltype(dys[i1]), eltype(x))
# The whole point of this gradient is that we can allocate one `dx` array:
dx = similar(x, T)
for (k, i) in enumerate(idxs)
slice = _selectdim(dx, dim, i)
if dys[k] isa AbstractZero
_zero_fill!(slice) # Avoids this: copyto!([1,2,3], ZeroTangent()) == [0,2,3]
else
copyto!(slice, dys[k])
end
end
return ProjectTo(x)(dx)
end
_zero_fill!(dx::AbstractArray{<:Number}) = fill!(dx, zero(eltype(dx)))
_zero_fill!(dx::AbstractArray) = map!(zero, dx, dx)
function rrule(::typeof(∇chunk), dys, x, idxs, vd::Val{dim}) where dim
n = length(dys)
function ∇∇chunk(dz_raw)
dz = chunk(unthunk(dz_raw), n; dims=dim)
return (NoTangent(), dz, NoTangent(), NoTangent(), NoTangent())
end
return ∇chunk(dys, x, idxs, vd), ∇∇chunk
end
"""
group_counts(x)
Count the number of times that each element of `x` appears.
See also [`group_indices`](@ref)
# Examples
```jldoctest
julia> group_counts(['a', 'b', 'b'])
Dict{Char, Int64} with 2 entries:
'a' => 1
'b' => 2
```
"""
function group_counts(x)
fs = Dict{eltype(x),Int}()
for a in x
fs[a] = get(fs, a, 0) + 1
end
return fs
end
"""
group_indices(x) -> Dict
Computes the indices of elements in the vector `x` for each distinct value contained.
This information is useful for resampling strategies, such as stratified sampling.
See also [`group_counts`](@ref).
# Examples
```jldoctest
julia> x = [:yes, :no, :maybe, :yes];
julia> group_indices(x)
Dict{Symbol, Vector{Int64}} with 3 entries:
:yes => [1, 4]
:maybe => [3]
:no => [2]
```
"""
function group_indices(classes::T) where T<:AbstractVector
dict = Dict{eltype(T), Vector{Int}}()
for (idx, elem) in enumerate(classes)
if !haskey(dict, elem)
push!(dict, elem => [idx])
else
push!(dict[elem], idx)
end
end
return dict
end
"""
batch(xs)
Batch the arrays in `xs` into a single array with
an extra dimension.
If the elements of `xs` are tuples, named tuples, or dicts,
the output will be of the same type.
See also [`unbatch`](@ref).
# Examples
```jldoctest
julia> batch([[1,2,3],
[4,5,6]])
3×2 Matrix{Int64}:
1 4
2 5
3 6
julia> batch([(a=[1,2], b=[3,4])
(a=[5,6], b=[7,8])])
(a = [1 5; 2 6], b = [3 7; 4 8])
```
"""
function batch(xs)
# Fallback for generric iterables
@assert length(xs) > 0 "Input should be non-empty"
data = first(xs) isa AbstractArray ?
similar(first(xs), size(first(xs))..., length(xs)) :
Vector{eltype(xs)}(undef, length(xs))
for (i, x) in enumerate(xs)
data[batchindex(data, i)...] = x
end
return data
end
batchindex(xs, i) = (reverse(Base.tail(reverse(axes(xs))))..., i)
batch(xs::AbstractArray{<:AbstractArray}) = stack(xs)
function batch(xs::Vector{<:Tuple})
@assert length(xs) > 0 "Input should be non-empty"
n = length(first(xs))
@assert all(length.(xs) .== n) "Cannot batch tuples with different lengths"
return ntuple(i -> batch([x[i] for x in xs]), n)
end
function batch(xs::Vector{<:NamedTuple})
@assert length(xs) > 0 "Input should be non-empty"
all_keys = [sort(collect(keys(x))) for x in xs]
ks = all_keys[1]
@assert all(==(ks), all_keys) "Cannot batch named tuples with different keys"
NamedTuple(k => batch([x[k] for x in xs]) for k in ks)
end
function batch(xs::Vector{<:Dict})
@assert length(xs) > 0 "Input should be non-empty"
all_keys = [sort(collect(keys(x))) for x in xs]
ks = all_keys[1]
@assert all(==(ks), all_keys) "cannot batch dicts with different keys"
Dict(k => batch([x[k] for x in xs]) for k in ks)
end
"""
unbatch(x)
Reverse of the [`batch`](@ref) operation,
unstacking the last dimension of the array `x`.
See also [`unstack`](@ref) and [`chunk`](@ref).
# Examples
```jldoctest
julia> unbatch([1 3 5 7;
2 4 6 8])
4-element Vector{Vector{Int64}}:
[1, 2]
[3, 4]
[5, 6]
[7, 8]
```
"""
unbatch(x::AbstractArray) = [getobs(x, i) for i in 1:numobs(x)]
unbatch(x::AbstractVector) = x
"""
batchseq(seqs, val = 0)
Take a list of `N` sequences, and turn them into a single sequence where each
item is a batch of `N`. Short sequences will be padded by `val`.
# Examples
```jldoctest
julia> batchseq([[1, 2, 3], [4, 5]], 0)
3-element Vector{Vector{Int64}}:
[1, 4]
[2, 5]
[3, 0]
```
"""
function batchseq(xs, val = 0, n = nothing)
n = n === nothing ? maximum(x -> size(x, ndims(x)), xs) : n
xs_ = [rpad_constant(x, n, val; dims=ndims(x)) for x in xs]
[batch([obsview(xs_[j], i) for j = 1:length(xs_)]) for i = 1:n]
end
"""
rpad_constant(v::AbstractArray, n::Union{Integer, Tuple}, val = 0; dims=:)
Return the given sequence padded with `val` along the dimensions `dims`
up to a maximum length in each direction specified by `n`.
# Examples
```jldoctest
julia> rpad_constant([1, 2], 4, -1) # passing with -1 up to size 4
4-element Vector{Int64}:
1
2
-1
-1
julia> rpad_constant([1, 2, 3], 2) # no padding if length is already greater than n
3-element Vector{Int64}:
1
2
3
julia> rpad_constant([1 2; 3 4], 4; dims=1) # padding along the first dimension
4×2 Matrix{Int64}:
1 2
3 4
0 0
0 0
julia> rpad_constant([1 2; 3 4], 4) # padding along all dimensions by default
4×2 Matrix{Int64}:
1 2
3 4
0 0
0 0
```
"""
function rpad_constant(x::AbstractArray, n::Union{Integer, Tuple}, val=0; dims=:)
ns = _rpad_pads(x, n, dims)
return NNlib.pad_constant(x, ns, val; dims)
end
function _rpad_pads(x, n, dims)
_dims = dims === Colon() ? (1:ndims(x)) : dims
_n = n isa Integer ? ntuple(i -> n, length(_dims)) : n
@assert length(_dims) == length(_n)
ns = ntuple(i -> isodd(i) ? 0 : max(_n[i÷2] - size(x, _dims[i÷2]), 0), 2*length(_n))
return ns
end
@non_differentiable _rpad_pads(::Any...)
"""
flatten(x::AbstractArray)
Reshape arbitrarly-shaped input into a matrix-shaped output,
preserving the size of the last dimension.
See also [`unsqueeze`](@ref).
# Examples
```jldoctest
julia> rand(3,4,5) |> flatten |> size
(12, 5)
```
"""
function flatten(x::AbstractArray)
return reshape(x, :, size(x)[end])
end
"""
normalise(x; dims=ndims(x), ϵ=1e-5)
Normalise the array `x` to mean 0 and standard deviation 1 across the dimension(s) given by `dims`.
Per default, `dims` is the last dimension.
`ϵ` is a small additive factor added to the denominator for numerical stability.
"""
function normalise(x::AbstractArray; dims=ndims(x), ϵ=ofeltype(x, 1e-5))
μ = mean(x, dims=dims)
# σ = std(x, dims=dims, mean=μ, corrected=false) # use this when Zygote#478 gets merged
σ = std(x, dims=dims, corrected=false)
return (x .- μ) ./ (σ .+ ϵ)
end
ofeltype(x, y) = convert(float(eltype(x)), y)
epseltype(x) = eps(float(eltype(x)))
"""
ones_like(x, [element_type=eltype(x)], [dims=size(x)]))
Create an array with the given element type and size, based upon the given source array `x`.
All element of the new array will be set to 1.
The second and third arguments are both optional, defaulting to the given array's eltype and
size. The dimensions may be specified as an integer or as a tuple argument.
See also [`zeros_like`](@ref) and [`fill_like`](@ref).
# Examples
```julia-repl
julia> x = rand(Float32, 2)
2-element Vector{Float32}:
0.8621633
0.5158395
julia> ones_like(x, (3, 3))
3×3 Matrix{Float32}:
1.0 1.0 1.0
1.0 1.0 1.0
1.0 1.0 1.0
julia> using CUDA
julia> x = CUDA.rand(2, 2)
2×2 CuArray{Float32, 2, CUDA.Mem.DeviceBuffer}:
0.82297 0.656143
0.701828 0.391335
julia> ones_like(x, Float64)
2×2 CuArray{Float64, 2, CUDA.Mem.DeviceBuffer}:
1.0 1.0
1.0 1.0
```
"""
ones_like(x::AbstractArray, T::Type, sz=size(x)) = fill!(similar(x, T, sz), 1)
ones_like(x::AbstractArray, sz=size(x)) = ones_like(x, eltype(x), sz)
"""
zeros_like(x, [element_type=eltype(x)], [dims=size(x)]))
Create an array with the given element type and size, based upon the given source array `x`.
All element of the new array will be set to 0.
The second and third arguments are both optional, defaulting to the given array's eltype and
size. The dimensions may be specified as an integer or as a tuple argument.
See also [`ones_like`](@ref) and [`fill_like`](@ref).
# Examples
```julia-repl
julia> x = rand(Float32, 2)
2-element Vector{Float32}:
0.4005432
0.36934233
julia> zeros_like(x, (3, 3))
3×3 Matrix{Float32}:
0.0 0.0 0.0
0.0 0.0 0.0
0.0 0.0 0.0
julia> using CUDA
julia> x = CUDA.rand(2, 2)
2×2 CuArray{Float32, 2, CUDA.Mem.DeviceBuffer}:
0.0695155 0.667979
0.558468 0.59903
julia> zeros_like(x, Float64)
2×2 CuArray{Float64, 2, CUDA.Mem.DeviceBuffer}:
0.0 0.0
0.0 0.0
```
"""
zeros_like(x::AbstractArray, T::Type, sz=size(x)) = fill!(similar(x, T, sz), 0)
zeros_like(x::AbstractArray, sz=size(x)) = zeros_like(x, eltype(x), sz)
"""
rand_like([rng=default_rng()], x, [element_type=eltype(x)], [dims=size(x)])
Create an array with the given element type and size, based upon the given source array `x`.
All element of the new array will be set to a random value.
The last two arguments are both optional, defaulting to the given array's eltype and
size. The dimensions may be specified as an integer or as a tuple argument.
The default random number generator is used, unless a custom one is passed in explicitly
as the first argument.
See also `Base.rand` and [`randn_like`](@ref).
# Examples
```julia-repl
julia> x = ones(Float32, 2)
2-element Vector{Float32}:
1.0
1.0
julia> rand_like(x, (3, 3))
3×3 Matrix{Float32}:
0.780032 0.920552 0.53689
0.121451 0.741334 0.5449
0.55348 0.138136 0.556404
julia> using CUDA
julia> CUDA.ones(2, 2)
2×2 CuArray{Float32, 2, CUDA.Mem.DeviceBuffer}:
1.0 1.0
1.0 1.0
julia> rand_like(x, Float64)
2×2 CuArray{Float64, 2, CUDA.Mem.DeviceBuffer}:
0.429274 0.135379
0.718895 0.0098756
```
"""
rand_like(x::AbstractArray, T::Type, sz=size(x)) = rand!(similar(x, T, sz))
rand_like(x::AbstractArray, sz=size(x)) = rand_like(x, eltype(x), sz)
rand_like(rng::AbstractRNG, x::AbstractArray, T::Type, sz=size(x)) = rand!(rng, similar(x, T, sz))
rand_like(rng::AbstractRNG, x::AbstractArray, sz=size(x)) = rand_like(rng, x, eltype(x), sz)
"""
randn_like([rng=default_rng()], x, [element_type=eltype(x)], [dims=size(x)])
Create an array with the given element type and size, based upon the given source array `x`.
All element of the new array will be set to a random value drawn from a normal distribution.
The last two arguments are both optional, defaulting to the given array's eltype and
size. The dimensions may be specified as an integer or as a tuple argument.
The default random number generator is used, unless a custom one is passed in explicitly
as the first argument.
See also `Base.randn` and [`rand_like`](@ref).
# Examples
```julia-repl
julia> x = ones(Float32, 2)
2-element Vector{Float32}:
1.0
1.0
julia> randn_like(x, (3, 3))
3×3 Matrix{Float32}:
-0.385331 0.956231 0.0745102
1.43756 -0.967328 2.06311
0.0482372 1.78728 -0.902547
julia> using CUDA
julia> CUDA.ones(2, 2)
2×2 CuArray{Float32, 2, CUDA.Mem.DeviceBuffer}:
1.0 1.0
1.0 1.0
julia> randn_like(x, Float64)
2×2 CuArray{Float64, 2, CUDA.Mem.DeviceBuffer}:
-0.578527 0.823445
-1.01338 -0.612053
```
"""
randn_like(x::AbstractArray, T::Type, sz=size(x)) = randn!(similar(x, T, sz))
randn_like(x::AbstractArray, sz=size(x)) = randn_like(x, eltype(x), sz)
randn_like(rng::AbstractRNG, x::AbstractArray, T::Type, sz=size(x)) = randn!(rng, similar(x, T, sz))
randn_like(rng::AbstractRNG, x::AbstractArray, sz=size(x)) = randn_like(rng, x, eltype(x), sz)
"""
fill_like(x, val, [element_type=eltype(x)], [dims=size(x)]))
Create an array with the given element type and size, based upon the given source array `x`.
All element of the new array will be set to `val`.
The third and fourth arguments are both optional, defaulting to the given array's eltype and
size. The dimensions may be specified as an integer or as a tuple argument.
See also [`zeros_like`](@ref) and [`ones_like`](@ref).
# Examples
```julia-repl
julia> x = rand(Float32, 2)
2-element Vector{Float32}:
0.16087806
0.89916044
julia> fill_like(x, 1.7, (3, 3))
3×3 Matrix{Float32}:
1.7 1.7 1.7
1.7 1.7 1.7
1.7 1.7 1.7
julia> using CUDA
julia> x = CUDA.rand(2, 2)
2×2 CuArray{Float32, 2, CUDA.Mem.DeviceBuffer}:
0.803167 0.476101
0.303041 0.317581
julia> fill_like(x, 1.7, Float64)
2×2 CuArray{Float64, 2, CUDA.Mem.DeviceBuffer}:
1.7 1.7
1.7 1.7
```
"""
fill_like(x::AbstractArray, val, T::Type, sz=size(x)) = fill!(similar(x, T, sz), val)
fill_like(x::AbstractArray, val, sz=size(x)) = fill_like(x, val, eltype(x), sz)
@non_differentiable zeros_like(::Any...)
@non_differentiable ones_like(::Any...)
@non_differentiable rand_like(::Any...)
@non_differentiable randn_like(::Any...)
function rrule(::typeof(fill_like), x::AbstractArray, val, T::Type, sz)
function fill_like_pullback(Δ)
return (NoTangent(), ZeroTangent(), sum(Δ), NoTangent(), NoTangent())
end
return fill_like(x, val, T, sz), fill_like_pullback
end
| MLUtils | https://github.com/JuliaML/MLUtils.jl.git |
|
[
"MIT"
] | 0.4.4 | b45738c2e3d0d402dffa32b2c1654759a2ac35a4 | code | 189 | module Datasets
using Random
using DelimitedFiles: readdlm
include("load_datasets.jl")
export load_iris
include("generators.jl")
export make_spiral,
make_poly,
make_sin
end | MLUtils | https://github.com/JuliaML/MLUtils.jl.git |
|
[
"MIT"
] | 0.4.4 | b45738c2e3d0d402dffa32b2c1654759a2ac35a4 | code | 2161 |
"""
make_sin(n, start, stop; noise = 0.3, f_rand = randn) -> x, y
Generates `n` noisy equally spaces samples of a sinus from `start` to `stop`
by adding `noise .* f_rand(length(x))` to the result of `fun(x)`.
"""
function make_sin(n::Int = 50, start::Real = 0, stop::Real = 2π; noise::Real = 0.3, f_rand::Function = randn)
x = collect(range(start, stop=stop, length=n))
y = sin.(x) .+ noise .* f_rand.()
return x, y
end
"""
make_poly(coef, x; noise = 0.01, f_rand = randn) -> x, y
Generates a noisy response for a polynomial of degree `length(coef)`
using the vector `x` as input and adding `noise .* f_randn(length(x))` to the result.
The vector `coef` contains the coefficients for the terms of the polynome.
The first element of `coef` denotes the coefficient for the term with
the highest degree, while the last element of `coef` denotes the intercept.
"""
function make_poly(coef::AbstractVector{R}, x::AbstractVector{T};
noise::Real = 0.1, f_rand::Function = randn) where {T<:Real,R<:Real}
n = length(x)
m = length(coef)
x_vec = collect(x)
y = zeros(n)
@inbounds for i = 1:n
for k = 1:m
y[i] += coef[k] * x_vec[i]^(m-k)
end
end
y .+= noise .* f_rand.()
x_vec, y
end
"""
make_spiral(n, a, theta, b; noise = 0.01, f_rand = randn) -> x, y
Generates `n` noisy responses for a spiral with two labels. Uses the radius, angle
and scaling arguments to space the points in 2D space and adding `noise .* f_randn(n)`
to the response.
"""
function make_spiral(n::Int = 97, a::Real = 6.5, theta::Real = 16.0, b::Real=104.0;
noise::Real = 0.1, f_rand::Function = randn)
x = zeros(Float64, (2, 2*n))
y = zeros(Int, 2*n)
index = 0:1.0:(n-1)
for i = 1:n
_angle = index[i]*pi/theta
_radius = a * (b-index[i]) / b
x_coord = _radius * sin(_angle)
y_coord = _radius * cos(_angle)
x[1, i] = x_coord
x[2, i] = y_coord
x[1, n+i] = -(x_coord)
x[2, n+i] = -(y_coord)
y[i] = 1
y[n+i] = 0
end
x[1, :] .+= noise .* f_rand.()
x[2, :] .+= noise .* f_rand.()
x, y
end | MLUtils | https://github.com/JuliaML/MLUtils.jl.git |
|
[
"MIT"
] | 0.4.4 | b45738c2e3d0d402dffa32b2c1654759a2ac35a4 | code | 827 | DATAPATH = joinpath(@__DIR__, "data")
"""
load_iris() -> X, y, names
Loads the first 150 observations from the
Iris flower data set introduced by Ronald Fisher (1936).
The 4 by 150 matrix `X` contains the numeric measurements,
in which each individual column denotes an observation.
The vector `y` contains the class labels as strings.
The vector `names` contains the names of the features (i.e. rows of `X`)
[1] Fisher, Ronald A. "The use of multiple measurements in taxonomic problems." Annals of eugenics 7.2 (1936): 179-188.
"""
function load_iris()
path = joinpath(DATAPATH, "iris.csv")
raw_csv = readdlm(path, ',')
X = convert(Matrix{Float64}, raw_csv[:, 1:4]')
y = convert(Vector{String}, raw_csv[:, 5])
vars = ["Sepal length", "Sepal width", "Petal length", "Petal width"]
X, y, vars
end
| MLUtils | https://github.com/JuliaML/MLUtils.jl.git |
|
[
"MIT"
] | 0.4.4 | b45738c2e3d0d402dffa32b2c1654759a2ac35a4 | code | 4679 | using MLUtils: obsview
@testset "BatchView" begin
@testset "constructor" begin
@test_throws DimensionMismatch BatchView((rand(2,10),rand(9)))
@test_throws DimensionMismatch BatchView((rand(2,10),rand(9)))
@test_throws DimensionMismatch BatchView((rand(2,10),rand(4,9,10),rand(9)))
@test_throws MethodError BatchView(EmptyType())
for var in (vars..., tuples..., Xs, ys)
@test_throws MethodError BatchView(var...)
@test_throws MethodError BatchView(var, 16)
A = BatchView(var, batchsize=3)
@test length(A) == 5
@test batchsize(A) == 3
@test numobs(A) == length(A)
@test @inferred(parent(A)) === var
end
A = BatchView(X, batchsize=16)
@test length(A) == 1
@test batchsize(A) == 15
end
@testset "collated" begin
@test BatchView(X, batchsize=2, collate=true)[1] |> size == (4, 2)
@test BatchView(X, batchsize=2, collate=false)[1] |> size == (2,)
@test size.(BatchView(tuples[1], batchsize=2, collate=true)[1]) == ((4, 2), (2,))
@test BatchView(tuples[1], batchsize=2, collate=false)[1] |> size == (2,)
end
@testset "typestability" begin
for var in (vars..., tuples..., Xs, ys), batchsize in (1, 3), partial in (true, false), collate in (Val(true), Val(false), Val(nothing))
@test typeof(@inferred(BatchView(var; batchsize, partial, collate))) <: BatchView
end
@test typeof(@inferred(BatchView(CustomType()))) <: BatchView
end
@testset "AbstractArray interface" begin
for var in (vars..., tuples..., Xs, ys)
A = BatchView(var, batchsize=5)
@test_throws BoundsError A[-1]
@test_throws BoundsError A[4]
@test @inferred(numobs(A)) == 3
@test @inferred(length(A)) == 3
@test @inferred(batchsize(A)) == 5
@test @inferred(size(A)) == (3,)
@test @inferred(getobs(A[2:3])) == getobs(BatchView(ObsView(var, 6:15), batchsize=5))
@test @inferred(getobs(A[[1,3]])) == getobs(BatchView(ObsView(var, [1:5..., 11:15...]), batchsize=5))
@test @inferred(A[1]) == obsview(var, 1:5)
@test @inferred(A[2]) == obsview(var, 6:10)
@test @inferred(A[3]) == obsview(var, 11:15)
@test A[end] == A[3]
@test @inferred(getobs(A,1)) == getobs(var, 1:5)
@test @inferred(getobs(A,2)) == getobs(var, 6:10)
@test @inferred(getobs(A,3)) == getobs(var, 11:15)
@test typeof(@inferred(collect(A))) <: Vector
end
for var in (vars..., tuples...)
A = BatchView(var, batchsize=5)
@test @inferred(getobs(A)) == var
@test A[2:3] == obsview(var, [6:15;])
@test A[[1,3]] == obsview(var, [1:5..., 11:15...])
end
end
@testset "subsetting" begin
for var in (vars..., tuples..., Xs, ys)
A = BatchView(var, batchsize=3)
@test getobs(@inferred(ObsView(A))) == @inferred(getobs(A))
@test_throws BoundsError ObsView(A,1:6)
S = @inferred(ObsView(A, 1:2))
@test typeof(S) <: ObsView
@test @inferred(numobs(S)) == 2
@test @inferred(length(S)) == numobs(S)
@test @inferred(size(S)) == (length(S),)
@test getobs(@inferred(A[1:2])) == getobs(S)
@test @inferred(getobs(A,1:2)) == getobs(S)
@test @inferred(getobs(S)) == getobs(BatchView(ObsView(var,1:6),batchsize=3))
S = @inferred(ObsView(A, 1:2))
@test typeof(S) <: ObsView
end
A = BatchView(X, batchsize=3)
@test typeof(A.data) <: Array
S = @inferred(obsview(A))
S === A
end
@testset "obsview and batchview" begin
x = rand(2, 6)
bv = BatchView(x; batchsize=2)
ov = obsview(bv, 1:2)
@test getobs(ov, 1) == x[:,1:2]
end
# @testset "nesting with ObsView" begin
# for var in vars
# @test eltype(@inferred(BatchView(ObsView(var)))[1]) <: Union{SubArray,String}
# end
# for var in tuples
# @test eltype(@inferred(BatchView(ObsView(var)))[1]) <: Tuple
# end
# for var in (Xs, ys)
# @test eltype(@inferred(BatchView(ObsView(var)))[1]) <: SubArray
# end
# end
@testset "partial=false" begin
x = [1:12;]
bv = BatchView(x, batchsize=5, partial=false)
@test length(bv) == 2
@test bv[1] == 1:5
@test bv[2] == 6:10
@test_throws BoundsError bv[3]
end
end
| MLUtils | https://github.com/JuliaML/MLUtils.jl.git |
|
[
"MIT"
] | 0.4.4 | b45738c2e3d0d402dffa32b2c1654759a2ac35a4 | code | 8266 |
@testset "DataLoader" begin
X2 = reshape([1:10;], (2, 5))
Y2 = [1:5;]
d = DataLoader(X2, batchsize=2)
@test_broken @inferred(first(d)) isa Array
batches = collect(d)
@test_broken eltype(d) == typeof(X2)
@test eltype(batches) == typeof(X2)
@test length(batches) == 3
@test batches[1] == X2[:,1:2]
@test batches[2] == X2[:,3:4]
@test batches[3] == X2[:,5:5]
d = DataLoader(X2, batchsize=2, partial=false)
# @inferred first(d)
batches = collect(d)
@test_broken eltype(d) == typeof(X2)
@test length(batches) == 2
@test batches[1] == X2[:,1:2]
@test batches[2] == X2[:,3:4]
d = DataLoader((X2,), batchsize=2, partial=false)
# @inferred first(d)
batches = collect(d)
@test_broken eltype(d) == Tuple{typeof(X2)}
@test eltype(batches) == Tuple{typeof(X2)}
@test length(batches) == 2
@test batches[1] == (X2[:,1:2],)
@test batches[2] == (X2[:,3:4],)
d = DataLoader((X2, Y2), batchsize=2)
# @inferred first(d)
batches = collect(d)
@test_broken eltype(d) == Tuple{typeof(X2), typeof(Y2)}
@test eltype(batches) == Tuple{typeof(X2), typeof(Y2)}
@test length(batches) == 3
@test length(batches[1]) == 2
@test length(batches[2]) == 2
@test length(batches[3]) == 2
@test batches[1][1] == X2[:,1:2]
@test batches[1][2] == Y2[1:2]
@test batches[2][1] == X2[:,3:4]
@test batches[2][2] == Y2[3:4]
@test batches[3][1] == X2[:,5:5]
@test batches[3][2] == Y2[5:5]
# test with NamedTuple
d = DataLoader((x=X2, y=Y2), batchsize=2)
# @inferred first(d)
batches = collect(d)
@test_broken eltype(d) == NamedTuple{(:x, :y), Tuple{typeof(X2), typeof(Y2)}}
@test eltype(batches) == NamedTuple{(:x, :y), Tuple{typeof(X2), typeof(Y2)}}
@test length(batches) == 3
@test length(batches[1]) == 2
@test length(batches[2]) == 2
@test length(batches[3]) == 2
@test batches[1][1] == batches[1].x == X2[:,1:2]
@test batches[1][2] == batches[1].y == Y2[1:2]
@test batches[2][1] == batches[2].x == X2[:,3:4]
@test batches[2][2] == batches[2].y == Y2[3:4]
@test batches[3][1] == batches[3].x == X2[:,5:5]
@test batches[3][2] == batches[3].y == Y2[5:5]
@testset "iteration default batchsize (+1)" begin
# test iteration
X3 = zeros(2, 10)
d = DataLoader(X3)
for x in d
@test size(x) == (2,1)
end
# test iteration
X3 = ones(2, 10)
Y3 = fill(5, 10)
d = DataLoader((X3, Y3))
for (x, y) in d
@test size(x) == (2,1)
@test y == [5]
end
end
@testset "partial=false" begin
x = [1:12;]
d = DataLoader(x, batchsize=5, partial=false) |> collect
@test length(d) == 2
@test d[1] == 1:5
@test d[2] == 6:10
end
@testset "shuffle & rng" begin
X4 = rand(2, 1000)
d1 = DataLoader(X4, batchsize=2; shuffle=true)
d2 = DataLoader(X4, batchsize=2; shuffle=true)
@test first(d1) != first(d2)
Random.seed!(17)
d1 = DataLoader(X4, batchsize=2; shuffle=true)
x1 = first(d1)
Random.seed!(17)
d2 = DataLoader(X4, batchsize=2; shuffle=true)
@test x1 == first(d2)
d1 = DataLoader(X4, batchsize=2; shuffle=true, rng=MersenneTwister(1))
d2 = DataLoader(X4, batchsize=2; shuffle=true, rng=MersenneTwister(1))
@test first(d1) == first(d2)
end
# numobs/getobs compatibility
d = DataLoader(CustomType(), batchsize=2)
@test first(d) == [1, 2]
@test length(collect(d)) == 8
@testset "Dict" begin
data = Dict("x" => rand(2,4), "y" => rand(4))
dloader = DataLoader(data, batchsize=2)
@test_broken eltype(dloader) == Dict{String, Array{Float64}}
c = collect(dloader)
@test eltype(c) == Dict{String, Array{Float64}}
@test c[1] == Dict("x" => data["x"][:,1:2], "y" => data["y"][1:2])
@test c[2] == Dict("x" => data["x"][:,3:4], "y" => data["y"][3:4])
data = Dict("x" => rand(2,4), "y" => rand(2,4))
dloader = DataLoader(data, batchsize=2)
@test_broken eltype(dloader) == Dict{String, Matrix{Float64}}
@test eltype(collect(dloader)) == Dict{String, Matrix{Float64}}
end
@testset "range" begin
data = 1:10
dloader = DataLoader(data, batchsize=2)
c = collect(dloader)
@test eltype(c) == UnitRange{Int64}
@test c[1] == 1:2
dloader = DataLoader(data, batchsize=2, shuffle=true)
c = collect(dloader)
@test eltype(c) == Vector{Int}
end
# https://github.com/FluxML/Flux.jl/issues/1935
@testset "no views of arrays" begin
x = CustomArrayNoView(6)
@test_throws ErrorException view(x, 1:2)
d = DataLoader(x)
@test length(collect(d)) == 6 # succesfull iteration
d = DataLoader(x, batchsize=2, shuffle=false)
@test length(collect(d)) == 3 # succesfull iteration
d = DataLoader(x, batchsize=2, shuffle=true)
@test length(collect(d)) == 3 # succesfull iteration
end
@testset "collating" begin
X_ = rand(10, 20)
d = DataLoader(X_, collate=false, batchsize = 2)
for (i, x) in enumerate(d)
@test x == [getobs(X_, 2i-1), getobs(X_, 2i)]
end
d = DataLoader(X_, collate=nothing, batchsize = 2)
for (i, x) in enumerate(d)
@test x == hcat(getobs(X_, 2i-1), getobs(X_, 2i))
end
d = DataLoader(X_, collate=true, batchsize = 2)
for (i, x) in enumerate(d)
@test x == hcat(getobs(X_, 2i-1), getobs(X_, 2i))
end
d = DataLoader((X_, X_), collate=false, batchsize = 2)
for (i, x) in enumerate(d)
@test x isa Vector
all((isa).(x, Tuple))
end
d = DataLoader((X_, X_), collate=true, batchsize = 2)
for (i, x) in enumerate(d)
@test all(==(hcat(getobs(X_, 2i-1), getobs(X_, 2i))), x)
end
@testset "nothing vs. true" begin
d = CustomRangeIndex(10)
@test first(DataLoader(d, batchsize = 2, collate=nothing)) isa UnitRange
@test first(DataLoader(d, batchsize = 2, collate=true)) isa Vector
end
end
@testset "Transducers foldl" begin
dloader = DataLoader(1:10)
@test foldl(+, Map(x -> x[1]), dloader; init = 0) == 55
@inferred foldl(+, Map(x -> x[1]), dloader; init = 0)
dloader = DataLoader(1:10; shuffle = true)
@test foldl(+, Map(x -> x[1]), dloader; init = 0) == 55
dloader = DataLoader(1:10; batchsize = 2)
@test foldl(+, Map(x -> x[1]), dloader; init = 0) == 25
dloader = DataLoader(1:1000; shuffle = false)
@test copy(Map(x -> x[1]), Vector{Int}, dloader) == collect(1:1000)
dloader = DataLoader(1:1000; shuffle = true)
@test copy(Map(x -> x[1]), Vector{Int}, dloader) != collect(1:1000)
dloader = DataLoader(1:1000; batchsize = 2, shuffle = false)
@test copy(Map(x -> x[1]), Vector{Int}, dloader) == collect(1:2:1000)
dloader = DataLoader(1:1000; batchsize = 2, shuffle = true)
@test copy(Map(x -> x[1]), Vector{Int}, dloader) != collect(1:2:1000)
end
if VERSION > v"1.10"
@testset "printing" begin
X2 = reshape(Float32[1:10;], (2, 5))
Y2 = [1:5;]
d = DataLoader((X2, Y2), batchsize=3)
@test contains(repr(d), "DataLoader(::Tuple{Matrix")
@test contains(repr(d), "batchsize=3")
@test contains(repr(MIME"text/plain"(), d), "2-element DataLoader")
@test contains(repr(MIME"text/plain"(), d), "2×3 Matrix{Float32}, 3-element Vector")
d2 = DataLoader((x = X2, y = Y2), batchsize=2, partial=false)
@test contains(repr(d2), "DataLoader(::@NamedTuple")
@test contains(repr(d2), "partial=false")
@test contains(repr(MIME"text/plain"(), d2), "2-element DataLoader(::@NamedTuple")
@test contains(repr(MIME"text/plain"(), d2), "x = 2×2 Matrix{Float32}, y = 2-element Vector")
end
end
end
| MLUtils | https://github.com/JuliaML/MLUtils.jl.git |
|
[
"MIT"
] | 0.4.4 | b45738c2e3d0d402dffa32b2c1654759a2ac35a4 | code | 2221 | @testset "eachobs" begin
for (i,x) in enumerate(eachobs(X))
@test x == X[:,i]
end
for (i,x) in enumerate(eachobs(X, buffer=true))
@test x == X[:,i]
end
b = zeros(size(X, 1))
for (i,x) in enumerate(eachobs(X, buffer=b))
@test x == X[:,i]
end
@test_broken b == X[:,end]
@testset "batched" begin
for (i, x) in enumerate(eachobs(X, batchsize=2, partial=true))
if i != 8
@test size(x) == (4,2)
@test x == X[:,2i-1:2i]
else
@test size(x) == (4,1)
@test x == X[:,2i-1:2i-1]
end
end
for (i, x) in enumerate(eachobs(X, batchsize=2, buffer=true, partial=false))
@test size(x) == (4,2)
@test x == X[:,2i-1:2i]
end
b = zeros(4, 2)
for (i, x) in enumerate(eachobs(X, batchsize=2, buffer=b, partial=false))
@test size(x) == (4,2)
@test x == X[:,2i-1:2i]
end
end
@testset "shuffled" begin
# does not reshuffle on iteration
shuffled = eachobs(shuffleobs(1:50))
@test collect(shuffled) == collect(shuffled)
# does reshuffle
reshuffled = eachobs(1:50, shuffle = true)
@test collect(reshuffled) != collect(reshuffled)
reshuffled = eachobs(1:50, shuffle = true, buffer = true)
@test collect(reshuffled) != collect(reshuffled)
reshuffled = eachobs(1:50, shuffle = true, parallel = true)
@test collect(reshuffled) != collect(reshuffled)
reshuffled = eachobs(1:50, shuffle = true, buffer = true, parallel = true)
@test collect(reshuffled) != collect(reshuffled)
end
@testset "Argument combinations" begin
for batchsize ∈ (-1, 2), buffer ∈ (true, false), collate ∈ (nothing, true, false),
parallel ∈ (true, false), shuffle ∈ (true, false), partial ∈ (true, false)
if !(buffer isa Bool) && batchsize > 0
buffer = getobs(BatchView(X; batchsize), 1)
end
iter = eachobs(X; batchsize, shuffle, buffer, parallel, partial)
@test_nowarn for _ in iter end
end
end
end
| MLUtils | https://github.com/JuliaML/MLUtils.jl.git |
|
[
"MIT"
] | 0.4.4 | b45738c2e3d0d402dffa32b2c1654759a2ac35a4 | code | 1212 | @testset "kfolds" begin
@test collect(kfolds(1:15, k=5)) == collect(kfolds(1:15, 5))
@test kfolds(15, k=5) == kfolds(15, 5)
@testset "int" begin
itrain, ival = kfolds(15, k=5)
@test size(itrain) == (5,)
@test size(ival) == (5,)
@test all(i -> size(i) == (12,), itrain)
@test all(i -> size(i) == (3,), ival)
tot = [[it;iv] for (it, iv) in zip(itrain, ival)]
@test all(x -> sort(x) == 1:15, tot)
end
@testset "data" begin
for (xtr, xval) in kfolds(1:15, k=5)
@test size(xtr) == (12,)
@test size(xval) == (3,)
@test sort([xtr; xval]) == 1:15
end
for ((xtr,ytr), (xval, yval)) in kfolds((1:15, 11:25), k=5)
@test size(xtr) == (12,)
@test size(xval) == (3,)
@test size(ytr) == (12,)
@test size(yval) == (3,)
@test sort([xtr; xval]) == 1:15
@test sort([ytr; yval]) == 11:25
end
end
end
@testset "leavepout" begin
@test leavepout(15) == kfolds(15, k=15)
@test collect(leavepout(1:15)) == collect(kfolds(1:15, 15))
@test collect(leavepout(1:15, p=5)) == collect(kfolds(1:15, 3))
end
| MLUtils | https://github.com/JuliaML/MLUtils.jl.git |
|
[
"MIT"
] | 0.4.4 | b45738c2e3d0d402dffa32b2c1654759a2ac35a4 | code | 6996 | @testset "fallbacks" begin
x = FallbackType()
@test getobs(x, 3) == 1234
@test numobs(x) == 5678
end
@testset "array" begin
a = rand(2,3)
@test numobs(a) == 3
@test @inferred getobs(a, 1) == a[:,1]
@test @inferred getobs(a, 2) == a[:,2]
@test @inferred getobs(a, 1:2) == a[:,1:2]
end
@testset "0-dim SubArray" begin
v = view([3], 1)
@test @inferred(numobs(v)) === 1
@test @inferred(getobs(v, 1)) === 3
@test_throws BoundsError getobs(v, 2)
@test_throws BoundsError getobs(v, 2:3)
end
@testset "named tuple" begin
X2, Y2 = rand(2, 3), rand(3)
dataset = (x=X2, y=Y2)
@test numobs(dataset) == 3
o = @inferred getobs(dataset, 2)
@test o.x == X2[:,2]
@test o.y == Y2[2]
o = @inferred getobs(dataset, 1:2)
@test o.x == X2[:,1:2]
@test o.y == Y2[1:2]
end
@testset "dict" begin
dataset = Dict("X" => X, "y" => y)
@test numobs(dataset) == 15
@test_broken @inferred getobs(dataset, 2) # not inferred
o = getobs(dataset, 2)
@test o["X"] == X[:,2]
@test o["y"] == y[2]
o = getobs(dataset, 1:2)
@test o["X"] == X[:,1:2]
@test o["y"] == y[1:2]
end
@testset "numobs" begin
@test_throws MethodError numobs(X,X)
@test_throws MethodError numobs(X,y)
@testset "Array, SparseArray, and Tuple" begin
@test_throws DimensionMismatch numobs((X,XX,rand(100)))
@test_throws DimensionMismatch numobs((X,X'))
for var in (Xs, ys, vars...)
@test @inferred(numobs(var)) === 15
end
@test @inferred(numobs(())) === 0
end
@testset "SubArray" begin
@test @inferred(numobs(view(X,:,:))) === 15
@test @inferred(numobs(view(X,:,:))) === 15
@test @inferred(numobs(view(XX,:,:,:))) === 15
@test @inferred(numobs(view(XXX,:,:,:,:))) === 15
@test @inferred(numobs(view(y,:))) === 15
@test @inferred(numobs(view(Y,:,:))) === 15
end
end
@testset "getobs" begin
@testset "Array and Subarray" begin
# access outside numobs bounds
@test_throws BoundsError getobs(X, -1)
@test_throws BoundsError getobs(X, 0)
@test_throws BoundsError getobs(X, 16)
for i in (2, 2:10, [2,1,4])
@test getobs(XX, i) == XX[:, :, i]
end
for i in (2, 1:15, 2:10, [2,5,7], [2,1])
@test typeof(getobs(Xv, i)) <: Array
@test typeof(getobs(yv, i)) <: ((i isa Int) ? String : Array)
@test all(getobs(Xv, i) .== X[:, i])
@test getobs(Xv,i) == X[:,i]
@test getobs(X,i) == X[:,i]
@test getobs(XX,i) == XX[:,:,i]
@test getobs(XXX,i) == XXX[:,:,:,i]
@test getobs(y,i) == y[i]
@test getobs(yv,i) == y[i]
@test getobs(Y,i) == Y[:,i]
end
end
@testset "SparseArray" begin
@test typeof(getobs(Xs,2)) <: SparseVector
@test typeof(getobs(Xs,1:5)) <: SparseMatrixCSC
@test typeof(getobs(ys,2)) <: Float64
@test typeof(getobs(ys,1:5)) <: SparseVector
for i in (2, 1:15, 2:10, [2,5,7], [2,1])
@test getobs(Xs,i) == Xs[:,i]
@test getobs(ys,i) == ys[i]
end
end
@testset "Tuple" begin
# bounds checking correctly
@test_throws BoundsError getobs((X,y), 16)
# special case empty tuple
@test @inferred(getobs((), 10)) === ()
tx, ty = getobs((Xv, yv), 2:5)
@test typeof(tx) <: Array
@test typeof(ty) <: Array
for i in (1:15, 2:10, [2,5,7], [2,1])
@test_throws DimensionMismatch getobs((X', y), i)
@test @inferred(getobs((X,y), i)) == (X[:,i], y[i])
@test @inferred(getobs((X,yv), i)) == (X[:,i], y[i])
@test @inferred(getobs((Xv,y), i)) == (X[:,i], y[i])
@test @inferred(getobs((X,Y), i)) == (X[:,i], Y[:,i])
@test @inferred(getobs((X,yt), i)) == (X[:,i], yt[:,i])
@test @inferred(getobs((XX,X,y), i)) == (XX[:,:,i], X[:,i], y[i])
# compare if obs match in tuple
x1, y1 = getobs((X1,Y1), i)
@test all(x1' .== y1)
x1, y1, z1 = getobs((X1,Y1,sparse(X1)), i)
@test all(x1' .== y1)
@test all(x1 .== z1)
end
@test getobs((Xv,y), 2) == (X[:,2], y[2])
@test getobs((X,yv), 2) == (X[:,2], y[2])
@test getobs((X,Y), 2) == (X[:,2], Y[:,2])
@test getobs((XX,X,y), 2) == (XX[:,:,2], X[:,2], y[2])
end
end
@testset "getobs!" begin
@testset "Array and Subarray" begin
Xbuf = similar(X)
getobs!(Xbuf, X)
@test Xbuf == X
# access outside numobs bounds
@test_throws BoundsError getobs!(Xbuf, X, -1)
@test_throws BoundsError getobs!(Xbuf, X, 0)
@test_throws BoundsError getobs!(Xbuf, X, 151)
buff = zeros(4)
@test @inferred(getobs!(buff, X, 5)) == getobs(X, 5)
buff = zeros(4, 8)
@test @inferred(getobs!(buff, X, 3:10)) == getobs(X, 3:10)
buff = zeros(20,30)
@test @inferred(getobs!(buff, XX, 5)) == XX[:,:,5]
buff = zeros(20, 30, 5)
@test @inferred(getobs!(buff, XX, 6:10)) == XX[:,:,6:10]
# string vector
@test getobs!("setosa", y, 1) == "setosa"
@test getobs!(nothing, y, 1) == "setosa"
end
@testset "SparseArray" begin
# Sparse Arrays opt-out of buffer usage
@test @inferred(getobs!(nothing, Xs, 1)) == getobs(Xs, 1)
@test @inferred(getobs!(nothing, Xs, 5:10)) == getobs(Xs, 5:10)
@test @inferred(getobs!(nothing, ys, 1)) === getobs(ys, 1)
@test @inferred(getobs!(nothing, ys, 5:10)) == getobs(ys, 5:10)
end
@testset "Tuple" begin
@test_throws MethodError getobs!((nothing,nothing), (X,y))
@test getobs!((nothing,nothing), (X,y), 1:5) == getobs((X,y), 1:5)
@test_throws MethodError getobs!((nothing,nothing,nothing), (X,y))
xbuf = zeros(4,2)
ybuf = ["foo", "bar"]
@test_throws MethodError getobs!((xbuf,), (X,y))
@test_throws MethodError getobs!((xbuf,ybuf,ybuf), (X,y))
@test_throws DimensionMismatch getobs!((xbuf,), (X,y), 1:5)
@test_throws DimensionMismatch getobs!((xbuf,ybuf,ybuf), (X,y), 1:5)
@test @inferred(getobs!((xbuf,ybuf),(X,y), 2:3)) === (xbuf,ybuf)
@test xbuf == getobs(X, 2:3)
@test ybuf == getobs(y, 2:3)
@test @inferred(getobs!((xbuf,ybuf),(X,y), [14,5])) === (xbuf,ybuf)
@test xbuf == getobs(X, [14,5])
@test ybuf == getobs(y, [14,5])
@test getobs!((nothing,xbuf),(Xs,X), 3:4) == (getobs(Xs,3:4),xbuf)
@test xbuf == getobs(X,3:4)
end
@testset "tables" begin
df = DataFrame(a=[1,2,3], y=["a","b","c"])
@test getobs(df) == df
@test getobs(df, 1) == df[1,:]
@test getobs(df, 2:3) == df[2:3,:]
@test numobs(df) == 3
end
end
| MLUtils | https://github.com/JuliaML/MLUtils.jl.git |
|
[
"MIT"
] | 0.4.4 | b45738c2e3d0d402dffa32b2c1654759a2ac35a4 | code | 4894 | @testset "mapobs" begin
data = 1:10
mdata = mapobs(-, data)
@test getobs(mdata, 8) == -8
@test length(mdata) == 10
@test numobs(mdata) == 10
mdata2 = mapobs((-, x -> 2x), data)
@test getobs(mdata2, 8) == (-8, 16)
nameddata = mapobs((x = sqrt, y = log), data)
@test getobs(nameddata, 10) == (x = sqrt(10), y = log(10))
@test getobs(nameddata.x, 10) == sqrt(10)
# colon
@test mapobs(x -> 2x, [1:10;])[:] == [2:2:20;]
@testset "batched = :auto" begin
data = (a = [1:10;],)
m = mapobs(data; batched=:auto) do x
@test x.a isa Int
return (; c = 2 .* x.a)
end[1]
@test m == (; c = 2)
m = mapobs(data) do x
@test x.a isa Vector{Int}
return (; c = 2 .* x.a)
end[1:2]
@test m == (; c = [2, 4])
# check that :auto is the default
m = mapobs(data) do x
@test x.a isa Int
return (; c = 2 .* x.a)
end[1]
@test m == (; c = 2)
m = mapobs(data) do x
@test x.a isa Vector{Int}
return (; c = 2 .* x.a)
end[1:2]
@test m == (; c = [2, 4])
end
@testset "batched = :always" begin
data = (; a = [1:10;],)
m = mapobs(data; batched=:always) do x
@test x.a isa Vector{Int}
return (; c = 2 .* x.a)
end[1]
@test m == (; c = 2)
m = mapobs(data; batched=:always) do x
@test x.a isa Vector{Int}
return (; c = 2 .* x.a)
end[1:2]
@test m == (; c = [2, 4])
end
@testset "batched = :never" begin
data = (; a = [1:10;],)
m = mapobs(data; batched=:never) do x
@test x.a isa Int
return (; c = 2 .* x.a)
end[1]
@test m == (; c = 2)
m = mapobs(data; batched=:never) do x
@test x.a isa Int
return (; c = 2 .* x.a)
end[1:2]
@test m == [(; c = 2), (; c = 4)]
end
end
@testset "filterobs" begin
data = 1:10
fdata = filterobs(>(5), data)
@test numobs(fdata) == 5
end
@testset "groupobs" begin
data = -10:10
datas = groupobs(>(0), data)
@test length(datas) == 2
end
@testset "joinobs" begin
data1, data2 = 1:10, 11:20
jdata = joinobs(data1, data2)
@test getobs(jdata, 15) == 15
end
@testset "shuffleobs" begin
@test_throws DimensionMismatch shuffleobs((X, rand(149)))
@testset "typestability" begin
for var in vars
@test typeof(@inferred(shuffleobs(var))) <: SubArray
end
for tup in tuples
@test typeof(@inferred(shuffleobs(tup))) <: Tuple
end
end
@testset "Array and SubArray" begin
for var in vars
@test size(shuffleobs(var)) == size(var)
end
# tests if all obs are still present and none duplicated
@test sum(shuffleobs(Y1)) == 120
end
@testset "Tuple of Array and SubArray" begin
for var in ((X,yv), (Xv,y), tuples...)
@test_throws MethodError shuffleobs(var...)
@test typeof(shuffleobs(var)) <: Tuple
@test all(map(x->(typeof(x)<:SubArray), shuffleobs(var)))
@test all(map(x->(numobs(x)===15), shuffleobs(var)))
end
# tests if all obs are still present and none duplicated
# also tests that both paramter are shuffled identically
x1, y1, z1 = shuffleobs((X1,Y1,X1))
@test vec(sum(x1,dims=2)) == fill(120,10)
@test vec(sum(z1,dims=2)) == fill(120,10)
@test sum(y1) == 120
@test all(x1' .== y1)
@test all(z1' .== y1)
end
@testset "SparseArray" begin
for var in (Xs, ys)
@test typeof(shuffleobs(var)) <: SubArray
@test numobs(shuffleobs(var)) == numobs(var)
end
# tests if all obs are still present and none duplicated
@test vec(sum(getobs(shuffleobs(sparse(X1))),dims=2)) == fill(120,10)
@test sum(getobs(shuffleobs(sparse(Y1)))) == 120
end
@testset "Tuple of SparseArray" begin
for var in ((Xs,ys), (X,ys), (Xs,y), (Xs,Xs), (XX,X,ys))
@test_throws MethodError shuffleobs(var...)
@test typeof(shuffleobs(var)) <: Tuple
@test numobs(shuffleobs(var)) == numobs(var)
end
# tests if all obs are still present and none duplicated
# also tests that both paramter are shuffled identically
x1, y1 = getobs(shuffleobs((sparse(X1),sparse(Y1))))
@test vec(sum(x1,dims=2)) == fill(120,10)
@test sum(y1) == 120
@test all(x1' .== y1)
end
@testset "RNG" begin
# tests reproducibility
explicit_shuffle = shuffleobs(MersenneTwister(42), (X, y))
@test explicit_shuffle == shuffleobs(MersenneTwister(42), (X, y))
end
end
| MLUtils | https://github.com/JuliaML/MLUtils.jl.git |
|
[
"MIT"
] | 0.4.4 | b45738c2e3d0d402dffa32b2c1654759a2ac35a4 | code | 9553 | @testset "ObsView constructor" begin
@test_throws DimensionMismatch ObsView((rand(2,10), rand(9)))
@test_throws DimensionMismatch ObsView((rand(2,10), rand(9)), 1:2)
@test_throws DimensionMismatch ObsView((rand(2,10), rand(4,9,10), rand(9)))
@testset "bounds check" begin
for var in (vars..., tuples..., CustomType())
@test_throws BoundsError ObsView(var, -1:100)
@test_throws BoundsError ObsView(var, 1:16)
@test_throws BoundsError ObsView(var, [1, 10, 0, 3])
@test_throws BoundsError ObsView(var, [1, 10, -10, 3])
@test_throws BoundsError ObsView(var, [1, 10, 18, 3])
end
end
@testset "Tuples" begin
@test typeof(@inferred(ObsView((X,X)))) <: ObsView
@test typeof(@inferred(ObsView((X,X), 1:15))) <: ObsView
d = ObsView((X, y), 5:10)
@test @inferred(getobs(d , 2)) == getobs((X, y), 6)
@test numobs(d) == 6
end
@testset "Array, SubArray, SparseArray" begin
for var in (Xs, ys, vars...)
subset = @inferred(ObsView(var))
@test subset.data === var
@test subset.indices === 1:15
@test typeof(subset) <: ObsView
@test @inferred(numobs(subset)) === numobs(var)
@test @inferred(getobs(subset)) == getobs(var)
@test @inferred(ObsView(subset)) === subset
@test @inferred(ObsView(subset, 1:15)) === subset
@test subset[begin] == obsview(var, 1)
@test subset[end] == obsview(var, 15)
@test @inferred(subset[15]) == obsview(var, 15)
@test @inferred(subset[2:5]) == obsview(var, 2:5)
for idx in (1:10, [1,10,15,3], [2])
@test ObsView(var)[idx] == obsview(var, idx)
@test ObsView(var)[idx] == obsview(var, collect(idx))
subset = @inferred(ObsView(var, idx))
@test typeof(subset) <: ObsView{typeof(var), typeof(idx)}
@test subset.data === var
@test subset.indices === idx
@test @inferred(numobs(subset)) === length(idx)
@test @inferred(getobs(subset)) == getobs(var, idx)
@test @inferred(ObsView(subset)) === subset
@test @inferred(subset[1]) == obsview(var, idx[1])
@test numobs(subset[1:1]) == numobs(ObsView(var, obsview(idx, 1:1)))
end
end
end
@testset "custom types" begin
@test_throws MethodError ObsView(EmptyType())
@test_throws MethodError ObsView(EmptyType(), 1:10)
@test_throws BoundsError getobs(ObsView(CustomType(), 11:20), 11)
@test typeof(@inferred(ObsView(CustomType()))) <: ObsView
@test numobs(ObsView(CustomType())) === 15
@test numobs(ObsView(CustomType(), 1:10)) === 10
@test getobs(ObsView(CustomType())) == collect(1:15)
@test getobs(ObsView(CustomType(),1:10),10) == 10
@test getobs(ObsView(CustomType(),1:10),[3,5]) == [3,5]
@test obsview(CustomArray(5)) isa SubArray
@test getobs(obsview(CustomArray(5)), 1:2) == CustomArray(2)
end
end
@testset "ObsView getindex and getobs" begin
@testset "Matrix and SubArray{T,2}" begin
for var in (X, Xv)
subset = @inferred(ObsView(var, 5:12))
@test typeof(@inferred(getobs(subset))) <: Array{Float64,2}
@test @inferred(numobs(subset)) == length(subset) == 8
@test @inferred(subset[2:5]) == obsview(X, 6:9)
@test @inferred(subset[3:6]) != obsview(X, 6:9)
@test @inferred(getobs(subset, 2:5)) == X[:, 6:9]
@test @inferred(getobs(subset, [3,1,4])) == X[:, [7,5,8]]
@test typeof(subset[2:5]) <: SubArray
@test @inferred(subset[collect(2:5)]) == obsview(X, collect(6:9))
@test typeof(subset[collect(2:5)]) <: SubArray
@test @inferred(getobs(subset)) == getobs(subset[1:end]) == X[:, 5:12]
end
end
@testset "Vector and SubArray{T,1}" begin
for var in (y, yv)
subset = @inferred(ObsView(var, 6:10))
@test typeof(getobs(subset)) <: Array{String,1}
@test @inferred(numobs(subset)) == length(subset) == 5
@test @inferred(subset[2:3]) == obsview(y, 7:8)
@test @inferred(getobs(subset, 2:3)) == y[7:8]
@test @inferred(getobs(subset, [2,1,4])) == y[[7,6,9]]
@test typeof(subset[2:3]) <: SubArray
@test @inferred(subset[collect(2:3)]) == obsview(y, collect(7:8))
@test typeof(subset[collect(2:3)]) <: SubArray
@test @inferred(getobs(subset)) == getobs(subset[1:end]) == y[6:10]
end
end
end
@testset "getobs!" begin
@test getobs!(nothing, ObsView(y, 1)) == "setosa"
@testset "ObsView" begin
xbuf1 = zeros(4,8)
s1 = ObsView(X, 2:9)
@test @inferred(getobs!(xbuf1,s1)) === xbuf1
@test xbuf1 == getobs(s1)
xbuf1 = zeros(4,5)
s1 = ObsView(X, 5:12)
@test @inferred(getobs!(xbuf1,s1,2:6)) === xbuf1
@test xbuf1 == getobs(s1,2:6) == getobs(X,6:10)
s3 = ObsView(Xs, 6:10)
@test @inferred(getobs!(nothing,s3)) == getobs(Xs,6:10)
s4 = ObsView(CustomType(), 6:10)
@test @inferred(getobs!(nothing,s4)) == getobs(s4)
s5 = ObsView(CustomType(), 3:10)
@test @inferred(getobs!(nothing,s5,2:6)) == getobs(s5,2:6)
end
@testset "Tuple with ObsView" begin
xbuf = zeros(4,2)
ybuf = ["foo", "bar"]
s1 = ObsView(Xs, 5:9)
s2 = ObsView(X, 5:9)
@test getobs!((nothing,xbuf),(s1,s2), 2:3) == (getobs(Xs,6:7),xbuf)
@test xbuf == getobs(X,6:7)
@test getobs!((nothing,xbuf),(s1,s2), 2:3) == (getobs(Xs,6:7),xbuf)
@test getobs!((nothing,xbuf),(s1,s2), 2:3) == (getobs(Xs,6:7),xbuf)
end
end
@testset "ObsView other" begin
@testset "constructor" begin
# @test_throws DimensionMismatch ObsView((rand(2,10),rand(9)))
# @test_throws DimensionMismatch ObsView((rand(2,10),rand(4,9,10),rand(9)))
@test_throws MethodError ObsView(EmptyType())
@test_throws MethodError ObsView((EmptyType(),EmptyType()))
@test_throws MethodError ObsView((EmptyType(),EmptyType()))
for var in (vars..., Xs, ys)
A = @inferred(ObsView(var))
end
for var in (vars..., tuples..., Xs, ys)
A = ObsView(var)
@test @inferred(parent(A)) === var
@test @inferred(ObsView(A)) == A
@test @inferred(ObsView(var)) == A
end
end
@testset "typestability" begin
for var in (vars..., tuples..., Xs, ys)
@test typeof(@inferred(ObsView(var))) <: ObsView
@test typeof(@inferred(ObsView(var))) <: ObsView
end
for tup in tuples
@test typeof(@inferred(ObsView(tup))) <: ObsView
end
@test typeof(@inferred(ObsView(CustomType()))) <: ObsView
end
@testset "AbstractArray interface" begin
for var in (vars..., tuples..., Xs, ys)
# for var in (vars[1], )
A = ObsView(var)
@test_throws BoundsError A[-1]
@test_throws BoundsError A[16]
@test @inferred(numobs(A)) == 15
@test @inferred(length(A)) == 15
@test @inferred(size(A)) == (15,)
@test @inferred(A[2:3]) == obsview(var, 2:3)
@test @inferred(A[[1,3]]) == obsview(var, [1,3])
@test @inferred(A[1]) == obsview(var, 1)
@test @inferred(A[11]) == obsview(var, 11)
@test @inferred(A[15]) == obsview(var, 15)
@test A[begin] == A[1]
@test A[end] == A[15]
@test @inferred(getobs(A,1)) == getobs(var, 1)
@test @inferred(getobs(A,11)) == getobs(var, 11)
@test @inferred(getobs(A,15)) == getobs(var, 15)
@test typeof(@inferred(collect(A))) <: Vector
end
for var in vars
A = ObsView(var)
@test getobs(A) == var
@test getobs.(A) == [getobs(var,i) for i in 1:numobs(var)]
end
for var in tuples
A = ObsView(var)
@test getobs(A) == var
@test getobs.(A) == [map(x->getobs(x,i), var) for i in 1:numobs(var)]
end
end
@testset "subsetting" begin
for var_raw in (vars..., tuples..., Xs, ys)
for var in (var_raw, ObsView(var_raw))
A = ObsView(var)
@test getobs(@inferred(ObsView(A))) == @inferred(getobs(A))
S = @inferred(ObsView(A, 1:5))
@test typeof(S) <: ObsView
@test @inferred(length(S)) == 5
@test @inferred(size(S)) == (5,)
@test @inferred(A[1:5]) == S[:]
@test @inferred(getobs(A,1:5)) == getobs(S)
@test @inferred(getobs(S)) == getobs(ObsView(ObsView(var,1:5)))
S = @inferred(ObsView(A, 1:5))
@test typeof(S) <: ObsView
end
end
A = ObsView(X)
@test typeof(A.data) <: Array
S = @inferred(ObsView(A))
@test typeof(S) <: ObsView
@test @inferred(length(S)) == 15
@test typeof(S.data) <: Array
end
@testset "iteration" begin
count = 0
for (i,x) in enumerate(ObsView(X1))
@test all(i .== x)
count += 1
end
@test count == 15
end
end
| MLUtils | https://github.com/JuliaML/MLUtils.jl.git |
|
[
"MIT"
] | 0.4.4 | b45738c2e3d0d402dffa32b2c1654759a2ac35a4 | code | 1489 | @testset "eachobsparallel" begin
@testset "Iteration" begin
iter = eachobsparallel(collect(1:10))
@test_nowarn for i in iter end
X_ = collect(iter)
@test all(x ∈ 1:10 for x in X_)
@test length(unique(X_)) == 10
end
@testset "With `ThreadedEx`" begin
iter = eachobsparallel(collect(1:10); executor = ThreadedEx())
@test_nowarn for i in iter end
X_ = collect(iter)
@test all(x ∈ 1:10 for x in X_)
@test length(unique(X_)) == 10
end
end
@testset "RingBuffer" begin
@testset "fills correctly" begin
x = rand(10, 10)
ringbuffer = RingBuffer([x, deepcopy(x), deepcopy(x)])
@async begin
for i ∈ 1:100
put!(ringbuffer) do buf
rand!(buf)
end
end
end
@test_nowarn for _ ∈ 1:100
take!(ringbuffer)
end
end
@testset "does mutate" begin
x = rand(10, 10)
ringbuffer = RingBuffer([x, deepcopy(x), deepcopy(x)])
put!(ringbuffer) do buf
@test x ≈ buf
copy!(buf, rand(10, 10))
buf
end
x_ = take!(ringbuffer)
@test !(x ≈ x_)
end
end
@testset "`eachobsparallel(buffer = true)`" begin
iter = eachobsparallel(collect(1:10), buffer=true)
@test_nowarn for i in iter end
X_ = collect(iter)
@test all(x ∈ 1:10 for x in X_)
@test length(unique(X_)) == 10
end
| MLUtils | https://github.com/JuliaML/MLUtils.jl.git |
|
[
"MIT"
] | 0.4.4 | b45738c2e3d0d402dffa32b2c1654759a2ac35a4 | code | 215 | x = randobs(X[:,1:4])
@test size(x) == (4,)
@test any(X[:,i] == x for i in 1:4)
x = randobs(X[:,1:4], 2)
@test size(x) == (4, 2)
@test any(X[:,i] == x[:,1] for i in 1:4)
@test any(X[:,i] == x[:,2] for i in 1:4)
| MLUtils | https://github.com/JuliaML/MLUtils.jl.git |
|
[
"MIT"
] | 0.4.4 | b45738c2e3d0d402dffa32b2c1654759a2ac35a4 | code | 1532 | @testset "oversample" begin
x = rand(2, 5)
ya = ["a", "c", "c", "a", "b"]
y2 = ["c", "c", "c", "a", "b"]
o = oversample((x, ya), fraction=1, shuffle=false)
@test o == oversample((x, ya), ya, shuffle=false)[1]
xo, yo = oversample(x, ya, shuffle=false)
@test (xo, yo) == o
ox, oy = getobs(o)
@test ox isa Matrix
@test oy isa Vector
@test size(ox) == (2, 6)
@test size(oy) == (6,)
@test ox[:,1:5] == x
@test ox[:,6] == ox[:,5]
@test oy[1:5] == ya
@test oy[6] == ya[5]
o = oversample((x, ya), y2, shuffle=false)[1]
ox, oy = getobs(o)
@test ox isa Matrix
@test oy isa Vector
@test size(ox) == (2, 9)
@test size(oy) == (9,)
@test ox[:,1:5] == x
@test ox[:,6] == ox[:,7] == x[:,5]
@test ox[:,8] == ox[:,9] == x[:,4]
@test oy[1:5] == ya
@test oy[6] == oy[7] == ya[5]
@test oy[8] == oy[9] == ya[4]
end
@testset "undersample" begin
x = rand(2, 5)
ya = ["a", "c", "c", "a", "b"]
y2 = ["c", "c", "c", "a", "b"]
o = undersample((x, ya), shuffle=false)
xo, yo = undersample(x, ya, shuffle=false)
@test (xo, yo) == o
ox, oy = getobs(o)
@test ox isa Matrix
@test oy isa Vector
@test size(ox) == (2, 3)
@test size(oy) == (3,)
@test ox[:,3] == x[:,5]
o = undersample((x, ya), y2, shuffle=false)[1]
ox, oy = getobs(o)
@test ox isa Matrix
@test oy isa Vector
@test size(ox) == (2, 3)
@test size(oy) == (3,)
@test ox[:,2:3] == x[:,4:5]
end
| MLUtils | https://github.com/JuliaML/MLUtils.jl.git |
|
[
"MIT"
] | 0.4.4 | b45738c2e3d0d402dffa32b2c1654759a2ac35a4 | code | 3513 | using MLUtils
using MLUtils.Datasets
using MLUtils: RingBuffer, eachobsparallel
using MLUtils: flatten, stack, unstack # also exported by DataFrames.jl
using SparseArrays
using Random, Statistics
using Test
using Transducers
using ChainRulesTestUtils: test_rrule
using Zygote: ZygoteRuleConfig
using ChainRulesCore: rrule_via_ad
using DataFrames
using CUDA
showcompact(io, x) = show(IOContext(io, :compact => true), x)
# --------------------------------------------------------------------
# create some test data
Random.seed!(1335)
const X = rand(4, 15)
const y = repeat(["setosa","versicolor","virginica"], inner = 5)
const Y = permutedims(hcat(y,y), [2,1])
const Yt = hcat(y,y)
const yt = Y[1:1,:]
const Xv = view(X,:,:)
const yv = view(y,:)
const XX = rand(20,30,15)
const XXX = rand(3,20,30,15)
const vars = (X, Xv, yv, XX, XXX, y)
const tuples = ((X,y), (X,Y), (XX,X,y), (XXX,XX,X,y))
const Xs = sprand(10, 15, 0.5)
const ys = sprand(15, 0.5)
const X1 = hcat((1:15 for i = 1:10)...)'
const Y1 = collect(1:15)
struct EmptyType end
struct FallbackType end
Base.getindex(::FallbackType, i) = 1234
Base.length(::FallbackType) = 5678
struct CustomType end
MLUtils.numobs(::CustomType) = 15
MLUtils.getobs(::CustomType, i::Int) = i
MLUtils.getobs(::CustomType, i::AbstractVector) = collect(i)
struct CustomArray{T,N} <: AbstractArray{T,N}
length::Int
size::NTuple{N, Int}
function CustomArray{T}(n...) where T
N = length(n)
new{T,N}(prod(n), Tuple(n))
end
end
CustomArray(n...) = CustomArray{Float32}(n...)
Base.length(x::CustomArray) = x.length
Base.size(x::CustomArray) = x.size
Base.getindex(x::CustomArray{T}, i::Int) where T = T(1)
Base.getindex(x::CustomArray{T, 1}, i::AbstractVector{Int}) where T = CustomArray{T}(length(i))
struct CustomArrayNoView{T,N} <: AbstractArray{T,N}
length::Int
size::NTuple{N, Int}
function CustomArrayNoView{T}(n...) where T
N = length(n)
new{T,N}(prod(n), Tuple(n))
end
end
CustomArrayNoView(n...) = CustomArrayNoView{Float32}(n...)
Base.length(x::CustomArrayNoView) = x.length
Base.size(x::CustomArrayNoView) = x.size
Base.getindex(x::CustomArrayNoView{T}, i::Int) where T = T(1)
Base.getindex(x::CustomArrayNoView{T, 1}, i::AbstractVector{Int}) where T = CustomArrayNoView{T}(length(i))
Base.view(x::CustomArrayNoView, i...) = error("view not allowed")
struct CustomRangeIndex
n::Int
end
Base.length(r::CustomRangeIndex) = r.n
Base.getindex(r::CustomRangeIndex, idx::Int) = idx
Base.getindex(r::CustomRangeIndex, idxs::UnitRange) = idxs
# --------------------------------------------------------------------
include("test_utils.jl")
# @testset "MLUtils.jl" begin
@testset "batchview" begin; include("batchview.jl"); end
@testset "eachobs" begin; include("eachobs.jl"); end
@testset "dataloader" begin; include("dataloader.jl"); end
@testset "folds" begin; include("folds.jl"); end
@testset "observation" begin; include("observation.jl"); end
@testset "obsview" begin; include("obsview.jl"); end
@testset "obstransform" begin; include("obstransform.jl"); end
@testset "randobs" begin; include("randobs.jl"); end
@testset "resample" begin; include("resample.jl"); end
@testset "splitobs" begin; include("splitobs.jl"); end
@testset "utils" begin; include("utils.jl"); end
@testset "eachobsparallel" begin; include("parallel.jl"); end
@testset "Datasets/datasets" begin; include("Datasets/datasets.jl"); end
@testset "Datasets/generators" begin; include("Datasets/generators.jl"); end
# end
| MLUtils | https://github.com/JuliaML/MLUtils.jl.git |
|
[
"MIT"
] | 0.4.4 | b45738c2e3d0d402dffa32b2c1654759a2ac35a4 | code | 2229 | @test_throws DimensionMismatch shuffleobs((X, rand(149)))
@testset "typestability" begin
for var in vars
@test typeof(@inferred(shuffleobs(var))) <: SubArray
end
for tup in tuples
@test typeof(@inferred(shuffleobs(tup))) <: Tuple
end
end
@testset "Array and SubArray" begin
for var in vars
@test size(shuffleobs(var)) == size(var)
end
# tests if all obs are still present and none duplicated
@test sum(shuffleobs(Y1)) == 120
end
@testset "Tuple of Array and SubArray" begin
for var in ((X,yv), (Xv,y), tuples...)
@test_throws MethodError shuffleobs(var...)
@test typeof(shuffleobs(var)) <: Tuple
@test all(map(x->(typeof(x)<:SubArray), shuffleobs(var)))
@test all(map(x->(numobs(x)===15), shuffleobs(var)))
end
# tests if all obs are still present and none duplicated
# also tests that both paramter are shuffled identically
x1, y1, z1 = shuffleobs((X1,Y1,X1))
@test vec(sum(x1,dims=2)) == fill(120,10)
@test vec(sum(z1,dims=2)) == fill(120,10)
@test sum(y1) == 120
@test all(x1' .== y1)
@test all(z1' .== y1)
end
@testset "SparseArray" begin
for var in (Xs, ys)
@test typeof(shuffleobs(var)) <: SubArray
@test numobs(shuffleobs(var)) == numobs(var)
end
# tests if all obs are still present and none duplicated
@test vec(sum(getobs(shuffleobs(sparse(X1))),dims=2)) == fill(120,10)
@test sum(getobs(shuffleobs(sparse(Y1)))) == 120
end
@testset "Tuple of SparseArray" begin
for var in ((Xs,ys), (X,ys), (Xs,y), (Xs,Xs), (XX,X,ys))
@test_throws MethodError shuffleobs(var...)
@test typeof(shuffleobs(var)) <: Tuple
@test numobs(shuffleobs(var)) == numobs(var)
end
# tests if all obs are still present and none duplicated
# also tests that both paramter are shuffled identically
x1, y1 = getobs(shuffleobs((sparse(X1),sparse(Y1))))
@test vec(sum(x1,dims=2)) == fill(120,10)
@test sum(y1) == 120
@test all(x1' .== y1)
end
@testset "RNG" begin
# tests reproducibility
explicit_shuffle = shuffleobs(MersenneTwister(42), (X, y))
@test explicit_shuffle == shuffleobs(MersenneTwister(42), (X, y))
end
| MLUtils | https://github.com/JuliaML/MLUtils.jl.git |
|
[
"MIT"
] | 0.4.4 | b45738c2e3d0d402dffa32b2c1654759a2ac35a4 | code | 4020 | @test_throws DimensionMismatch splitobs((X, rand(149)), at=0.7)
# ## These tests pass on julia 1.6 but fail on higher versions
# @testset "typestability" begin
# @testset "Int" begin
# @test typeof(@inferred(splitobs(10, at=0.))) <: NTuple{2}
# @test eltype(@inferred(splitobs(10, at=0.))) <: UnitRange
# @test typeof(@inferred(splitobs(10, at=1.))) <: NTuple{2}
# @test eltype(@inferred(splitobs(10, at=1.))) <: UnitRange
# @test typeof(@inferred(splitobs(10, at=0.7))) <: NTuple{2}
# @test eltype(@inferred(splitobs(10, at=0.7))) <: UnitRange
# @test typeof(@inferred(splitobs(10, at=0.5))) <: NTuple{2}
# @test typeof(@inferred(splitobs(10, at=(0.5,0.2)))) <: NTuple{3}
# @test eltype(@inferred(splitobs(10, at=0.5))) <: UnitRange
# @test eltype(@inferred(splitobs(10, at=(0.5,0.2)))) <: UnitRange
# @test eltype(@inferred(splitobs(10, at=0.5))) <: UnitRange
# @test eltype(@inferred(splitobs(10, at=(0.,0.2)))) <: UnitRange
# end
# for var in vars
# @test typeof(@inferred(splitobs(var, at=0.7))) <: NTuple{2}
# @test eltype(@inferred(splitobs(var, at=0.7))) <: SubArray
# @test typeof(@inferred(splitobs(var, at=0.5))) <: NTuple{2}
# @test typeof(@inferred(splitobs(var, at=(0.5,0.2)))) <: NTuple{3}
# @test eltype(@inferred(splitobs(var, at=0.5))) <: SubArray
# @test eltype(@inferred(splitobs(var, at=(0.5,0.2)))) <: SubArray
# end
# for tup in tuples
# @test typeof(@inferred(splitobs(tup, at=0.5))) <: NTuple{2}
# @test typeof(@inferred(splitobs(tup, at=(0.5,0.2)))) <: NTuple{3}
# @test eltype(@inferred(splitobs(tup, at=0.5))) <: Tuple
# @test eltype(@inferred(splitobs(tup, at=(0.5,0.2)))) <: Tuple
# end
# end
@testset "Int" begin
@test splitobs(10, at=0.7) == (1:7,8:10)
@test splitobs(10, at=0.5) == (1:5,6:10)
@test splitobs(10, at=(0.5,0.3)) == (1:5,6:8,9:10)
@test splitobs(150, at=0.7) == splitobs(150, at=0.7)
@test splitobs(150, at=0.5) == splitobs(150, at=0.5)
@test splitobs(150, at=(0.5,0.2)) == splitobs(150, at=(0.5,0.2))
@test numobs.(splitobs(150, at=0.7)) == (105,45)
@test numobs.(splitobs(150, at=(.2,.3))) == (30,45,75)
@test numobs.(splitobs(150, at=(.1,.2,.3))) == (15,30,45,60)
# tests if all obs are still present and none duplicated
@test sum(sum.(getobs.(splitobs(150, at=0.7)))) == 11325
@test sum(sum.(splitobs(150,at=.1))) == 11325
@test sum(sum.(splitobs(150,at=(.2,.1)))) == 11325
@test sum(sum.(splitobs(150,at=(.1,.4,.2)))) == 11325
@test sum.(splitobs(150, at=0.7)) == (5565, 5760)
end
@testset "Array, SparseArray, and SubArray" begin
for var in (Xs, ys, vars...)
@test numobs.(splitobs(var, at=10)) == (10,5)
@test numobs.(splitobs(var, at=0.7)) == (10, 5)
@test numobs.(splitobs(var, at=(.2,.3))) == (3,4, 8)
@test numobs.(splitobs(var, at=(.11,.2,.3))) == (2,3,4,6)
@test numobs.(splitobs(var, at=(2,3,4))) == (2,3,4,6)
end
# tests if all obs are still present and none duplicated
@test sum(sum.(splitobs(X1,at=.1))) == 1200
@test sum(sum.(splitobs(X1,at=(.2,.1)))) == 1200
@test sum(sum.(splitobs(X1,at=(.1,.4,.2)))) == 1200
end
@testset "Tuple of Array, SparseArray, and SubArray" begin
for tup in ((Xs,ys), (X,ys), (Xs,y), (Xs,Xs), (XX,X,ys), (X,yv), (Xv,y), tuples...)
@test_throws MethodError splitobs(tup..., at=0.5)
@test all(map(x->(typeof(x)<:Tuple), splitobs(tup,at=0.5)))
@test numobs.(splitobs(tup, at=0.6)) == (9, 6)
@test numobs.(splitobs(tup, at=(.2,.3))) == (3,4,8)
end
end
@testset "shuffle" begin
s = splitobs(X, at=0.1)[1]
@test s == X[:,1:2]
s = splitobs(X, at=0.1, shuffle=true)[1]
@test size(s) == size(X[:,1:2])
@test s[:,1] !== s[:,2]
@test s != X[:,1:2]
@test any(s[:,1] == x for x in eachcol(X))
@test any(s[:,2] == x for x in eachcol(X))
end
| MLUtils | https://github.com/JuliaML/MLUtils.jl.git |
|
[
"MIT"
] | 0.4.4 | b45738c2e3d0d402dffa32b2c1654759a2ac35a4 | code | 409 |
"""
Test gradients through zygote.
# Arguments
- `f`: function to test
- `xs`: inputs to `f`
# Keyword Arguments
Keyword arguments are passed to `rrule`.
- `fkwargs`: keyword arguments to `f`
"""
function test_zygote(f, xs...; kws...)
config = ZygoteRuleConfig()
test_rrule(config, f, xs...; kws..., rrule_f = rrule_via_ad)
end
function rr(seed)
rng = Random.seed!(seed)
return rng
end
| MLUtils | https://github.com/JuliaML/MLUtils.jl.git |
|
[
"MIT"
] | 0.4.4 | b45738c2e3d0d402dffa32b2c1654759a2ac35a4 | code | 7933 | @testset "unsqueeze" begin
x = randn(2, 3, 2)
@test @inferred(unsqueeze(x; dims=1)) == reshape(x, 1, 2, 3, 2)
@test @inferred(unsqueeze(x; dims=2)) == reshape(x, 2, 1, 3, 2)
@test @inferred(unsqueeze(x; dims=3)) == reshape(x, 2, 3, 1, 2)
@test @inferred(unsqueeze(x; dims=4)) == reshape(x, 2, 3, 2, 1)
@test unsqueeze(dims=2)(x) == unsqueeze(x, dims=2)
@test_throws AssertionError unsqueeze(rand(2,2), dims=4)
end
@testset "stack and unstack" begin
x = randn(3,3)
stacked = stack([x, x], dims=2)
@test size(stacked) == (3,2,3)
@test @inferred(stack([x, x], dims=2)) == stacked
stacked_array=[ 8 9 3 5; 9 6 6 9; 9 1 7 2; 7 4 10 6 ]
unstacked_array=[[8, 9, 9, 7], [9, 6, 1, 4], [3, 6, 7, 10], [5, 9, 2, 6]]
@test unstack(stacked_array, dims=2) == unstacked_array
@test @inferred(unstack(stacked_array, dims=Val(2))) == unstacked_array
@test stack(unstacked_array, dims=2) == stacked_array
@test stack(unstack(stacked_array, dims=1), dims=1) == stacked_array
for d in (1,2,3)
test_zygote(stack, [x,2x], fkwargs=(; dims=d), check_inferred=false)
end
# Issue #121
a = [[1] for i in 1:10000]
@test size(stack(a, dims=1)) == (10000, 1)
@test size(stack(a, dims=2)) == (1, 10000)
end
@testset "batch and unbatch" begin
stacked_array=[ 8 9 3 5
9 6 6 9
9 1 7 2
7 4 10 6 ]
unstacked_array=[[8, 9, 9, 7], [9, 6, 1, 4], [3, 6, 7, 10], [5, 9, 2, 6]]
@test @inferred(unbatch(stacked_array)) == unstacked_array
@test @inferred(batch(unstacked_array)) == stacked_array
# no-op for vector of non-arrays
@test batch([1,2,3]) == [1,2,3]
@test unbatch([1,2,3]) == [1,2,3]
# batching multi-dimensional arrays
x = map(_ -> rand(4), zeros(2, 3))
@test size(batch(x)) == (4, 2, 3)
x = map(_ -> rand(4, 5), zeros(2, 3, 6))
@test size(batch(x)) == (4, 5, 2, 3, 6)
# generic iterable
@test batch(ones(2) for i=1:3) == ones(2, 3)
@test unbatch(ones(2, 3)) == [ones(2) for i=1:3]
@testset "tuple" begin
@test batch([(1,2), (3,4)]) == ([1,3], [2,4])
@test batch([([1,2], [3,4]), ([5,6],[7,8])]) == ([1 5
2 6],
[3 7
4 8])
end
@testset "named tuple" begin
@test batch([(a=1,b=2), (a=3,b=4)]) == (a=[1,3], b=[2,4])
@test batch([(a=1,b=2), (b=4,a=3)]) == (a=[1,3], b=[2,4])
nt = [(a=[1,2], b=[3,4]), (a=[5,6],b=[7,8])]
@test batch(nt) == (a = [1 5
2 6],
b = [3 7
4 8])
end
@testset "dict" begin
@test batch([Dict(:a=>1,:b=>2), Dict(:a=>3,:b=>4)]) == Dict(:a=>[1,3], :b=>[2,4])
@test batch([Dict(:a=>1,:b=>2), Dict(:b=>4,:a=>3)]) == Dict(:a=>[1,3], :b=>[2,4])
d = [Dict(:a=>[1,2], :b=>[3,4]), Dict(:a=>[5,6],:b=>[7,8])]
@test batch(d) == Dict(:a => [1 5
2 6],
:b => [3 7
4 8])
end
end
@testset "flatten" begin
x = randn(Float32, 10, 10, 3, 2)
@test size(flatten(x)) == (300, 2)
end
@testset "normalise" begin
x = randn(Float32, 3, 2, 2)
@test normalise(x) == normalise(x; dims=3)
end
@testset "chunk" begin
cs = chunk(collect(1:10), 3)
@test length(cs) == 3
@test cs[1] == [1, 2, 3, 4]
@test cs[2] == [5, 6, 7, 8]
@test cs[3] == [9, 10]
cs = chunk(collect(1:10), 3)
@test length(cs) == 3
@test cs[1] == [1, 2, 3, 4]
@test cs[2] == [5, 6, 7, 8]
@test cs[3] == [9, 10]
x = reshape(collect(1:20), (5, 4))
cs = chunk(x, 2)
@test length(cs) == 2
@test cs[1] == [1 6; 2 7; 3 8; 4 9; 5 10]
@test cs[2] == [11 16; 12 17; 13 18; 14 19; 15 20]
x = permutedims(reshape(collect(1:10), (2, 5)))
cs = chunk(x; size = 2, dims = 1)
@test length(cs) == 3
@test cs[1] == [1 2; 3 4]
@test cs[2] == [5 6; 7 8]
@test cs[3] == [9 10]
# test gradient
test_zygote(chunk, rand(10), 3, check_inferred=false)
# indirect test of second order derivates
n = 2
dims = 2
x = rand(4, 5)
l = chunk(x, 2)
dl = randn!.(collect.(l))
idxs = MLUtils._partition_idxs(x, cld(size(x, dims), n), dims)
test_zygote(MLUtils.∇chunk, dl, x, idxs, Val(dims), check_inferred=false)
if CUDA.functional()
# https://github.com/JuliaML/MLUtils.jl/issues/103
x = rand(2, 10) |> cu
cs = chunk(x, 2)
@test length(cs) == 2
@test cs[1] isa CuArray
@test cs[1] == x[:, 1:5]
end
@testset "size collection" begin
a = reshape(collect(1:10), (5, 2))
y = chunk(a; dims = 1, size = (1, 4))
@test length(y) == 2
@test y[1] == [1 6]
@test y[2] == [2 7; 3 8; 4 9; 5 10]
test_zygote(x -> chunk(x; dims = 1, size = (1, 4)), a)
end
@testset "chunk by partition_idxs" begin
x = reshape(collect(1:15), (3, 5))
partition_idxs = [1,1,3,3,4]
y = chunk(x, partition_idxs)
@test length(y) == 4
@test y[1] == [1 4; 2 5; 3 6]
@test size(y[2]) == (3, 0)
@test y[3] == [7 10; 8 11; 9 12]
@test y[4] == reshape([13, 14, 15], 3, 1)
y = chunk(x, partition_idxs; npartitions=5)
@test length(y) == 5
@test size(y[5]) == (3, 0)
y = chunk(x, [1,1,2]; dims=1)
@test length(y) == 2
@test y[1] == [1 4 7 10 13; 2 5 8 11 14]
@test y[2] == [3 6 9 12 15]
end
end
@testset "group_counts" begin
d = group_counts(['a','b','b'])
@test d == Dict('a' => 1, 'b' => 2)
end
@testset "batchseq" begin
bs = batchseq([[1, 2, 3], [4, 5]], 0)
@test bs[1] == [1, 4]
@test bs[2] == [2, 5]
@test bs[3] == [3, 0]
bs = batchseq([[1, 2, 3], [4, 5]], -1)
@test bs[1] == [1, 4]
@test bs[2] == [2, 5]
@test bs[3] == [3, -1]
batchseq([ones(2,4), zeros(2, 3), ones(2,2)]) ==[[1.0 0.0 1.0; 1.0 0.0 1.0]
[1.0 0.0 1.0; 1.0 0.0 1.0]
[1.0 0.0 0.0; 1.0 0.0 0.0]
[1.0 0.0 0.0; 1.0 0.0 0.0]]
end
@testset "ones_like" begin
x = rand(Float16, 2, 3)
y = ones_like(x, (2, 4, 2))
@test y isa AbstractArray{Float16}
@test y == ones(Float16, 2, 4, 2)
test_zygote(ones_like, rand(5), (2, 4, 2))
end
@testset "zeros_like" begin
x = rand(Float16, 2, 3)
y = zeros_like(x, (2, 4, 2))
@test y isa AbstractArray{Float16}
@test y == zeros(Float16, 2, 4, 2)
test_zygote(zeros_like, rand(5), (2, 4, 2))
end
@testset "rand_like" begin
seed = 42
x = rand(Float16, 2, 3)
y = rand_like(rr(seed), x, (2, 4, 2))
@test y isa AbstractArray{Float16}
@test y == rand(rr(seed), Float16, 2, 4, 2)
end
@testset "randn_like" begin
seed = 42
x = rand(Float16, 2, 3)
y = randn_like(rr(seed), x, (2, 4, 2))
@test y isa AbstractArray{Float16}
@test y == randn(rr(seed), Float16, 2, 4, 2)
end
@testset "fill_like" begin
x = rand(Float16, 2, 3)
y = fill_like(x, 2.2, (2, 4, 2))
@test y isa AbstractArray{Float16}
@test y == fill!(rand(Float16, 2, 4, 2), 2.2)
test_zygote(fill_like, rand(5), rand(), (2, 4, 2))
end
@testset "rpad_constant" begin
@test rpad_constant([1, 2], 4, -1) == [1, 2, -1, -1]
@test rpad_constant([1, 2, 3], 2) == [1, 2, 3]
@test rpad_constant([1 2; 3 4], 4; dims=1) == [1 2; 3 4; 0 0; 0 0]
@test rpad_constant([1 2; 3 4], 4) == [1 2 0 0; 3 4 0 0; 0 0 0 0; 0 0 0 0]
@test rpad_constant([1 2; 3 4], (3, 4)) == [1 2 0 0; 3 4 0 0; 0 0 0 0]
end | MLUtils | https://github.com/JuliaML/MLUtils.jl.git |
|
[
"MIT"
] | 0.4.4 | b45738c2e3d0d402dffa32b2c1654759a2ac35a4 | code | 534 | @testset "load_iris" begin
xtmp, ytmp, vars = load_iris()
@test typeof(xtmp) <: Matrix{Float64}
@test typeof(ytmp) <: Vector{String}
@test typeof(vars) <: Vector{String}
@test size(xtmp) == (4, 150)
@test length(ytmp) == 150
@test length(vars) == size(xtmp, 1)
@test mean(xtmp, dims=2) ≈ [5.843333333333333333, 3.05733333333333333, 3.758000, 1.199333333333333]
@test mean(xtmp[:,1:50], dims=2) ≈ [5.006, 3.428, 1.462, 0.246]
@test mean(xtmp[:,51:100], dims=2) ≈ [5.936, 2.77, 4.26, 1.326]
end
| MLUtils | https://github.com/JuliaML/MLUtils.jl.git |
|
[
"MIT"
] | 0.4.4 | b45738c2e3d0d402dffa32b2c1654759a2ac35a4 | code | 942 | @testset "make_sin" begin
n = 50
xtmp, ytmp = make_sin(n; noise = 0.)
@test length(xtmp) == length(ytmp) == n
for i = 1:length(xtmp)
@test sin.(xtmp[i]) ≈ ytmp[i]
end
# print(scatterplot(xtmp, ytmp; color = :blue, height = 5))
end
@testset "make_poly" begin
coef = [.8, .5, 2]
xtmp, ytmp = make_poly(coef, -10:.1:10; noise = 0)
@test length(xtmp) == length(ytmp)
for i = 1:length(xtmp)
@test (coef[1] * xtmp[i]^2 + coef[2] * xtmp[i]^1 + coef[3]) ≈ ytmp[i]
end
# print(scatterplot(xtmp, ytmp; color = :blue, height = 5))
end
@testset "make_spiral" begin
n = 97
xtmp, ytmp = make_spiral(n; noise = 0.)
@test length(xtmp[1, :]) == length(ytmp) == 2*n
# test_plot = scatterplot(xtmp[1, 1:97], xtmp[2, 1:97], title="Spiral Function", color=:blue, name="pos")
# print(scatterplot!(test_plot, xtmp[1, 98:194], xtmp[2, 98:194], color=:yellow, name="neg" ))
end
| MLUtils | https://github.com/JuliaML/MLUtils.jl.git |
|
[
"MIT"
] | 0.4.4 | b45738c2e3d0d402dffa32b2c1654759a2ac35a4 | docs | 3090 | # MLUtils.jl
[](https://JuliaML.github.io/MLUtils.jl/stable)
[](https://JuliaML.github.io/MLUtils.jl/dev)
[](https://github.com/JuliaML/MLUtils.jl/actions/workflows/CI.yml?query=branch%3Amain)
[](https://codecov.io/gh/JuliaML/MLUtils.jl)
*MLUtils.jl* defines interfaces and implements common utilities for Machine Learning pipelines.
## Features
- An extensible dataset interface (`numobs` and `getobs`).
- Data iteration and dataloaders (`eachobs` and `DataLoader`).
- Lazy data views (`obsview`).
- Resampling procedures (`undersample` and `oversample`).
- Train/test splits (`splitobs`)
- Data partitioning and aggregation tools (`batch`, `unbatch`, `chunk`, `group_counts`, `group_indices`).
- Folds for cross-validation (`kfolds`, `leavepout`).
- Datasets lazy tranformations (`mapobs`, `filterobs`, `groupobs`, `joinobs`, `shuffleobs`).
- Toy datasets for demonstration purpose.
- Other data handling utilities (`flatten`, `normalise`, `unsqueeze`, `stack`, `unstack`).
## Examples
Let us take a look at a hello world example to get a feeling for
how to use this package in a typical ML scenario.
```julia
using MLUtils
# X is a matrix of floats
# Y is a vector of strings
X, Y = load_iris()
# The iris dataset is ordered according to their labels,
# which means that we should shuffle the dataset before
# partitioning it into training- and test-set.
Xs, Ys = shuffleobs((X, Y))
# We leave out 15 % of the data for testing
cv_data, test_data = splitobs((Xs, Ys); at=0.85)
# Next we partition the data using a 10-fold scheme.
for (train_data, val_data) in kfolds(cv_data; k=10)
# We apply a lazy transform for data augmentation
train_data = mapobs(xy -> (xy[1] .+ 0.1 .* randn.(), xy[2]), train_data)
for epoch = 1:10
# Iterate over the data using mini-batches of 5 observations each
for (x, y) in eachobs(train_data, batchsize=5)
# ... train supervised model on minibatches here
end
end
end
```
In the above code snippet, the inner loop for `eachobs` is the
only place where data other than indices is actually being
copied. In fact, while `x` and `y` are materialized arrays,
all the rest are data views.
## Related Packages
*MLUtils.jl* brings together functionalities previously found in [LearnBase.jl](https://github.com/JuliaML/LearnBase.jl) , [MLDataPattern.jl](https://github.com/JuliaML/MLDataPattern.jl) and [MLLabelUtils.jl](https://github.com/JuliaML/MLLabelUtils.jl). These packages are now discontinued.
Other features were ported from the deep learning library [Flux.jl](https://github.com/FluxML/Flux.jl), as they are of general use.
[MLJ.jl](https://alan-turing-institute.github.io/MLJ.jl/dev/) is a more complete package for managing the whole machine learning pipeline if you are looking for a sklearn replacement.
| MLUtils | https://github.com/JuliaML/MLUtils.jl.git |
|
[
"MIT"
] | 0.4.4 | b45738c2e3d0d402dffa32b2c1654759a2ac35a4 | docs | 564 | # API Reference
## Index
```@index
Order = [:type, :function]
Modules = [MLUtils]
Pages = ["api.md"]
```
## Docs
```@docs
batch
batchsize
batchseq
BatchView
chunk
DataLoader
eachobs
fill_like
filterobs
flatten
getobs
getobs!
joinobs
group_counts
group_indices
groupobs
kfolds
leavepout
mapobs
numobs
normalise
obsview
ObsView
ones_like
oversample
randobs
rpad_constant
shuffleobs
splitobs
stack
unbatch
undersample
unsqueeze
unstack
zeros_like
```
## Datasets Docs
```@docs
Datasets.load_iris
Datasets.make_sin
Datasets.make_spiral
Datasets.make_poly
```
| MLUtils | https://github.com/JuliaML/MLUtils.jl.git |
|
[
"MIT"
] | 0.4.4 | b45738c2e3d0d402dffa32b2c1654759a2ac35a4 | docs | 2962 | # MLUtils.jl
[](https://JuliaML.github.io/MLUtils.jl/stable)
[](https://JuliaML.github.io/MLUtils.jl/dev)
[](https://github.com/JuliaML/MLUtils.jl/actions/workflows/CI.yml?query=branch%3Amain)
[](https://codecov.io/gh/JuliaML/MLUtils.jl)
`MLUtils.jl` defines interfaces and implements common utilities for Machine Learning pipelines.
## Features
- An extensible dataset interface (`numobs` and `getobs`).
- Data iteration and dataloaders (`eachobs` and `DataLoader`).
- Lazy data views (`obsview`).
- Resampling procedures (`undersample` and `oversample`).
- Train/test splits (`splitobs`)
- Data partitioning and aggregation tools (`batch`, `unbatch`, `chunk`, `group_counts`, `group_indices`).
- Folds for cross-validation (`kfolds`, `leavepout`).
- Datasets lazy tranformations (`mapobs`, `filterobs`, `groupobs`, `joinobs`, `shuffleobs`).
- Toy datasets for demonstration purpose.
- Other data handling utilities (`flatten`, `normalise`, `unsqueeze`, `stack`, `unstack`).
## Examples
Let us take a look at a hello world example to get a feeling for
how to use this package in a typical ML scenario.
```julia
using MLUtils
# X is a matrix of floats
# Y is a vector of strings
X, Y = load_iris()
# The iris dataset is ordered according to their labels,
# which means that we should shuffle the dataset before
# partitioning it into training- and test-set.
Xs, Ys = shuffleobs((X, Y))
# We leave out 15 % of the data for testing
cv_data, test_data = splitobs((Xs, Ys); at=0.85)
# Next we partition the data using a 10-fold scheme.
for (train_data, val_data) in kfolds(cv_data; k=10)
for epoch = 1:100
# Iterate over the data using mini-batches of 5 observations each
for (x, y) in eachobs(train_data, batchsize=5)
# ... train supervised model on minibatches here
end
end
end
```
In the above code snippet, the inner loop for `eachobs` is the
only place where data other than indices is actually being
copied. In fact, while `x` and `y` are materialized arrays,
all the rest are data views.
## Related Packages
`MLUtils.jl` brings together functionalities previously found in [LearnBase.jl](https://github.com/JuliaML/LearnBase.jl) , [MLDataPattern.jl](https://github.com/JuliaML/MLDataPattern.jl) and [MLLabelUtils.jl](https://github.com/JuliaML/MLLabelUtils.jl). These packages are now discontinued.
Other features were ported from the deep learning library [`Flux.jl`](https://github.com/FluxML/Flux.jl), as they are of general use.
[` MLJ.jl`](https://alan-turing-institute.github.io/MLJ.jl/dev/) is a more complete package for managing the whole machine learning pipeline if you are looking for a sklearn replacement.
| MLUtils | https://github.com/JuliaML/MLUtils.jl.git |
|
[
"MIT"
] | 0.9.4 | 36b450a98090c6b6c57cc84fa647013402c84650 | code | 2674 | using BenchmarkTools
using EarthSciData
using Dates
const fs = EarthSciData.GEOSFPFileSet("4x5", "A3dyn")
const itp4 = EarthSciData.DataSetInterpolator{Float64}(fs, "U", DateTime(2022, 5, 1))
const ts = DateTime(2022, 5, 1):Hour(1):DateTime(2022, 5, 3)
const lons = deg2rad.(-180.0:1:174)
const lats = deg2rad.(-90:1:85)
function interpfunc_serial()
for t ∈ datetime2unix.(ts)
EarthSciData.lazyload!(itp4, t)
for lon ∈ lons, lat ∈ lats
EarthSciData.interp_unsafe(itp4, t, lon, lat, 1.0)
end
end
end
function interpfunc_threads()
for t ∈ datetime2unix.(ts)
EarthSciData.lazyload!(itp4, t)
Threads.@threads for lon ∈ deg2rad.(-180.0:1:174)
for lat ∈ deg2rad.(-90:1:85)
EarthSciData.interp_unsafe(itp4, t, lon, lat, 1.0)
end
end
end
end
suite = BenchmarkGroup()
suite["GEOSFP"] = BenchmarkGroup()
suite["GEOSFP"]["Interpolation serial"] = @benchmarkable interpfunc_serial()
suite["GEOSFP"]["Interpolation threaded"] = @benchmarkable interpfunc_threads()
using EarthSciMLBase, ModelingToolkit
using ModelingToolkit: t, D
using DomainSets, Dates
using DifferentialEquations
using DynamicQuantities
struct SysCoupler
sys
end
function EarthSciMLBase.couple2(sys::SysCoupler, emis::EarthSciData.NEI2016MonthlyEmisCoupler)
sys, emis = sys.sys, emis.sys
operator_compose(sys, emis)
end
function nei_simulator()
@parameters lat = deg2rad(40.0) lon = deg2rad(-97.0) lev = 0.0
@variables ACET(t) = 0.0 [unit = u"kg*m^-3"]
@constants c = 1000 [unit = u"s"]
@named sys = ODESystem(
[D(ACET) ~ 0], t,
metadata=Dict(:coupletype => SysCoupler)
)
emis = NEI2016MonthlyEmis("mrggrid_withbeis_withrwc", lon, lat, lev; dtype=Float64)
starttime = datetime2unix(DateTime(2016, 5, 1))
endtime = datetime2unix(DateTime(2016, 5, 2))
domain = DomainInfo(
constIC(16.0, t ∈ Interval(starttime, endtime)),
constBC(16.0,
lon ∈ Interval(deg2rad(-115), deg2rad(-68.75)),
lat ∈ Interval(deg2rad(25), deg2rad(53.7)),
lev ∈ Interval(1, 2)
))
csys = couple(sys, emis, domain)
Simulator(csys, [deg2rad(1.25), deg2rad(1.2), 1])
end
suite["NEI Simulator"] = BenchmarkGroup()
sim = nei_simulator()
st = SimulatorStrangSerial(Tsit5(), Euler(), 100.0)
suite["NEI Simulator"]["Serial"] = @benchmarkable run!($sim, $st)
st = SimulatorStrangThreads(Tsit5(), Euler(), 100.0)
suite["NEI Simulator"]["Threads"] = @benchmarkable run!($sim, $st)
tune!(suite, verbose = true)
results = run(suite, verbose = true)
BenchmarkTools.save("output.json", median(results))
| EarthSciData | https://github.com/EarthSciML/EarthSciData.jl.git |
|
[
"MIT"
] | 0.9.4 | 36b450a98090c6b6c57cc84fa647013402c84650 | code | 841 | using EarthSciData
using Documenter
DocMeta.setdocmeta!(EarthSciData, :DocTestSetup, :(using EarthSciData); recursive=true)
makedocs(;
modules=[EarthSciData],
authors="EarthSciML Authors",
repo="https://github.com/EarthSciML/EarthSciData.jl/blob/{commit}{path}#{line}",
sitename="EarthSciData.jl",
format=Documenter.HTML(;
prettyurls=get(ENV, "CI", "false") == "true",
canonical="https://earthsciml.github.io/EarthSciData.jl",
assets=String[],
repolink="https://github.com/EarthSciML/EarthSciData.jl"
),
pages=[
"Home" => "index.md",
"GEOS-FP" => "geosfp.md",
"2016 NEI" => "nei2016.md",
"API" => "api.md",
"🔗 Benchmarks" => "benchmarks.md",
],
)
deploydocs(;
repo="github.com/EarthSciML/EarthSciData.jl",
devbranch="main",
)
| EarthSciData | https://github.com/EarthSciML/EarthSciData.jl.git |
|
[
"MIT"
] | 0.9.4 | 36b450a98090c6b6c57cc84fa647013402c84650 | code | 812 | module EarthSciData
using Dates, Downloads, Printf
using DocStringExtensions
using SciMLBase: DiscreteCallback
using Interpolations, DataInterpolations
using NCDatasets, ModelingToolkit, Symbolics, Proj
using ModelingToolkit: t
using EarthSciMLBase, DiffEqCallbacks
using DynamicQuantities, Latexify, ProgressMeter
using Scratch
# TODO: Hotfix to deal with issue https://github.com/SciML/DataInterpolations.jl/issues/331
# Remove this when the issue is fixed.
(itp::DataInterpolations.LinearInterpolation)(x::DynamicQuantities.Quantity) = itp(ustrip(x.value))
# General utilities
include("load.jl")
include("utils.jl")
include("update_callback.jl")
# Specific data sets
include("netcdf.jl")
include("geosfp.jl")
include("nei2016monthly.jl")
include("netcdf_output.jl")
# Coupling
include("coupling.jl")
end
| EarthSciData | https://github.com/EarthSciML/EarthSciData.jl.git |
|
[
"MIT"
] | 0.9.4 | 36b450a98090c6b6c57cc84fa647013402c84650 | code | 270 | function EarthSciMLBase.couple2(e::NEI2016MonthlyEmisCoupler, g::GEOSFPCoupler)
e, g = e.sys, g.sys
e = param_to_var(e, :lat, :lon, :lev)
ConnectorSystem([
e.lat ~ g.lat,
e.lon ~ g.lon,
e.lev ~ g.lev,
], e, g)
end | EarthSciData | https://github.com/EarthSciML/EarthSciData.jl.git |
|
[
"MIT"
] | 0.9.4 | 36b450a98090c6b6c57cc84fa647013402c84650 | code | 11651 | export GEOSFP, partialderivatives_δPδlev_geosfp
"""
$(SIGNATURES)
GEOS-FP data as archived for use with GEOS-Chem classic.
Domain options (as of 2022-01-30):
- 4x5
- 0.125x0.15625_AS
- 0.125x0.15625_EU
- 0.125x0.15625_NA
- 0.25x0.3125
- 0.25x0.3125_AF
- 0.25x0.3125_AS
- 0.25x0.3125_CH
- 0.25x0.3125_EU
- 0.25x0.3125_ME
- 0.25x0.3125_NA
- 0.25x0.3125_OC
- 0.25x0.3125_RU
- 0.25x0.3125_SA
- 0.5x0.625
- 0.5x0.625_AS
- 0.5x0.625_CH
- 0.5x0.625_EU
- 0.5x0.625_NA
- 2x2.5
- 4x5
- C180
- C720
- NATIVE
- c720
Possible `filetype`s are:
- `:A1`
- `:A3cld`
- `:A3dyn`
- `:A3mstC`
- `:A3mstE`
- `:I3`
See http://geoschemdata.wustl.edu/ExtData/ for current options.
"""
struct GEOSFPFileSet <: FileSet
mirror::AbstractString
domain
filetype
GEOSFPFileSet(domain, filetype) = new("http://geoschemdata.wustl.edu/ExtData/", domain, filetype)
end
"""
$(SIGNATURES)
File path on the server relative to the host root; also path on local disk relative to `ENV["EARTHSCIDATADIR"]`
(or a scratch directory if that environment variable is not set).
"""
function relpath(fs::GEOSFPFileSet, t::DateTime)
year = Dates.format(t, "Y")
month = @sprintf("%.2d", Dates.month(t))
day = @sprintf("%.2d", Dates.day(t))
domain = replace(fs.domain, '.' => "")
domain = replace(domain, '_' => ".")
return joinpath("GEOS_$(fs.domain)/GEOS_FP/$year/$month", "GEOSFP.$(year)$(month)$day.$(fs.filetype).$(domain).nc")
end
function DataFrequencyInfo(fs::GEOSFPFileSet, t::DateTime)::DataFrequencyInfo
lock(nclock) do
filepath = maybedownload(fs, t)
ds = getnc(filepath)
sd = ds.attrib["Start_Date"]
st = ds.attrib["Start_Time"]
dt = ds.attrib["Delta_Time"]
start = DateTime(sd * " " * st, dateformat"yyyymmdd HH:MM:SS.s")
frequency = Second(parse(Int64, dt[1:2])) * 3600 + Second(parse(Int64, dt[3:4])) * 60 +
Second(parse(Int64, dt[5:6]))
centerpoints = ds["time"][:]
return DataFrequencyInfo(start, frequency, centerpoints)
end
end
"""
$(SIGNATURES)
Load the data in place for the given variable name at the given time.
"""
function loadslice!(data::AbstractArray, fs::GEOSFPFileSet, t::DateTime, varname)
lock(nclock) do
filepath = maybedownload(fs, t)
ds = getnc(filepath)
var = loadslice!(data, fs, ds, t, varname, "time") # Load data from NetCDF file.
scale, _ = to_unit(var.attrib["units"])
if scale != 1
data .*= scale
end
end
nothing
end
"""
$(SIGNATURES)
Load the data for the given variable name at the given time.
"""
function loadmetadata(fs::GEOSFPFileSet, t::DateTime, varname)::MetaData
lock(nclock) do
filepath = maybedownload(fs, t)
ds = getnc(filepath)
timedim = "time"
var = ds[varname]
dims = collect(NCDatasets.dimnames(var))
@assert timedim ∈ dims "Variable $varname does not have a dimension named '$timedim'."
time_index = findfirst(isequal(timedim), dims)
dims = deleteat!(dims, time_index)
varsize = deleteat!(collect(size(var)), time_index)
_, units = to_unit(var.attrib["units"])
description = var.attrib["long_name"]
@assert var.attrib["scale_factor"] == 1.0 "Unexpected scale factor."
coords = [ds[d][:] for d ∈ dims]
xdim = findfirst((x) -> x == "lon", dims)
ydim = findfirst((x) -> x == "lat", dims)
@assert xdim > 0 "GEOSFP `lon` dimension not found"
@assert ydim > 0 "GEOSFP `lat` dimension not found"
# Convert from degrees to radians (so we are using SI units)
coords[xdim] .= deg2rad.(coords[xdim])
coords[ydim] .= deg2rad.(coords[ydim])
# This projection will assume the inputs are radians when used within
# a Proj pipeline: https://proj.org/en/9.3/operations/pipeline.html
prj = "+proj=longlat +datum=WGS84 +no_defs"
return MetaData(coords, units, description, dims, varsize, prj, xdim, ydim)
end
end
"""
$(SIGNATURES)
Return the variable names associated with this FileSet.
"""
function varnames(fs::GEOSFPFileSet, t::DateTime)
lock(nclock) do
filepath = maybedownload(fs, t)
ds = getnc(filepath)
return [setdiff(keys(ds), keys(ds.dim))...]
end
end
# Hybrid grid parameters from https://wiki.seas.harvard.edu/geos-chem/index.php/GEOS-Chem_vertical_grids
const Ap = DataInterpolations.LinearInterpolation([
0.000000e+00, 4.804826e-02, 6.593752e+00, 1.313480e+01, 1.961311e+01, 2.609201e+01,
3.257081e+01, 3.898201e+01, 4.533901e+01, 5.169611e+01, 5.805321e+01, 6.436264e+01,
7.062198e+01, 7.883422e+01, 8.909992e+01, 9.936521e+01, 1.091817e+02, 1.189586e+02,
1.286959e+02, 1.429100e+02, 1.562600e+02, 1.696090e+02, 1.816190e+02, 1.930970e+02,
2.032590e+02, 2.121500e+02, 2.187760e+02, 2.238980e+02, 2.243630e+02, 2.168650e+02,
2.011920e+02, 1.769300e+02, 1.503930e+02, 1.278370e+02, 1.086630e+02, 9.236572e+01,
7.851231e+01, 6.660341e+01, 5.638791e+01, 4.764391e+01, 4.017541e+01, 3.381001e+01,
2.836781e+01, 2.373041e+01, 1.979160e+01, 1.645710e+01, 1.364340e+01, 1.127690e+01,
9.292942e+00, 7.619842e+00, 6.216801e+00, 5.046801e+00, 4.076571e+00, 3.276431e+00,
2.620211e+00, 2.084970e+00, 1.650790e+00, 1.300510e+00, 1.019440e+00, 7.951341e-01,
6.167791e-01, 4.758061e-01, 3.650411e-01, 2.785261e-01, 2.113490e-01, 1.594950e-01,
1.197030e-01, 8.934502e-02, 6.600001e-02, 4.758501e-02, 3.270000e-02, 2.000000e-02,
1.000000e-02] .* 100, 1:73) # Pa
const Bp = DataInterpolations.LinearInterpolation([
1.000000e+00, 9.849520e-01, 9.634060e-01, 9.418650e-01, 9.203870e-01, 8.989080e-01,
8.774290e-01, 8.560180e-01, 8.346609e-01, 8.133039e-01, 7.919469e-01, 7.706375e-01,
7.493782e-01, 7.211660e-01, 6.858999e-01, 6.506349e-01, 6.158184e-01, 5.810415e-01,
5.463042e-01, 4.945902e-01, 4.437402e-01, 3.928911e-01, 3.433811e-01, 2.944031e-01,
2.467411e-01, 2.003501e-01, 1.562241e-01, 1.136021e-01, 6.372006e-02, 2.801004e-02,
6.960025e-03, 8.175413e-09, 0.000000e+00, 0.000000e+00, 0.000000e+00, 0.000000e+00,
0.000000e+00, 0.000000e+00, 0.000000e+00, 0.000000e+00, 0.000000e+00, 0.000000e+00,
0.000000e+00, 0.000000e+00, 0.000000e+00, 0.000000e+00, 0.000000e+00, 0.000000e+00,
0.000000e+00, 0.000000e+00, 0.000000e+00, 0.000000e+00, 0.000000e+00, 0.000000e+00,
0.000000e+00, 0.000000e+00, 0.000000e+00, 0.000000e+00, 0.000000e+00, 0.000000e+00,
0.000000e+00, 0.000000e+00, 0.000000e+00, 0.000000e+00, 0.000000e+00, 0.000000e+00,
0.000000e+00, 0.000000e+00, 0.000000e+00, 0.000000e+00, 0.000000e+00, 0.000000e+00,
0.000000e+00], 1:73)
struct GEOSFPCoupler
sys
end
"""
$(SIGNATURES)
A data loader for GEOS-FP data as archived for use with GEOS-Chem classic.
Domain options (as of 2022-01-30):
- 4x5
- 0.125x0.15625_AS
- 0.125x0.15625_EU
- 0.125x0.15625_NA
- 0.25x0.3125
- 0.25x0.3125_AF
- 0.25x0.3125_AS
- 0.25x0.3125_CH
- 0.25x0.3125_EU
- 0.25x0.3125_ME
- 0.25x0.3125_NA
- 0.25x0.3125_OC
- 0.25x0.3125_RU
- 0.25x0.3125_SA
- 0.5x0.625
- 0.5x0.625_AS
- 0.5x0.625_CH
- 0.5x0.625_EU
- 0.5x0.625_NA
- 2x2.5
- 4x5
- C180
- C720
- NATIVE
- c720
`coord_defaults` can be used to provide default values for the coordinates of the
domain. For example if we want to perform a 2D simulation with a vertical dimension,
we can set `coord_defaults = Dict(:lev => 1)`.
`dtype` represents the desired data type of the interpolated values. The native data type
for this dataset is Float32.
See http://geoschemdata.wustl.edu/ExtData/ for current options.
"""
function GEOSFP(domain::AbstractString; coord_defaults=Dict{Symbol,Number}(), spatial_ref="+proj=longlat +datum=WGS84 +no_defs", dtype=Float32, name=:GEOSFP, kwargs...)
filesets = Dict{String,GEOSFPFileSet}(
"A1" => GEOSFPFileSet(domain, "A1"),
"A3cld" => GEOSFPFileSet(domain, "A3cld"),
"A3dyn" => GEOSFPFileSet(domain, "A3dyn"),
"A3mstC" => GEOSFPFileSet(domain, "A3mstC"),
"A3mstE" => GEOSFPFileSet(domain, "A3mstE"),
"I3" => GEOSFPFileSet(domain, "I3"))
sample_time = DateTime(2022, 5, 1) # Dummy time to get variable names and dimensions from data.
eqs = []
vars = []
itps = []
for (filename, fs) in filesets
for varname ∈ varnames(fs, sample_time)
itp = DataSetInterpolator{dtype}(fs, varname, sample_time; spatial_ref, kwargs...)
dims = dimnames(itp, sample_time)
coords = Num[]
for dim ∈ dims
d = Symbol(dim)
if d ∈ keys(coord_defaults) # Set a default value for this coordinate.
v = (@parameters $d = coord_defaults[d])[1]
else # No default value.
v = (@parameters $d)[1]
end
push!(coords, v)
end
eq = create_interp_equation(itp, filename, t, sample_time, coords)
push!(eqs, eq)
push!(vars, eq.lhs)
push!(itps, itp)
end
end
# Implement hybrid grid pressure: https://wiki.seas.harvard.edu/geos-chem/index.php/GEOS-Chem_vertical_grids
@constants P_unit = 1.0 [unit = u"Pa", description = "Unit pressure"]
@variables P(t) [unit = u"Pa", description = "Pressure"]
@variables I3₊PS(t) [unit = u"Pa", description = "Pressure at the surface"]
d = :lev
if d ∈ keys(coord_defaults) # Set a default value for this coordinate.
lev = (@parameters $d = coord_defaults[d])[1]
else # No default value.
lev = (@parameters $d)[1]
end
pressure_eq = P ~ P_unit * Ap(lev) + Bp(lev) * I3₊PS
push!(eqs, pressure_eq)
sys = ODESystem(eqs, t, name=name,
metadata=Dict(:coupletype => GEOSFPCoupler))
cb = UpdateCallbackCreator(sys, vars, itps)
return sys, cb
end
function EarthSciMLBase.couple2(mw::EarthSciMLBase.MeanWindCoupler, g::GEOSFPCoupler)
mw, g = mw.sys, g.sys
eqs = [mw.v_lon ~ g.A3dyn₊U]
# Only add the number of dimensions present in the mean wind system.
length(unknowns(mw)) > 1 ? push!(eqs, mw.v_lat ~ g.A3dyn₊V) : nothing
length(unknowns(mw)) > 2 ? push!(eqs, mw.v_lev ~ g.A3dyn₊OMEGA) : nothing
ConnectorSystem(
eqs,
mw, g,
)
end
"""
$(SIGNATURES)
Return a function to calculate coefficients to multiply the
`δ(u)/δ(lev)` partial derivative operator by
to convert a variable named `u` from δ(u)/δ(lev)` to `δ(u)/δ(P)`,
i.e. from vertical level number to pressure in hPa.
The return format is `coordinate_index => conversion_factor`.
"""
function partialderivatives_δPδlev_geosfp(geosfp; default_lev=1.0)
# Find index for surface pressure.
ii = findfirst((x) -> x == :I3₊PS, [Symbolics.tosymbol(eq.lhs, escape=false) for eq in equations(geosfp)])
# Get interpolator for surface pressure.
ps = equations(geosfp)[ii].rhs
@constants P_unit = 1.0 [unit = u"Pa", description = "Unit pressure"]
# Function to calculate pressure at a given level in the hybrid grid.
# This is on a staggered grid so level=1 is the grid bottom.
P(levx) = (P_unit * Ap(levx) + Bp(levx) * ps)
(pvars::AbstractVector) -> begin
levindex = EarthSciMLBase.varindex(pvars, :lev)
if !isnothing(levindex)
lev = pvars[levindex]
else
lev = default_lev
end
# d(u) / d(P) = d(u) / d(lev) / ( d(P) / d(lev) )
δPδlev = 0.5 / (P(Num(lev) + 0.5) - P(Num(lev)))
return Dict(levindex => δPδlev)
end
end
| EarthSciData | https://github.com/EarthSciML/EarthSciData.jl.git |
|
[
"MIT"
] | 0.9.4 | 36b450a98090c6b6c57cc84fa647013402c84650 | code | 18435 | export interp!
download_cache = ("EARTHSCIDATADIR" ∈ keys(ENV)) ? ENV["EARTHSCIDATADIR"] : @get_scratch!("earthsci_data")
function __init__()
global download_cache = ("EARTHSCIDATADIR" ∈ keys(ENV)) ? ENV["EARTHSCIDATADIR"] : @get_scratch!("earthsci_data")
[delete!(ncfiledict, key) for key in keys(ncfiledict)] # Remove any files opened during precompilation because they're not valid any more.
end
"""
An interface for types describing a dataset, potentially comprised of multiple files.
To satisfy this interface, a type must implement the following methods:
- `relpath(fs::FileSet, t::DateTime)`
- `url(fs::FileSet, t::DateTime)`
- `localpath(fs::FileSet, t::DateTime)`
- `DataFrequencyInfo(fs::FileSet, t::DateTime)::DataFrequencyInfo`
- `loadmetadata(fs::FileSet, t::DateTime, varname)::MetaData`
- `loadslice!(cache::AbstractArray, fs::FileSet, t::DateTime, varname)`
- `varnames(fs::FileSet, t::DateTime)`
"""
abstract type FileSet end
"""
$(SIGNATURES)
Return the URL for the file for the given `DateTime`.
"""
url(fs::FileSet, t::DateTime) = joinpath(fs.mirror, relpath(fs, t))
"""
$(SIGNATURES)
Return the local path for the file for the given `DateTime`.
"""
localpath(fs::FileSet, t::DateTime) = joinpath(download_cache, relpath(fs, t))
"""
$(SIGNATURES)
Check if the specified file exists locally. If not, download it.
"""
function maybedownload(fs::FileSet, t::DateTime)
p = localpath(fs, t)
if isfile(p)
return p
end
if !isdir(dirname(p))
@info "Creating directory $(dirname(p))"
mkpath(dirname(p))
end
u = url(fs, t)
try
prog = Progress(100; desc="Downloading $(basename(u)):", dt=0.1)
Downloads.download(u, p, progress=(total::Integer, now::Integer) -> begin
prog.n = total
update!(prog, now)
end)
catch e # Delete partially downloaded file if an error occurs.
rm(p, force=true)
rethrow(e)
end
return p
end
"""
Information about a data array.
$(FIELDS)
"""
struct MetaData
"The locations associated with each data point in the array."
coords::Vector{Vector{Float64}}
"Physical units of the data, e.g. m s⁻¹."
units::DynamicQuantities.AbstractQuantity
"Description of the data."
description::AbstractString
"Dimensions of the data, e.g. (lat, lon, layer)."
dimnames::AbstractVector
"Dimension sizes of the data, e.g. (180, 360, 30)."
varsize::AbstractVector
"The spatial reference system of the data, e.g. \"+proj=longlat +datum=WGS84 +no_defs\" for lat-lon data."
native_sr::AbstractString
"The index number of the x-dimension (e.g. longitude)"
xdim::Int
"The index number of the y-dimension (e.g. latitude)"
ydim::Int
end
"""
Information about the temporal frequency of archived data.
$(FIELDS)
"""
struct DataFrequencyInfo
"Beginning of time of the time series."
start::DateTime
"Interval between each record."
frequency::Union{Dates.Period,Dates.CompoundPeriod}
"Time representing the temporal center of each record."
centerpoints::AbstractVector
end
"""
Return the time endpoints correcponding to each centerpoint
"""
endpoints(t::DataFrequencyInfo) = [(cp - t.frequency / 2, cp + t.frequency / 2) for cp in t.centerpoints]
"""
Return the index of the centerpoint closest to the given time.
"""
function centerpoint_index(t_info::DataFrequencyInfo, t)
eps = endpoints(t_info)
if t > eps[end][2]
return length(eps) + 1
end
t_index = ((ep) -> ep[1] <= t < ep[2]).(eps)
@assert sum(t_index) == 1 "Expected exactly one time step to match, instead $(sum(t_index)) timesteps match."
argmax(t_index)
end
"""
$(SIGNATURES)
DataSetInterpolators are used to interpolate data from a `FileSet` to represent a given time and location.
Data is loaded (and downloaded) lazily, so the first time you use it on a for a given
dataset and time period it may take a while to load. Each time step is downloaded and loaded as it is needed
during the simulation and cached on the hard drive at the path specified by the `\\\$EARTHSCIDATADIR`
environment variable, or in a scratch directory if that environment variable has not been specified.
The interpolator will also cache data in memory representing the
data records for the times immediately before and after the current time step.
`varname` is the name of the variable to interpolate. `default_time` is the time to use when initializing
the interpolator. `spatial_ref` is the spatial reference system that the simulation will be using.
`cache_size` is the number of time steps that should be held in the cache at any given time
(default=3; must be >=3).
!!! warning
WARNING: This interpolator includes a hack so that the function `deepcopy` does not copy the interpolator,
it just returns the interpolator.
This is necessary to allow us to update the interpolator from a callback, but it may cause unintended side effects.
"""
mutable struct DataSetInterpolator{To,N,N2,FT,ITPT}
fs::FileSet
varname::AbstractString
data::Array{To,N}
interp_cache::Array{To,N}
itp::ITPT
load_cache::Array{To,N2}
metadata::MetaData
times::Vector{DateTime}
currenttime::DateTime
coord_trans::FT
loadrequest::Channel{DateTime}
loadresult::Channel
copyfinish::Channel{Int}
lock::ReentrantLock
initialized::Bool
kwargs
function DataSetInterpolator{To}(fs::FileSet, varname::AbstractString, default_time::DateTime; spatial_ref="+proj=longlat +datum=WGS84 +no_defs", cache_size=3, kwargs...) where {To<:Real}
cache_size >= 3 || throw(ArgumentError("cache_size must be at least 3"))
metadata = loadmetadata(fs, default_time, varname; kwargs...)
load_cache = zeros(To, repeat([1], length(metadata.varsize))...)
data = zeros(To, repeat([2], length(metadata.varsize))..., cache_size) # Add a dimension for time.
interp_cache = similar(data)
N = ndims(data)
N2 = N - 1
times = [DateTime(0, 1, 1) + Hour(i) for i ∈ 1:cache_size]
_, itp2 = create_interpolator!(To, interp_cache, data, metadata, times)
ITPT = typeof(itp2)
if spatial_ref == metadata.native_sr
coord_trans = (x) -> x # No transformation needed.
else
t = Proj.Transformation("+proj=pipeline +step " * spatial_ref * " +step " * metadata.native_sr)
coord_trans = (locs) -> begin
x, y = t(locs[metadata.xdim], locs[metadata.ydim])
replace_in_tuple(locs, metadata.xdim, To(x), metadata.ydim, To(y))
end
end
FT = typeof(coord_trans)
itp = new{To,N,N2,FT,ITPT}(fs, varname, data, interp_cache, itp2, load_cache,
metadata, times, DateTime(1, 1, 1), coord_trans,
Channel{DateTime}(0), Channel(1), Channel{Int}(0),
ReentrantLock(), false, kwargs)
Threads.@spawn async_loader(itp)
itp
end
end
function replace_in_tuple(t::NTuple{N,T}, index1::Int, v1::T, index2::Int, v2::T) where {T,N}
ntuple(i -> i == index1 ? v1 : i == index2 ? v2 : t[i], N)
end
function Base.show(io::IO, itp::DataSetInterpolator)
print(io, "DataSetInterpolator{$(typeof(itp.fs)), $(itp.varname)}")
end
# FIXME: WARNING: This is a hack to make sure that the interpolator is not copied
# so that we can update it from a callback. It may cause unintended side effects.
Base.deepcopy_internal(itp::DataSetInterpolator, dict::IdDict) = itp
""" Return the units of the data. """
ModelingToolkit.get_unit(itp::DataSetInterpolator) = itp.metadata.units
"""
Convert a vector of evenly spaced grid points to a range.
The `reltol` parameter specifies the relative tolerance for the grid spacing,
which is necessary to account for different numbers of days in each month
and things like that.
"""
function knots2range(knots, reltol=0.05)
dx = diff(knots)
dx_mean = sum(dx) / length(dx)
@assert all(abs.(1 .- dx ./ dx_mean) .<= reltol) "Knots ($knots) must be evenly spaced within reltol=$reltol."
dx = (knots[end] - knots[begin]) / (length(knots) - 1)
# Need to do weird range creation to avoid rounding errors.
return knots[begin]:dx:(knots[begin]+dx*(length(knots)-1))
end
"""Create a new interpolator, overwriting `interp_cache`."""
function create_interpolator!(To, interp_cache, data, metadata::MetaData, times)
# We originally create the interpolator with a small array to avoid
# unnecessary memory use, so we size the coordinate to match the data size.
# However, when we're updating the interpolator below me make sure the
# data size matches the original coordinate size.
coords = [metadata.coords[i][1:size(data, i)] for i ∈ 1:length(metadata.coords)]
grid = Tuple(knots2range.([coords..., datetime2unix.(times)]))
copyto!(interp_cache, data)
itp = interpolate!(interp_cache, BSpline(Linear()))
itp = scale(itp, grid)
return grid, itp
end
function update_interpolator!(itp::DataSetInterpolator{To}) where {To}
if size(itp.interp_cache) != size(itp.data)
itp.interp_cache = similar(itp.data)
end
grid, itp2 = create_interpolator!(To, itp.interp_cache, itp.data, itp.metadata, itp.times)
@assert all([length(g) for g in grid] .== size(itp.data)) "invalid data size: $([length(g) for g in grid]) != $(size(itp.data))"
itp.itp = itp2
end
" Return the next interpolation time point for this interpolator. "
function nexttimepoint(itp::DataSetInterpolator, t::DateTime)
ti = DataFrequencyInfo(itp.fs, t)
currenttimepoint(itp, t + ti.frequency)
end
" Return the previous interpolation time point for this interpolator. "
function prevtimepoint(itp::DataSetInterpolator, t::DateTime)
ti = DataFrequencyInfo(itp.fs, t)
ci = centerpoint_index(ti, t)
if ci != 1
return ti.centerpoints[ci-1]
end
tt = t - ti.frequency * 0.75 # Just go most of the way because some months etc. have different lengths.
ti = DataFrequencyInfo(itp.fs, tt)
ti.centerpoints[centerpoint_index(ti, tt)]
end
" Return the current interpolation time point for this interpolator. "
function currenttimepoint(itp::DataSetInterpolator, t::DateTime)
ti = DataFrequencyInfo(itp.fs, t)
ci = centerpoint_index(ti, t)
if ci <= length(ti.centerpoints)
return ti.centerpoints[ci]
end
tt = t + ti.frequency * 0.75 # Just go most of the way because some months etc. have different lengths.
ti = DataFrequencyInfo(itp.fs, tt)
ti.centerpoints[centerpoint_index(ti, tt)]
end
" Load the time points that should be cached in this interpolator. "
function interp_cache_times!(itp::DataSetInterpolator, t::DateTime)
cache_size = length(itp.times)
times = Vector{DateTime}(undef, cache_size)
centerpoint = currenttimepoint(itp, t)
# Currently assuming we're going forwards in time.
if t < centerpoint # Load data starting with current time step.
tt = prevtimepoint(itp, t)
else # Load data starting with previous time step.
tt = centerpoint
end
for i in 1:cache_size
times[i] = tt
tt = nexttimepoint(itp, tt)
end
times
end
" Asynchronously load data, anticipating which time will be requested next. "
function async_loader(itp::DataSetInterpolator)
tt = DateTime(0, 1, 10)
for t ∈ itp.loadrequest
if t != tt
try
loadslice!(itp.load_cache, itp.fs, t, itp.varname; itp.kwargs...)
tt = t
catch err
@error err
put!(itp.loadresult, err)
rethrow(err)
end
end
put!(itp.loadresult, 0) # Let the requestor know that we've finished.
# Anticipate what the next request is going to be for and load that data.
take!(itp.copyfinish)
try
tt = nexttimepoint(itp, tt)
loadslice!(itp.load_cache, itp.fs, tt, itp.varname; itp.kwargs...)
catch err
@error err
rethrow(err)
end
end
end
function initialize!(itp::DataSetInterpolator, t::DateTime)
if itp.initialized == false
itp.load_cache = zeros(eltype(itp.load_cache), itp.metadata.varsize...)
itp.data = zeros(eltype(itp.data), itp.metadata.varsize..., size(itp.data, length(size(itp.data)))) # Add a dimension for time.
itp.initialized = true
end
times = interp_cache_times!(itp, t) # Figure out which times we need.
# Figure out the overlap between the times we have and the times we need.
times_in_cache = intersect(times, itp.times)
idxs_in_cache = [findfirst(x -> x == times_in_cache[i], itp.times) for i in eachindex(times_in_cache)]
idxs_in_times = [findfirst(x -> x == times_in_cache[i], times) for i in eachindex(times_in_cache)]
idxs_not_in_times = setdiff(eachindex(times), idxs_in_times)
# Move data we already have to where it should be.
N = ndims(itp.data)
selectdim(itp.data, N, idxs_in_times) .= selectdim(itp.data, N, idxs_in_cache)
# Load the additional times we need
for idx in idxs_not_in_times
d = selectdim(itp.data, N, idx)
put!(itp.loadrequest, times[idx]) # Request next data
r = take!(itp.loadresult) # Wait for results
if r != 0
throw(r)
end
d .= itp.load_cache # Copy results to correct location
put!(itp.copyfinish, 0) # Let the loader know we've finished copying
end
itp.times = times
itp.currenttime = t
@assert issorted(itp.times) "Interpolator times are in wrong order"
update_interpolator!(itp)
end
function lazyload!(itp::DataSetInterpolator, t::DateTime)
lock(itp.lock) do
if itp.currenttime == t
return
end
if !itp.initialized # Initialize new interpolator.
initialize!(itp, t)
return
end
if t <= itp.times[begin] || t > itp.times[end-1]
initialize!(itp, t)
end
end
end
lazyload!(itp::DataSetInterpolator, t::AbstractFloat) = lazyload!(itp, Dates.unix2datetime(t))
"""
$(SIGNATURES)
Return the dimension names associated with this interpolator.
"""
function dimnames(itp::DataSetInterpolator, t::DateTime)
lazyload!(itp, t)
itp.metadata.dimnames
end
"""
$(SIGNATURES)
Return the units of the data associated with this interpolator.
"""
function units(itp::DataSetInterpolator, t::DateTime)
lazyload!(itp, t)
itp.metadata.units
end
"""
$(SIGNATURES)
Return the description of the data associated with this interpolator.
"""
function description(itp::DataSetInterpolator, t::DateTime)
lazyload!(itp, t)
itp.metadata.description
end
"""
$(SIGNATURES)
Return the value of the given variable from the given dataset at the given time and location.
"""
function interp!(itp::DataSetInterpolator{T,N,N2}, t::DateTime, locs::Vararg{T,N2})::T where {T,N,N2}
lazyload!(itp, t)
interp_unsafe(itp, t, locs...)
end
"""
Interpolate without checking if the data has been correctly loaded for the given time.
"""
@generated function interp_unsafe(itp::DataSetInterpolator{T,N,N2}, t::DateTime, locs::Vararg{T,N2})::T where {T,N,N2}
if N2 == N - 1 # Number of locs has to be one less than the number of data dimensions so we can add the time in.
quote
locs = itp.coord_trans(locs)
try
itp.itp(locs..., datetime2unix(t))
catch err
# FIXME(CT): This is needed because ModelingToolkit sometimes
# calls the interpolator for the beginning of the simulation time period,
# and we don't have a way to update for that proactively.
lazyload!(itp, t)
itp.itp(locs..., datetime2unix(t))
end
end
else
throw(ArgumentError("N2 must be equal to N-1"))
end
end
"""
Interpolation with a unix timestamp.
"""
function interp!(itp::DataSetInterpolator, t::Real, locs::Vararg{T,N})::T where {T,N}
interp!(itp, Dates.unix2datetime(t), locs...)
end
function interp_unsafe(itp::DataSetInterpolator, t::Real, locs::Vararg{T,N})::T where {T,N}
interp_unsafe(itp, Dates.unix2datetime(t), locs...)
end
# Dummy function for unit validation. Basically ModelingToolkit
# will call the function with a DynamicQuantities.Quantity or an integer to
# get information about the type and units of the output.
interp!(itp::Union{DynamicQuantities.AbstractQuantity,Real}, t, locs...) = itp
interp_unsafe(itp::Union{DynamicQuantities.AbstractQuantity,Real}, t, locs...) = itp
# Symbolic tracing, for different numbers of dimensions (up to three dimensions).
@register_symbolic interp!(itp::DataSetInterpolator, t, loc1, loc2, loc3)
@register_symbolic interp!(itp::DataSetInterpolator, t, loc1, loc2) false
@register_symbolic interp!(itp::DataSetInterpolator, t, loc1) false
@register_symbolic interp_unsafe(itp::DataSetInterpolator, t, loc1, loc2, loc3)
@register_symbolic interp_unsafe(itp::DataSetInterpolator, t, loc1, loc2) false
@register_symbolic interp_unsafe(itp::DataSetInterpolator, t, loc1) false
"""
$(SIGNATURES)
Create an equation that interpolates the given dataset at the given time and location.
`filename` is an identifier for the dataset, and `t` is the time variable.
`wrapper_f` can specify a function to wrap the interpolated value, for example `eq -> eq / 2`
to divide the interpolated value by 2.
"""
function create_interp_equation(itp::DataSetInterpolator, filename, t, sample_time, coords; wrapper_f=v -> v)
# Create right hand side of equation.
if length(coords) == 3
rhs = wrapper_f(interp_unsafe(itp, t, coords[1], coords[2], coords[3]))
elseif length(coords) == 2
rhs = wrapper_f(interp_unsafe(itp, t, coords[1], coords[2]))
elseif length(coords) == 1
rhs = wrapper_f(interp_unsafe(itp, t, coords[1]))
else
error("Unexpected number of coordinates: $(length(coords))")
end
# Create left hand side of equation.
desc = description(itp, sample_time)
uu = ModelingToolkit.get_unit(rhs)
n = length(filename) > 0 ? Symbol("$(filename)₊$(itp.varname)") : Symbol("$(itp.varname)")
lhs = only(@variables $n(t) [unit = uu, description = desc])
lhs ~ rhs
end
Latexify.@latexrecipe function f(itp::EarthSciData.DataSetInterpolator)
return "$(split(string(typeof(itp.fs)), ".")[end]).$(itp.varname)"
end
| EarthSciData | https://github.com/EarthSciML/EarthSciData.jl.git |
|
[
"MIT"
] | 0.9.4 | 36b450a98090c6b6c57cc84fa647013402c84650 | code | 6251 | export NEI2016MonthlyEmis
"""
$(SIGNATURES)
Archived CMAQ emissions data.
Currently, only data for year 2016 is available.
"""
struct NEI2016MonthlyEmisFileSet <: FileSet
mirror::AbstractString
sector
NEI2016MonthlyEmisFileSet(sector) = new("https://gaftp.epa.gov/Air/", sector)
end
"""
$(SIGNATURES)
File path on the server relative to the host root; also path on local disk relative to `ENV["EARTHSCIDATADIR"]`.
"""
function relpath(fs::NEI2016MonthlyEmisFileSet, t::DateTime)
@assert Dates.year(t) == 2016 "Only 2016 emissions data is available with `NEI2016MonthlyEmis`."
month = @sprintf("%.2d", Dates.month(t))
return "emismod/2016/v1/gridded/monthly_netCDF/2016fh_16j_$(fs.sector)_12US1_month_$(month).ncf"
end
function DataFrequencyInfo(fs::NEI2016MonthlyEmisFileSet, t::DateTime)::DataFrequencyInfo
month = Dates.month(t)
year = Dates.year(t)
start = Dates.DateTime(year, month, 1)
frequency = ((start + Dates.Month(1)) - start)
centerpoints = [start + frequency / 2]
return DataFrequencyInfo(start, frequency, centerpoints)
end
"""
$(SIGNATURES)
Load the data in place for the given variable name at the given time.
"""
function loadslice!(data::AbstractArray, fs::NEI2016MonthlyEmisFileSet, t::DateTime, varname)
lock(nclock) do
filepath = maybedownload(fs, t)
ds = getnc(filepath)
data = reshape(data, size(data)..., 1)
var = loadslice!(data, fs, ds, t, varname, "TSTEP")
Δx = ds.attrib["XCELL"]
Δy = ds.attrib["YCELL"]
scale, _ = to_unit(var.attrib["units"])
if scale != 1
data .*= scale
end
data ./= (Δx * Δy)
end
nothing
end
"""
$(SIGNATURES)
Load the data for the given variable name at the given time.
"""
function loadmetadata(fs::NEI2016MonthlyEmisFileSet, t::DateTime, varname)::MetaData
lock(nclock) do
filepath = maybedownload(fs, t)
ds = getnc(filepath)
timedim = "TSTEP"
var = ds[varname]
dims = collect(NCDatasets.dimnames(var))
@assert timedim ∈ dims "Variable $varname does not have a dimension named '$timedim'."
time_index = findfirst(isequal(timedim), dims)
dims = deleteat!(dims, time_index)
varsize = deleteat!(collect(size(var)), time_index)
@assert varsize[end] == 1 "Only 2D data is supported."
varsize = varsize[1:end-1] # Last dimension is 1.
Δx = ds.attrib["XCELL"]
Δy = ds.attrib["YCELL"]
_, units = to_unit(var.attrib["units"])
units /= u"m^2"
description = var.attrib["var_desc"]
x₀ = ds.attrib["XORIG"]
y₀ = ds.attrib["YORIG"]
Δx = ds.attrib["XCELL"]
Δy = ds.attrib["YCELL"]
nx = ds.attrib["NCOLS"]
ny = ds.attrib["NROWS"]
xs = x₀ + Δx / 2 .+ Δx .* (0:nx-1)
ys = y₀ + Δy / 2 .+ Δy .* (0:ny-1)
coords = [xs, ys]
p_alp = ds.attrib["P_ALP"]
p_bet = ds.attrib["P_BET"]
#p_gam = ds.attrib["P_GAM"] # Don't think this is used for anything.
x_cent = ds.attrib["XCENT"]
y_cent = ds.attrib["YCENT"]
native_sr = "+proj=lcc +lat_1=$(p_alp) +lat_2=$(p_bet) +lat_0=$(y_cent) +lon_0=$(x_cent) +x_0=0 +y_0=0 +a=6370997.000000 +b=6370997.000000 +to_meter=1"
xdim = findfirst((x) -> x == "COL", dims)
ydim = findfirst((x) -> x == "ROW", dims)
@assert xdim > 0 "NEI2016 `COL` dimension not found"
@assert ydim > 0 "NEI2016 `ROW` dimension not found"
return MetaData(coords, units, description, dims, varsize, native_sr, xdim, ydim)
end
end
"""
$(SIGNATURES)
Return the variable names associated with this FileSet.
"""
function varnames(fs::NEI2016MonthlyEmisFileSet, t::DateTime)
lock(nclock) do
filepath = maybedownload(fs, t)
ds = getnc(filepath)
return [setdiff(keys(ds), ["TFLAG"; keys(ds.dim)])...]
end
end
struct NEI2016MonthlyEmisCoupler
sys
end
"""
$(SIGNATURES)
A data loader for CMAQ-formatted monthly US National Emissions Inventory data for year 2016,
available from: https://gaftp.epa.gov/Air/emismod/2016/v1/gridded/monthly_netCDF/.
The emissions here are monthly averages, so there is no information about diurnal variation etc.
`spatial_ref` should be the spatial reference system that
the simulation will be using. `x` and `y`, and should be the coordinate variables and grid
spacing values for the simulation that is going to be run, corresponding to the given x and y
values of the given `spatial_ref`,
and the `lev` represents the variable for the vertical grid level.
x and y must be in the same units as `spatial_ref`.
`dtype` represents the desired data type of the interpolated values. The native data type
for this dataset is Float32.
`scale` is a scaling factor to apply to the emissions data. The default value is 1.0.
NOTE: This is an interpolator that returns an emissions value by interpolating between the
centers of the nearest grid cells in the underlying emissions grid, so it may not exactly conserve the total
emissions mass, especially if the simulation grid is coarser than the emissions grid.
"""
function NEI2016MonthlyEmis(sector, x, y, lev; spatial_ref="+proj=longlat +datum=WGS84 +no_defs", dtype=Float32, scale=1.0, name=:NEI2016MonthlyEmis, kwargs...)
fs = NEI2016MonthlyEmisFileSet(sector)
sample_time = DateTime(2016, 5, 1) # Dummy time to get variable names and dimensions from data.
eqs = []
@parameters(
Δz = 60.0, [unit = u"m", description = "Height of the first vertical grid layer"],
)
vars = []
itps = []
for varname ∈ varnames(fs, sample_time)
itp = DataSetInterpolator{dtype}(fs, varname, sample_time; spatial_ref, kwargs...)
@constants zero_emis = 0 [unit = units(itp, sample_time) / u"m"]
eq = create_interp_equation(itp, "", t, sample_time, [x, y],
wrapper_f=(eq) -> ifelse(lev < 2, eq / Δz * scale, zero_emis),
)
push!(eqs, eq)
push!(vars, eq.lhs)
push!(itps, itp)
end
sys = ODESystem(eqs, t; name=name,
metadata=Dict(:coupletype => NEI2016MonthlyEmisCoupler))
cb = UpdateCallbackCreator(sys, vars, itps)
return sys, cb
end
| EarthSciData | https://github.com/EarthSciML/EarthSciData.jl.git |
|
[
"MIT"
] | 0.9.4 | 36b450a98090c6b6c57cc84fa647013402c84650 | code | 2090 | function loadslice!(data::AbstractArray{T}, fs::FileSet, ds::NCDataset, t::DateTime, varname::AbstractString, timedim::AbstractString) where {T<:Number}
var = ds[varname]
dims = collect(NCDatasets.dimnames(var))
@assert timedim ∈ dims "Variable $varname does not have a dimension named '$timedim'."
time_index = findfirst(isequal(timedim), dims)
# Load only one time step, but the full array for everything else.
slices = repeat(Any[:], length(dims))
slices[time_index] = centerpoint_index(DataFrequencyInfo(fs, t), t)
varsize = deleteat!(collect(size(var)), time_index)
rightsize = (varsize == collect(size(data)))
vartype = only(setdiff(Base.uniontypes(eltype(var)), [Missing]))
righttype = (vartype == T)
if rightsize && righttype
# The data is already the correct size and type, so
# load in place.
NCDatasets.load!(var, data, data, slices...)
elseif rightsize && !righttype
# The data is not the correct type, but is the correct size,
# so we load it into a temporary array and then copy it
tmp = zeros(vartype, size(data)) # TODO(CT): Figure out how to avoid allocating the temporary array.
NCDatasets.load!(var, data, tmp, slices...)
else
# The data is not the correct size.
ArgumentError("Data array is not the correct size for variable $varname.")
end
var
end
const ncfiledict = Dict{String,NCDataset}()
const ncfilelist = Vector{String}()
const nclock = ReentrantLock()
" Get the NCDataset for the given file path, caching the last 20 files. "
function getnc(filepath::String)::NCDataset
if haskey(ncfiledict, filepath)
return ncfiledict[filepath]
else
ds = NCDataset(filepath)
push!(ncfilelist, filepath)
ncfiledict[filepath] = ds
# if length(ncfilelist) > 20 #TODO(CT): Tests fail when this is uncommented, don't know why.
# fname = popfirst!(ncfilelist)
# close(ncfiledict[fname])
# delete!(ncfiledict, fname)
# end
return ds
end
end | EarthSciData | https://github.com/EarthSciML/EarthSciData.jl.git |
|
[
"MIT"
] | 0.9.4 | 36b450a98090c6b6c57cc84fa647013402c84650 | code | 3909 | export NetCDFOutputter
"""
$(TYPEDSIGNATURES)
Create an `EarthSciMLBase.Operator` to write simulation output to a NetCDF file.
$(TYPEDFIELDS)
"""
mutable struct NetCDFOutputter
"The path of the NetCDF file to write to"
filepath::String
"The netcdf dataset"
file
"The netcdf variables corresponding to the state variables"
vars
"The netcdf variable for time"
tvar
"Current time index for writing"
h::Int
"Simulation time interval (in seconds) at which to write to disk"
time_interval::AbstractFloat
"Extra observed variables to write to disk"
extra_vars::AbstractVector
"Functions to get the extra vars"
extra_var_fs::AbstractVector
"Spatial grid specification"
grid
"Data type of the output"
dtype
function NetCDFOutputter(filepath::AbstractString, time_interval::AbstractFloat; extra_vars=[], dtype=Float32)
new(filepath, nothing, nothing, nothing, 1, time_interval, extra_vars, [], nothing, dtype)
end
end
"Set up the output file and the callback function."
function EarthSciMLBase.init_callback(nc::NetCDFOutputter, s::Simulator)
rm(nc.filepath, force=true)
ds = NCDataset(nc.filepath, "c")
pv = EarthSciMLBase.pvars(s.sys.domaininfo)
@assert length(pv) == 3 "Currently only 3D simulations are supported."
@assert length(s.grid) == 3 "Currently only 3D simulations are supported."
pvstr = [String(Symbol(p)) for p in pv]
for (i, p) in enumerate(pvstr)
ds.dim[p] = length(s.grid[i])
end
ds.dim["time"] = Inf
function makencvar(v, dims)
n = string(Symbolics.tosymbol(v, escape=false))
ncvar = defVar(ds, n, Float32, dims)
ncvar.attrib["description"] = ModelingToolkit.getdescription(v)
ncvar.attrib["units"] = string(DynamicQuantities.dimension(ModelingToolkit.get_unit(v)))
ncvar
end
ncvars = [makencvar(v, [pvstr..., "time"]) for v in vcat(unknowns(s.sys_mtk), nc.extra_vars)]
nctvar = defVar(ds, "time", Float64, ("time",))
nctvar.attrib["description"] = "Time"
nctvar.attrib["units"] = "seconds since 1970-1-1"
for (i, p) in enumerate(pvstr)
d = defVar(ds, p, nc.dtype, (p,))
d.attrib["description"] = ModelingToolkit.getdescription(pv[i])
d.attrib["units"] = string(DynamicQuantities.dimension(ModelingToolkit.get_unit(pv[i])))
d[:] = s.grid[i]
end
for j in eachindex(nc.extra_vars)
push!(nc.extra_var_fs, s.obs_fs[s.obs_fs_idx[nc.extra_vars[j]]])
end
nc.file = ds
nc.vars = ncvars
nc.tvar = nctvar
nc.grid = s.grid
nc.h = 1
start, finish = EarthSciMLBase.time_range(s.domaininfo)
return PresetTimeCallback(start:nc.time_interval:finish,
(integrator) -> affect!(nc, integrator),
finalize=(c, u, t, integrator) -> close(nc.file),
save_positions=(false, false),
filter_tstops=false,
)
end
"""
Write the current state of the `Simulator` to the NetCDF file.
"""
function affect!(nc::NetCDFOutputter, integrator)
u = reshape(integrator.u, length(nc.vars) - length(nc.extra_vars), [length(g) for g in nc.grid]...)
for j in 1:(length(nc.vars)-length(nc.extra_vars))
v = nc.vars[j]
v[:, :, :, nc.h] = u[j, :, :, :]
end
if length(nc.extra_vars) > 0
u = zeros(length.(nc.grid)...) # Temporary array.
for j in eachindex(nc.extra_vars)
v = nc.vars[j+length(nc.vars)-length(nc.extra_vars)]
f = nc.extra_var_fs[j]
for (i, c1) ∈ enumerate(nc.grid[1])
for (j, c2) ∈ enumerate(nc.grid[2])
for (k, c3) ∈ enumerate(nc.grid[3])
u[i, j, k] = f(integrator.t, c1, c2, c3)
end
end
end
v[:, :, :, nc.h] = u
end
end
nc.tvar[nc.h] = integrator.t
nc.h += 1
return false
end | EarthSciData | https://github.com/EarthSciML/EarthSciData.jl.git |
|
[
"MIT"
] | 0.9.4 | 36b450a98090c6b6c57cc84fa647013402c84650 | code | 1484 |
"""
This struct holds information that can be used to create a callback function that updates the
states of the interpolators.
"""
struct UpdateCallbackCreator
sys::ODESystem
variables
interpolators
end
function lazyload!(uc::UpdateCallbackCreator, t::AbstractFloat)
dt = unix2datetime(t)
for itp in uc.interpolators
lazyload!(itp, dt)
end
end
"""
Create a callback for this simulator. We only want to update the interpolators
that are actually used in the system.
"""
function EarthSciMLBase.init_callback(uc::UpdateCallbackCreator, s::Simulator)
sysname = nameof(uc.sys)
needvars = Symbol.([unknowns(s.sys_mtk); [eq.lhs for eq in observed(s.sys_mtk)]])
itps = []
for (v, itp) in zip(uc.variables, uc.interpolators)
nv = Symbol(sysname, "₊", v)
if nv ∈ needvars
push!(itps, itp)
end
end
function initialize(c, u, t, integrator)
dt = unix2datetime(integrator.t)
for itp in itps
itp.initialized = false
lazyload!(itp, dt)
end
end
function update_callback(integrator)
dt = unix2datetime(integrator.t)
for itp in itps
lazyload!(itp, dt)
end
end
DiscreteCallback(
(u, t, integrator) -> true, # TODO(CT): Could change to only run when we know interpolators need to be updated.
update_callback,
initialize = initialize,
save_positions = (false, false),
)
end
| EarthSciData | https://github.com/EarthSciML/EarthSciData.jl.git |
|
[
"MIT"
] | 0.9.4 | 36b450a98090c6b6c57cc84fa647013402c84650 | code | 954 | """
Convert a string to a `DynamicQuantities.Quantity` object.
"""
function to_unit(u)
d = Dict(
"m s-1" => (1, u"m/s"),
"Pa s-1" => (1, u"Pa/s"),
"kg m-2 s-2" => (1, u"kg/m^2/s^2"),
"kg kg-1" => (1, u"kg/kg"),
"K" => (1, u"K"),
"K m-2 kg-1 s-1" => (1, u"K/m^2/kg/s"),
"hPa" => (100, u"Pa"),
"kg m-2 s-1" => (1, u"kg/m^2/s"),
"W m-2" => (1, u"W/m^2"),
"m" => (1, u"m"),
"Dobsons" => (2.69e16/6.022e23 * 10000, u"mol/m^2"), # Dobson Unit: https://ozonewatch.gsfc.nasa.gov/facts/dobson_SH.html
"m2 m-2" => (1, u"m^2/m^2"),
"kg m-2" => (1, u"kg/m^2"),
"kg kg-1 s-1" => (1, u"kg/kg/s"),
"tons/day" => (907.185 / 86400, u"kg/s"),
"1" => (1, Quantity(1.0)), # unitless
"<YYYYDD,HHMMSS>" => (1, Quantity(1.0)),
)
if haskey(d, u)
return d[u]
end
error(ArgumentError("unregistered unit `$(u)`"))
end | EarthSciData | https://github.com/EarthSciML/EarthSciData.jl.git |
|
[
"MIT"
] | 0.9.4 | 36b450a98090c6b6c57cc84fa647013402c84650 | code | 5425 | using Main.EarthSciData
using EarthSciMLBase
using Test
using Dates
using ModelingToolkit, DomainSets
using ModelingToolkit: t, D
using DynamicQuantities
import NCDatasets
@testset "GEOS-FP" begin
@parameters lev
@parameters lon [unit = u"rad"]
@parameters lat [unit = u"rad"]
@constants c_unit = 6.0 [unit = u"rad" description = "constant to make units cancel out"]
geosfp, _ = GEOSFP("4x5"; dtype=Float64)
function Example()
@variables c(t) = 5.0 [unit = u"mol/m^3"]
ODESystem([D(c) ~ (sin(lat * c_unit) + sin(lon * c_unit)) * c / t], t, name=:ExampleSys)
end
examplesys = Example()
domain = DomainInfo(
[
partialderivatives_δxyδlonlat,
partialderivatives_δPδlev_geosfp(geosfp),
],
constIC(0.0, t ∈ Interval(Dates.datetime2unix(DateTime(2022, 1, 1)), Dates.datetime2unix(DateTime(2022, 1, 3)))),
zerogradBC(lat ∈ Interval(deg2rad(-85.0f0), deg2rad(85.0f0))),
periodicBC(lon ∈ Interval(deg2rad(-180.0f0), deg2rad(175.0f0))),
zerogradBC(lev ∈ Interval(1.0f0, 10.0f0)),
)
composed_sys = couple(examplesys, domain, Advection(), geosfp)
pde_sys = convert(PDESystem, composed_sys)
eqs = equations(pde_sys)
want_terms = [
"MeanWind₊v_lon(t, lat, lon, lev)", "GEOSFP₊A3dyn₊U(t, lat, lon, lev)",
"MeanWind₊v_lat(t, lat, lon, lev)", "GEOSFP₊A3dyn₊V(t, lat, lon, lev)",
"MeanWind₊v_lev(t, lat, lon, lev)", "GEOSFP₊A3dyn₊OMEGA(t, lat, lon, lev)",
"GEOSFP₊A3dyn₊U(t, lat, lon, lev)", "EarthSciData.interp_unsafe(DataSetInterpolator{EarthSciData.GEOSFPFileSet, U}, t, lon, lat, lev)",
"GEOSFP₊A3dyn₊OMEGA(t, lat, lon, lev)", "EarthSciData.interp_unsafe(DataSetInterpolator{EarthSciData.GEOSFPFileSet, OMEGA}, t, lon, lat, lev)",
"GEOSFP₊A3dyn₊V(t, lat, lon, lev)", "EarthSciData.interp_unsafe(DataSetInterpolator{EarthSciData.GEOSFPFileSet, V}, t, lon, lat, lev)",
"Differential(t)(ExampleSys₊c(t, lat, lon, lev))", "Differential(lon)(ExampleSys₊c(t, lat, lon, lev)",
"MeanWind₊v_lon(t, lat, lon, lev)", "lon2m",
"Differential(lat)(ExampleSys₊c(t, lat, lon, lev)",
"MeanWind₊v_lat(t, lat, lon, lev)", "lat2meters",
"sin(ExampleSys₊c_unit*lat)", "sin(ExampleSys₊c_unit*lon)",
"ExampleSys₊c(t, lat, lon, lev)", "t",
"Differential(lev)(ExampleSys₊c(t, lat, lon, lev))",
"MeanWind₊v_lev(t, lat, lon, lev)", "P_unit",
]
have_eqs = string.(eqs)
have_eqs = replace.(have_eqs, ("Main."=>"",))
for term ∈ want_terms
@test any(occursin.((term,), have_eqs))
end
end
@testset "GEOS-FP pressure levels" begin
@parameters lat, [unit=u"rad"], lon, [unit=u"rad"], lev
geosfp, updater = GEOSFP("4x5"; dtype=Float64,
coord_defaults=Dict(:lev => 1.0, :lat => deg2rad(39.1), :lon => deg2rad(-155.7)))
# Rearrange pressure equation so it can be evaluated for P.
iips = findfirst((x) -> x == :I3₊PS, [Symbolics.tosymbol(eq.lhs, escape=false) for eq in equations(geosfp)])
iip = findfirst((x) -> x == :P, [Symbolics.tosymbol(eq.lhs, escape=false) for eq in equations(geosfp)])
pseq = equations(geosfp)[iips]
peq = substitute(equations(geosfp)[iip], pseq.lhs => pseq.rhs)
# Check Pressure levels
EarthSciData.lazyload!(updater, datetime2unix(DateTime(2022, 5, 1)))
P = ModelingToolkit.subs_constants(peq.rhs)
P_expr = build_function(P, [t, lon, lat, lev])
mypf = eval(P_expr)
p_levels = [mypf([DateTime(2022, 5, 1), deg2rad(-155.7), deg2rad(39.1), lev]) for lev in [1, 1.5, 2, 72, 72.5, 73]]
@test p_levels ≈ [1021.6242118225098, 1013.9615353827572, 1006.2988589430047, 0.02, 0.015, 0.01] .* 100
dp = partialderivatives_δPδlev_geosfp(geosfp)
# Check level coordinate index
ff = dp([lat, lon, lev])
@test all(keys(ff) .=== [3])
fff = ModelingToolkit.subs_constants(ff[3])
# Check δP at different levels
f_expr = build_function(fff, [t, lon, lat, lev])
myf = eval(f_expr)
δP_levels = [myf([DateTime(2022, 5, 1), deg2rad(-155.7), deg2rad(39.1), lev]) for lev in [1, 1.5, 2, 71.5, 72, 72.5]]
@test 1.0 ./ δP_levels ≈ [-15.32535287950509, -15.325352879504862, -15.466211527927955,
-0.012699999999999994, -0.010000000000000002, -0.009999999999999998] .* 100.0
end
@testset "GEOS-FP new day" begin
@parameters(
lon = 0.0, [unit=u"rad"],
lat = 0.0, [unit=u"rad"],
lev = 1.0,
)
starttime = datetime2unix(DateTime(2022, 5, 1, 23, 58))
endtime = datetime2unix(DateTime(2022, 5, 2, 0, 3))
geosfp, updater = GEOSFP("4x5"; dtype=Float64,
coord_defaults=Dict(:lon => 0.0, :lat => 0.0, :lev => 1.0))
iips = findfirst((x) -> x == :I3₊PS, [Symbolics.tosymbol(eq.lhs, escape=false) for eq in equations(geosfp)])
pseq = equations(geosfp)[iips]
PS_expr = build_function(pseq.rhs, t, lon, lat, lev)
psf = eval(PS_expr)
EarthSciData.lazyload!(updater, starttime)
psf(starttime, 0.0, 0.0, 1.0)
end
@testset "GEOS-FP wrong year" begin
@parameters(
lon = 0.0, [unit=u"rad"],
lat = 0.0, [unit=u"rad"],
lev = 1.0,
)
starttime = datetime2unix(DateTime(5000, 1, 1))
geosfp, updater = GEOSFP("4x5"; dtype=Float64,
coord_defaults=Dict(:lon => 0.0, :lat => 0.0, :lev => 1.0))
@test_throws Base.Exception EarthSciData.lazyload!(updater, starttime)
end
| EarthSciData | https://github.com/EarthSciML/EarthSciData.jl.git |
|
[
"MIT"
] | 0.9.4 | 36b450a98090c6b6c57cc84fa647013402c84650 | code | 5221 | using Main.EarthSciData
using Dates
using ModelingToolkit
using Random
using Latexify, LaTeXStrings
using AllocCheck
using DynamicQuantities
using Interpolations
using Test
fs = EarthSciData.GEOSFPFileSet("4x5", "A3dyn")
t = DateTime(2022, 5, 1)
@test EarthSciData.url(fs, t) == "http://geoschemdata.wustl.edu/ExtData/GEOS_4x5/GEOS_FP/2022/05/GEOSFP.20220501.A3dyn.4x5.nc"
@test endswith(EarthSciData.localpath(fs, t), joinpath("GEOS_4x5", "GEOS_FP", "2022", "05", "GEOSFP.20220501.A3dyn.4x5.nc"))
ti = EarthSciData.DataFrequencyInfo(fs, t)
epp = EarthSciData.endpoints(ti)
@test epp[1] == (DateTime("2022-05-01T00:00:00"), DateTime("2022-05-01T03:00:00"))
@test epp[8] == (DateTime("2022-05-01T21:00:00"), DateTime("2022-05-02T00:00:00"))
metadata = EarthSciData.loadmetadata(fs, t, "U")
@test metadata.varsize == [72, 46, 72]
@test metadata.dimnames == ["lon", "lat", "lev"]
itp = EarthSciData.DataSetInterpolator{Float32}(fs, "U", t)
@test String(latexify(itp)) == "\$\\mathrm{GEOSFPFileSet}\\left( U \\right)\$"
@test EarthSciData.dimnames(itp, t) == ["lon", "lat", "lev"]
@test issetequal(EarthSciData.varnames(fs, t), ["U", "OMEGA", "RH", "DTRAIN", "V"])
@testset "interpolation" begin
uvals = []
times = DateTime(2022, 5, 1):Hour(1):DateTime(2022, 5, 3)
for t ∈ times
push!(uvals, interp!(itp, t, deg2rad(1.0f0), deg2rad(0.0f0), 1.0f0))
end
for i ∈ 4:3:length(uvals)-1
@test uvals[i] ≈ (uvals[i-1] + uvals[i+1]) / 2 atol = 1e-2
end
want_uvals = [-0.047425747f0, 0.064035736f0, 0.11166346f0, 0.09545743f0, 0.07925139f0,
-0.011301707f0, -0.17620188f0, -0.34110206f0, -0.501398f0, -0.65708977f0]
@test uvals[1:10] ≈ want_uvals
# Test that shuffling the times doesn't change the results.
uvals2 = []
idx = randperm(length(times))
for t ∈ times[idx]
push!(uvals2, interp!(itp, t, deg2rad(1.0f0), deg2rad(0.0f0), 1.0f0))
end
@test uvals2 ≈ uvals[idx]
end
@testset "DummyFileSet" begin
struct DummyFileSet <: EarthSciData.FileSet
start::DateTime
finish::DateTime
end
function EarthSciData.DataFrequencyInfo(fs::DummyFileSet, t::DateTime)::EarthSciData.DataFrequencyInfo
frequency = Second(3 * 3600)
centerpoints = collect(fs.start+frequency/2:frequency:fs.finish)
EarthSciData.DataFrequencyInfo(t, frequency, centerpoints)
end
tv(fs, t) = (t - fs.start) / (fs.finish - fs.start)
function EarthSciData.loadslice!(cache::AbstractArray, fs::DummyFileSet, t::DateTime, varname)
dfi = EarthSciData.DataFrequencyInfo(fs, t)
tt = dfi.centerpoints[EarthSciData.centerpoint_index(dfi, t)]
v = tv(fs, tt)
cache .= [v, v * 0.5, v * 2.0]
end
function EarthSciData.loadmetadata(fs::DummyFileSet, t::DateTime, varname)
return EarthSciData.MetaData([[0.0, 0.5, 1.0]], u"m", "description", ["x"], [3], "+proj=longlat +datum=WGS84 +no_defs", 1, 1)
end
fs = DummyFileSet(DateTime(2022, 4, 30), DateTime(2022, 5, 4))
@testset "big cache" begin
@test_nowarn EarthSciData.DataSetInterpolator{Float32}(fs, "U", fs.start; cache_size=100)
end
itp = EarthSciData.DataSetInterpolator{Float32}(fs, "U", fs.start; cache_size=5)
dfi = EarthSciData.DataFrequencyInfo(fs, fs.start)
answerdata = [tv(fs, t) * v for t ∈ dfi.centerpoints, v ∈ [1.0, 0.5, 2.0]]
grid = Tuple(EarthSciData.knots2range.([datetime2unix.(dfi.centerpoints), [0.0, 0.5, 1.0]]))
answer_itp = scale(interpolate(answerdata, BSpline(Linear())), grid)
times = DateTime(2022, 5, 1):Hour(1):DateTime(2022, 5, 3)
xs = [0.0f0, 0.25f0, 0.75f0]
uvals = zeros(Float32, length(times), length(xs))
answers = zeros(Float32, length(times), length(xs))
for (i, tt) ∈ enumerate(times)
for (j, x) ∈ enumerate(xs)
uvals[i, j] = interp!(itp, tt, x)
answers[i, j] = answer_itp(datetime2unix(tt), x)
end
end
@test uvals ≈ answers
@test length(itp.times) == 5
@test itp.times == [DateTime("2022-05-02T19:30:00"), DateTime("2022-05-02T22:30:00"),
DateTime("2022-05-03T01:30:00"), DateTime("2022-05-03T04:30:00"),
DateTime("2022-05-03T07:30:00")]
uvals = zeros(Float32, length(times), length(xs))
answers = zeros(Float32, length(times), length(xs))
for i ∈ randperm(length(times))
tt = times[i]
for j ∈ randperm(length(xs))
x = xs[j]
uvals[i, j] = interp!(itp, tt, x)
answers[i, j] = answer_itp(datetime2unix(tt), x)
end
end
@test uvals ≈ answers
end
@testset "allocations" begin
itp = EarthSciData.DataSetInterpolator{Float64}(fs, "U", t)
tt = DateTime(2022, 5, 1)
interp!(itp, tt, 1.0, 0.0, 1.0)
@test begin
@check_allocs checkf(itp, t, loc1, loc2, loc3) = EarthSciData.interp_unsafe(itp, t, loc1, loc2, loc3)
try
checkf(itp, tt, 1.0, 0.0, 1.0)
catch err
@warn err.errors
rethrow(err)
end
itp2 = EarthSciData.DataSetInterpolator{Float32}(fs, "U", t)
interp!(itp2, tt, 1.0f0, 0.0f0, 1.0f0)
checkf(itp2, tt, 1.0f0, 0.0f0, 1.0f0)
true
end
end
| EarthSciData | https://github.com/EarthSciML/EarthSciData.jl.git |
|
[
"MIT"
] | 0.9.4 | 36b450a98090c6b6c57cc84fa647013402c84650 | code | 4192 | using Main.EarthSciData
using Test
using DynamicQuantities, EarthSciMLBase, ModelingToolkit
using ModelingToolkit: t
using Dates
using DifferentialEquations
import Proj
using AllocCheck
@parameters lat, [unit = u"rad"], lon, [unit = u"rad"], lev
emis, updater = NEI2016MonthlyEmis("mrggrid_withbeis_withrwc", lon, lat, lev; dtype=Float64)
fileset = EarthSciData.NEI2016MonthlyEmisFileSet("mrggrid_withbeis_withrwc")
eqs = equations(emis)
@test length(eqs) == 69
@test contains(string(eqs[1].rhs), "/ Δz")
sample_time = DateTime(2016, 5, 1)
@testset "can't deepcopy" begin
itp = EarthSciData.DataSetInterpolator{Float32}(fileset, "NOX", sample_time; spatial_ref="+proj=longlat +datum=WGS84 +no_defs")
deepcopy(itp) === itp
end
@testset "correct projection" begin
itp = EarthSciData.DataSetInterpolator{Float32}(fileset, "NOX", sample_time; spatial_ref="+proj=longlat +datum=WGS84 +no_defs")
@test interp!(itp, sample_time, deg2rad(-97.0f0), deg2rad(40.0f0)) ≈ 9.211331f-10
end
@testset "incorrect projection" begin
itp = EarthSciData.DataSetInterpolator{Float32}(fileset, "NOX", sample_time;
spatial_ref="+proj=axisswap +order=2,1 +step +proj=longlat +datum=WGS84 +no_defs")
@test_throws Proj.PROJError interp!(itp, sample_time, deg2rad(-97.0f0), deg2rad(40.0f0))
end
@testset "Out of domain" begin
itp = EarthSciData.DataSetInterpolator{Float32}(fileset, "NOX", sample_time)
@test_throws BoundsError interp!(itp, sample_time, deg2rad(0.0f0), deg2rad(40.0f0))
end
@testset "monthly frequency" begin
sample_time = DateTime(2016, 5, 1)
itp = EarthSciData.DataSetInterpolator{Float32}(fileset, "NOX", sample_time; spatial_ref="+proj=longlat +datum=WGS84 +no_defs")
EarthSciData.initialize!(itp, sample_time)
ti = EarthSciData.DataFrequencyInfo(itp.fs, sample_time)
@test month(itp.times[1]) == 4
@test month(itp.times[2]) == 5
sample_time = DateTime(2016, 5, 31)
EarthSciData.initialize!(itp, sample_time)
@test month(itp.times[1]) == 5
@test month(itp.times[2]) == 6
end
@testset "run" begin
@constants uc = 1.0 [unit = u"s" description = "unit conversion"]
eq = Differential(t)(emis.ACET) ~ equations(emis)[1].rhs * 1e10 / uc
sys = extend(ODESystem([eq], t, [], []; name=:test_sys), emis)
sys = structural_simplify(sys)
tt = Dates.datetime2unix(sample_time)
EarthSciData.lazyload!(updater, tt)
prob = ODEProblem(sys, zeros(1), (tt, tt + 60.0), [lat => deg2rad(40.0), lon => deg2rad(-97.0), lev => 1.0])
sol = solve(prob)
@test 2 > sol.u[end][end] > 1
end
@testset "allocations" begin
@check_allocs checkf(itp, t, loc1, loc2) = EarthSciData.interp_unsafe(itp, t, loc1, loc2)
sample_time = DateTime(2016, 5, 1)
itp = EarthSciData.DataSetInterpolator{Float32}(fileset, "NOX", sample_time)
interp!(itp, sample_time, deg2rad(-97.0f0), deg2rad(40.0f0))
# If there is an error, it should occur in the proj library.
# https://github.com/JuliaGeo/Proj.jl/issues/104
try
checkf(itp, sample_time, deg2rad(-97.0f0), deg2rad(40.0f0))
catch err
@test length(err.errors) == 1
s = err.errors[1]
contains(string(s), "libproj.proj_trans")
end
itp2 = EarthSciData.DataSetInterpolator{Float64}(fileset, "NOX", sample_time)
interp!(itp2, sample_time, deg2rad(-97.0), deg2rad(40.0))
try # If there is an error, it should occur in the proj library.
checkf(itp2, sample_time, deg2rad(-97.0), deg2rad(40.0))
catch err
@test length(err.errors) == 1
s = err.errors[1]
contains(string(s), "libproj.proj_trans")
end
end
@testset "Coupling with GEOS-FP" begin
gfp = GEOSFP("4x5"; dtype=Float64,
coord_defaults=Dict(:lon => 0.0, :lat => 0.0, :lev => 1.0))
eqs = equations(convert(ODESystem, couple(emis, gfp)))
@test occursin("NEI2016MonthlyEmis₊lat(t) ~ GEOSFP₊lat", string(eqs))
end
@testset "wrong year" begin
sample_time = DateTime(2016, 5, 1)
itp = EarthSciData.DataSetInterpolator{Float32}(fileset, "NOX", sample_time)
sample_time = DateTime(2017, 5, 1)
@test_throws AssertionError EarthSciData.initialize!(itp, sample_time)
end
| EarthSciData | https://github.com/EarthSciML/EarthSciData.jl.git |
|
[
"MIT"
] | 0.9.4 | 36b450a98090c6b6c57cc84fa647013402c84650 | code | 2066 | using EarthSciData
using Test
using EarthSciMLBase, ModelingToolkit, DomainSets
using ModelingToolkit: t, D
using NCDatasets, DynamicQuantities, DifferentialEquations, Dates
using SciMLOperators
@parameters lev = 1.0
@parameters y = 2.0 [unit = u"kg"]
@parameters x = 1.0 [unit = u"kg", description = "x coordinate"]
@variables u(t) = 1.0 [unit = u"kg", description = "u value"]
@variables v(t) = 2.0 [unit = u"kg", description = "v value"]
@constants c = 1.0 [unit = u"kg^2"]
@constants p = 1.0 [unit = u"kg/s"]
eqs = [
D(u) ~ p + 1e-20*lev*p*x*y/c # Need to make sure all coordinates are included in model.
v ~ (x + y) * lev
]
sys = ODESystem(eqs, t; name=:Test₊sys)
domain = DomainInfo(
constIC(0.0, t ∈ Interval(0.0, 2.0)),
constBC(16.0, x ∈ Interval(-1.0, 1.0),
y ∈ Interval(-2.0, 2.0),
lev ∈ Interval(1.0, 3.0)))
file = tempname() * ".nc"
csys = couple(sys, domain)
o = NetCDFOutputter(file, 1.0; extra_vars=[
structural_simplify(convert(ODESystem, csys)).Test₊sys.v
])
csys = couple(csys, o)
sim = Simulator(csys, [0.1, 0.1, 1])
st = SimulatorStrangThreads(Tsit5(), Euler(), 0.01)
run!(sim, st)
ds = NCDataset(file, "r")
@test size(ds["Test₊sys₊u"], 4) == 3
@test all(isapprox.(ds["Test₊sys₊u"][:, :, :, 1], 1.0, atol=0.011))
@test sum(abs.(ds["Test₊sys₊v"][:, :, :, 1])) ≈ 5754.0f0
@test all(isapprox.(ds["Test₊sys₊u"][:, :, :, 2], 2.0, atol=0.011))
@test sum(abs.(ds["Test₊sys₊v"][:, :, :, 2])) ≈ 5754.0f0
@test all(isapprox.(ds["Test₊sys₊u"][:, :, :, 3], 3.0, atol=0.011))
@test sum(abs.(ds["Test₊sys₊v"][:, :, :, 3])) ≈ 5754.0f0
@test size(ds["Test₊sys₊u"]) == (21, 41, 3, 3)
@test ds["time"][:] == [DateTime("1970-01-01T00:00:00"), DateTime("1970-01-01T00:00:01"), DateTime("1970-01-01T00:00:02")]
@test ds["x"][:] ≈ -1.0:0.1:1.0
@test ds["y"][:] ≈ -2.0:0.1:2.0
@test ds["lev"] ≈ 1:3
@test ds["x"].attrib["description"] == "x coordinate"
@test ds["x"].attrib["units"] == "kg"
@test ds["Test₊sys₊u"].attrib["description"] == "u value"
@test ds["Test₊sys₊u"].attrib["units"] == "kg"
rm(file, force=true)
| EarthSciData | https://github.com/EarthSciML/EarthSciData.jl.git |
|
[
"MIT"
] | 0.9.4 | 36b450a98090c6b6c57cc84fa647013402c84650 | code | 439 | using EarthSciData
using Test, SafeTestsets
@testset "EarthSciData.jl" begin
@safetestset "load" begin include("load_test.jl") end
@safetestset "geosfp" begin include("geosfp_test.jl") end
@safetestset "nei2016monthly" begin include("nei2016monthly_test.jl") end
@safetestset "NetCDFOutputter" begin include("netcdf_output_test.jl") end
@safetestset "Update Callback" begin include("update_callback_test.jl") end
end
| EarthSciData | https://github.com/EarthSciML/EarthSciData.jl.git |
|
[
"MIT"
] | 0.9.4 | 36b450a98090c6b6c57cc84fa647013402c84650 | code | 1365 | using Main.EarthSciData
using Test
using EarthSciMLBase, ModelingToolkit
using ModelingToolkit: t, D
using DomainSets, Dates
using DifferentialEquations
using DynamicQuantities
@parameters lat = deg2rad(40.0) lon = deg2rad(-97.0) lev = 0.0
@variables ACET(t) = 0.0 [unit = u"kg*m^-3"]
@constants c = 1000 [unit = u"s"]
struct SysCoupler
sys
end
@named sys = ODESystem(
[D(ACET) ~ 0], t,
metadata=Dict(:coupletype => SysCoupler)
)
function EarthSciMLBase.couple2(sys::SysCoupler, emis::EarthSciData.NEI2016MonthlyEmisCoupler)
sys, emis = sys.sys, emis.sys
operator_compose(sys, emis)
end
emis = NEI2016MonthlyEmis("mrggrid_withbeis_withrwc", lon, lat, lev; dtype=Float64)
starttime = datetime2unix(DateTime(2016, 3, 1))
endtime = datetime2unix(DateTime(2016, 5, 2))
domain = DomainInfo(
constIC(16.0, t ∈ Interval(starttime, endtime)),
constBC(16.0,
lon ∈ Interval(deg2rad(-115), deg2rad(-68.75)),
lat ∈ Interval(deg2rad(25), deg2rad(53.71875)),
lev ∈ Interval(1, 2)
))
csys = couple(sys, emis, domain)
sim = Simulator(csys, [deg2rad(15.0), deg2rad(15.0), 1])
st = SimulatorStrangSerial(Tsit5(), Euler(), 100.0)
sol = run!(sim, st)
@test sum(sol.u[end]) ≈ 3.3756746955152187e-6
st = SimulatorStrangThreads(Tsit5(), Euler(), 100.0)
sol = run!(sim, st)
@test sum(sol.u[end]) ≈ 3.3756746955152187e-6
| EarthSciData | https://github.com/EarthSciML/EarthSciData.jl.git |
|
[
"MIT"
] | 0.9.4 | 36b450a98090c6b6c57cc84fa647013402c84650 | docs | 585 | # EarthSciData
[](https://earthsciml.github.io/EarthSciData.jl/stable)
[](https://earthsciml.github.io/EarthSciData.jl/dev)
[](https://github.com/EarthSciML/EarthSciData.jl/actions/workflows/CI.yml?query=branch%3Amain)
[](https://codecov.io/gh/EarthSciML/EarthSciData.jl)
| EarthSciData | https://github.com/EarthSciML/EarthSciData.jl.git |
|
[
"MIT"
] | 0.9.4 | 36b450a98090c6b6c57cc84fa647013402c84650 | docs | 57 | ```@index
```
```@autodocs
Modules = [EarthSciData]
```
| EarthSciData | https://github.com/EarthSciML/EarthSciData.jl.git |
|
[
"MIT"
] | 0.9.4 | 36b450a98090c6b6c57cc84fa647013402c84650 | docs | 290 | # Redirecting...
```@raw html
<html>
<head>
<meta http-equiv="refresh" content="0; url=https://data.earthsci.dev/benchmarks/" />
</head>
<body>
<p>If you are not redirected automatically, follow this <a href="https://data.earthsci.dev/benchmarks/">link</a>.</p>
</body>
</html>
``` | EarthSciData | https://github.com/EarthSciML/EarthSciData.jl.git |
|
[
"MIT"
] | 0.9.4 | 36b450a98090c6b6c57cc84fa647013402c84650 | docs | 3980 | # Using data from GEOS-FP
This example demonstrates how to use the GEOS-FP data loader in the EarthSciML ecosystem. The GEOS-FP data loader is used to load data from the [GEOS-FP](https://gmao.gsfc.nasa.gov/GMAO_products/NRT_products.php) dataset.
First, let's initialize some packages and set up the [GEOS-FP](@ref GEOSFP) equation system.
```@example geosfp
using EarthSciData, EarthSciMLBase
using DomainSets, ModelingToolkit, MethodOfLines, DifferentialEquations
using ModelingToolkit: t, D
using Dates, Plots, DataFrames
using DynamicQuantities
using DynamicQuantities: dimension
# Set up system
@parameters(
lev,
lon, [unit=u"rad"],
lat, [unit=u"rad"],
)
geosfp, geosfp_updater = GEOSFP("4x5")
geosfp
```
Note that the [`GEOSFP`](@ref) function returns to things, an equation system and an object that can used to update the time in the underlying data loaders.
We can see above the different variables that are available in the GEOS-FP dataset.
But also, here they are in table form:
```@example geosfp
vars = unknowns(geosfp)
DataFrame(
:Name => [string(Symbolics.tosymbol(v, escape=false)) for v ∈ vars],
:Units => [dimension(ModelingToolkit.get_unit(v)) for v ∈ vars],
:Description => [ModelingToolkit.getdescription(v) for v ∈ vars],
)
```
The GEOS-FP equation system isn't an ordinary differential equation (ODE) system, so we can't run it by itself.
To fix this, we create another equation system that is an ODE.
(We don't actually end up using this system for anything, it's just necessary to get the system to compile.)
```@example geosfp
function Example()
@variables c(t) = 5.0 [unit=u"s"]
ODESystem([D(c) ~ sin(lat * 6) + sin(lon * 6)], t, name=:Docs₊Example)
end
examplesys = Example()
```
Now, let's couple these two systems together, and also add in advection and some information about the domain:
```@example geosfp
domain = DomainInfo(
partialderivatives_δxyδlonlat,
constIC(0.0, t ∈ Interval(Dates.datetime2unix(DateTime(2022, 1, 1)), Dates.datetime2unix(DateTime(2022, 1, 3)))),
zerogradBC(lat ∈ Interval(deg2rad(-80.0f0), deg2rad(80.0f0))),
periodicBC(lon ∈ Interval(deg2rad(-180.0f0), deg2rad(180.0f0))),
zerogradBC(lev ∈ Interval(1.0f0, 11.0f0)),
)
composed_sys = couple(examplesys, domain, geosfp, geosfp_updater)
pde_sys = convert(PDESystem, composed_sys)
```
You can see above that we add both `geosfp` and `geosfp_updater` to our coupled system.
If we didn't include the updater, the resulting model would not give the correct results.
Now, finally, we can run the simulation and plot the GEOS-FP wind fields in the result:
(The code below is commented out because it is very slow right now. A faster solution is coming soon!)
```julia
# discretization = MOLFiniteDifference([lat => 10, lon => 10, lev => 10], t, approx_order=2)
# @time pdeprob = discretize(pde_sys, discretization)
# pdesol = solve(pdeprob, Tsit5(), saveat=3600.0)
# discrete_lon = pdesol[lon]
# discrete_lat = pdesol[lat]
# discrete_lev = pdesol[lev]
# discrete_t = pdesol[t]
# @variables meanwind₊u(..) meanwind₊v(..) examplesys₊c(..)
# sol_u = pdesol[meanwind₊u(t, lat, lon, lev)]
# sol_v = pdesol[meanwind₊v(t, lat, lon, lev)]
# sol_c = pdesol[examplesys₊c(t, lat, lon, lev)]
# anim = @animate for k in 1:length(discrete_t)
# p1 = heatmap(discrete_lon, discrete_lat, sol_c[k, 1:end, 1:end, 2], clim=(minimum(sol_c[:, :, :, 2]), maximum(sol_c[:, :, :, 2])),
# xlabel="Longitude", ylabel="Latitude", title="examplesys.c: $(Dates.unix2datetime(discrete_t[k]))")
# p2 = heatmap(discrete_lon, discrete_lat, sol_u[k, 1:end, 1:end, 2], clim=(minimum(sol_u[:, :, :, 2]), maximum(sol_u[:, :, :, 2])),
# title="U")
# p3 = heatmap(discrete_lon, discrete_lat, sol_v[k, 1:end, 1:end, 2], clim=(minimum(sol_v[:, :, :, 2]), maximum(sol_v[:, :, :, 2])),
# title="V")
# plot(p1, p2, p3, size=(800, 500))
# end
# gif(anim, "animation.gif", fps = 8)
``` | EarthSciData | https://github.com/EarthSciML/EarthSciData.jl.git |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.