licenses
sequencelengths
1
3
version
stringclasses
677 values
tree_hash
stringlengths
40
40
path
stringclasses
1 value
type
stringclasses
2 values
size
stringlengths
2
8
text
stringlengths
25
67.1M
package_name
stringlengths
2
41
repo
stringlengths
33
86
[ "MIT" ]
1.0.3
4313f4d37ec6b34bb53214759f8a0df02458b6e9
code
1905
module BoundTypes export ConstraintError export BoundNumber, NumberCustomBound, NumberPositive, NumberNonPositive, NumberNegative, NumberNonNegative, NumberGreater, NumberGreaterOrEqual, NumberLess, NumberLessOrEqual, NumberOdd, NumberEven, NumberInterval export BoundString, StringCustomBound, StringLowerCase, StringUpperCase, StringMinLength, StringMaxLength, StringFixedLength, StringPattern export BoundTime, TimeCustomBound, TimeAfter, TimeAfterNow, TimeAfterOrEqual, TimePeriodAfterNow, TimeBefore, TimeBeforeNow, TimeBeforeOrEqual, TimePeriodBeforeNow, TimeInterval export bound_value, bound_type export @pattern_str using Dates """ ConstraintError Exception thrown when a constraint is violated on bound type creation. ## Fields - `message::String`: The error message. """ struct ConstraintError{T} <: Exception message::String end function Base.showerror(io::IO, exception::ConstraintError{T}) where {T} print(io, "ConstraintError: constraints of type $T violated.\n") print(io, "Wrong value: $(exception.message)") end """ bound_value(x) -> value Getter function for the underlying value from the bound type object `x`. ## Examples ```jldoctest julia> val = StringFixedLength{String,3}("abc") "abc" julia> typeof(val) StringFixedLength{String, 3} julia> inner_val = bound_value(val) "abc" julia> typeof(inner_val) String ``` """ function bound_value end """ bound_type(x) -> type Returns the type of the internal object of `x`. ## Examples ```jldoctest julia> bound_type(NumberPositive{Float64}(1.0)) Float64 julia> bound_type(NumberLess{NumberGreater{Int64,2},8}(6)) Int64 ``` """ function bound_type end include("bound_number/bound_number.jl") include("bound_string/bound_string.jl") include("bound_time/bound_time.jl") end
BoundTypes
https://github.com/bhftbootcamp/BoundTypes.jl.git
[ "MIT" ]
1.0.3
4313f4d37ec6b34bb53214759f8a0df02458b6e9
code
2659
# bound_number/bound_number """ BoundNumber{N<:Number} <: Number Abstract type for number constraints. """ abstract type BoundNumber{N<:Number} <: Number end bound_type(::Type{<:BoundNumber{T}}) where {T<:Number} = T bound_type(::Type{<:BoundNumber{T}}) where {T<:BoundNumber} = bound_type(T) bound_type(x::BoundNumber) = bound_type(typeof(x)) bound_value(x::BoundNumber) = x.value bound_value(x::BoundNumber{T}) where {T<:BoundNumber} = bound_value(x.value) Base.eltype(::Type{<:BoundNumber{T}}) where {T} = T Base.eltype(x::BoundNumber) = eltype(typeof(x)) Base.convert(::Type{T}, x::BoundNumber) where {T<:Number} = T(bound_value(x)) Base.tryparse(::Type{T}, x::String) where {T<:BoundNumber} = convert(T, (tryparse(bound_type(T), x))) for op in [:+, :-, :/, :*, :^] @eval Base.$op(x::BoundNumber, y::BoundNumber) = $op(bound_value(x), bound_value(y)) @eval Base.$op(x::Number, y::BoundNumber) = $op(x, bound_value(y)) @eval Base.$op(x::BoundNumber, y::Number) = $op(bound_value(x), y) end for op in [:isless, :isequal, :(==)] @eval Base.$op(x::BoundNumber, y::BoundNumber) = $op(bound_value(x), bound_value(y)) @eval Base.$op(x::Number, y::BoundNumber) = $op(x, bound_value(y)) @eval Base.$op(x::BoundNumber, y::Number) = $op(bound_value(x), y) end for op in [:div, :fld, :rem, :mod, :mod1, :atan, :atand] @eval Base.$op(x::BoundNumber, y::BoundNumber) = $op(bound_value(x), bound_value(y)) @eval Base.$op(x::Number, y::BoundNumber) = $op(x, bound_value(y)) @eval Base.$op(x::BoundNumber, y::Number) = $op(bound_value(x), y) end for op in [:isinf, :isnan, :iszero, :isreal, :isempty, :isodd, :iseven, :ispow2] @eval Base.$op(x::BoundNumber) = $op(bound_value(x)) end for op in [:sqrt, :abs, :abs2, :sign, :one, :zero] @eval Base.$op(x::BoundNumber) = $op(bound_value(x)) end for op in [:log, :log2, :log1p, :log10, :exp, :exp2, :rad2deg, :deg2rad] @eval Base.$op(x::BoundNumber) = $op(bound_value(x)) end for op in [:sin, :sinh, :asin, :asinh, :sec, :asec, :sech, :asech, :sinc, :secd, :sind, :asecd, :asind, :sinpi] @eval Base.$op(x::BoundNumber) = $op(bound_value(x)) end for op in [:cos, :cosh, :acos, :acosh, :csc, :acsc, :csch, :acsch, :cosc, :cotd, :cscd, :acosd, :acscd, :cospi] @eval Base.$op(x::BoundNumber) = $op(bound_value(x)) end for op in [:tan, :tanh, :atan, :atanh, :cot, :acot, :coth, :acoth, :atand, :tand, :acotd] @eval Base.$op(x::BoundNumber) = $op(bound_value(x)) end function Base.print(io::IO, x::BoundNumber) print(io, bound_value(x)) end function Base.show(io::IO, x::BoundNumber) print(io, bound_value(x)) end include("number_types.jl")
BoundTypes
https://github.com/bhftbootcamp/BoundTypes.jl.git
[ "MIT" ]
1.0.3
4313f4d37ec6b34bb53214759f8a0df02458b6e9
code
8768
# bound_number/number_types """ NumberCustomBound{T<:Number,B} <: BoundNumber{T} NumberCustomBound{T,B}(x::Number) A number constraint for a value `x` of type `T` using custom function `B`. Function `B` should only accept object `x` and return `true` or `false` (or throw a custom [`ConstraintError`](@ref)). ## Examples ```julia-repl julia> NumberCustomBound{Float64,x -> x % 2 == 0}(10.0) 10.0 julia> NumberCustomBound{Float64,x -> x % 2 == 0}(13.0) ERROR: ConstraintError: constraints of type NumberCustomBound violated. Wrong value: Custom constraint '#7' violated for value "13.0" of type Float64. [...] ``` """ struct NumberCustomBound{T<:Number,B} <: BoundNumber{T} value::T function NumberCustomBound{T,B}(x::Number) where {T<:Number,B} !B(x) && throw(ConstraintError{NumberCustomBound}("Custom constraint '$B' violated for value \"$x\" of type $T.")) return new{T,B}(x) end end """ NumberPositive{T<:Number} <: BoundNumber{T} NumberPositive{T}(x::Number) A number constraint that enforces `x > 0` for value `x` of type `T`. ## Examples ```jldoctest julia> NumberPositive{Float64}(10.0) 10.0 julia> NumberPositive{Float64}(-10.0) ERROR: ConstraintError: constraints of type NumberPositive violated. Wrong value: number -10.0 must be a positive (x > 0). [...] ``` """ struct NumberPositive{T<:Number} <: BoundNumber{T} value::T function NumberPositive{T}(x::Number) where {T<:Number} x <= 0 && throw(ConstraintError{NumberPositive}("number $x must be a positive (x > 0).")) return new{T}(x) end end """ NumberNonPositive{T<:Number} <: BoundNumber{T} NumberNonPositive{T}(x::Number) A number constraint that enforces `x ≤ 0` for value `x` of type `T`. ## Examples ```jldoctest julia> NumberNonPositive{Float64}(-10.0) -10.0 julia> NumberNonPositive{Float64}(10.0) ERROR: ConstraintError: constraints of type NumberNonPositive violated. Wrong value: number 10.0 must be a negative or zero (x ≤ 0). [...] ``` """ struct NumberNonPositive{T<:Number} <: BoundNumber{T} value::T function NumberNonPositive{T}(x::Number) where {T<:Number} x > 0 && throw(ConstraintError{NumberNonPositive}("number $x must be a negative or zero (x ≤ 0).")) return new{T}(x) end end """ NumberNegative{T<:Number} <: BoundNumber{T} NumberNegative{T}(x::Number) A number constraint that enforces `x < 0` for value `x` of type `T`. ## Examples ```jldoctest julia> NumberNegative{Float64}(-10.0) -10.0 julia> NumberNegative{Float64}(10.0) ERROR: ConstraintError: constraints of type NumberNegative violated. Wrong value: 10.0 must be a negative (x < 0). [...] ``` """ struct NumberNegative{T<:Number} <: BoundNumber{T} value::T function NumberNegative{T}(x::Number) where {T<:Number} x >= 0 && throw(ConstraintError{NumberNegative}("$x must be a negative (x < 0).")) return new{T}(x) end end """ NumberNonNegative{T<:Number} <: BoundNumber{T} NumberNonNegative{T}(x::Number) A number constraint that enforces `x ≥ 0` for value `x` of type `T`. ## Examples ```jldoctest julia> NumberNonNegative{Float64}(10.0) 10.0 julia> NumberNonNegative{Float64}(-10.0) ERROR: ConstraintError: constraints of type NumberNonNegative violated. Wrong value: -10.0 must be a positive or zero (x ≥ 0). [...] ``` """ struct NumberNonNegative{T<:Number} <: BoundNumber{T} value::T function NumberNonNegative{T}(x::Number) where {T<:Number} x < 0 && throw(ConstraintError{NumberNonNegative}("$x must be a positive or zero (x ≥ 0).")) return new{T}(x) end end """ NumberGreater{T<:Number,V} <: BoundNumber{T} NumberGreater{T,V}(x::Number) A number constraint that enforces `x > V` for value `x` of type `T`. ## Examples ```jldoctest julia> NumberGreater{Float64,10.0}(20.0) 20.0 julia> NumberGreater{Float64,10.0}(5.0) ERROR: ConstraintError: constraints of type NumberGreater violated. Wrong value: 5.0 must be greater than 10.0. [...] ``` """ struct NumberGreater{T<:Number,V} <: BoundNumber{T} value::T function NumberGreater{T,V}(x::Number) where {T<:Number,V} x <= V && throw(ConstraintError{NumberGreater}("$x must be greater than $V.")) return new{T,V}(x) end end """ NumberGreaterOrEqual{T<:Number,V} <: BoundNumber{T} NumberGreaterOrEqual{T,V}(x::Number) A number constraint that enforces `x ≥ V` for value `x` of type `T`. ## Examples ```jldoctest julia> NumberGreaterOrEqual{Float64,10.0}(20.0) 20.0 julia> NumberGreaterOrEqual{Float64,10.0}(5.0) ERROR: ConstraintError: constraints of type NumberGreaterOrEqual violated. Wrong value: 5.0 must be greater or equal than 10.0. [...] ``` """ struct NumberGreaterOrEqual{T<:Number,V} <: BoundNumber{T} value::T function NumberGreaterOrEqual{T,V}(x::Number) where {T<:Number,V} x < V && throw(ConstraintError{NumberGreaterOrEqual}("$x must be greater or equal than $V.")) return new{T,V}(x) end end """ NumberLess{T<:Number,V} <: BoundNumber{T} NumberLess{T,V}(x::Number) A number constraint that enforces `x < V` for value `x` of type `T`. ## Examples ```jldoctest julia> NumberLess{Float64,10.0}(5.0) 5.0 julia> NumberLess{Float64,10.0}(20.0) ERROR: ConstraintError: constraints of type NumberLess violated. Wrong value: 20.0 must be less than 10.0. [...] ``` """ struct NumberLess{T<:Number,V} <: BoundNumber{T} value::T function NumberLess{T,V}(x::Number) where {T<:Number,V} x >= V && throw(ConstraintError{NumberLess}("$x must be less than $V.")) return new{T,V}(x) end end """ NumberLessOrEqual{T<:Number,V} <: BoundNumber{T} NumberLessOrEqual{T,V}(x::Number) A number constraint that enforces `x ≤ V` for value `x` of type `T`. ## Examples ```jldoctest julia> NumberLessOrEqual{Float64,10.0}(5.0) 5.0 julia> NumberLessOrEqual{Float64,10.0}(20.0) ERROR: ConstraintError: constraints of type NumberLessOrEqual violated. Wrong value: 20.0 must be less or equal than 10.0. [...] ``` """ struct NumberLessOrEqual{T<:Number,V} <: BoundNumber{T} value::T function NumberLessOrEqual{T,V}(x::Number) where {T<:Number,V} x > V && throw(ConstraintError{NumberLessOrEqual}("$x must be less or equal than $V.")) return new{T,V}(x) end end """ NumberOdd{T<:Number} <: BoundNumber{T} NumberOdd{T}(x::Number) A numeric constraint to ensure that the value `x` of type `T` is odd. ## Examples ```jldoctest julia> NumberOdd{Float64}(5.0) 5.0 julia> NumberOdd{Float64}(4.0) ERROR: ConstraintError: constraints of type NumberOdd violated. Wrong value: 4.0 must be odd. [...] ``` """ struct NumberOdd{T<:Number} <: BoundNumber{T} value::T function NumberOdd{T}(x::Number) where {T<:Number} !isodd(x) && throw(ConstraintError{NumberOdd}("$x must be odd.")) return new{T}(x) end end """ NumberEven{T<:Number} <: BoundNumber{T} NumberEven{T}(x::Number) A numeric constraint to ensure that the value `x` of type `T` is even. ## Examples ```jldoctest julia> NumberEven{Float64}(4.0) 4.0 julia> NumberEven{Float64}(5.0) ERROR: ConstraintError: constraints of type NumberEven violated. Wrong value: 5.0 must be even. [...] ``` """ struct NumberEven{T<:Number} <: BoundNumber{T} value::T function NumberEven{T}(x::Number) where {T<:Number} !iseven(x) && throw(ConstraintError{NumberEven}("$x must be even.")) return new{T}(x) end end """ NumberInterval{T<:Number,A,L,R,B} <: BoundNumber{T} NumberInterval{T,A,L,R,B}(x::Number) A numeric constraint for a value `x` of type `T` which belongs to an interval between `A` and `B`. Parameters `L` and `R` are the comparison functions e.g `<` or `<=` which determine whether interval boundaries are included. ## Examples ```jldoctest julia> NumberInterval{Float64,5,<,<=,10}(7.0) 7.0 julia> NumberInterval{Float64,5,<,<=,10}(10.0) 10.0 julia> NumberInterval{Float64,5,<,<=,10}(15.0) ERROR: ConstraintError: constraints of type NumberInterval violated. Wrong value: 15.0 must be in interval between 5 and 10. [...] ``` """ struct NumberInterval{T<:Number,A,L,R,B} <: BoundNumber{T} value::T function NumberInterval{T,A,L,R,B}(x::Number) where {T<:Number,A,L,R,B} !(A <= B) && throw(ArgumentError("Wrong interval: A = $A must be less or equal than B = $B.")) !L(zero(x), one(x)) && throw(ArgumentError("Wrong left comparison function: $L must be one of '<' or '<='.")) !R(zero(x), one(x)) && throw(ArgumentError("Wrong right comparison function: $R must be one of '<' or '<='.")) (!L(A, x) || !R(x, B)) && throw(ConstraintError{NumberInterval}("$x must be in interval between $A and $B.")) return new{T,A,L,R,B}(x) end end
BoundTypes
https://github.com/bhftbootcamp/BoundTypes.jl.git
[ "MIT" ]
1.0.3
4313f4d37ec6b34bb53214759f8a0df02458b6e9
code
1138
# bound_string/bound_string """ BoundString{T<:AbstractString} <: AbstractString Abstract type for string constraints. """ abstract type BoundString{T<:AbstractString} <: AbstractString end bound_type(::Type{<:BoundString{T}}) where {T<:AbstractString} = T bound_type(::Type{<:BoundString{T}}) where {T<:BoundString} = bound_type(T) bound_type(x::BoundString) = bound_type(typeof(x)) bound_value(x::BoundString) = x.value bound_value(x::BoundString{T}) where {T<:BoundString} = bound_value(x.value) Base.convert(::Type{T}, x::BoundString) where {T<:AbstractString} = T(bound_value(x)) Base.ncodeunits(x::BoundString) = ncodeunits(bound_value(x)) Base.isvalid(x::BoundString, i::Integer) = isvalid(bound_value(x), i) Base.iterate(x::BoundString, i::Integer = firstindex(bound_value(x))) = iterate(bound_value(x), i) Base.codeunit(x::BoundString) = codeunit(bound_value(x)) Base.codeunit(x::BoundString, i::Integer) = codeunit(bound_value(x), i) function Base.print(io::IO, x::BoundString) print(io, bound_value(x)) end function Base.show(io::IO, x::BoundString) show(io, bound_value(x)) end include("string_types.jl")
BoundTypes
https://github.com/bhftbootcamp/BoundTypes.jl.git
[ "MIT" ]
1.0.3
4313f4d37ec6b34bb53214759f8a0df02458b6e9
code
7513
# bound_string/string_types """ StringCustomBound{T<:AbstractString,B} <: BoundString{T} StringCustomBound{T,B}(x::AbstractString) A string constraint for a value `x` of type `T` using custom function `B`. Function `B` should only accept object `x` and return `true` or `false` (or throw a custom [`ConstraintError`](@ref)). ## Examples ```julia-repl julia> StringCustomBound{String,x -> length(x) > 5}("abcdef") "abcdef" julia> StringCustomBound{String,x -> length(x) > 5}("abc") ERROR: ConstraintError: constraints of type StringCustomBound violated. Wrong value: Custom constraint '#5' violated for value "abc" of type String. [...] ``` """ struct StringCustomBound{T<:AbstractString,B} <: BoundString{T} value::T function StringCustomBound{T,B}(x::AbstractString) where {T<:AbstractString,B} !B(x) && throw(ConstraintError{StringCustomBound}("Custom constraint '$B' violated for value \"$x\" of type $T.")) return new{T,B}(x) end function StringCustomBound{T,B}(x::AbstractVector{<:Unsigned}) where {T<:AbstractString,B} return StringCustomBound{T,B}(String(x)) end end """ StringLowerCase{T<:AbstractString} <: BoundString{T} StringLowerCase{T}(x::AbstractString) A string constraint for a value `x` of type `T` which characters must be in lowercase. ## Examples ```jldoctest julia> StringLowerCase{String}("abcdef") "abcdef" julia> StringLowerCase{String}("aBcdEf") ERROR: ConstraintError: constraints of type StringLowerCase violated. Wrong value: some characters of "aBcdEf" must be in lowercase (B,E). [...] ``` """ struct StringLowerCase{T<:AbstractString} <: BoundString{T} value::T function StringLowerCase{T}(x::AbstractString) where {T<:AbstractString} !all(x -> islowercase(x) || !isletter(x), x) && throw(ConstraintError{StringLowerCase}( "some characters of \"$x\" must be in lowercase ($(join(x[findall(isuppercase, x)], ","))).") ) return new{T}(x) end function StringLowerCase{T}(x::AbstractVector{<:Unsigned}) where {T<:AbstractString} return StringLowerCase{T}(String(x)) end end """ StringUpperCase{T<:AbstractString} <: BoundString{T} StringUpperCase{T}(x::AbstractString) A string constraint for a value `x` of type `T` which characters must be in uppercase. ## Examples ```jldoctest julia> StringUpperCase{String}("ABCDEF") "ABCDEF" julia> StringUpperCase{String}("AbCDeF") ERROR: ConstraintError: constraints of type StringUpperCase violated. Wrong value: some characters of "AbCDeF" must be in uppercase (b,e). [...] ``` """ struct StringUpperCase{T<:AbstractString} <: BoundString{T} value::T function StringUpperCase{T}(x::AbstractString) where {T<:AbstractString} !all(x -> isuppercase(x) || !isletter(x), x) && throw(ConstraintError{StringUpperCase}( "some characters of \"$x\" must be in uppercase ($(join(x[findall(islowercase, x)], ","))).") ) return new{T}(x) end function StringUpperCase{T}(x::AbstractVector{<:Unsigned}) where {T<:AbstractString} return StringUpperCase{T}(String(x)) end end """ StringMinLength{T<:AbstractString,V} <: BoundString{T} StringMinLength{T,V}(x::AbstractString) A string constraint for a value `x` of type `T` which length must be at least `V` characters. ## Examples ```jldoctest julia> StringMinLength{String,5}("abcdef") "abcdef" julia> StringMinLength{String,5}("abc") ERROR: ConstraintError: constraints of type StringMinLength violated. Wrong value: length of the "abc" must be at least 5 characters (3). [...] ``` """ struct StringMinLength{T<:AbstractString,V} <: BoundString{T} value::T function StringMinLength{T,V}(x::AbstractString) where {T<:AbstractString,V} length(x) < V && throw(ConstraintError{StringMinLength}( "length of the \"$x\" must be at least $V characters ($(length(x))).") ) return new{T,V}(x) end function StringMinLength{T,V}(x::AbstractVector{<:Unsigned}) where {T<:AbstractString,V} return StringMinLength{T,V}(String(x)) end end """ StringMaxLength{T<:AbstractString,V} <: BoundString{T} StringMaxLength{T,V}(x::AbstractString) A string constraint for a value `x` of type `T` which length must be no more than `V` characters. ## Examples ```jldoctest julia> StringMaxLength{String,5}("abc") "abc" julia> StringMaxLength{String,5}("abcdef") ERROR: ConstraintError: constraints of type StringMaxLength violated. Wrong value: length of the "abcdef" must be no more than 5 characters (6). [...] ``` """ struct StringMaxLength{T<:AbstractString,V} <: BoundString{T} value::T function StringMaxLength{T,V}(x::AbstractString) where {T<:AbstractString,V} length(x) > V && throw(ConstraintError{StringMaxLength}( "length of the \"$x\" must be no more than $V characters ($(length(x))).") ) return new{T,V}(x) end function StringMaxLength{T,V}(x::AbstractVector{<:Unsigned}) where {T<:AbstractString,V} return StringMaxLength{T,V}(String(x)) end end """ StringFixedLength{T<:AbstractString,V} <: BoundString{T} StringFixedLength{T,V}(x::AbstractString) A string constraint for a value `x` of type `T` which length must be equal to `V` characters. ## Examples ```jldoctest julia> StringFixedLength{String,5}("abcde") "abcde" julia> StringFixedLength{String,5}("abc") ERROR: ConstraintError: constraints of type StringFixedLength violated. Wrong value: length of the "abc" must be equal to 5 characters (3). [...] ``` """ struct StringFixedLength{T<:AbstractString,V} <: BoundString{T} value::T function StringFixedLength{T,V}(x::AbstractString) where {T<:AbstractString,V} length(x) != V && throw(ConstraintError{StringFixedLength}( "length of the \"$x\" must be equal to $V characters ($(length(x))).") ) return new{T,V}(x) end function StringFixedLength{T,V}(x::AbstractVector{<:Unsigned}) where {T<:AbstractString,V} return StringFixedLength{T,V}(String(x)) end end """ @pattern_str -> Symbol An auxiliary function that allows you to pass a regex string to [`StringPattern`](@ref) parameters, turning it into a Symbol. """ macro pattern_str(p) esc(:(Symbol($p))) end """ StringPattern{T<:AbstractString,P} <: BoundString{T} StringPattern{T,P}(x::AbstractString) A string constraint for a value `x` of type `T` which must match regex pattern `P`. !!! note Use a helper function [`@pattern_str`](@ref) to pass a regex expression. ## Examples ```jldoctest julia> StringPattern{String,pattern"^[a-zA-Z0-9_]+\$"}("abcde") "abcde" julia> StringPattern{String,pattern"^[a-zA-Z0-9_]+\$"}("abc+def") ERROR: ConstraintError: constraints of type StringPattern violated. Wrong value: "abc+def" must match to regex pattern /^[a-zA-Z0-9_]+\$/. [...] ``` """ struct StringPattern{T<:AbstractString,P} <: BoundString{T} value::T function StringPattern{T,P}(x::AbstractString) where {T<:AbstractString,P} isnothing(match(Regex(String(P)), x)) && throw(ConstraintError{StringPattern}( "\"$x\" must match to regex pattern /$P/.") ) return new{T,P}(x) end function StringPattern{T,P}(x::AbstractVector{<:Unsigned}) where {T<:AbstractString,P} return StringPattern{T,P}(String(x)) end end function Base.show(io::IO, ::Type{StringPattern{T,P}}) where {T,P} print(io, "StringPattern{$T,/$P/}") end
BoundTypes
https://github.com/bhftbootcamp/BoundTypes.jl.git
[ "MIT" ]
1.0.3
4313f4d37ec6b34bb53214759f8a0df02458b6e9
code
2912
# bound_time/bound_time """ BoundTime{T<:TimeType} <: TimeType Abstract type for time constraints. """ abstract type BoundTime{T<:TimeType} <: TimeType end bound_type(::Type{<:BoundTime{T}}) where {T<:TimeType} = T bound_type(::Type{<:BoundTime{T}}) where {T<:BoundTime} = bound_type(T) bound_type(x::BoundTime) = bound_type(typeof(x)) bound_value(x::BoundTime) = x.value bound_value(x::BoundTime{T}) where {T<:BoundTime} = bound_value(x.value) Base.eltype(::Type{<:BoundTime{T}}) where {T} = T Base.eltype(x::BoundTime) = eltype(typeof(x)) Base.promote_rule(::Type{T1}, ::Type{BoundTime{T2}}) where {T1<:TimeType,T2<:TimeType} = T1 Base.promote_rule(::Type{BoundTime{T1}}, ::Type{T2}) where {T1<:TimeType,T2<:TimeType} = T2 Base.convert(::Type{T}, x::BoundTime) where {T<:BoundTime} = T(bound_value(x)) Base.convert(::Type{T}, x::TimeType) where {T<:BoundTime} = T(x) Base.convert(::Type{T}, x::BoundTime) where {T<:TimeType} = convert(T, bound_value(x)) Base.convert(::Type{T}, x::BoundTime{T}) where {T<:TimeType} = bound_value(x) Base.convert(::Type{Time}, x::BoundTime{T}) where {T<:DateTime} = Time(bound_value(x)) Base.convert(::Type{Date}, x::BoundTime{T}) where {T<:DateTime} = Date(bound_value(x)) for op in [:+, :-] @eval Base.$op(x::BoundTime, y::Period) = $op(bound_value(x), y) end for op in [:isless, :isequal, :(==)] @eval Base.$op(x::BoundTime, y::BoundTime) = $op(bound_value(x), bound_value(y)) @eval Base.$op(x::TimeType, y::BoundTime) = $op(x, bound_value(y)) @eval Base.$op(x::BoundTime, y::TimeType) = $op(bound_value(x), y) end for op in [:year, :month, :week, :day, :hour, :minute, :second, :millisecond, :microsecond, :nanosecond] @eval Dates.$op(x::BoundTime) = $op(bound_value(x)) end for op in [:Year, :Quarter, :Month, :Week, :Day, :Hour, :Minute, :Second, :Millisecond, :Microsecond, :Nanosecond] @eval Dates.$op(x::BoundTime) = $op(bound_value(x)) end for op in [:yearmonth, :monthday, :yearmonthday] @eval Dates.$op(x::BoundTime) = $op(bound_value(x)) end for op in [:dayofyear, :dayofquarter, :quarterofyear] @eval Dates.$op(x::BoundTime) = $op(bound_value(x)) end for op in [:dayofmonth, :dayofweek, :dayofweekofmonth, :daysofweekinmonth] @eval Dates.$op(x::BoundTime) = $op(bound_value(x)) end for op in [:monthname, :monthabbr, :dayname, :dayabbr] @eval Dates.$op(x::BoundTime) = $op(bound_value(x)) end for op in [:firstdayofweek, :firstdayofmonth, :firstdayofquarter, :firstdayofyear] @eval Dates.$op(x::BoundTime) = $op(bound_value(x)) end for op in [:lastdayofweek, :lastdayofmonth, :lastdayofquarter, :lastdayofyear] @eval Dates.$op(x::BoundTime) = $op(bound_value(x)) end for op in [:eps, :daysinmonth, :daysinyear, :isleapyear, :value] @eval Dates.$op(x::BoundTime) = $op(bound_value(x)) end function Base.show(io::IO, x::BoundTime) print(io, bound_value(x)) end include("time_types.jl")
BoundTypes
https://github.com/bhftbootcamp/BoundTypes.jl.git
[ "MIT" ]
1.0.3
4313f4d37ec6b34bb53214759f8a0df02458b6e9
code
9327
# bound_time/time_types """ TimeCustomBound{T<:TimeType,B} <: BoundTime{T} TimeCustomBound{T,B}(x::TimeType) A time constraint for a value `x` of type `T` using custom function `B`. Function `B` should only accept object `x` and return `true` or `false` (or throw a custom [`ConstraintError`](@ref)). ## Examples ```julia-repl julia> using Dates julia> TimeCustomBound{DateTime,isleapyear}(DateTime(2024)) 2024-01-01T00:00:00 julia> TimeCustomBound{DateTime,isleapyear}(DateTime(2023)) ERROR: ConstraintError: constraints of type TimeCustomBound violated. Wrong value: Custom constraint 'isleapyear' violated for value "2023-01-01T00:00:00" of type DateTime. [...] ``` """ struct TimeCustomBound{T<:TimeType,B} <: BoundTime{T} value::T function TimeCustomBound{T,B}(x::TimeType) where {T<:TimeType,B} !B(x) && throw(ConstraintError{TimeCustomBound}("Custom constraint '$B' violated for value \"$x\" of type $T.")) return new{T,B}(x) end end """ TimeAfter{T<:TimeType,V} <: BoundTime{T} TimeAfter{T,V}(x::TimeType) A time constraint for a value `x` of type `T` which must exceed the time `V`. ## Examples ```jldoctest julia> using Dates julia> TimeAfter{DateTime,DateTime(2023)}(DateTime(2024)) 2024-01-01T00:00:00 julia> TimeAfter{DateTime,DateTime(2023)}(DateTime(2022)) ERROR: ConstraintError: constraints of type TimeAfter violated. Wrong value: 2022-01-01T00:00:00 must exceed 2023-01-01T00:00:00. [...] ``` """ struct TimeAfter{T<:TimeType,V} <: BoundTime{T} value::T function TimeAfter{T,V}(x::TimeType) where {T<:TimeType,V} t = convert(typeof(x), V) x <= t && throw(ConstraintError{TimeAfter}("$x must exceed $t.")) return new{T,V}(x) end end """ TimeAfterNow{T<:TimeType} <: BoundTime{T} TimeAfterNow{T}(x::TimeType) A time constraint for a value `x` of type `T` which must exceed the current time. ## Examples ```julia-repl julia> using Dates julia> TimeAfterNow{DateTime}(DateTime(2030)) 2030-01-01T00:00:00 julia> TimeAfterNow{DateTime}(DateTime(2020)) ERROR: ConstraintError: constraints of type TimeAfterNow violated. Wrong value: 2020-01-01T00:00:00 must exceed 2024-05-03T11:25:26.689. [...] ``` """ struct TimeAfterNow{T<:TimeType} <: BoundTime{T} value::T function TimeAfterNow{T}(x::TimeType) where {T<:TimeType} t = convert(typeof(x), now()) x <= t && throw(ConstraintError{TimeAfterNow}("$x must exceed $t.")) return new{T}(x) end end """ TimePeriodAfterNow{T<:TimeType,P} <: BoundTime{T} TimePeriodAfterNow{T,P}(x::TimeType) A time constraint for a value `x` of type `T` which must exceed the current time during period `P`. ## Examples ```julia-repl julia> using Dates julia> TimePeriodAfterNow{DateTime,Year(10)}(DateTime(2030)) 2030-01-01T00:00:00 julia> TimePeriodAfterNow{DateTime,Year(10)}(DateTime(2050)) ERROR: ConstraintError: constraints of type TimePeriodAfterNow violated. Wrong value: 2050-01-01T00:00:00 must be in interval between 2024-05-03T11:29:14 and 2034-05-03T11:29:14. [...] ``` """ struct TimePeriodAfterNow{T<:TimeType,P} <: BoundTime{T} value::T function TimePeriodAfterNow{T,P}(x::TimeType) where {T<:TimeType,P} t = convert(typeof(x), now()) (x < t || x > t + P) && throw(ConstraintError{TimePeriodAfterNow}("$x must be in interval between $t and $(t + P).")) return new{T,P}(x) end end """ TimeAfterOrEqual{T<:TimeType,V} <: BoundTime{T} TimeAfterOrEqual{T,V}(x::TimeType) A time constraint for a value `x` of type `T` which must exceed or be equal to the time `V`. ## Examples ```jldoctest julia> using Dates julia> TimeAfterOrEqual{DateTime,DateTime(2023)}(DateTime(2024)) 2024-01-01T00:00:00 julia> TimeAfterOrEqual{DateTime,DateTime(2023)}(DateTime(2023)) 2023-01-01T00:00:00 julia> TimeAfterOrEqual{DateTime,DateTime(2023)}(DateTime(2022)) ERROR: ConstraintError: constraints of type TimeAfterOrEqual violated. Wrong value: 2022-01-01T00:00:00 must exceed or be equal to 2023-01-01T00:00:00. [...] ``` """ struct TimeAfterOrEqual{T<:TimeType,V} <: BoundTime{T} value::T function TimeAfterOrEqual{T,V}(x::TimeType) where {T<:TimeType,V} t = convert(typeof(x), V) x < t && throw(ConstraintError{TimeAfterOrEqual}("$x must exceed or be equal to $t.")) return new{T,V}(x) end end """ TimeBefore{T<:TimeType,V} <: BoundTime{T} TimeBefore{T,V}(x::TimeType) A time constraint for a value `x` of type `T` which must precede the time `V`. ## Examples ```jldoctest julia> using Dates julia> TimeBefore{DateTime,DateTime(2023)}(DateTime(2022)) 2022-01-01T00:00:00 julia> TimeBefore{DateTime,DateTime(2023)}(DateTime(2024)) ERROR: ConstraintError: constraints of type TimeBefore violated. Wrong value: 2024-01-01T00:00:00 must precede 2023-01-01T00:00:00. [...] ``` """ struct TimeBefore{T<:TimeType,V} <: BoundTime{T} value::T function TimeBefore{T,V}(x::TimeType) where {T<:TimeType,V} t = convert(typeof(x), V) x >= t && throw(ConstraintError{TimeBefore}("$x must precede $t.")) return new{T,V}(x) end end """ TimeBeforeNow{T<:TimeType} <: BoundTime{T} TimeBeforeNow{T}(x::TimeType) A time constraint for a value `x` of type `T` which must precede the current time. ## Examples ```julia-repl julia> using Dates julia> TimeBeforeNow{DateTime}(DateTime(2020)) 2020-01-01T00:00:00 julia> TimeBeforeNow{DateTime}(DateTime(2030)) ERROR: ConstraintError: constraints of type TimeBeforeNow violated. Wrong value: 2030-01-01T00:00:00 must precede 2024-05-03T11:36:37.848. [...] ``` """ struct TimeBeforeNow{T<:TimeType} <: BoundTime{T} value::T function TimeBeforeNow{T}(x::TimeType) where {T<:TimeType} t = convert(typeof(x), now()) x >= t && throw(ConstraintError{TimeBeforeNow}("$x must precede $t.")) return new{T}(x) end end """ TimePeriodBeforeNow{T<:TimeType,P} <: BoundTime{T} TimePeriodBeforeNow{T,P}(x::TimeType) A time constraint for a value `x` of type `T` which must precede the current time during period `P`. ## Examples ```julia-repl julia> using Dates julia> TimePeriodBeforeNow{DateTime,Year(10)}(DateTime(2020)) 2020-01-01T00:00:00 julia> TimePeriodBeforeNow{DateTime,Year(10)}(DateTime(2030)) ERROR: ConstraintError: constraints of type TimePeriodBeforeNow violated. Wrong value: 2030-01-01T00:00:00 must be in interval between 2014-05-03T11:38:35.124 and 2024-05-03T11:38:35.124. [...] ``` """ struct TimePeriodBeforeNow{T<:TimeType,P} <: BoundTime{T} value::T function TimePeriodBeforeNow{T,P}(x::TimeType) where {T<:TimeType,P} t = convert(typeof(x), now()) (x < t - P || x > t) && throw(ConstraintError{TimePeriodBeforeNow}("$x must be in interval between $(t - P) and $t.")) return new{T,P}(x) end end """ TimeBeforeOrEqual{T<:TimeType,V} <: BoundTime{T} TimeBeforeOrEqual{T,V}(x::TimeType) A time constraint for a value `x` of type `T` which must precede or be equal to the time `V`. ## Examples ```jldoctest julia> using Dates julia> TimeBeforeOrEqual{DateTime,DateTime(2023)}(DateTime(2022)) 2022-01-01T00:00:00 julia> TimeBeforeOrEqual{DateTime,DateTime(2023)}(DateTime(2023)) 2023-01-01T00:00:00 julia> TimeBeforeOrEqual{DateTime,DateTime(2023)}(DateTime(2024)) ERROR: ConstraintError: constraints of type TimeBeforeOrEqual violated. Wrong value: 2024-01-01T00:00:00 must precede or be equal to 2023-01-01T00:00:00. [...] ``` """ struct TimeBeforeOrEqual{T<:TimeType,V} <: BoundTime{T} value::T function TimeBeforeOrEqual{T,V}(x::TimeType) where {T<:TimeType,V} t = convert(typeof(x), V) x > t && throw(ConstraintError{TimeBeforeOrEqual}("$x must precede or be equal to $t.")) return new{T,V}(x) end end """ TimeInterval{T<:TimeType,A,L,R,B} <: BoundTime{T} TimeInterval{T,A,L,R,B}(x::TimeType) A time constraint for a value `x` of type `T` which belongs to an interval between times `A` and `B`. Parameters `L` and `R` are the comparison functions e.g `<` or `<=` which determine whether interval boundaries are included. ## Examples ```jldoctest julia> using Dates julia> TimeInterval{DateTime,DateTime(2023),<,<,DateTime(2025)}(DateTime(2024)) 2024-01-01T00:00:00 julia> TimeInterval{DateTime,DateTime(2023),<,<=,DateTime(2025)}(DateTime(2025)) 2025-01-01T00:00:00 julia> TimeInterval{DateTime,DateTime(2023),<,<,DateTime(2025)}(DateTime(2025)) ERROR: ConstraintError: constraints of type TimeInterval violated. Wrong value: 2025-01-01T00:00:00 must be in interval between 2023-01-01T00:00:00 and 2025-01-01T00:00:00. [...] ``` """ struct TimeInterval{T<:TimeType,A,L,R,B} <: BoundTime{T} value::T function TimeInterval{T,A,L,R,B}(x::TimeType) where {T<:TimeType,A,L,R,B} !(A <= B) && throw(ArgumentError("Wrong interval: A = $A must be less or equal than B = $B")) !L(DateTime(0), DateTime(1)) && throw(ArgumentError("Wrong left comparison function: $L must be one of '<' or '<='")) !R(DateTime(0), DateTime(1)) && throw(ArgumentError("Wrong right comparison function: $R must be one of '<' or '<='")) (!L(A, x) || !R(x, B)) && throw(ConstraintError{TimeInterval}("$x must be in interval between $A and $B.")) return new{T,A,L,R,B}(x) end end
BoundTypes
https://github.com/bhftbootcamp/BoundTypes.jl.git
[ "MIT" ]
1.0.3
4313f4d37ec6b34bb53214759f8a0df02458b6e9
code
9919
# test/numbers @testset verbose = true "BoundNumber" begin @testset "Case №1: NumberPositive constructor" begin @test NumberPositive{Float64}(10.0) == 10.0 @test NumberPositive{Float64}(10) == 10.0 @test_throws ConstraintError{<:NumberPositive} NumberPositive{Float64}(-10.0) @test_throws ConstraintError{<:NumberPositive} NumberPositive{Float64}(-10) @test_throws ConstraintError{<:NumberPositive} NumberPositive{Float64}(0) end @testset "Case №2: NumberNonPositive constructor" begin @test NumberNonPositive{Float64}(-10.0) == -10.0 @test NumberNonPositive{Float64}(-10) == -10.0 @test NumberNonPositive{Float64}(0) == 0.0 @test_throws ConstraintError{<:NumberNonPositive} NumberNonPositive{Float64}(10.0) @test_throws ConstraintError{<:NumberNonPositive} NumberNonPositive{Float64}(10) end @testset "Case №3: NumberNegative constructor" begin @test NumberNegative{Float64}(-10.0) == -10.0 @test NumberNegative{Float64}(-10) == -10.0 @test_throws ConstraintError{<:NumberNegative} NumberNegative{Float64}(10.0) @test_throws ConstraintError{<:NumberNegative} NumberNegative{Float64}(10) @test_throws ConstraintError{<:NumberNegative} NumberNegative{Float64}(0) end @testset "Case №4: NumberNonNegative constructor" begin @test NumberNonNegative{Float64}(10.0) == 10.0 @test NumberNonNegative{Float64}(10) == 10.0 @test NumberNonNegative{Float64}(0) == 0.0 @test_throws ConstraintError{<:NumberNonNegative} NumberNonNegative{Float64}(-10.0) @test_throws ConstraintError{<:NumberNonNegative} NumberNonNegative{Float64}(-10) end @testset "Case №5: NumberGreater constructor" begin @test NumberGreater{Float64,5}(10.0) == 10.0 @test NumberGreater{Float64,5.0}(10) == 10.0 @test_throws ConstraintError{<:NumberGreater} NumberGreater{Float64,5}(-10.0) @test_throws ConstraintError{<:NumberGreater} NumberGreater{Float64,5}(-10) @test_throws ConstraintError{<:NumberGreater} NumberGreater{Float64,5}(5) end @testset "Case №6: NumberGreaterOrEqual constructor" begin @test NumberGreaterOrEqual{Float64,5}(10.0) == 10.0 @test NumberGreaterOrEqual{Float64,5.0}(10) == 10.0 @test NumberGreaterOrEqual{Float64,5}(5.0) == 5.0 @test_throws ConstraintError{<:NumberGreaterOrEqual} NumberGreaterOrEqual{Float64,5}(-10.0) @test_throws ConstraintError{<:NumberGreaterOrEqual} NumberGreaterOrEqual{Float64,5}(-10) end @testset "Case №7: NumberLess constructor" begin @test NumberLess{Float64,5}(-10.0) == -10.0 @test NumberLess{Float64,5.0}(-10) == -10.0 @test_throws ConstraintError{<:NumberLess} NumberLess{Float64,5}(10.0) @test_throws ConstraintError{<:NumberLess} NumberLess{Float64,5}(10) @test_throws ConstraintError{<:NumberLess} NumberLess{Float64,5}(5) end @testset "Case №8: NumberLessOrEqual constructor" begin @test NumberLessOrEqual{Float64,5}(-10.0) == -10.0 @test NumberLessOrEqual{Float64,5.0}(-10) == -10.0 @test NumberLessOrEqual{Float64,5}(5.0) == 5.0 @test_throws ConstraintError{<:NumberLessOrEqual} NumberLessOrEqual{Float64,5}(10.0) @test_throws ConstraintError{<:NumberLessOrEqual} NumberLessOrEqual{Float64,5}(10) end @testset "Case №9: NumberInterval constructor" begin @test NumberInterval{Float64,5,<,<,15}(10.0) == 10.0 @test NumberInterval{Float64,5,<,<,15}(10) == 10.0 @test_throws ConstraintError{<:NumberInterval} NumberInterval{Float64,5,<,<,15}(5.0) @test_throws ConstraintError{<:NumberInterval} NumberInterval{Float64,5,<,<,15}(15) @test_throws ConstraintError{<:NumberInterval} NumberInterval{Float64,5,<,<,15}(0.0) @test_throws ConstraintError{<:NumberInterval} NumberInterval{Float64,5,<,<,15}(20) @test NumberInterval{Float64,5,<,<=,15}(10.0) == 10.0 @test NumberInterval{Float64,5,<,<=,15}(10) == 10.0 @test NumberInterval{Float64,5,<,<=,15}(15) == 15.0 @test_throws ConstraintError{<:NumberInterval} NumberInterval{Float64,5,<,<=,15}(5.0) @test_throws ConstraintError{<:NumberInterval} NumberInterval{Float64,5,<,<=,15}(0.0) @test_throws ConstraintError{<:NumberInterval} NumberInterval{Float64,5,<,<=,15}(20) @test NumberInterval{Float64,5,<=,<,15}(10.0) == 10.0 @test NumberInterval{Float64,5,<=,<,15}(10) == 10.0 @test NumberInterval{Float64,5,<=,<,15}(5) == 5.0 @test_throws ConstraintError{<:NumberInterval} NumberInterval{Float64,5,<=,<,15}(15.0) @test_throws ConstraintError{<:NumberInterval} NumberInterval{Float64,5,<=,<,15}(0.0) @test_throws ConstraintError{<:NumberInterval} NumberInterval{Float64,5,<=,<,15}(20) @test NumberInterval{Float64,5,<=,<=,15}(10.0) == 10.0 @test NumberInterval{Float64,5,<=,<=,15}(10) == 10.0 @test NumberInterval{Float64,5,<=,<=,15}(5.0) == 5.0 @test NumberInterval{Float64,5,<=,<=,15}(15) == 15.0 @test_throws ConstraintError{<:NumberInterval} NumberInterval{Float64,5,<=,<=,15}(0.0) @test_throws ConstraintError{<:NumberInterval} NumberInterval{Float64,5,<=,<=,15}(20) end @testset "Case №10: NumberOdd constructor" begin @test NumberOdd{Float64}(3.0) == 3.0 @test NumberOdd{Float64}(9) == 9.0 @test_throws ConstraintError{<:NumberOdd} NumberOdd{Float64}(4.0) @test_throws ConstraintError{<:NumberOdd} NumberOdd{Float64}(10) end @testset "Case №11: NumberEven constructor" begin @test NumberEven{Float64}(2.0) == 2.0 @test NumberEven{Float64}(4) == 4.0 @test_throws ConstraintError{<:NumberEven} NumberEven{Float64}(3.0) @test_throws ConstraintError{<:NumberEven} NumberEven{Float64}(5) end @testset "Case №12: Nesting constructor" begin @test NumberOdd{NumberPositive{NumberLess{Float64,10}}}(7) == 7.0 @test_throws ConstraintError{<:NumberLess} NumberOdd{NumberPositive{NumberLess{Float64,10}}}(29) @test_throws ConstraintError{<:NumberPositive} NumberOdd{NumberPositive{NumberLess{Float64,10}}}(-7) @test_throws ConstraintError{<:NumberOdd} NumberOdd{NumberPositive{NumberLess{Float64,10}}}(6) @test NumberEven{NumberInterval{Int64,4,<,<,10}}(8) == 8 @test_throws ConstraintError{<:NumberInterval} NumberEven{NumberInterval{Int64,4,<,<,10}}(4) @test_throws ConstraintError{<:NumberInterval} NumberEven{NumberInterval{Int64,4,<,<,10}}(10.0) @test_throws ConstraintError{<:NumberEven} NumberEven{NumberInterval{Int64,4,<,<,10}}(9) end @testset "Case №13: Custom constructor" begin @test NumberCustomBound{Float64,x -> x % 2 == 0 && x < 10}(6) == 6.0 @test_throws ConstraintError{<:NumberCustomBound} NumberCustomBound{Float64,x -> x % 2 == 0 && x < 10}(5) @test_throws ConstraintError{<:NumberCustomBound} NumberCustomBound{Float64,x -> x % 2 == 0 && x < 10}(15) @test NumberCustomBound{Int64,iseven}(4) == 4 @test_throws ConstraintError{<:NumberCustomBound} NumberCustomBound{Int64,iseven}(3) end @testset "Case №14: Basic methods" begin a = NumberPositive{Float64}(10.0) b = NumberGreater{Float64,0.0}(2.0) @test a + a == 20.0 @test a + 10.0 == 20.0 @test 10.0 + a == 20.0 @test a + b == 12.0 @test a - a == 0.0 @test a - 10.0 == 0.0 @test 10.0 - a == 0.0 @test a - b == 8.0 @test a * a == 100.0 @test a * 10.0 == 100.0 @test 10.0 * a == 100.0 @test a * b == 20.0 @test a / a == 1.0 @test a / 10.0 == 1.0 @test 10.0 / a == 1.0 @test a / b == 5.0 @test a ^ a == 10000000000.0 @test a ^ 10.0 == 10000000000.0 @test 10.0 ^ a == 10000000000.0 @test a ^ b == 100.0 @test a == a @test a == 10.0 @test 10.0 == a @test a != b @test a > b @test a > 2.0 @test 2.0 < a @test b <= a @test div(a, b) == 5.0 @test div(10.0, b) == 5.0 @test div(a, 2.0) == 5.0 @test fld(a, b) == 5.0 @test fld(10.0, b) == 5.0 @test fld(a, 2.0) == 5.0 @test rem(a, b) == 0.0 @test rem(10.0, b) == 0.0 @test rem(a, 2.0) == 0.0 @test mod(a, b) == 0.0 @test mod(10.0, b) == 0.0 @test mod(a, 2.0) == 0.0 @test mod1(a, b) == 2.0 @test mod1(10.0, b) == 2.0 @test mod1(a, 2.0) == 2.0 @test atan(a, b) == atan(10.0, 2.0) @test atan(10.0, b) == atan(10.0, 2.0) @test atan(a, 2.0) == atan(10.0, 2.0) @test atand(a, b) == atand(10.0, 2.0) @test atand(10.0, b) == atand(10.0, 2.0) @test atand(a, 2.0) == atand(10.0, 2.0) @test isinf(a) == false @test isnan(a) == false @test iszero(a) == false @test isreal(a) == true @test isempty(a) == false @test isodd(a) == false @test iseven(a) == true @test ispow2(a) == false @test sqrt(a) == sqrt(10.0) @test abs(a) == abs(10.0) @test abs2(a) == abs2(10.0) @test sign(a) == sign(10.0) @test one(a) == one(10.0) @test zero(a) == zero(10.0) @test log(a) == log(10.0) @test log2(a) == log2(10.0) @test log1p(a) == log1p(10.0) @test log10(a) == log10(10.0) @test exp(a) == exp(10.0) @test exp2(a) == exp2(10.0) @test rad2deg(a) == rad2deg(10.0) @test deg2rad(a) == deg2rad(10.0) end end
BoundTypes
https://github.com/bhftbootcamp/BoundTypes.jl.git
[ "MIT" ]
1.0.3
4313f4d37ec6b34bb53214759f8a0df02458b6e9
code
6477
# test/strings @testset verbose = true "BoundString" begin @testset "Case №1: StringLowerCase constructor" begin @test StringLowerCase{String}("abcdef") == "abcdef" @test StringLowerCase{String}("a.b/c#d_e f") == "a.b/c#d_e f" @test StringLowerCase{String}("a1b2c3d4e5f") == "a1b2c3d4e5f" @test StringLowerCase{String}(Vector{UInt8}("abcdef")) == "abcdef" @test StringLowerCase{String}(Vector{UInt8}("a.b/c#d_e f")) == "a.b/c#d_e f" @test StringLowerCase{String}(Vector{UInt8}("a1b2c3d4e5f")) == "a1b2c3d4e5f" @test_throws ConstraintError{<:StringLowerCase} StringLowerCase{String}("abcdEf") @test_throws ConstraintError{<:StringLowerCase} StringLowerCase{String}("./-_A") @test_throws ConstraintError{<:StringLowerCase} StringLowerCase{String}("123Q456") end @testset "Case №2: StringUpperCase constructor" begin @test StringUpperCase{String}("ABCDEF") == "ABCDEF" @test StringUpperCase{String}("A.B/C#D_E F") == "A.B/C#D_E F" @test StringUpperCase{String}("A1B2C3D4E5F") == "A1B2C3D4E5F" @test StringUpperCase{String}(Vector{UInt8}("ABCDEF")) == "ABCDEF" @test StringUpperCase{String}(Vector{UInt8}("A.B/C#D_E F")) == "A.B/C#D_E F" @test StringUpperCase{String}(Vector{UInt8}("A1B2C3D4E5F")) == "A1B2C3D4E5F" @test_throws ConstraintError{<:StringUpperCase} StringUpperCase{String}("ABCDeF") @test_throws ConstraintError{<:StringUpperCase} StringUpperCase{String}("./-_a") @test_throws ConstraintError{<:StringUpperCase} StringUpperCase{String}("123q456") end @testset "Case №3: StringMinLength constructor" begin @test StringMinLength{String,4}("abcdef") == "abcdef" @test StringMinLength{String,8}("a.b/c#d_e f") == "a.b/c#d_e f" @test StringMinLength{String,11}("a1b2c3d4e5f") == "a1b2c3d4e5f" @test StringMinLength{String,4}(Vector{UInt8}("abcdef")) == "abcdef" @test StringMinLength{String,8}(Vector{UInt8}("a.b/c#d_e f")) == "a.b/c#d_e f" @test StringMinLength{String,11}(Vector{UInt8}("a1b2c3d4e5f")) == "a1b2c3d4e5f" @test_throws ConstraintError{<:StringMinLength} StringMinLength{String,10}("ABCDeF") @test_throws ConstraintError{<:StringMinLength} StringMinLength{String,10}("./-_a") @test_throws ConstraintError{<:StringMinLength} StringMinLength{String,10}("123q456") end @testset "Case №4: StringMaxLength constructor" begin @test StringMaxLength{String,10}("abcdef") == "abcdef" @test StringMaxLength{String,15}("a.b/c#d_e f") == "a.b/c#d_e f" @test StringMaxLength{String,11}("a1b2c3d4e5f") == "a1b2c3d4e5f" @test StringMaxLength{String,10}(Vector{UInt8}("abcdef")) == "abcdef" @test StringMaxLength{String,15}(Vector{UInt8}("a.b/c#d_e f")) == "a.b/c#d_e f" @test StringMaxLength{String,11}(Vector{UInt8}("a1b2c3d4e5f")) == "a1b2c3d4e5f" @test_throws ConstraintError{<:StringMaxLength} StringMaxLength{String,3}("ABCDeF") @test_throws ConstraintError{<:StringMaxLength} StringMaxLength{String,3}("./-_a") @test_throws ConstraintError{<:StringMaxLength} StringMaxLength{String,3}("123q456") end @testset "Case №5: StringFixedLength constructor" begin @test StringFixedLength{String,6}("abcdef") == "abcdef" @test StringFixedLength{String,11}("a.b/c#d_e f") == "a.b/c#d_e f" @test StringFixedLength{String,11}("a1b2c3d4e5f") == "a1b2c3d4e5f" @test StringFixedLength{String,6}(Vector{UInt8}("abcdef")) == "abcdef" @test StringFixedLength{String,11}(Vector{UInt8}("a.b/c#d_e f")) == "a.b/c#d_e f" @test StringFixedLength{String,11}(Vector{UInt8}("a1b2c3d4e5f")) == "a1b2c3d4e5f" @test_throws ConstraintError{<:StringFixedLength} StringFixedLength{String,2}("ABCDeF") @test_throws ConstraintError{<:StringFixedLength} StringFixedLength{String,3}("./-_a") @test_throws ConstraintError{<:StringFixedLength} StringFixedLength{String,20}("123q456") end @testset "Case №6: StringPattern constructor" begin @test StringPattern{String,pattern"^[a-z]+$"}("abcdef") == "abcdef" @test StringPattern{String,pattern"^[A-Z]+$"}("ABCDEF") == "ABCDEF" @test StringPattern{String,pattern"^[a-z\d]+$"}("a1b2c3d4e5f") == "a1b2c3d4e5f" @test StringPattern{String,pattern"^[a-z]+$"}(Vector{UInt8}("abcdef")) == "abcdef" @test StringPattern{String,pattern"^[A-Z]+$"}(Vector{UInt8}("ABCDEF")) == "ABCDEF" @test StringPattern{String,pattern"^[a-z\d]+$"}(Vector{UInt8}("a1b2c3d4e5f")) == "a1b2c3d4e5f" @test_throws ConstraintError{<:StringPattern} StringPattern{String,pattern"^[a-z]+$"}("ab234def") @test_throws ConstraintError{<:StringPattern} StringPattern{String,pattern"^[A-Z]+$"}("A!BC2D_EF") @test_throws ConstraintError{<:StringPattern} StringPattern{String,pattern"^[a-z\d]+$"}("_a1b2c3d4e5f_") end @testset "Case №7: Nesting tests constructor" begin @test StringLowerCase{StringMaxLength{String,5}}("abc") == "abc" @test_throws ConstraintError{<:StringMaxLength} StringLowerCase{StringMaxLength{String,5}}("abcdef") @test_throws ConstraintError{<:StringLowerCase} StringLowerCase{StringMaxLength{String,5}}("aBc") @test StringUpperCase{StringMinLength{String,5}}("ABCDEF") == "ABCDEF" @test_throws ConstraintError{<:StringMinLength} StringUpperCase{StringMinLength{String,5}}("ABC") @test_throws ConstraintError{<:StringUpperCase} StringUpperCase{StringMinLength{String,5}}("AbC") @test StringFixedLength{StringPattern{String,pattern"^[a-z]+$"},5}("abcde") == "abcde" @test_throws ConstraintError{<:StringPattern} StringFixedLength{StringPattern{String,pattern"^[a-z]+$"},5}("ab1de") @test_throws ConstraintError{<:StringFixedLength} StringFixedLength{StringPattern{String,pattern"^[a-z]+$"},5}("abcdef") end @testset "Case №8: Custom constructor" begin @test StringCustomBound{String,x -> x <= "bbb" && length(x) < 5}("aaa") == "aaa" @test_throws ConstraintError{<:StringCustomBound} StringCustomBound{String,x -> x <= "bbb" && length(x) < 5}("ccc") @test_throws ConstraintError{<:StringCustomBound} StringCustomBound{String,x -> x <= "bbb" && length(x) < 5}("aaaaaa") end end
BoundTypes
https://github.com/bhftbootcamp/BoundTypes.jl.git
[ "MIT" ]
1.0.3
4313f4d37ec6b34bb53214759f8a0df02458b6e9
code
10140
# test/dates using Test using Dates using BoundTypes @testset verbose = true "BoundTime" begin @testset "Case №1: TimeAfterNow constructor" begin current_time = now() @test TimeAfterNow{Time}(current_time + Minute(1)) == Time(current_time + Minute(1)) @test TimeAfterNow{Date}(current_time + Day(1)) == Date(current_time + Day(1)) @test TimeAfterNow{DateTime}(current_time + Day(1)) == DateTime(current_time + Day(1)) @test_throws ConstraintError TimeAfterNow{Time}(current_time - Minute(1)) @test_throws ConstraintError TimeAfterNow{Date}(current_time - Day(1)) @test_throws ConstraintError TimeAfterNow{DateTime}(current_time - Day(1)) end @testset "Case №2: TimeAfter constructor" begin @test TimeAfter{Time,Time(12)}(Time(13)) == Time(13) @test TimeAfter{Date,Date(2024)}(Date(2025)) == Date(Date(2025)) @test TimeAfter{DateTime,DateTime(2024)}(DateTime(2025)) == DateTime(DateTime(2025)) @test_throws ConstraintError TimeAfter{Time,Time(12)}(Time(11)) @test_throws ConstraintError TimeAfter{Date,Date(2024)}(Date(2023)) @test_throws ConstraintError TimeAfter{DateTime,DateTime(2024)}(DateTime(2023)) @test_throws ConstraintError TimeAfter{Time,Time(12)}(Time(12)) @test_throws ConstraintError TimeAfter{Date,Date(2024)}(Date(2024)) @test_throws ConstraintError TimeAfter{DateTime,DateTime(2024)}(DateTime(2024)) end @testset "Case №3: TimeAfterOrEqual constructor" begin @test TimeAfterOrEqual{Time,Time(12)}(Time(13)) == Time(13) @test TimeAfterOrEqual{Date,Date(2024)}(Date(2025)) == Date(Date(2025)) @test TimeAfterOrEqual{DateTime,DateTime(2024)}(DateTime(2025)) == DateTime(DateTime(2025)) @test TimeAfterOrEqual{Time,Time(12)}(Time(12)) == Time(12) @test TimeAfterOrEqual{Date,Date(2024)}(Date(2024)) == Date(Date(2024)) @test TimeAfterOrEqual{DateTime,DateTime(2024)}(DateTime(2024)) == DateTime(DateTime(2024)) @test_throws ConstraintError TimeAfterOrEqual{Time,Time(12)}(Time(11)) @test_throws ConstraintError TimeAfterOrEqual{Date,Date(2024)}(Date(2023)) @test_throws ConstraintError TimeAfterOrEqual{DateTime,DateTime(2024)}(DateTime(2023)) end @testset "Case №4: TimePeriodAfterNow constructor" begin current_time = now() @test TimePeriodAfterNow{Time,Hour(1)}(current_time + Minute(1)) == Time(current_time + Minute(1)) @test TimePeriodAfterNow{Date,Week(1)}(current_time + Day(1)) == Date(current_time + Day(1)) @test TimePeriodAfterNow{DateTime,Month(1)}(current_time + Week(1)) == DateTime(current_time + Week(1)) @test_throws ConstraintError TimePeriodAfterNow{Time,Hour(1)}(current_time - Hour(2)) @test_throws ConstraintError TimePeriodAfterNow{Date,Week(1)}(current_time - Month(1)) @test_throws ConstraintError TimePeriodAfterNow{DateTime,Month(1)}(current_time - Year(1)) end @testset "Case №5: TimeBeforeNow constructor" begin current_time = now() @test TimeBeforeNow{Time}(current_time - Minute(1)) == Time(current_time - Minute(1)) @test TimeBeforeNow{Date}(current_time - Day(1)) == Date(current_time - Day(1)) @test TimeBeforeNow{DateTime}(current_time - Day(1)) == DateTime(current_time - Day(1)) @test_throws ConstraintError TimeBeforeNow{Time}(current_time + Minute(1)) @test_throws ConstraintError TimeBeforeNow{Date}(current_time + Day(1)) @test_throws ConstraintError TimeBeforeNow{DateTime}(current_time + Day(1)) end @testset "Case №6: TimeBefore constructor" begin @test TimeBefore{Time,Time(12)}(Time(11)) == Time(11) @test TimeBefore{Date,Date(2024)}(Date(2023)) == Date(Date(2023)) @test TimeBefore{DateTime,DateTime(2024)}(DateTime(2023)) == DateTime(DateTime(2023)) @test_throws ConstraintError TimeBefore{Time,Time(12)}(Time(13)) @test_throws ConstraintError TimeBefore{Date,Date(2024)}(Date(2025)) @test_throws ConstraintError TimeBefore{DateTime,DateTime(2024)}(DateTime(2025)) @test_throws ConstraintError TimeBefore{Time,Time(12)}(Time(12)) @test_throws ConstraintError TimeBefore{Date,Date(2024)}(Date(2024)) @test_throws ConstraintError TimeBefore{DateTime,DateTime(2024)}(DateTime(2024)) end @testset "Case №7: TimeBeforeOrEqual constructor" begin @test TimeBeforeOrEqual{Time,Time(12)}(Time(11)) == Time(11) @test TimeBeforeOrEqual{Date,Date(2024)}(Date(2023)) == Date(Date(2023)) @test TimeBeforeOrEqual{DateTime,DateTime(2024)}(DateTime(2023)) == DateTime(DateTime(2023)) @test TimeBeforeOrEqual{Time,Time(12)}(Time(12)) == Time(12) @test TimeBeforeOrEqual{Date,Date(2024)}(Date(2024)) == Date(Date(2024)) @test TimeBeforeOrEqual{DateTime,DateTime(2024)}(DateTime(2024)) == DateTime(DateTime(2024)) @test_throws ConstraintError TimeBeforeOrEqual{Time,Time(12)}(Time(13)) @test_throws ConstraintError TimeBeforeOrEqual{Date,Date(2024)}(Date(2025)) @test_throws ConstraintError TimeBeforeOrEqual{DateTime,DateTime(2024)}(DateTime(2025)) end @testset "Case №8: TimePeriodBeforeNow constructor" begin current_time = now() @test TimePeriodBeforeNow{Time,Hour(1)}(current_time - Minute(1)) == Time(current_time - Minute(1)) @test TimePeriodBeforeNow{Date,Week(1)}(current_time - Day(1)) == Date(current_time - Day(1)) @test TimePeriodBeforeNow{DateTime,Month(1)}(current_time - Week(1)) == DateTime(current_time - Week(1)) @test_throws ConstraintError TimePeriodBeforeNow{Time,Hour(1)}(current_time + Hour(2)) @test_throws ConstraintError TimePeriodBeforeNow{Date,Week(1)}(current_time + Month(1)) @test_throws ConstraintError TimePeriodBeforeNow{DateTime,Month(1)}(current_time + Year(1)) end @testset "Case №9: TimeInterval constructor" begin @test TimeInterval{Time,Time(5),<=,<,Time(15)}(Time(10)) == Time(10) @test TimeInterval{Time,Time(5),<=,<,Time(15)}(Time(5)) == Time(5) @test TimeInterval{Date,Date(2023),<=,<,Date(2025)}(Date(2024)) == Date(2024) @test TimeInterval{Date,Date(2023),<=,<,Date(2025)}(Date(2023)) == Date(2023) @test TimeInterval{DateTime,DateTime(2023),<=,<,DateTime(2025)}(DateTime(2024)) == DateTime(2024) @test TimeInterval{DateTime,DateTime(2023),<=,<,DateTime(2025)}(DateTime(2023)) == DateTime(2023) @test_throws ConstraintError TimeInterval{Time,Time(5),<=,<,Time(15)}(Time(15)) @test_throws ConstraintError TimeInterval{Time,Time(5),<=,<,Time(15)}(Time(1)) @test_throws ConstraintError TimeInterval{Time,Time(5),<=,<,Time(15)}(Time(20)) @test_throws ConstraintError TimeInterval{Date,Date(2023),<=,<,Date(2025)}(Date(2025)) @test_throws ConstraintError TimeInterval{Date,Date(2023),<=,<,Date(2025)}(Date(2020)) @test_throws ConstraintError TimeInterval{Date,Date(2023),<=,<,Date(2025)}(Date(2030)) @test_throws ConstraintError TimeInterval{DateTime,DateTime(2023),<=,<,DateTime(2025)}(DateTime(2025)) @test_throws ConstraintError TimeInterval{DateTime,DateTime(2023),<=,<,DateTime(2025)}(DateTime(2020)) @test_throws ConstraintError TimeInterval{DateTime,DateTime(2023),<=,<,DateTime(2025)}(DateTime(2030)) end @testset "Case №10: Nested constructor" begin @test TimeAfter{TimeBeforeOrEqual{Time,Time(4)},Time(2)}(Time(3)) == Time(3) @test TimeAfter{TimeBeforeOrEqual{Time,Time(4)},Time(2)}(Time(4)) == Time(4) @test_throws ConstraintError TimeAfter{TimeBeforeOrEqual{Time,Time(4)},Time(2)}(Time(1)) @test_throws ConstraintError TimeAfter{TimeBeforeOrEqual{Time,Time(4)},Time(2)}(Time(2)) @test_throws ConstraintError TimeAfter{TimeBeforeOrEqual{Time,Time(4)},Time(2)}(Time(5)) @test TimeAfterOrEqual{TimeBefore{Time,Time(4)},Time(2)}(Time(3)) == Time(3) @test TimeAfterOrEqual{TimeBefore{Time,Time(4)},Time(2)}(Time(2)) == Time(2) @test_throws ConstraintError TimeAfterOrEqual{TimeBefore{Time,Time(4)},Time(2)}(Time(1)) @test_throws ConstraintError TimeAfterOrEqual{TimeBefore{Time,Time(4)},Time(2)}(Time(4)) @test_throws ConstraintError TimeAfterOrEqual{TimeBefore{Time,Time(4)},Time(2)}(Time(5)) end @testset "Case №11: Custom constructor" begin @test TimeCustomBound{Time, x -> x > Time(2) && x <= Time(4)}(Time(3)) == Time(3) @test TimeCustomBound{Time, x -> x > Time(2) && x <= Time(4)}(Time(4)) == Time(4) @test_throws ConstraintError TimeCustomBound{Time, x -> x > Time(2) && x <= Time(4)}(Time(1)) @test_throws ConstraintError TimeCustomBound{Time, x -> x > Time(2) && x <= Time(4)}(Time(2)) @test_throws ConstraintError TimeCustomBound{Time, x -> x > Time(2) && x <= Time(4)}(Time(5)) end @testset "Case №12: Basic methods" begin a = TimeAfter{DateTime,DateTime(2024)}(DateTime(2025)) b = TimeBefore{DateTime,DateTime(2025)}(DateTime(2024)) c = TimeBefore{DateTime,DateTime(2025)}(DateTime(1, 2, 3, 4, 5, 6, 7)) @test a == a @test a == DateTime(2025) @test a != b @test a > b @test b <= a @test a + Year(1) == DateTime(2026) @test a - Year(1) == b @test year(c) == 1 @test month(c) == 2 @test day(c) == 3 @test hour(c) == 4 @test minute(c) == 5 @test second(c) == 6 @test millisecond(c) == 7 @test Year(c) == Year(1) @test Month(c) == Month(2) @test Day(c) == Day(3) @test Hour(c) == Hour(4) @test Minute(c) == Minute(5) @test Second(c) == Second(6) @test Millisecond(c) == Millisecond(7) end end
BoundTypes
https://github.com/bhftbootcamp/BoundTypes.jl.git
[ "MIT" ]
1.0.3
4313f4d37ec6b34bb53214759f8a0df02458b6e9
code
158
using Test using Dates using Serde using BoundTypes include("bound_number.jl") include("bound_string.jl") include("bound_time.jl") include("serde_usage.jl")
BoundTypes
https://github.com/bhftbootcamp/BoundTypes.jl.git
[ "MIT" ]
1.0.3
4313f4d37ec6b34bb53214759f8a0df02458b6e9
code
13054
# test/extensions @testset verbose = true "Serde extension" begin struct UserProfile username::StringPattern{String,pattern"^[a-zA-Z0-9_]+$"} password::StringFixedLength{String,12} email::StringPattern{String,pattern"^\S+@\S+\.\S+$"} age::NumberPositive{Int64} bio::String height_in_cm::NumberInterval{Float64,50,<,<,250} weight_in_kg::NumberNonNegative{Float64} account_creation_date::TimeBeforeNow{DateTime} subscription_end_date::TimeAfter{DateTime,DateTime(2024,1,1)} is_email_verified::Bool end function Serde.deser(::Type{<:UserProfile}, ::Type{<:TimeType}, x::String) return DateTime(x) end correct_user_info = """ { "username": "user123_", "password": "Abc123!@#Def", "email": "user123@example.com", "age": 25, "bio": "Just a simple bio.", "height_in_cm": 175.5, "weight_in_kg": 70.0, "account_creation_date": "2023-01-15T14:22:00", "subscription_end_date": "2030-01-15T00:00:00", "is_email_verified": true } """ @testset "Case №1: Deserialization" begin @test UserProfile( "user123_", "Abc123!@#Def", "user123@example.com", 25, "Just a simple bio.", 175.5, 70.0, DateTime("2023-01-15T14:22:00"), DateTime("2030-01-15T00:00:00"), true, ) == deser_json(UserProfile, correct_user_info) null_bio = """ { "username": "user123_", "password": "Abc123!@#Def", "email": "user123@example.com", "age": 25, "bio": null, "height_in_cm": 175.5, "weight_in_kg": 70.0, "account_creation_date": "2023-01-15T14:22:00", "subscription_end_date": "2030-01-15T00:00:00", "is_email_verified": true } """ @test_throws Serde.ParamError deser_json(UserProfile, null_bio) incorrect_username = """ { "username": "user@@@", "password": "Abc123!@#Def", "email": "user123@example.com", "age": 25, "bio": "A bio with special characters in the username.", "height_in_cm": 175, "weight_in_kg": 70, "account_creation_date": "2023-01-15T14:22:00", "subscription_end_date": "2024-01-15T00:00:00", "is_email_verified": true } """ @test_throws ConstraintError{<:StringPattern} deser_json(UserProfile, incorrect_username) incorrect_password = """ { "username": "user123_", "password": "Short1!", "email": "user123@example.com", "age": 25, "bio": "Password is too short.", "height_in_cm": 175, "weight_in_kg": 70, "account_creation_date": "2023-01-15T14:22:00", "subscription_end_date": "2024-01-15T00:00:00", "is_email_verified": true } """ @test_throws ConstraintError{<:StringFixedLength} deser_json(UserProfile, incorrect_password) incorrect_age = """ { "username": "user123_", "password": "Abc123!@#Def", "email": "user123@example.com", "age": -5, "bio": "Age cannot be negative.", "height_in_cm": 175, "weight_in_kg": 70, "account_creation_date": "2023-01-15T14:22:00", "subscription_end_date": "2024-01-15T00:00:00", "is_email_verified": true } """ @test_throws ConstraintError{NumberPositive} deser_json(UserProfile, incorrect_age) incorrect_height = """ { "username": "user123_", "password": "Abc123!@#Def", "email": "user123@example.com", "age": 25, "bio": "Height is too tall.", "height_in_cm": 300, "weight_in_kg": 70, "account_creation_date": "2023-01-15T14:22:00", "subscription_end_date": "2024-01-15T00:00:00", "is_email_verified": true } """ @test_throws ConstraintError{NumberInterval} deser_json(UserProfile, incorrect_height) incorrect_sub_date = """ { "username": "user123_", "password": "Abc123!@#Def", "email": "user123@example.com", "age": 25, "bio": "Subscription end date is in the past.", "height_in_cm": 175, "weight_in_kg": 70, "account_creation_date": "2023-01-15T14:22:00", "subscription_end_date": "2023-01-01T00:00:00", "is_email_verified": true } """ @test_throws ConstraintError{TimeAfter} deser_json(UserProfile, incorrect_sub_date) end @testset "Case №2: Serialization" begin user = deser_json(UserProfile, correct_user_info) @test to_json(user) == """ {\ "username":"user123_",\ "password":"Abc123!@#Def",\ "email":"user123@example.com",\ "age":25,\ "bio":"Just a simple bio.",\ "height_in_cm":175.5,\ "weight_in_kg":70.0,\ "account_creation_date":"2023-01-15T14:22:00",\ "subscription_end_date":"2030-01-15T00:00:00",\ "is_email_verified":true\ }\ """ @test to_csv([user]) == """ username,password,email,age,bio,height_in_cm,weight_in_kg,account_creation_date,subscription_end_date,is_email_verified user123_,Abc123!@#Def,user123@example.com,25,Just a simple bio.,175.5,70.0,2023-01-15T14:22:00,2030-01-15T00:00:00,true """ @test to_query(user) == """ username=user123_&\ password=Abc123%21%40%23Def&\ email=user123%40example.com&\ age=25&\ bio=Just%20a%20simple%20bio.&\ height_in_cm=175.5&\ weight_in_kg=70.0&\ account_creation_date=2023-01-15T14%3A22%3A00&\ subscription_end_date=2030-01-15T00%3A00%3A00&\ is_email_verified=true\ """ @test to_toml(user) == """ username = \"user123_\" password = \"Abc123!@#Def\" email = \"user123@example.com\" age = 25 bio = \"Just a simple bio.\" height_in_cm = 175.5 weight_in_kg = 70.0 account_creation_date = \"2023-01-15T14:22:00\" subscription_end_date = \"2030-01-15T00:00:00\" is_email_verified = true """ @test to_xml(user) == """ <xml username=\"user123_\" \ password=\"Abc123!@#Def\" \ email=\"user123@example.com\" \ age=\"25\" \ bio=\"Just a simple bio.\" \ height_in_cm=\"175.5\" \ weight_in_kg=\"70.0\" \ account_creation_date=\"2023-01-15T14:22:00\" \ subscription_end_date=\"2030-01-15T00:00:00\" \ is_email_verified=\"true\"/> """ end @testset "Case №3: Nested boundbypes deserialization" begin struct StringAndFloat a::StringMaxLength{StringMinLength{StringLowerCase{String},10},20} b::Float64 end obj = StringAndFloat("1234567890a", 1) json = "{\"a\":\"1234567890a\",\"b\":1.0}" toml = "a = \"1234567890a\"\nb = 1.0\n" csv = "a,b\n1234567890a,1.0\n" query = "a=1234567890a&b=1.0" xml = "<xml a=\"1234567890a\" b=\"1.0\"/>\n" yaml = "a: \"1234567890a\"\nb: 1.0\n" @test to_json(obj) == json @test to_toml(obj) == toml @test to_csv([obj]) == csv @test to_query(obj) == query @test to_xml(obj) == xml @test to_yaml(obj) == yaml @test Serde.deser_json(StringAndFloat, json) == obj @test Serde.deser_toml(StringAndFloat, toml) == obj @test Serde.deser_csv(StringAndFloat, csv)[1] == obj @test Serde.deser_query(StringAndFloat, query) == obj @test Serde.deser_xml(StringAndFloat, xml) == obj @test Serde.deser_yaml(StringAndFloat, yaml) == obj struct StringAndNumber a::StringMaxLength{StringMinLength{StringLowerCase{String},10},20} b::NumberPositive{Float64} end obj = StringAndNumber("1234567890a", 1) json = "{\"a\":\"1234567890a\",\"b\":1.0}" toml = "a = \"1234567890a\"\nb = 1.0\n" csv = "a,b\n1234567890a,1.0\n" query = "a=1234567890a&b=1.0" xml = "<xml a=\"1234567890a\" b=\"1.0\"/>\n" yaml = "a: \"1234567890a\"\nb: 1.0\n" @test to_json(obj) == json @test to_toml(obj) == toml @test to_csv([obj]) == csv @test to_query(obj) == query @test to_xml(obj) == xml @test to_yaml(obj) == yaml @test Serde.deser_json(StringAndNumber, json) == obj @test Serde.deser_toml(StringAndNumber, toml) == obj @test Serde.deser_csv(StringAndNumber, csv)[1] == obj @test Serde.deser_query(StringAndNumber, query) == obj @test Serde.deser_xml(StringAndNumber, xml) == obj @test Serde.deser_yaml(StringAndNumber, yaml) == obj struct StringsAndNumber a::StringMaxLength{StringMinLength{StringLowerCase{String},10},20} b::StringMinLength{String,5} c::NumberPositive{Float64} end obj = StringsAndNumber("1234567890a", "asdfdasf", 1.0) json = "{\"a\":\"1234567890a\",\"b\":\"asdfdasf\",\"c\":1.0}" toml = "a = \"1234567890a\"\nb = \"asdfdasf\"\nc = 1.0\n" csv = "a,b,c\n1234567890a,asdfdasf,1.0\n" query = "a=1234567890a&b=asdfdasf&c=1.0" xml = "<xml a=\"1234567890a\" b=\"asdfdasf\" c=\"1.0\"/>\n" yaml = "a: \"1234567890a\"\nb: \"asdfdasf\"\nc: 1.0\n" @test to_json(obj) == json @test to_toml(obj) == toml @test to_csv([obj]) == csv @test to_query(obj) == query @test to_xml(obj) == xml @test to_yaml(obj) == yaml @test Serde.deser_json(StringsAndNumber, json) == obj @test Serde.deser_toml(StringsAndNumber, toml) == obj @test Serde.deser_csv(StringsAndNumber, csv)[1] == obj @test Serde.deser_query(StringsAndNumber, query) == obj @test Serde.deser_xml(StringsAndNumber, xml) == obj @test Serde.deser_yaml(StringsAndNumber, yaml) == obj struct TwoStrings a::StringMaxLength{StringMinLength{StringLowerCase{String},10},20} b::StringMinLength{String,5} end obj = TwoStrings("1234567890a", "asdfdasf") json = "{\"a\":\"1234567890a\",\"b\":\"asdfdasf\"}" toml = "a = \"1234567890a\"\nb = \"asdfdasf\"\n" csv = "a,b\n1234567890a,asdfdasf\n" query = "a=1234567890a&b=asdfdasf" xml = "<xml a=\"1234567890a\" b=\"asdfdasf\"/>\n" yaml = "a: \"1234567890a\"\nb: \"asdfdasf\"\n" @test to_json(obj) == json @test to_toml(obj) == toml @test to_csv([obj]) == csv @test to_query(obj) == query @test to_xml(obj) == xml @test to_yaml(obj) == yaml @test Serde.deser_json(TwoStrings, json) == obj @test Serde.deser_toml(TwoStrings, toml) == obj @test Serde.deser_csv(TwoStrings, csv)[1] == obj @test Serde.deser_query(TwoStrings, query) == obj @test Serde.deser_xml(TwoStrings, xml) == obj @test Serde.deser_yaml(TwoStrings, yaml) == obj struct BasicTimeTypes a::TimeAfter{Time,Time(10)} b::TimeBefore{TimeAfter{Date,Date(2020)},Date(2025)} c::TimeInterval{DateTime,DateTime(2020),<,<,DateTime(2025)} end Serde.deser(::Type{BasicTimeTypes}, ::Type{Time}, x::String) = Time(x) Serde.deser(::Type{BasicTimeTypes}, ::Type{Date}, x::String) = Date(x) Serde.deser(::Type{BasicTimeTypes}, ::Type{DateTime}, x::String) = DateTime(x) function Serde.deser(::Type{BasicTimeTypes}, ::Type{T}, x::String) where {T<:BoundTime} return T(Serde.deser(BasicTimeTypes, bound_type(T), x)) end obj = BasicTimeTypes(Time(15), Date(2023), DateTime(2024)) json = "{\"a\":\"15:00:00\",\"b\":\"2023-01-01\",\"c\":\"2024-01-01T00:00:00\"}" toml = "a = \"15:00:00\"\nb = \"2023-01-01\"\nc = \"2024-01-01T00:00:00\"\n" csv = "a,b,c\n15:00:00,2023-01-01,2024-01-01T00:00:00\n" query = "a=15%3A00%3A00&b=2023-01-01&c=2024-01-01T00%3A00%3A00" xml = "<xml a=\"15:00:00\" b=\"2023-01-01\" c=\"2024-01-01T00:00:00\"/>\n" yaml = "a: \"15:00:00\"\nb: \"2023-01-01\"\nc: \"2024-01-01T00:00:00\"\n" @test to_json(obj) == json @test to_toml(obj) == toml @test to_csv([obj]) == csv @test to_query(obj) == query @test to_xml(obj) == xml @test to_yaml(obj) == yaml @test Serde.deser_json(BasicTimeTypes, json) == obj @test Serde.deser_toml(BasicTimeTypes, toml) == obj @test Serde.deser_csv(BasicTimeTypes, csv)[1] == obj @test Serde.deser_query(BasicTimeTypes, query) == obj @test Serde.deser_xml(BasicTimeTypes, xml) == obj @test Serde.deser_yaml(BasicTimeTypes, yaml) == obj end end
BoundTypes
https://github.com/bhftbootcamp/BoundTypes.jl.git
[ "MIT" ]
1.0.3
4313f4d37ec6b34bb53214759f8a0df02458b6e9
docs
175
# BoundTypes.jl Changelog The latest version of this file can be found at the master branch of the [BoundTypes.jl repository](https://github.com/bhftbootcamp/BoundTypes.jl).
BoundTypes
https://github.com/bhftbootcamp/BoundTypes.jl.git
[ "MIT" ]
1.0.3
4313f4d37ec6b34bb53214759f8a0df02458b6e9
docs
2703
![animation](docs/src/assets/animation.gif) # BoundTypes.jl [![Stable](https://img.shields.io/badge/docs-stable-blue.svg)](https://bhftbootcamp.github.io/BoundTypes.jl/stable/) [![Dev](https://img.shields.io/badge/docs-dev-blue.svg)](https://bhftbootcamp.github.io/BoundTypes.jl/dev/) [![Build Status](https://github.com/bhftbootcamp/BoundTypes.jl/actions/workflows/CI.yml/badge.svg?branch=master)](https://github.com/bhftbootcamp/BoundTypes.jl/actions/workflows/CI.yml?query=branch%3Amaster) [![Coverage](https://codecov.io/gh/bhftbootcamp/BoundTypes.jl/branch/master/graph/badge.svg)](https://codecov.io/gh/bhftbootcamp/BoundTypes.jl) [![Registry](https://img.shields.io/badge/registry-General-4063d8)](https://github.com/JuliaRegistries/General) The BoundTypes library helps you to seamlessly design and set rules for data types in your code, making it safer and more reliable. ## Installation To install BoundTypes, simply use the Julia package manager: ```julia ] add BoundTypes ``` ## Usage Demonstrate value validation during object construction: ```julia using BoundTypes struct CoinInfo asset::StringPattern{String,pattern"^([A-Z]+)$"} network::StringMinLength{String,3} address::StringFixedLength{StringPattern{String,pattern"^0x([abcdef0-9]+)$"},40} deposit_fee::NumberNonNegative{Float64} withdrawal_fee::NumberPositive{Float64} end julia> CoinInfo("ETH", "Ethereum", "0xc0ffee254729296a45a3885639ac7e10f9d549", 0.0, 0.01) CoinInfo("ETH", "Ethereum", "0xc0ffee254729296a45a3885639ac7e10f9d549", 0.0, 0.01) julia> CoinInfo("eth!", "EM", "0xc0FFE12A2", -1.0, 0.0) Wrong value: "eth!" must match to regex pattern ^([A-Z]+)$. ``` Using BoundTypes for serialization and deserialization with [Serde.jl](https://github.com/bhftbootcamp/Serde.jl): ```julia using Serde using BoundTypes struct User name::StringMinLength{String,5} pass::StringMaxLength{StringMinLength{StringPattern{String,pattern"^[\w@]+$"},10},20} end julia> Serde.deser_json(User, """ {"name": "Julia", "pass": "MyBestP@ssw0rdEv3r"} """) User("Julia", "MyBestP@ssw0rdEv3r") julia> Serde.deser_json(User, """ {"name": "Julia", "pass": "2ShrtP@ss"} """) Wrong value: length of the "2ShrtP@ss" must be at least 10 characters (9). julia> Serde.deser_json(User, """ {"name": "Julia", "pass": "Bad/Password#"} """) Wrong value: "Bad/Password#" must match to regex pattern ^[\w@]+$. julia> Serde.to_json(User("Julia", "MyBestP@ssw0rdEv3r")) "{\"name\":\"Julia\",\"pass\":\"MyBestP@ssw0rdEv3r\"}" ``` ## Contributing Contributions to BoundTypes are welcome! If you encounter a bug, have a feature request, or would like to contribute code, please open an issue or a pull request on GitHub.
BoundTypes
https://github.com/bhftbootcamp/BoundTypes.jl.git
[ "MIT" ]
1.0.3
4313f4d37ec6b34bb53214759f8a0df02458b6e9
docs
179
### Pull request checklist - [ ] Did you bump the project version? - [ ] Did you add a description to the Pull Request? - [ ] Did you add new tests? - [ ] Did you add reviewers?
BoundTypes
https://github.com/bhftbootcamp/BoundTypes.jl.git
[ "MIT" ]
1.0.3
4313f4d37ec6b34bb53214759f8a0df02458b6e9
docs
712
--- name: 'Bug report' about: Create a report to help us improve title: '' labels: bug assignees: '' --- Describe the bug --- > A clear and concise description of what the bug is. To Reproduce --- > Add a Minimal, Complete, and Verifiable example (for more details, see e.g. https://stackoverflow.com/help/mcve) > > If the code is too long, feel free to put it in a public gist and link it in the issue: https://gist.github.com ```julia # Past your code here. ``` Expected behavior --- > A clear and concise description of what you expected to happen. Additional context --- > Add any other context about the problem here.\ > Please include the output of\ > `julia> versioninfo()`\ > and\ > `pkg> st`
BoundTypes
https://github.com/bhftbootcamp/BoundTypes.jl.git
[ "MIT" ]
1.0.3
4313f4d37ec6b34bb53214759f8a0df02458b6e9
docs
618
--- name: Feature request about: Suggest an idea for this project title: '' labels: 'feature' assignees: '' --- Is your feature request related to a problem? Please describe. --- > A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] Describe the solution you'd like --- > A clear and concise description of what you want to happen. Describe alternatives you've considered --- > A clear and concise description of any alternative solutions or features you've considered. Additional context --- > Add any other context or screenshots about the feature request here.
BoundTypes
https://github.com/bhftbootcamp/BoundTypes.jl.git
[ "MIT" ]
1.0.3
4313f4d37ec6b34bb53214759f8a0df02458b6e9
docs
1813
![animation](assets/animation.gif) # BoundTypes.jl The BoundTypes library helps you to seamlessly design and set rules for data types in your code, making it safer and more reliable. ## Installation To install BoundTypes, simply use the Julia package manager: ```julia ] add BoundTypes ``` ## Usage Demonstrate value validation during object construction: ```julia using BoundTypes struct CoinInfo asset::StringPattern{String,pattern"^([A-Z]+)$"} network::StringMinLength{String,3} address::StringFixedLength{StringPattern{String,pattern"^0x([abcdef0-9]+)$"},40} deposit_fee::NumberNonNegative{Float64} withdrawal_fee::NumberPositive{Float64} end julia> CoinInfo("ETH", "Ethereum", "0xc0ffee254729296a45a3885639ac7e10f9d549", 0.0, 0.01) CoinInfo("ETH", "Ethereum", "0xc0ffee254729296a45a3885639ac7e10f9d549", 0.0, 0.01) julia> CoinInfo("eth!", "EM", "0xc0FFE12A2", -1.0, 0.0) Wrong value: "eth!" must match to regex pattern ^([A-Z]+)$. ``` Using BoundTypes for serialization and deserialization with [Serde.jl](https://github.com/bhftbootcamp/Serde.jl): ```julia using Serde using BoundTypes struct User name::StringMinLength{String,5} pass::StringMaxLength{StringMinLength{StringPattern{String,pattern"^[\w@]+$"},10},20} end julia> Serde.deser_json(User, """ {"name": "Julia", "pass": "MyBestP@ssw0rdEv3r"} """) User("Julia", "MyBestP@ssw0rdEv3r") julia> Serde.deser_json(User, """ {"name": "Julia", "pass": "2ShrtP@ss"} """) Wrong value: length of the "2ShrtP@ss" must be at least 10 characters (9). julia> Serde.deser_json(User, """ {"name": "Julia", "pass": "Bad/Password#"} """) Wrong value: "Bad/Password#" must match to regex pattern ^[\w@]+$. julia> Serde.to_json(User("Julia", "MyBestP@ssw0rdEv3r")) "{\"name\":\"Julia\",\"pass\":\"MyBestP@ssw0rdEv3r\"}" ```
BoundTypes
https://github.com/bhftbootcamp/BoundTypes.jl.git
[ "MIT" ]
1.0.3
4313f4d37ec6b34bb53214759f8a0df02458b6e9
docs
624
# BoundNumber ```@docs BoundNumber ``` ## NumberCustomBound ```@docs NumberCustomBound ``` ## NumberPositive ```@docs NumberPositive ``` ## NumberNegative ```@docs NumberNegative ``` ## NumberNonPositive ```@docs NumberNonPositive ``` ## NumberNonNegative ```@docs NumberNonNegative ``` ## NumberGreater ```@docs NumberGreater ``` ## NumberGreaterOrEqual ```@docs NumberGreaterOrEqual ``` ## NumberLess ```@docs NumberLess ``` ## NumberLessOrEqual ```@docs NumberLessOrEqual ``` ## NumberOdd ```@docs NumberOdd ``` ## NumberEven ```@docs NumberEven ``` ## NumberInterval ```@docs NumberInterval ```
BoundTypes
https://github.com/bhftbootcamp/BoundTypes.jl.git
[ "MIT" ]
1.0.3
4313f4d37ec6b34bb53214759f8a0df02458b6e9
docs
407
# BoundString ```@docs BoundString ``` ## StringCustomBound ```@docs StringCustomBound ``` ## StringLowerCase ```@docs StringLowerCase ``` ## StringUpperCase ```@docs StringUpperCase ``` ## StringMinLength ```@docs StringMinLength ``` ## StringMaxLength ```@docs StringMaxLength ``` ## StringFixedLength ```@docs StringFixedLength ``` ## StringPattern ```@docs StringPattern @pattern_str ```
BoundTypes
https://github.com/bhftbootcamp/BoundTypes.jl.git
[ "MIT" ]
1.0.3
4313f4d37ec6b34bb53214759f8a0df02458b6e9
docs
517
# BoundTime ```@docs BoundTime ``` ## TimeCustomBound ```@docs TimeCustomBound ``` ## TimeAfter ```@docs TimeAfter ``` ## TimeAfterNow ```@docs TimeAfterNow ``` ## TimeAfterOrEqual ```@docs TimeAfterOrEqual ``` ## TimePeriodAfterNow ```@docs TimePeriodAfterNow ``` ## TimeBefore ```@docs TimeBefore ``` ## TimeBeforeNow ```@docs TimeBeforeNow ``` ## TimeBeforeOrEqual ```@docs TimeBeforeOrEqual ``` ## TimePeriodBeforeNow ```@docs TimePeriodBeforeNow ``` ## TimeInterval ```@docs TimeInterval ```
BoundTypes
https://github.com/bhftbootcamp/BoundTypes.jl.git
[ "MIT" ]
1.0.3
4313f4d37ec6b34bb53214759f8a0df02458b6e9
docs
2176
# For Developers ## Define custom bound type A user can define his own boundary types: ```julia struct SomeBound{T<:ElType} <: SomeExistingBoundType{T} value::T function SomeBound{T}(x::AbstractString) where {T<:AbstractString} !condition_1(x) && throw(ConstraintError{SomeBound}("Error message 1")) !condition_2(x) && throw(ConstraintError{SomeBound}("Error message 2")) # other conditions ... return new{T}(x) end end ``` Here are some guidelines for defining your own bound types: - Names of new boundary types should characterize them (for example `NumberPositive`, `StringUpperCase` or `TimeInterval`). - The element type and supertype must correspond to the same data class: - `ELTYPE` must be a `Number`, `AbstractString` or `TimeType`. - Respectively `BOUNDTYPE` might be a [`BoundNumber`](@ref), [`BoundString`](@ref) or [`BoundTime`](@ref). - Next, inside the constructor you need to perform a bounds check: - Formulate simple and easy to understand checks, i.e. if you want to allow numbers that are greater than 0, then you would have an expression like this `x <= 0 && throw(...)`. - If any of the conditions are violated then error [`ConstraintError`](@ref) should be thrown. ### Example ```julia using BoundTypes struct StringValidAddress{T<:AbstractString} <: BoundString{T} value::T function StringValidAddress{T}(x::AbstractString) where {T<:AbstractString} length(x) != 40 && throw( ConstraintError{StringFixedLength}( "length of the \"$x\" must be equal to 40 characters ($(length(x))).", ), ) isnothing(match(r"^0x([abcdef0-9])+$", x)) && throw( ConstraintError{StringPattern}( "\"$x\" must match to regex pattern /^0x([abcdef0-9])+\$./", ), ) return new{T}(x) end end ``` ```@julia-repl julia> StringValidAddress{String}("0xf343a817e5f5243190d3c52bf347daf876de1d") "0xf343a817e5f5243190d3c52bf347daf876de1d" julia> StringValidAddress{String}("0x14__1ylad2g_-as2@>>") Wrong value: "0x14__1ylad2g_-as2@>>" must match to regex pattern /^0x([abcdef0-9])+$/. ```
BoundTypes
https://github.com/bhftbootcamp/BoundTypes.jl.git
[ "MIT" ]
1.0.3
4313f4d37ec6b34bb53214759f8a0df02458b6e9
docs
107
# Utils ## Getter functions ```@docs bound_type bound_value ``` ## Errors ```@docs ConstraintError ```
BoundTypes
https://github.com/bhftbootcamp/BoundTypes.jl.git
[ "MIT" ]
0.1.1
cdded46ce7b0a2716f0cd4b37933b968fb8b58fd
code
194
module ESAInterpolationFiles using Mmap using PreallocationTools include("utils.jl") include("header.jl") include("block.jl") include("interp.jl") include("file.jl") include("compute.jl") end
ESAInterpolationFiles
https://github.com/andreapasquale94/ESAInterpolationFiles.jl.git
[ "MIT" ]
0.1.1
cdded46ce7b0a2716f0cd4b37933b968fb8b58fd
code
874
struct IPFBlockInfo start_key::Float64 end_key::Float64 offset::Int n_records::Int header::Vector{Int32} end function Base.show(io::IO, b::IPFBlockInfo) print(io, "IPFBlockInfo(") print(io, "header=$(Int.(b.header)), "), print(io, "$(b.start_key), ") print(io, "$(b.end_key), ") print(io, "$(b.offset), ") print(io, "$(b.n_records)") print(io, ")") end @inbounds function IPFBlockInfo(array, offset, block_header_size, bend) block_start_key = get_float(array, offset, bend) block_end_key = get_float(array, offset+8, bend) block_offset = get_int64(array, offset+16, bend) n_records = get_int64(array, offset+24, bend) @views header = reinterpret(UInt32, array[block_offset+1 : block_offset+block_header_size*4]) return IPFBlockInfo(block_start_key, block_end_key, block_offset, n_records, header) end
ESAInterpolationFiles
https://github.com/andreapasquale94/ESAInterpolationFiles.jl.git
[ "MIT" ]
0.1.1
cdded46ce7b0a2716f0cd4b37933b968fb8b58fd
code
1967
export compute, compute_derivative """ compute(file::IPF, key::Number) Compute Interpolation File value at the given `key` value. """ function compute(file::IPF, key::Number) return compute(file, get_block(file, key), key) end """ compute_derivative(file::IPF, key::Number) Compute Interpolation File derivative value at the given `key` value. !!! warning To use this function the `IPF` file shall contains derivatives. """ function compute_derivative(file::IPF, key::Number) return compute_derivative(file, get_block(file, key), key) end function _update_cache!(file::IPF, block::IPFBlockInfo, key::Number) header = file.header cache = file.cache # Get maximum order order = header.user_header[2] n_records = block.n_records # Find record rid = find_record(file, block, key) if n_records ≤ order+1 left, right = 1, n_records else # Find left and right records left = max(1, rid - (order÷2)) right = min(n_records, rid + (order+1)÷2 + 1) end # Number of points/interpolation order points = right - left order = points - 1 get_records!( cache.y, file, block, left, points, header.n_columns * (1 + header.n_derivatives) + 1 ) return header, cache, order end function compute(file::IPF, block::IPFBlockInfo, key::Number) header, cache, order = _update_cache!(file, block, key) if header.n_derivatives > 0 return hermite(cache, order, header.n_columns, key) else return lagrange(cache, order, header.n_columns, key) end end function compute_derivative(file::IPF, block::IPFBlockInfo, key::Number) header, cache, order = _update_cache!(file, block, key) if header.n_derivatives == 0 throw( ErrorException("Cannot compute derivatives as they are not present!") ) end return lagrange(cache, order, header.n_columns, key, header.n_columns+1) end
ESAInterpolationFiles
https://github.com/andreapasquale94/ESAInterpolationFiles.jl.git
[ "MIT" ]
0.1.1
cdded46ce7b0a2716f0cd4b37933b968fb8b58fd
code
6008
export IPF, get_block, get_record, get_records """ IPF{C, V} Struct to store ESA/ESOC Interpolation File data. - `filepath::String`: The path to the IPF file. - `header::IPFHeader`: The header information of the IPF file. - `blocks::Vector{IPFBlockInfo}`: Information about the blocks within the IPF file. - `first_key::V`: The first key value stored in the IPF file. - `last_key::V`: The last key value stored in the IPF file. - `array::Vector{UInt8}`: An array containing the binary data of the IPF file. - `cache::InterpCache{C, V}`: Cache for interpolation data. Here the parameters are the cache-type `C` and the value type `V`. ## Constructors - `IPF{C, V}(filepath::String)`: Constructs an `IPF` object from the specified file path, with the option to specify the types for cache (`C`) and values (`V`). - `IPF(filepath::String)`: Constructs an `IPF` object with default types `Float64` for both cache and values. """ struct IPF{cType, vType} filepath::String header::IPFHeader blocks::Vector{IPFBlockInfo} first_key::vType last_key::vType array::Vector{UInt8} cache::InterpCache{cType, vType} end function IPF{cType, vType}(filepath::String) where {cType, vType} array = Mmap.mmap(filepath) # Construct header header = IPFHeader(array) # Read first and last key first_key = get_float(array, 52, header.bigend) last_key = get_float(array, 60, header.bigend) # Build blocks info blocks = blocks_info(array, header.tail_offset, header) cache = InterpCache{cType, vType}( header.user_header[2]+1, header.n_columns*(1 + header.n_derivatives) + 1, header.n_derivatives > 0 ? 2 : 1 ) # Create Ipf file return IPF{cType, vType}(filepath, header, blocks, first_key, last_key, array, cache) end function IPF(filepath::String) return IPF{Float64, Float64}(filepath) end function blocks_info(array::Vector{UInt8}, offset, header) # Construct all the ipfblockinfo structures found in the file blocks = Vector{IPFBlockInfo}(undef, header.n_blocks) step = 2*8 + 2*8 for i in eachindex(blocks) blocks[i] = IPFBlockInfo(array, offset, header.block_header_size, header.bigend) offset += step end return blocks end function Base.show(io::IO, f::IPF) print(io, "IPF(") print(io, "file='$(f.filepath)', ") print(io, "n_blocks=$(f.header.n_blocks), ") print(io, "first_key=$(f.first_key), ") print(io, "last_key=$(f.last_key)") print(io, ")") end function find_block(file::IPF, key::Number) # binary search to find the block that contains the key inside lo = 1 hi = length(file.blocks) while lo ≤ hi mid = lo + (hi - lo) ÷ 2 block = file.blocks[mid] if key ≥ block.start_key && key < block.end_key return (key ≥ block.start_key && key < block.end_key) ? mid : @goto err elseif key < block.start_key hi = mid - 1 else lo = mid + 1 end end @label err throw(ErrorException("Cannot find any block that contains key = $(key).")) end function get_block(file::IPF, key::Number) bid = find_block(file, key) return file.blocks[bid] end function get_record!(cache::AbstractVector, file::IPF, bid::Integer, rid::Integer) block = file.blocks[bid] # Offset to record start # this include the block offset, the block header size and the previous records size offset = block.offset + file.header.block_header_size*4 + (rid-1)*file.header.record_size # Dimension of the record (in Float64) dim = file.header.record_size ÷ 8 @assert length(cache) ≥ dim "not enough space in the cache to get the required record" for i in 1:dim cache[i] = get_float(file.array, offset + (i-1)*8, file.header.bigend) end nothing end function get_record(file::IPF, bid::Integer, rid::Integer) dim = file.header.record_size ÷ 8 cache = zeros(Float64, dim) get_record!(cache, file, bid, rid) return cache end function get_records!( out, file::IPF, b::IPFBlockInfo, first::Int, count::Int, maxdim::Int, initdim::Int = 1 ) # Find offset of the first element offset = b.offset + file.header.block_header_size*4 offset += (first-1)*file.header.record_size for i in 1:count k = offset + (i-1)*file.header.record_size for j in initdim:maxdim out[i][j] = get_float( file.array, k+(j-1)*8, file.header.bigend ) end end nothing end function get_records!(out, file::IPF, bid::Int, first::Int, count::Int) get_records!(out, file, file.blocks[bid], first, count) nothing end function get_records(file::IPF, block::IPFBlockInfo) records = Vector{Vector{Float64}}() for i in 1:block.n_records offset = block.offset + file.header.block_header_size*4 + (i-1)*file.header.record_size push!( records, reinterpret(Float64, file.array[offset+1 : offset+file.header.record_size]) ) end return records end function get_records(file::IPF, bid::Integer) block = file.blocks[bid] return get_records(file, block) end function find_record(file::IPF, block::IPFBlockInfo, key::Number) # binary search to find the closest record lo = 1 hi = block.n_records while lo ≤ hi mid = lo + (hi - lo) ÷ 2 offset = block.offset + file.header.block_header_size*4 + (mid-1)*file.header.record_size val = get_float(file.array, offset, file.header.bigend) if key < val hi = mid - 1 else lo = mid + 1 end end return lo-1 end function find_record(file::IPF, bid::Integer, key::Number) block = file.blocks[bid] return find_record(file, block, key) end function get_block_maxsize(file::IPF) maxs = 0 for b in file.blocks b.n_records > maxs ? maxs = b.n_records : nothing end return maxs end
ESAInterpolationFiles
https://github.com/andreapasquale94/ESAInterpolationFiles.jl.git
[ "MIT" ]
0.1.1
cdded46ce7b0a2716f0cd4b37933b968fb8b58fd
code
2704
struct IPFHeader type::Int version::Int n_columns::Int n_derivatives::Int n_blocks::Int user_header::Vector{Int32} tail_offset::Int block_header_size::Int bigend::Bool record_size::UInt end function Base.show(io::IO, h::IPFHeader) print(io, "IPFHeader(") print(io, "type=$(h.type), ") print(io, "version=$(h.version), ") print(io, "n_columns=$(h.n_columns), ") print(io, "n_derivatives=$(h.n_derivatives), ") print(io, "n_blocks=$(h.n_blocks), ") print(io, "user_header=$(Int.(h.user_header)), ") print(io, "tail_offset=$(h.tail_offset), ") print(io, "block_header_size=$(h.block_header_size), ") print(io, "bigend=$(h.bigend), ") print(io, "record_size=$(h.record_size)") print(io, ")") end @inbounds function IPFHeader(array::Vector{UInt8}) # Read the magic string (8 bytes) @views magic = String(array[1:8]) if magic != "ESAFDIPF" throw( ErrorException("Corrupted file, magic number is wrong!") ) end # Read endianness indicator (4 bytes) tmp = get_int32(array, 8, false) bend = !(tmp == 1) if tmp == (1 << 24) bend = true end # Read version number (uint32, 4 bytes) version = get_int32(array, 12, bend) # Read key type (int32, 4 bytes) key_type = get_int32(array, 16, bend) # Read value type (int32, 4 bytes) value_type = get_int32(array, 20, bend) if key_type != 3 || value_type != 3 throw( ErrorException("Type not handles. Only doubles are handled (i.e. type = 3).") ) end # byte size of keys and values key_bsize = 8 value_bsize = 8 # Read other entries n_cols = get_int32(array, 24, bend) if n_cols == 0 error("The file has no columns and is invalid!") end n_der = get_int32(array, 28, bend) file_type = get_int32(array, 32, bend) n_blocks = get_int64(array, 36, bend) tail_offset = get_int64(array, 44, bend) if tail_offset > length(array) throw( ErrorException("Corrupted file: file tail offset is larger than file size!") ) end padding = 2*key_bsize # 2*sizeof(double) off = 52 + padding user_file_header_size = get_int32(array, off, bend) user_block_header_size = get_int32(array, off+4, bend) Δ = user_file_header_size * 4 - 1 @views user_header = reinterpret(Int32, array[77:77+Δ]) record_size = key_bsize + n_cols*(n_der+1)*value_bsize # this depends on key/value types return IPFHeader( file_type, version, n_cols, n_der, n_blocks, user_header, tail_offset, user_block_header_size, bend, record_size ) end
ESAInterpolationFiles
https://github.com/andreapasquale94/ESAInterpolationFiles.jl.git
[ "MIT" ]
0.1.1
cdded46ce7b0a2716f0cd4b37933b968fb8b58fd
code
1983
struct InterpCache{cType, vType} y::Vector{Vector{vType}} # buffers l::Vector{DiffCache{Vector{cType}, Vector{cType}}} buff::DiffCache{Vector{cType}, Vector{cType}} function InterpCache{cType, vType}(max_dim::Int, cols::Int, diff::Int) where {cType, vType} v = [zeros(vType, cols+1) for _ in 1:max_dim] l = [DiffCache(ones(cType, max_dim)) for _ in 1:diff] buff = DiffCache(zeros(cType, cols)) return new{cType, vType}(v, l, buff) end end @inbounds function lagrange( cache::InterpCache{cType, vType}, order::Int, cols::Int, x::Number, offset::Int = 1 ) where {cType, vType} n = order+1 # get and reset caches l = get_tmp(cache.l[1], x) fill!(l, cType(1)) buff = get_tmp(cache.buff, x) fill!(buff, cType(0)) # update basis for j in 1:n, i in 1:n if i ≠ j l[j] *= (x - cache.y[i][1])/(cache.y[j][1] - cache.y[i][1]) end end # update buffer for k in offset:offset+cols-1, j in 1:n buff[k] += l[j] * cache.y[j][k+1] end return @views buff[offset:offset+cols-1] end @inbounds function hermite( cache::InterpCache{cType, vType}, order::Int, cols::Int, x::Number, offset::Int = 1 ) where {cType, vType} n = order+1 # get and reset caches l1 = get_tmp(cache.l[1], x) fill!(l1, cType(1)) l2 = get_tmp(cache.l[2], x) fill!(l2, cType(0)) buff = get_tmp(cache.buff, x) fill!(buff, cType(0)) # update basis for j in 1:n, i in 1:n if i ≠ j Δx = cache.y[j][1] - cache.y[i][1] l1[j] *= (x - cache.y[i][1])/Δx l2[j] += 1/Δx end end # update buffer for k in offset:offset+cols-1, j in 1:n Δx = x - cache.y[j][1] l² = l1[j] * l1[j] ϕ = (1 - 2*Δx*l2[j]) * l² ψ = Δx * l² buff[k] += ϕ * cache.y[j][k+1] + ψ * cache.y[j][offset+cols+k] end return @views buff[offset:offset+cols-1] end
ESAInterpolationFiles
https://github.com/andreapasquale94/ESAInterpolationFiles.jl.git
[ "MIT" ]
0.1.1
cdded46ce7b0a2716f0cd4b37933b968fb8b58fd
code
852
# Read from array the string at address with given length function get_string(array, address::Integer, bytes::Integer) # address is in 0-index notation! @inbounds rstrip(String(@view(array[address+1:address+bytes]))) end @inline get_num(x::Number, bend::Bool) = bend ? hton(x) : htol(x) function get_int32(array, address::Integer, bend::Bool) # address is in 0-index notation! ptr = unsafe_load(Ptr{Int32}(pointer(array, address+1))) get_num(ptr, bend) end function get_int64(array, address::Integer, bend::Bool) # address is in 0-index notation! ptr = unsafe_load(Ptr{Int64}(pointer(array, address+1))) get_num(ptr, bend) end function get_float(array, address::Integer, bend::Bool) # address is in 0-index notation! ptr = unsafe_load(Ptr{Float64}(pointer(array, address+1))) get_num(ptr, bend) end
ESAInterpolationFiles
https://github.com/andreapasquale94/ESAInterpolationFiles.jl.git
[ "MIT" ]
0.1.1
cdded46ce7b0a2716f0cd4b37933b968fb8b58fd
docs
1030
# ESAInterpolationFiles.jl _ESA Interpolation Files made easy._ ESAInterpolationFiles.jl is a Julia library that provides fast and allocation-free access to binary ESA/ESOC interpolation files or IPF. Completely written in Julia, it enables Automatic-Differentiation (AD) via [ForwardDiff.jl](https://github.com/JuliaDiff/ForwardDiff.jl) and [TaylorSeries.jl](https://github.com/JuliaDiff/TaylorSeries.jl) across all of its function calls. ## Usage The `compute` and `compute_derivative` functions can be used to perform interpolation and compute derivatives from an IPF file. ### Example Usage: ```julia using ESAInterpolationFiles: IPF, compute, compute_derivatives # Load an IPF file file = IPF("example.ipf") # Compute interpolated value for a given key value = compute(file, 10.5) # Compute derivative for a given key derivative = compute_derivative(file, 10.5) ``` ## Support If you found this package useful, please consider starring the repository. ## Disclaimer This package is not affiliated with ESA/ESOC.
ESAInterpolationFiles
https://github.com/andreapasquale94/ESAInterpolationFiles.jl.git
[ "MIT" ]
1.1.0
b974d55cbe0aec030b1985cfb0d396aae5f56195
code
720
using LibAwsChecksums using Documenter DocMeta.setdocmeta!(LibAwsChecksums, :DocTestSetup, :(using LibAwsChecksums); recursive=true) makedocs(; modules=[LibAwsChecksums], repo="https://github.com/JuliaServices/LibAwsChecksums.jl/blob/{commit}{path}#{line}", sitename="LibAwsChecksums.jl", format=Documenter.HTML(; prettyurls=get(ENV, "CI", "false") == "true", canonical="https://github.com/JuliaServices/LibAwsChecksums.jl", assets=String[], size_threshold=2_000_000, # 2 MB, we generate about 1 MB page size_threshold_warn=2_000_000, ), pages=["Home" => "index.md"], ) deploydocs(; repo="github.com/JuliaServices/LibAwsChecksums.jl", devbranch="main")
LibAwsChecksums
https://github.com/JuliaServices/LibAwsChecksums.jl.git
[ "MIT" ]
1.1.0
b974d55cbe0aec030b1985cfb0d396aae5f56195
code
3001
using Clang.Generators using Clang.JLLEnvs using JLLPrefixes import aws_c_common_jll, aws_checksums_jll using LibAwsCommon cd(@__DIR__) # This is called if the docs generated from the extract_c_comment_style method did not generate any lines. # We need to generate at least some docs so that cross-references work with Documenter.jl. function get_docs(node, docs) # The macro node types (except for MacroDefault) seem to not generate code, but they will still emit docs and then # you end up with docs stacked on top of each other, which is a Julia LoadError. if node.type isa Generators.AbstractMacroNodeType && !(node.type isa Generators.MacroDefault) return String[] end # don't generate empty docs because it makes Documenter.jl mad if isempty(docs) return ["Documentation not found."] end return docs end function should_skip_target(target) # aws_c_common_jll does not support i686 windows https://github.com/JuliaPackaging/Yggdrasil/blob/bbab3a916ae5543902b025a4a873cf9ee4a7de68/A/aws_c_common/build_tarballs.jl#L48-L49 return target == "i686-w64-mingw32" end const deps_jlls = [aws_c_common_jll] const deps = [LibAwsCommon] const deps_names = sort(collect(Iterators.flatten(names.(deps)))) # clang can emit code for forward declarations of structs defined in our dependencies. we need to skip those, otherwise # we'll have duplicate struct definitions. function skip_nodes_in_dependencies!(dag::ExprDAG) replace!(get_nodes(dag)) do node if insorted(node.id, deps_names) return ExprNode(node.id, Generators.Skip(), node.cursor, Expr[], node.adj) end return node end end # download toolchains in parallel Threads.@threads for target in JLLEnvs.JLL_ENV_TRIPLES if should_skip_target(target) continue end get_default_args(target) # downloads the toolchain end for target in JLLEnvs.JLL_ENV_TRIPLES if should_skip_target(target) continue end options = load_options(joinpath(@__DIR__, "generator.toml")) options["general"]["output_file_path"] = joinpath(@__DIR__, "..", "lib", "$target.jl") options["general"]["callback_documentation"] = get_docs args = get_default_args(target) for dep in deps_jlls inc = JLLEnvs.get_pkg_include_dir(dep, target) push!(args, "-isystem$inc") end header_dirs = [] inc = JLLEnvs.get_pkg_include_dir(aws_checksums_jll, target) push!(args, "-I$inc") push!(header_dirs, inc) headers = String[] for header_dir in header_dirs for (root, dirs, files) in walkdir(header_dir) for file in files if endswith(file, ".h") push!(headers, joinpath(root, file)) end end end end unique!(headers) ctx = create_context(headers, args, options) build!(ctx, BUILDSTAGE_NO_PRINTING) skip_nodes_in_dependencies!(ctx.dag) build!(ctx, BUILDSTAGE_PRINTING_ONLY) end
LibAwsChecksums
https://github.com/JuliaServices/LibAwsChecksums.jl.git
[ "MIT" ]
1.1.0
b974d55cbe0aec030b1985cfb0d396aae5f56195
code
1258
using CEnum """ aws_checksums_crc32(input, length, previousCrc32) The entry point function to perform a CRC32 (Ethernet, gzip) computation. Selects a suitable implementation based on hardware capabilities. Pass 0 in the previousCrc32 parameter as an initial value unless continuing to update a running crc in a subsequent call. ### Prototype ```c uint32_t aws_checksums_crc32(const uint8_t *input, int length, uint32_t previousCrc32); ``` """ function aws_checksums_crc32(input, length, previousCrc32) ccall((:aws_checksums_crc32, libaws_checksums), UInt32, (Ptr{UInt8}, Cint, UInt32), input, length, previousCrc32) end """ aws_checksums_crc32c(input, length, previousCrc32) The entry point function to perform a Castagnoli CRC32c (iSCSI) computation. Selects a suitable implementation based on hardware capabilities. Pass 0 in the previousCrc32 parameter as an initial value unless continuing to update a running crc in a subsequent call. ### Prototype ```c uint32_t aws_checksums_crc32c(const uint8_t *input, int length, uint32_t previousCrc32); ``` """ function aws_checksums_crc32c(input, length, previousCrc32) ccall((:aws_checksums_crc32c, libaws_checksums), UInt32, (Ptr{UInt8}, Cint, UInt32), input, length, previousCrc32) end
LibAwsChecksums
https://github.com/JuliaServices/LibAwsChecksums.jl.git
[ "MIT" ]
1.1.0
b974d55cbe0aec030b1985cfb0d396aae5f56195
code
1258
using CEnum """ aws_checksums_crc32(input, length, previousCrc32) The entry point function to perform a CRC32 (Ethernet, gzip) computation. Selects a suitable implementation based on hardware capabilities. Pass 0 in the previousCrc32 parameter as an initial value unless continuing to update a running crc in a subsequent call. ### Prototype ```c uint32_t aws_checksums_crc32(const uint8_t *input, int length, uint32_t previousCrc32); ``` """ function aws_checksums_crc32(input, length, previousCrc32) ccall((:aws_checksums_crc32, libaws_checksums), UInt32, (Ptr{UInt8}, Cint, UInt32), input, length, previousCrc32) end """ aws_checksums_crc32c(input, length, previousCrc32) The entry point function to perform a Castagnoli CRC32c (iSCSI) computation. Selects a suitable implementation based on hardware capabilities. Pass 0 in the previousCrc32 parameter as an initial value unless continuing to update a running crc in a subsequent call. ### Prototype ```c uint32_t aws_checksums_crc32c(const uint8_t *input, int length, uint32_t previousCrc32); ``` """ function aws_checksums_crc32c(input, length, previousCrc32) ccall((:aws_checksums_crc32c, libaws_checksums), UInt32, (Ptr{UInt8}, Cint, UInt32), input, length, previousCrc32) end
LibAwsChecksums
https://github.com/JuliaServices/LibAwsChecksums.jl.git
[ "MIT" ]
1.1.0
b974d55cbe0aec030b1985cfb0d396aae5f56195
code
1258
using CEnum """ aws_checksums_crc32(input, length, previousCrc32) The entry point function to perform a CRC32 (Ethernet, gzip) computation. Selects a suitable implementation based on hardware capabilities. Pass 0 in the previousCrc32 parameter as an initial value unless continuing to update a running crc in a subsequent call. ### Prototype ```c uint32_t aws_checksums_crc32(const uint8_t *input, int length, uint32_t previousCrc32); ``` """ function aws_checksums_crc32(input, length, previousCrc32) ccall((:aws_checksums_crc32, libaws_checksums), UInt32, (Ptr{UInt8}, Cint, UInt32), input, length, previousCrc32) end """ aws_checksums_crc32c(input, length, previousCrc32) The entry point function to perform a Castagnoli CRC32c (iSCSI) computation. Selects a suitable implementation based on hardware capabilities. Pass 0 in the previousCrc32 parameter as an initial value unless continuing to update a running crc in a subsequent call. ### Prototype ```c uint32_t aws_checksums_crc32c(const uint8_t *input, int length, uint32_t previousCrc32); ``` """ function aws_checksums_crc32c(input, length, previousCrc32) ccall((:aws_checksums_crc32c, libaws_checksums), UInt32, (Ptr{UInt8}, Cint, UInt32), input, length, previousCrc32) end
LibAwsChecksums
https://github.com/JuliaServices/LibAwsChecksums.jl.git
[ "MIT" ]
1.1.0
b974d55cbe0aec030b1985cfb0d396aae5f56195
code
1258
using CEnum """ aws_checksums_crc32(input, length, previousCrc32) The entry point function to perform a CRC32 (Ethernet, gzip) computation. Selects a suitable implementation based on hardware capabilities. Pass 0 in the previousCrc32 parameter as an initial value unless continuing to update a running crc in a subsequent call. ### Prototype ```c uint32_t aws_checksums_crc32(const uint8_t *input, int length, uint32_t previousCrc32); ``` """ function aws_checksums_crc32(input, length, previousCrc32) ccall((:aws_checksums_crc32, libaws_checksums), UInt32, (Ptr{UInt8}, Cint, UInt32), input, length, previousCrc32) end """ aws_checksums_crc32c(input, length, previousCrc32) The entry point function to perform a Castagnoli CRC32c (iSCSI) computation. Selects a suitable implementation based on hardware capabilities. Pass 0 in the previousCrc32 parameter as an initial value unless continuing to update a running crc in a subsequent call. ### Prototype ```c uint32_t aws_checksums_crc32c(const uint8_t *input, int length, uint32_t previousCrc32); ``` """ function aws_checksums_crc32c(input, length, previousCrc32) ccall((:aws_checksums_crc32c, libaws_checksums), UInt32, (Ptr{UInt8}, Cint, UInt32), input, length, previousCrc32) end
LibAwsChecksums
https://github.com/JuliaServices/LibAwsChecksums.jl.git
[ "MIT" ]
1.1.0
b974d55cbe0aec030b1985cfb0d396aae5f56195
code
1258
using CEnum """ aws_checksums_crc32(input, length, previousCrc32) The entry point function to perform a CRC32 (Ethernet, gzip) computation. Selects a suitable implementation based on hardware capabilities. Pass 0 in the previousCrc32 parameter as an initial value unless continuing to update a running crc in a subsequent call. ### Prototype ```c uint32_t aws_checksums_crc32(const uint8_t *input, int length, uint32_t previousCrc32); ``` """ function aws_checksums_crc32(input, length, previousCrc32) ccall((:aws_checksums_crc32, libaws_checksums), UInt32, (Ptr{UInt8}, Cint, UInt32), input, length, previousCrc32) end """ aws_checksums_crc32c(input, length, previousCrc32) The entry point function to perform a Castagnoli CRC32c (iSCSI) computation. Selects a suitable implementation based on hardware capabilities. Pass 0 in the previousCrc32 parameter as an initial value unless continuing to update a running crc in a subsequent call. ### Prototype ```c uint32_t aws_checksums_crc32c(const uint8_t *input, int length, uint32_t previousCrc32); ``` """ function aws_checksums_crc32c(input, length, previousCrc32) ccall((:aws_checksums_crc32c, libaws_checksums), UInt32, (Ptr{UInt8}, Cint, UInt32), input, length, previousCrc32) end
LibAwsChecksums
https://github.com/JuliaServices/LibAwsChecksums.jl.git
[ "MIT" ]
1.1.0
b974d55cbe0aec030b1985cfb0d396aae5f56195
code
1258
using CEnum """ aws_checksums_crc32(input, length, previousCrc32) The entry point function to perform a CRC32 (Ethernet, gzip) computation. Selects a suitable implementation based on hardware capabilities. Pass 0 in the previousCrc32 parameter as an initial value unless continuing to update a running crc in a subsequent call. ### Prototype ```c uint32_t aws_checksums_crc32(const uint8_t *input, int length, uint32_t previousCrc32); ``` """ function aws_checksums_crc32(input, length, previousCrc32) ccall((:aws_checksums_crc32, libaws_checksums), UInt32, (Ptr{UInt8}, Cint, UInt32), input, length, previousCrc32) end """ aws_checksums_crc32c(input, length, previousCrc32) The entry point function to perform a Castagnoli CRC32c (iSCSI) computation. Selects a suitable implementation based on hardware capabilities. Pass 0 in the previousCrc32 parameter as an initial value unless continuing to update a running crc in a subsequent call. ### Prototype ```c uint32_t aws_checksums_crc32c(const uint8_t *input, int length, uint32_t previousCrc32); ``` """ function aws_checksums_crc32c(input, length, previousCrc32) ccall((:aws_checksums_crc32c, libaws_checksums), UInt32, (Ptr{UInt8}, Cint, UInt32), input, length, previousCrc32) end
LibAwsChecksums
https://github.com/JuliaServices/LibAwsChecksums.jl.git
[ "MIT" ]
1.1.0
b974d55cbe0aec030b1985cfb0d396aae5f56195
code
1258
using CEnum """ aws_checksums_crc32(input, length, previousCrc32) The entry point function to perform a CRC32 (Ethernet, gzip) computation. Selects a suitable implementation based on hardware capabilities. Pass 0 in the previousCrc32 parameter as an initial value unless continuing to update a running crc in a subsequent call. ### Prototype ```c uint32_t aws_checksums_crc32(const uint8_t *input, int length, uint32_t previousCrc32); ``` """ function aws_checksums_crc32(input, length, previousCrc32) ccall((:aws_checksums_crc32, libaws_checksums), UInt32, (Ptr{UInt8}, Cint, UInt32), input, length, previousCrc32) end """ aws_checksums_crc32c(input, length, previousCrc32) The entry point function to perform a Castagnoli CRC32c (iSCSI) computation. Selects a suitable implementation based on hardware capabilities. Pass 0 in the previousCrc32 parameter as an initial value unless continuing to update a running crc in a subsequent call. ### Prototype ```c uint32_t aws_checksums_crc32c(const uint8_t *input, int length, uint32_t previousCrc32); ``` """ function aws_checksums_crc32c(input, length, previousCrc32) ccall((:aws_checksums_crc32c, libaws_checksums), UInt32, (Ptr{UInt8}, Cint, UInt32), input, length, previousCrc32) end
LibAwsChecksums
https://github.com/JuliaServices/LibAwsChecksums.jl.git
[ "MIT" ]
1.1.0
b974d55cbe0aec030b1985cfb0d396aae5f56195
code
1258
using CEnum """ aws_checksums_crc32(input, length, previousCrc32) The entry point function to perform a CRC32 (Ethernet, gzip) computation. Selects a suitable implementation based on hardware capabilities. Pass 0 in the previousCrc32 parameter as an initial value unless continuing to update a running crc in a subsequent call. ### Prototype ```c uint32_t aws_checksums_crc32(const uint8_t *input, int length, uint32_t previousCrc32); ``` """ function aws_checksums_crc32(input, length, previousCrc32) ccall((:aws_checksums_crc32, libaws_checksums), UInt32, (Ptr{UInt8}, Cint, UInt32), input, length, previousCrc32) end """ aws_checksums_crc32c(input, length, previousCrc32) The entry point function to perform a Castagnoli CRC32c (iSCSI) computation. Selects a suitable implementation based on hardware capabilities. Pass 0 in the previousCrc32 parameter as an initial value unless continuing to update a running crc in a subsequent call. ### Prototype ```c uint32_t aws_checksums_crc32c(const uint8_t *input, int length, uint32_t previousCrc32); ``` """ function aws_checksums_crc32c(input, length, previousCrc32) ccall((:aws_checksums_crc32c, libaws_checksums), UInt32, (Ptr{UInt8}, Cint, UInt32), input, length, previousCrc32) end
LibAwsChecksums
https://github.com/JuliaServices/LibAwsChecksums.jl.git
[ "MIT" ]
1.1.0
b974d55cbe0aec030b1985cfb0d396aae5f56195
code
1258
using CEnum """ aws_checksums_crc32(input, length, previousCrc32) The entry point function to perform a CRC32 (Ethernet, gzip) computation. Selects a suitable implementation based on hardware capabilities. Pass 0 in the previousCrc32 parameter as an initial value unless continuing to update a running crc in a subsequent call. ### Prototype ```c uint32_t aws_checksums_crc32(const uint8_t *input, int length, uint32_t previousCrc32); ``` """ function aws_checksums_crc32(input, length, previousCrc32) ccall((:aws_checksums_crc32, libaws_checksums), UInt32, (Ptr{UInt8}, Cint, UInt32), input, length, previousCrc32) end """ aws_checksums_crc32c(input, length, previousCrc32) The entry point function to perform a Castagnoli CRC32c (iSCSI) computation. Selects a suitable implementation based on hardware capabilities. Pass 0 in the previousCrc32 parameter as an initial value unless continuing to update a running crc in a subsequent call. ### Prototype ```c uint32_t aws_checksums_crc32c(const uint8_t *input, int length, uint32_t previousCrc32); ``` """ function aws_checksums_crc32c(input, length, previousCrc32) ccall((:aws_checksums_crc32c, libaws_checksums), UInt32, (Ptr{UInt8}, Cint, UInt32), input, length, previousCrc32) end
LibAwsChecksums
https://github.com/JuliaServices/LibAwsChecksums.jl.git
[ "MIT" ]
1.1.0
b974d55cbe0aec030b1985cfb0d396aae5f56195
code
1258
using CEnum """ aws_checksums_crc32(input, length, previousCrc32) The entry point function to perform a CRC32 (Ethernet, gzip) computation. Selects a suitable implementation based on hardware capabilities. Pass 0 in the previousCrc32 parameter as an initial value unless continuing to update a running crc in a subsequent call. ### Prototype ```c uint32_t aws_checksums_crc32(const uint8_t *input, int length, uint32_t previousCrc32); ``` """ function aws_checksums_crc32(input, length, previousCrc32) ccall((:aws_checksums_crc32, libaws_checksums), UInt32, (Ptr{UInt8}, Cint, UInt32), input, length, previousCrc32) end """ aws_checksums_crc32c(input, length, previousCrc32) The entry point function to perform a Castagnoli CRC32c (iSCSI) computation. Selects a suitable implementation based on hardware capabilities. Pass 0 in the previousCrc32 parameter as an initial value unless continuing to update a running crc in a subsequent call. ### Prototype ```c uint32_t aws_checksums_crc32c(const uint8_t *input, int length, uint32_t previousCrc32); ``` """ function aws_checksums_crc32c(input, length, previousCrc32) ccall((:aws_checksums_crc32c, libaws_checksums), UInt32, (Ptr{UInt8}, Cint, UInt32), input, length, previousCrc32) end
LibAwsChecksums
https://github.com/JuliaServices/LibAwsChecksums.jl.git
[ "MIT" ]
1.1.0
b974d55cbe0aec030b1985cfb0d396aae5f56195
code
1258
using CEnum """ aws_checksums_crc32(input, length, previousCrc32) The entry point function to perform a CRC32 (Ethernet, gzip) computation. Selects a suitable implementation based on hardware capabilities. Pass 0 in the previousCrc32 parameter as an initial value unless continuing to update a running crc in a subsequent call. ### Prototype ```c uint32_t aws_checksums_crc32(const uint8_t *input, int length, uint32_t previousCrc32); ``` """ function aws_checksums_crc32(input, length, previousCrc32) ccall((:aws_checksums_crc32, libaws_checksums), UInt32, (Ptr{UInt8}, Cint, UInt32), input, length, previousCrc32) end """ aws_checksums_crc32c(input, length, previousCrc32) The entry point function to perform a Castagnoli CRC32c (iSCSI) computation. Selects a suitable implementation based on hardware capabilities. Pass 0 in the previousCrc32 parameter as an initial value unless continuing to update a running crc in a subsequent call. ### Prototype ```c uint32_t aws_checksums_crc32c(const uint8_t *input, int length, uint32_t previousCrc32); ``` """ function aws_checksums_crc32c(input, length, previousCrc32) ccall((:aws_checksums_crc32c, libaws_checksums), UInt32, (Ptr{UInt8}, Cint, UInt32), input, length, previousCrc32) end
LibAwsChecksums
https://github.com/JuliaServices/LibAwsChecksums.jl.git
[ "MIT" ]
1.1.0
b974d55cbe0aec030b1985cfb0d396aae5f56195
code
1258
using CEnum """ aws_checksums_crc32(input, length, previousCrc32) The entry point function to perform a CRC32 (Ethernet, gzip) computation. Selects a suitable implementation based on hardware capabilities. Pass 0 in the previousCrc32 parameter as an initial value unless continuing to update a running crc in a subsequent call. ### Prototype ```c uint32_t aws_checksums_crc32(const uint8_t *input, int length, uint32_t previousCrc32); ``` """ function aws_checksums_crc32(input, length, previousCrc32) ccall((:aws_checksums_crc32, libaws_checksums), UInt32, (Ptr{UInt8}, Cint, UInt32), input, length, previousCrc32) end """ aws_checksums_crc32c(input, length, previousCrc32) The entry point function to perform a Castagnoli CRC32c (iSCSI) computation. Selects a suitable implementation based on hardware capabilities. Pass 0 in the previousCrc32 parameter as an initial value unless continuing to update a running crc in a subsequent call. ### Prototype ```c uint32_t aws_checksums_crc32c(const uint8_t *input, int length, uint32_t previousCrc32); ``` """ function aws_checksums_crc32c(input, length, previousCrc32) ccall((:aws_checksums_crc32c, libaws_checksums), UInt32, (Ptr{UInt8}, Cint, UInt32), input, length, previousCrc32) end
LibAwsChecksums
https://github.com/JuliaServices/LibAwsChecksums.jl.git
[ "MIT" ]
1.1.0
b974d55cbe0aec030b1985cfb0d396aae5f56195
code
1258
using CEnum """ aws_checksums_crc32(input, length, previousCrc32) The entry point function to perform a CRC32 (Ethernet, gzip) computation. Selects a suitable implementation based on hardware capabilities. Pass 0 in the previousCrc32 parameter as an initial value unless continuing to update a running crc in a subsequent call. ### Prototype ```c uint32_t aws_checksums_crc32(const uint8_t *input, int length, uint32_t previousCrc32); ``` """ function aws_checksums_crc32(input, length, previousCrc32) ccall((:aws_checksums_crc32, libaws_checksums), UInt32, (Ptr{UInt8}, Cint, UInt32), input, length, previousCrc32) end """ aws_checksums_crc32c(input, length, previousCrc32) The entry point function to perform a Castagnoli CRC32c (iSCSI) computation. Selects a suitable implementation based on hardware capabilities. Pass 0 in the previousCrc32 parameter as an initial value unless continuing to update a running crc in a subsequent call. ### Prototype ```c uint32_t aws_checksums_crc32c(const uint8_t *input, int length, uint32_t previousCrc32); ``` """ function aws_checksums_crc32c(input, length, previousCrc32) ccall((:aws_checksums_crc32c, libaws_checksums), UInt32, (Ptr{UInt8}, Cint, UInt32), input, length, previousCrc32) end
LibAwsChecksums
https://github.com/JuliaServices/LibAwsChecksums.jl.git
[ "MIT" ]
1.1.0
b974d55cbe0aec030b1985cfb0d396aae5f56195
code
1933
module LibAwsChecksums using aws_checksums_jll using LibAwsCommon const IS_LIBC_MUSL = occursin("musl", Base.BUILD_TRIPLET) if Sys.isapple() && Sys.ARCH === :aarch64 include("../lib/aarch64-apple-darwin20.jl") elseif Sys.islinux() && Sys.ARCH === :aarch64 && !IS_LIBC_MUSL include("../lib/aarch64-linux-gnu.jl") elseif Sys.islinux() && Sys.ARCH === :aarch64 && IS_LIBC_MUSL include("../lib/aarch64-linux-musl.jl") elseif Sys.islinux() && startswith(string(Sys.ARCH), "arm") && !IS_LIBC_MUSL include("../lib/armv7l-linux-gnueabihf.jl") elseif Sys.islinux() && startswith(string(Sys.ARCH), "arm") && IS_LIBC_MUSL include("../lib/armv7l-linux-musleabihf.jl") elseif Sys.islinux() && Sys.ARCH === :i686 && !IS_LIBC_MUSL include("../lib/i686-linux-gnu.jl") elseif Sys.islinux() && Sys.ARCH === :i686 && IS_LIBC_MUSL include("../lib/i686-linux-musl.jl") elseif Sys.iswindows() && Sys.ARCH === :i686 error("LibAwsCommon.jl does not support i686 windows https://github.com/JuliaPackaging/Yggdrasil/blob/bbab3a916ae5543902b025a4a873cf9ee4a7de68/A/aws_c_common/build_tarballs.jl#L48-L49") elseif Sys.islinux() && Sys.ARCH === :powerpc64le include("../lib/powerpc64le-linux-gnu.jl") elseif Sys.isapple() && Sys.ARCH === :x86_64 include("../lib/x86_64-apple-darwin14.jl") elseif Sys.islinux() && Sys.ARCH === :x86_64 && !IS_LIBC_MUSL include("../lib/x86_64-linux-gnu.jl") elseif Sys.islinux() && Sys.ARCH === :x86_64 && IS_LIBC_MUSL include("../lib/x86_64-linux-musl.jl") elseif Sys.isbsd() && !Sys.isapple() include("../lib/x86_64-unknown-freebsd13.2.jl") elseif Sys.iswindows() && Sys.ARCH === :x86_64 include("../lib/x86_64-w64-mingw32.jl") else error("Unknown platform: $(Base.BUILD_TRIPLET)") end # exports for name in names(@__MODULE__; all=true) if name == :eval || name == :include || contains(string(name), "#") continue end @eval export $name end end
LibAwsChecksums
https://github.com/JuliaServices/LibAwsChecksums.jl.git
[ "MIT" ]
1.1.0
b974d55cbe0aec030b1985cfb0d396aae5f56195
code
609
using Test, Aqua, LibAwsChecksums, LibAwsCommon, CRC32c @testset "LibAwsChecksums" begin @testset "aqua" begin Aqua.test_all(LibAwsChecksums, ambiguities=false) Aqua.test_ambiguities(LibAwsChecksums) end @testset "basic usage to test the library loads" begin alloc = aws_default_allocator() # important! this shouldn't need to be qualified! if we generate a definition for it in LibAwsChecksums that is a bug. input = rand(UInt8, 10) actual = aws_checksums_crc32c(input, 10, 0) expected = crc32c(input) @test actual == expected end end
LibAwsChecksums
https://github.com/JuliaServices/LibAwsChecksums.jl.git
[ "MIT" ]
1.1.0
b974d55cbe0aec030b1985cfb0d396aae5f56195
docs
513
[![](https://img.shields.io/badge/docs-stable-blue.svg)](https://JuliaServices.github.io/LibAwsChecksums.jl/stable) [![](https://img.shields.io/badge/docs-dev-blue.svg)](https://JuliaServices.github.io/LibAwsChecksums.jl/dev) [![CI](https://github.com/JuliaServices/LibAwsChecksums.jl/actions/workflows/ci.yml/badge.svg)](https://github.com/JuliaServices/LibAwsChecksums.jl/actions/workflows/ci.yml) # LibAwsChecksums.jl Julia bindings for the [aws-checksums](https://github.com/awslabs/aws-checksums) library.
LibAwsChecksums
https://github.com/JuliaServices/LibAwsChecksums.jl.git
[ "MIT" ]
1.1.0
b974d55cbe0aec030b1985cfb0d396aae5f56195
docs
216
```@meta CurrentModule = LibAwsChecksums ``` # LibAwsChecksums Documentation for [LibAwsChecksums](https://github.com/JuliaServices/LibAwsChecksums.jl). ```@index ``` ```@autodocs Modules = [LibAwsChecksums] ```
LibAwsChecksums
https://github.com/JuliaServices/LibAwsChecksums.jl.git
[ "MIT" ]
0.1.0
b3603370187989e1e57d512450f6e0016c838289
code
739
using ArrayInitializers using Documenter DocMeta.setdocmeta!(ArrayInitializers, :DocTestSetup, :(using ArrayInitializers); recursive=true) makedocs(; modules=[ArrayInitializers], authors="Mark Kittisopikul <kittisopikulm@janelia.hhmi.org> and contributors", repo="https://github.com/mkitti/ArrayInitializers.jl/blob/{commit}{path}#{line}", sitename="ArrayInitializers.jl", format=Documenter.HTML(; prettyurls=get(ENV, "CI", "false") == "true", canonical="https://mkitti.github.io/ArrayInitializers.jl", edit_link="main", assets=String[], ), pages=[ "Home" => "index.md", ], ) deploydocs(; repo="github.com/mkitti/ArrayInitializers.jl", devbranch="main", )
ArrayInitializers
https://github.com/mkitti/ArrayInitializers.jl.git
[ "MIT" ]
0.1.0
b3603370187989e1e57d512450f6e0016c838289
code
13556
module ArrayInitializers using Random export init, undeftype, zeroinit, oneinit, randinit const NArray{N} = Array{T,N} where T const NAbstractArray{N} = AbstractArray{T,N} where T abstract type AbstractArrayInitializer{T} end """ FillArrayInitializer{T}(value::T) When passed to an `AbstractArray` constructor as the first argument, the constructed array will be filled with value via `fill!`. """ struct FillArrayInitializer{T} <: AbstractArrayInitializer{T} value::T end """ init(value::T) Create a `FillArrayInitializer{T}`. When passed to an `AbstractArray` constructor as the first argument, the constructed array will be filled with `value` via `fill!`. Also the result can be called with an array argument. It will `fill!` the array. ```julia julia> const threes = init(3) ArrayInitializers.FillArrayInitializer{Int64}(3) julia> Array(threes, 5) 5-element Vector{Int64}: 3 3 3 3 3 julia> const fives! = init(5) ArrayInitializers.FillArrayInitializer{Int64}(5) julia> fives!(ones(3)) 3-element Vector{Float64}: 5.0 5.0 5.0 ``` """ init(value::T) where T = FillArrayInitializer{T}(value) @inline (fai::FillArrayInitializer)(array) = Base.fill!(array, fai.value) @inline (fai::FillArrayInitializer{T})(dims::Dims{N}) where {T,N} = Base.fill!(Array{T,N}(undef, dims), fai.value) @inline (fai::FillArrayInitializer{T})(dims::Vararg{<: Integer}) where {T} = Base.fill!(Array{T}(undef, dims), fai.value) # Does not override Base.fill!, no type piracy """ ArrayInitializers.fill!(value) Alias for [`ArrayInitializers.init`](@ref). ```julia julia> import ArrayInitializers: fill! julia> const fives = fill!(5) ArrayInitializers.FillArrayInitializer{Int64}(5) julia> Matrix(fives, 5, 9) 5×9 Matrix{Int64}: 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 ``` """ @inline fill!(value) = init(value) @inline fill!(array, args...) = Base.fill!(array, args...) """ ZeroInitializer{T} When passed as the first argument of an `AbstractArray` constructor, fill the constructed array with zeros. This will also add a type to an untyped array. """ struct ZeroInitializer{T} <: AbstractArrayInitializer{T} end ZeroInitializer(::Type{T}) where T = ZeroInitializer{T}() """ zeroinit zeroinit(::Type{T}) Singleton instance of `ZeroInitializer{Any}`. The instance can be called with a type argument to create a typed zero initializer. ```julia julia> Vector{Int}(zeroinit, 5) 5-element Vector{Int64}: 0 0 0 0 0 julia> Matrix(zeroinit(Rational), 4, 2) 4×2 Matrix{Rational}: 0//1 0//1 0//1 0//1 0//1 0//1 0//1 0//1 ``` """ const zeroinit = ZeroInitializer{Any}() (::ZeroInitializer{Any})(::Type{T}) where T = ZeroInitializer{T}() """ OneInitializer{T} When passed as the first argument of an `AbstractArray` constructor, fill the constructed array with ones. This will also add a type to an untyped array. """ struct OneInitializer{T} <: AbstractArrayInitializer{T} end OneInitializer(::Type{T}) where T = OneInitializer{T}() """ oneinit oneinit(::Type{T}) Singleton instance of `oneInitializer{Any}`. The instance can be called with a type argument to create a typed one initializer. ```julia julia> Matrix(oneinit(Rational), 3, 6) 3×6 Matrix{Rational}: 1//1 1//1 1//1 1//1 1//1 1//1 1//1 1//1 1//1 1//1 1//1 1//1 1//1 1//1 1//1 1//1 1//1 1//1 julia> Matrix{Number}(oneinit, 3, 6) 3×6 Matrix{Number}: 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 ``` """ const oneinit = OneInitializer{Any}() (::OneInitializer{Any})(::Type{T}) where T = OneInitializer{T}() """ UndefTypeArrayInitializer{T} When passed as the first argument of an `AbstractArray` constructor, confer the type `T` if the `AbstractArray` is not typed. The array is not initialized. See [`undeftype`](@ref) """ struct UndefTypeArrayInitializer{T} <: AbstractArrayInitializer{T} end """ undeftype(::Type{T}) When passed as the first argument of an `AbstractArray` constructor, confer the type `T` if the `AbstractArray` is not typed. The array is not initialized. ``` julia> Matrix(undeftype(Float64), 3, 6) 3×6 Matrix{Float64}: 1.5e-323 2.0e-323 7.0e-323 2.5e-323 3.5e-323 3.0e-323 1.0e-323 1.5e-323 2.0e-323 2.0e-323 2.5e-323 2.5e-323 1.13396e-311 6.95272e-310 6.95272e-310 1.13394e-311 6.95272e-310 6.95272e-310 julia> Matrix(undeftype(Number), 3, 6) 3×6 Matrix{Number}: #undef #undef #undef #undef #undef #undef #undef #undef #undef #undef #undef #undef #undef #undef #undef #undef #undef #undef ``` """ undeftype(::Type{T}) where T = UndefTypeArrayInitializer{T}() # Array(init(2), (3,)) @inline (::Type{A})(fai::FillArrayInitializer{T}, dims::Dims{N}) where {T, N, A <: AbstractArray} = Base.fill!(A{T,N}(undef, dims...), fai.value) # Array(init(2), 1, 2) @inline (::Type{A})(fai::FillArrayInitializer{T}, dims...) where {T, A <: AbstractArray} = Base.fill!(A{T,length(dims)}(undef, dims...), fai.value) # e.g. Array{Float64}(fai, 1, 2) @inline (::Type{A})(fai::FillArrayInitializer{T}, dims...) where {T, T2, A <: AbstractArray{T2}} = Base.fill!(A{length(dims)}(undef, dims...), fai.value) # e.g. Vector(fai, 1) @inline (::Type{A})(fai::FillArrayInitializer{T}, dims...) where {T, N, A <: NAbstractArray{N}} = Base.fill!(A{T}(undef, dims...), fai.value) # e.g. Vector{T}(fai::FillArrayInitializer{T}, 1) @inline (::Type{A})(fai::FillArrayInitializer, dims...) where {T, N, A <: AbstractArray{T,N}} = Base.fill!(A(undef, dims...), fai.value) @inline (::Type{A})(oi::ZeroInitializer{T}, dims::Dims{N}) where {T, N, A <: AbstractArray} = Base.fill!(A{T,N}(undef, dims...), zero(T)) @inline (::Type{A})(oi::ZeroInitializer{T}, dims...) where {T, A <: AbstractArray} = Base.fill!(A{T,length(dims)}(undef, dims...), zero(T)) @inline (::Type{A})(oi::ZeroInitializer{T}, dims...) where {T, N, A <: NAbstractArray{N}} = Base.fill!(A{T}(undef, dims...), zero(T)) @inline (::Type{A})(oi::ZeroInitializer, dims...) where {T, A <: AbstractArray{T}} = Base.fill!(A{length(dims)}(undef, dims...), zero(T)) @inline (::Type{A})(oi::ZeroInitializer, dims...) where {T, N, A <: AbstractArray{T,N}} = Base.fill!(A(undef, dims...), zero(T)) @inline (::Type{A})(oi::OneInitializer{T}, dims::Dims{N}) where {T, N, A <: AbstractArray} = Base.fill!(A{T,N}(undef, dims...), oneunit(T)) @inline (::Type{A})(oi::OneInitializer{T}, dims...) where {T, A <: AbstractArray} = Base.fill!(A{T,length(dims)}(undef, dims...), oneunit(T)) @inline (::Type{A})(oi::OneInitializer{T}, dims...) where {T, N, A <: NAbstractArray{N}} = Base.fill!(A{T}(undef, dims...), oneunit(T)) @inline (::Type{A})(oi::OneInitializer, dims...) where {T, A <: AbstractArray{T}} = Base.fill!(A{length(dims)}(undef, dims...), oneunit(T)) @inline (::Type{A})(oi::OneInitializer, dims...) where {T, N, A <: AbstractArray{T,N}} = Base.fill!(A(undef, dims...), oneunit(T)) @inline (::Type{A})(::UndefTypeArrayInitializer{T}, dims::Dims{N}) where {T, N, A <: AbstractArray} = A{T,N}(undef, dims...) @inline (::Type{A})(::UndefTypeArrayInitializer{T}, dims...) where {T, A <: AbstractArray} = A{T,length(dims)}(undef, dims...) @inline (::Type{A})(::UndefTypeArrayInitializer{T}, dims...) where {T, T2, A <: AbstractArray{T2}} = throw(ArgumentError("Tried to initialize $A with a $(UndefTypeArrayInitializer{T})")) @inline (::Type{A})(::UndefTypeArrayInitializer{T}, dims...) where {T, N, A <: NAbstractArray{N} where T2} = A{T}(undef, dims...) abstract type AbstractRandomArrayInitializer{T} <: AbstractArrayInitializer{T} end struct RandomTypeInitializer{T} <: AbstractArrayInitializer{T} end """ randinit Initialize array with random values. ```julia julia> Array{UInt8}(randinit, 5) 5-element Vector{UInt8}: 0x91 0xcb 0xf0 0xa5 0x9e julia> Array(randinit(1:3), 5) 5-element Vector{Int64}: 3 3 2 2 3 julia> ri = randinit(MersenneTwister(1234), Int8) ArrayInitializers.RNGArrayInitializer{Int8, Type{Int8}, MersenneTwister}(Int8, MersenneTwister(1234)) julia> Matrix(ri, 2, 3) 2×3 Matrix{Int8}: -20 75 126 -105 115 -42 ``` """ const randinit = RandomTypeInitializer{Any}() (::RandomTypeInitializer{Any})(::Type{T}) where T = RandomTypeInitializer{T}() @inline (::Type{A})(ri::RandomTypeInitializer{T}, dims::Dims{N}) where {T, N, A <: Array} = rand(T, dims...) @inline (::Type{A})(ri::RandomTypeInitializer{T}, dims...) where {T, A <: Array} = rand(T, dims...) @inline (::Type{A})(ri::RandomTypeInitializer{T}, dims...) where {T, N, A <: NArray{N}} = rand(T, dims...) @inline (::Type{A})(ri::RandomTypeInitializer, dims...) where {T, A <: Array{T}} = rand(T, dims...) @inline (::Type{A})(ri::RandomTypeInitializer, dims...) where {T, N, A <: Array{T,N}} = rand(T, dims...) @inline (::Type{A})(ri::RandomTypeInitializer{T}, dims::Dims{N}) where {T, N, A <: AbstractArray} = rand!(A{T,N}(undef, dims)) @inline (::Type{A})(ri::RandomTypeInitializer{T}, dims...) where {T, A <: AbstractArray} = rand!(A{T,length(dims)}(undef, dims...)) @inline (::Type{A})(ri::RandomTypeInitializer{T}, dims...) where {T, N, A <: NAbstractArray{N}} = rand!(A{T}(undef, dims...)) @inline (::Type{A})(ri::RandomTypeInitializer, dims...) where {T, A <: AbstractArray{T}} = rand!(A{length(dims)}(undef, dims...)) @inline (::Type{A})(ri::RandomTypeInitializer, dims...) where {T, N, A <: AbstractArray{T,N}} = rand!(A(undef, dims...)) struct RandomCollectionInitializer{T,C} <: AbstractArrayInitializer{T} S::C end (::RandomTypeInitializer{Any})(S::C) where C = RandomCollectionInitializer{eltype(C), C}(S) @inline (::Type{A})(ri::RandomCollectionInitializer{T}, dims::Dims{N}) where {T, N, A <: Array} = Base.rand(ri.S, dims...) @inline (::Type{A})(ri::RandomCollectionInitializer{T}, dims...) where {T, A <: Array} = Base.rand(ri.S, dims...) @inline (::Type{A})(ri::RandomCollectionInitializer{T}, dims...) where {T, N, A <: NArray{N}} = Base.rand(ri.S, dims...) @inline (::Type{A})(ri::RandomCollectionInitializer, dims...) where {T, A <: Array{T}} = Base.rand(ri.S, dims...) @inline (::Type{A})(ri::RandomCollectionInitializer, dims...) where {T, N, A <: Array{T,N}} = Base.rand(ri.S, dims...) @inline (::Type{A})(ri::RandomCollectionInitializer{T}, dims::Dims{N}) where {T, N, A <: AbstractArray} = Random.rand!(A{T,N}(undef, dims), ri.S) @inline (::Type{A})(ri::RandomCollectionInitializer{T}, dims...) where {T, A <: AbstractArray} = Random.rand!(A{T,length(dims)}(undef, dims...), ri.S) @inline (::Type{A})(ri::RandomCollectionInitializer{T}, dims...) where {T, N, A <: NAbstractArray{N}} = Random.rand!(A{T}(undef, dims...), ri.S) @inline (::Type{A})(ri::RandomCollectionInitializer, dims...) where {T, A <: AbstractArray{T}} = Random.rand!(A{length(dims)}(undef, dims...), ri.S) @inline (::Type{A})(ri::RandomCollectionInitializer, dims...) where {T, N, A <: AbstractArray{T,N}} = Random.rand!(A(undef, dims...), ri.S) struct RNGArrayInitializer{T, C, RNG} <: AbstractArrayInitializer{T} S::C rng::RNG end (::RandomTypeInitializer{Any})(rng::RNG, S::C) where {RNG, C} = RNGArrayInitializer{eltype(C), C, RNG}(S, rng) (::RandomTypeInitializer{Any})(rng::RNG, T::Type{TY}) where {RNG, TY} = RNGArrayInitializer{T, Type{TY}, RNG}(T, rng) @inline (::Type{A})(ri::RNGArrayInitializer{T}, dims::Dims{N}) where {T, N, A <: Array} = Base.rand(ri.rng, ri.S, dims...) @inline (::Type{A})(ri::RNGArrayInitializer{T}, dims...) where {T, A <: Array} = Base.rand(ri.rng, ri.S, dims...) @inline (::Type{A})(ri::RNGArrayInitializer{T}, dims...) where {T, N, A <: NArray{N}} = Base.rand(ri.rng, ri.S, dims...) @inline (::Type{A})(ri::RNGArrayInitializer, dims...) where {T, A <: Array{T}} = Base.rand(ri.rng, ri.S, dims...) @inline (::Type{A})(ri::RNGArrayInitializer, dims...) where {T, N, A <: Array{T,N}} = Base.rand(ri.rng, ri.S, dims...) @inline (::Type{A})(ri::RNGArrayInitializer{T}, dims::Dims{N}) where {T, N, A <: AbstractArray} = Random.rand!(ri.rng, A{T,N}(undef, dims), ri.S) @inline (::Type{A})(ri::RNGArrayInitializer{T}, dims...) where {T, A <: AbstractArray} = Random.rand!(ri.rng, A{T,length(dims)}(undef, dims...), ri.S) @inline (::Type{A})(ri::RNGArrayInitializer{T}, dims...) where {T, N, A <: NAbstractArray{N}} = Random.rand!(ri.rng, A{T}(undef, dims...), ri.S) @inline (::Type{A})(ri::RNGArrayInitializer, dims...) where {T, A <: AbstractArray{T}} = Random.rand!(ri.rng, A{length(dims)}(undef, dims...), ri.S) @inline (::Type{A})(ri::RNGArrayInitializer, dims...) where {T, N, A <: AbstractArray{T,N}} = Random.rand!(ri.rng, A(undef, dims...), ri.S) """ SizedArrayInitializer(initializer, dims) `Array` initializer with dimensions. Construct using `Base.reshape` ```julia julia> twos = init(2) ArrayInitializers.FillArrayInitializer{Int64}(2) julia> twos_3x5 = reshape(twos, 3, 5) ArrayInitializers.SizedArrayInitializer{Int64, ArrayInitializers.FillArrayInitializer{Int64}, Tuple{Int64, Int64}}(ArrayInitializers.FillArrayInitializer{Int64}(2), (3, 5)) julia> Array(twos_3x5) 3×5 Matrix{Int64}: 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 ``` """ struct SizedArrayInitializer{T, I <: AbstractArrayInitializer{T}, D} <: AbstractArrayInitializer{T} initializer::I dims::D end Base.reshape(aai::AbstractArrayInitializer{T}, dims) where T = SizedArrayInitializer(aai, dims) Base.reshape(aai::AbstractArrayInitializer{T}, dims...) where T = SizedArrayInitializer(aai, dims) @inline (::Type{A})(si::SizedArrayInitializer) where {A <: AbstractArray} = A(si.initializer, si.dims...) end
ArrayInitializers
https://github.com/mkitti/ArrayInitializers.jl.git
[ "MIT" ]
0.1.0
b3603370187989e1e57d512450f6e0016c838289
code
4799
using ArrayInitializers using ArrayInitializers: fill! using OffsetArrays using Random using Test @testset "ArrayInitializers.jl" begin # FillArrayInitializer fives = init(5) @test Array(fives, 3) == Base.fill!(Vector{Int}(undef, 3), 5) @test Array(fives, 3) |> typeof == Vector{Int} @test Array{Float64}(fives, 3) == Base.fill!(Vector{Float64}(undef, 3), 5.0) @test typeof(Array{Float64}(fives, 3)) == Vector{Float64} @test Array{Any}(fives, 3) == Base.fill!(Vector{Float64}(undef, 3), 5.0) @test typeof(Array{Any}(fives, 3)) == Vector{Any} @test Vector(fives, 9) == Base.fill!(Vector{Int}(undef, 9), 5) @test typeof(Vector(fives, 9)) == Vector{Int} @test Matrix(fives, 3, 6) == Base.fill!(Matrix{Int}(undef, 3, 6), 5) @test typeof(Matrix(fives, 3, 6)) == Matrix{Int} @test fives(3, 6, 9) == Base.fill!(Array{Int}(undef, 3, 6, 9), 5) @test typeof(fives(3, 6, 9)) == Array{Int, 3} @test OffsetArray(fives, 5:9, 2:3) == Base.fill!(OffsetArray{Int}(undef, 5:9, 2:3), 5) @test OffsetArray(fives, 5:9, 2:3) |> typeof == OffsetMatrix{Int, Matrix{Int}} @test OffsetMatrix(fives, 5:9, 2:3) == Base.fill!(OffsetArray{Int}(undef, 5:9, 2:3), 5) @test OffsetMatrix(fives, 5:9, 2:3) |> typeof == OffsetMatrix{Int, Matrix{Int}} @test OffsetMatrix{Float64}(fives, 5:9, 2:3) == Base.fill!(OffsetArray{Float64}(undef, 5:9, 2:3), 5) @test OffsetVector(fives, 5:9) |> typeof == OffsetVector{Int, Vector{Int}} # fill! alias @test Array(fill!(3), 5) == Base.fill!(Vector{Int}(undef, 5), 3) @test Array(fill!(3.5), 5) == Base.fill!(Vector{Float64}(undef, 5), 3.5) # ZeroInitializer @test Array{Int}(zeroinit, 5) == zeros(Int, 5) @test Array(zeroinit(Int), 5) == zeros(Int, 5) @test Matrix(zeroinit(Int), 5, 3) == zeros(Int, 5, 3) @test Matrix{Float64}(zeroinit(Int), 5, 3) == zeros(Float64, 5, 3) @test Matrix{Float64}(zeroinit(Int), 5, 3) |> typeof == Matrix{Float64} @test Array{Float64}(zeroinit(Int), 3, 2, 1) == zeros(Float64, 3, 2, 1) @test Array{Float64}(zeroinit(Int), 3, 2, 1) |> typeof == Array{Float64, 3} @test OffsetVector{Rational}(zeroinit, 2:5) == Base.fill!(OffsetVector{Rational}(undef, 2:5), 0) @test OffsetVector{Rational}(zeroinit, 2:5) |> typeof == OffsetVector{Rational, Vector{Rational}} # OneInitializer @test Array{Int}(oneinit, 5) == ones(Int, 5) @test Array(oneinit(Int), 5) == ones(Int, 5) @test Matrix(oneinit(Int), 5, 3) == ones(Int, 5, 3) @test Matrix{Float64}(oneinit(Int), 5, 3) == ones(Float64, 5, 3) @test Matrix{Float64}(oneinit(Int), 5, 3) |> typeof == Matrix{Float64} @test Array{Float64}(oneinit(Int), 3, 2, 1) == ones(Float64, 3, 2, 1) @test Array{Float64}(oneinit(Int), 3, 2, 1) |> typeof == Array{Float64, 3} @test OffsetVector{Number}(oneinit, 2:5) == Base.fill!(OffsetVector{Number}(undef, 2:5), 1) @test OffsetVector{Number}(oneinit, 2:5) |> typeof == OffsetVector{Number, Vector{Number}} # UndefTypeArrayInitializer A = Array(undeftype(Int), 5) @test typeof(A) == Vector{Int} @test size(A) == (5,) B = Vector(undeftype(Float64), 9) @test typeof(B) == Vector{Float64} @test size(B) == (9,) C = Matrix(undeftype(Float64), 9, 6) @test typeof(C) == Matrix{Float64} @test size(C) == (9,6) @test_throws ArgumentError Array{Int}(undeftype(Float64), 3, 6) @test_throws MethodError Matrix{Int}(undeftype(Float64), 3, 6) D = OffsetMatrix(undeftype(Int), 1:3, 2:5) @test size(D) == (3,4) @test typeof(D) == OffsetMatrix{Int, Matrix{Int}} # RandomTypeInitializer E = Array{Int}(randinit, 3, 5) @test size(E) == (3,5) @test typeof(E) == Matrix{Int} F = Array(randinit(Float64), 7, 9) @test size(F) == (7,9) @test typeof(F) == Matrix{Float64} # RandomCollectionInitializer G = Array(randinit(1:10), 8, 2) @test size(G) == (8,2) @test typeof(G) == Matrix{Int} # SizedArrayInitializer szinit = reshape(fives, 3, 8) H = Array(szinit) @test size(H) == (3,8) @test typeof(H) == Matrix{Int} @test all(==(5), H) I = OffsetArray(szinit) @test size(I) == (3,8) @test typeof(I) == OffsetMatrix{Int, Matrix{Int}} @test all(==(5), I) offset_sz_init = reshape(randinit(1:10), 2:5, 8:9) J = OffsetArray(offset_sz_init) @test size(J) == (4, 2) @test typeof(I) == OffsetMatrix{Int, Matrix{Int}} @test all(in(1:10), J) # RNGArrayInitializer ri = randinit(MersenneTwister(1234), 3:5) K = Array(ri, 2, 3) @test size(K) == (2,3) @test typeof(K) == Matrix{Int} @test all(in(3:5), K) ri = randinit(MersenneTwister(1234), Float64) L = Array(ri, 2, 3) @test size(L) == (2,3) @test typeof(L) == Matrix{Float64} end
ArrayInitializers
https://github.com/mkitti/ArrayInitializers.jl.git
[ "MIT" ]
0.1.0
b3603370187989e1e57d512450f6e0016c838289
docs
1423
# ArrayInitializers.jl [![Stable](https://img.shields.io/badge/docs-stable-blue.svg)](https://mkitti.github.io/ArrayInitializers.jl/stable/) [![Dev](https://img.shields.io/badge/docs-dev-blue.svg)](https://mkitti.github.io/ArrayInitializers.jl/dev/) [![Build Status](https://github.com/mkitti/ArrayInitializers.jl/actions/workflows/CI.yml/badge.svg?branch=main)](https://github.com/mkitti/ArrayInitializers.jl/actions/workflows/CI.yml?query=branch%3Amain) Create array initializers and allocate arrays without curly braces in Julia. The initializer instances can be passed as the first argument of an `AbstractArray` constructor to initialize the array. If the initializer is typed, the element type of the `AbstractArray` constructor is optional. Compatible with `OffsetArrays` and other subtypes of Julia arrays that implement `Base.fill!`. ```julia julia> using ArrayInitializers julia> fives = init(5) ArrayInitializers.FillArrayInitializer{Int64}(5) julia> Array(fives, 3) 3-element Vector{Int64}: 5 5 5 julia> Vector(fives, 3) 3-element Vector{Any}: 5 5 5 julia> Array{Float64}(fives, 3) 3-element Vector{Float64}: 5.0 5.0 5.0 julia> Array(oneinit(Int), 5) 5-element Vector{Int64}: 1 1 1 1 1 julia> Array(zeroinit(Float64), 5) 5-element Vector{Float64}: 0.0 0.0 0.0 0.0 0.0 julia> Array(undeftype(Rational), 3, 2) 3×2 Matrix{Rational}: #undef #undef #undef #undef #undef #undef ```
ArrayInitializers
https://github.com/mkitti/ArrayInitializers.jl.git
[ "MIT" ]
0.1.0
b3603370187989e1e57d512450f6e0016c838289
docs
219
```@meta CurrentModule = ArrayInitializers ``` # ArrayInitializers Documentation for [ArrayInitializers](https://github.com/mkitti/ArrayInitializers.jl). ```@index ``` ```@autodocs Modules = [ArrayInitializers] ```
ArrayInitializers
https://github.com/mkitti/ArrayInitializers.jl.git
[ "MIT" ]
0.3.8
07af26e8d08c211ef85918f3e25d4c0990d20d70
code
243
module AccurateArithmetic include("EFT.jl") using .EFT export two_sum, two_prod include("Summation.jl") using .Summation export sum_naive, sum_kbn, sum_oro, sum_mixed export dot_naive, dot_oro, dot_mixed include("Test.jl") end # module
AccurateArithmetic
https://github.com/JuliaMath/AccurateArithmetic.jl.git
[ "MIT" ]
0.3.8
07af26e8d08c211ef85918f3e25d4c0990d20d70
code
127
module EFT export two_sum, fast_two_sum, two_prod using VectorizationBase: ifelse, AbstractSIMD include("errorfree.jl") end
AccurateArithmetic
https://github.com/JuliaMath/AccurateArithmetic.jl.git
[ "MIT" ]
0.3.8
07af26e8d08c211ef85918f3e25d4c0990d20d70
code
4948
module Summation export sum_naive, sum_kbn, sum_oro, sum_mixed export dot_naive, dot_oro, dot_mixed import VectorizationBase using VectorizationBase: Vec, vload, vsum, vzero, AbstractSIMD, MM fptype(::Type{V}) where {W, T, V <: AbstractSIMD{W, T}} = T @inline f64(x::Number) = convert(Float64, x) using ..EFT: two_sum, fast_two_sum, two_prod include("accumulators/sum.jl") include("accumulators/dot.jl") include("accumulators/compSum.jl") include("accumulators/compDot.jl") include("accumulators/mixedSum.jl") include("accumulators/mixedDot.jl") # T. Ogita, S. Rump and S. Oishi, "Accurate sum and dot product", # SIAM Journal on Scientific Computing, 6(26), 2005. # DOI: 10.1137/030601818 @generated function accumulate(x::NTuple{A, AbstractArray{T}}, accType::F, rem_handling = Val(:scalar), ::Val{Ushift} = Val(2), ::Val{Prefetch} = Val(0), ) where {F, A, T <: Union{Float32,Float64}, Ushift, Prefetch} @assert 0 ≤ Ushift < 6 U = 1 << Ushift W, shift = VectorizationBase.pick_vector_width_shift(T) WU = W * U V = Vec{Int(W),T} quote $(Expr(:meta,:inline)) px = VectorizationBase.zstridedpointer.(x) N = length(first(x)) Base.Cartesian.@nexprs $U u -> begin acc_u = accType($V) end Nshift = N >> $(shift + Ushift) offset = MM{$(Int(W))}(0) for n in 1:Nshift if $Prefetch > 0 # VectorizationBase.prefetch.(px.+offset.+$(Prefetch*WT), Val(3), Val(0)) VectorizationBase.prefetch0.(px, offset + $(Prefetch*W)) end Base.Cartesian.@nexprs $U u -> begin xi = vload.(px, tuple(tuple(offset))) # vload expects the index to be wrapped in a tuple, and broadcasting strips one layer add!(acc_u, xi...) offset += $W end end rem = N & $(WU-1) for n in 1:(rem >> $shift) xi = vload.(px, tuple(tuple(offset))) add!(acc_1, xi...) offset += $W end if $rem_handling <: Val{:mask} rem &= $(W-1) if rem > 0 mask = VectorizationBase.mask($W, rem) xi = vload.(px, tuple(tuple(offset)), mask) add!(acc_1, xi...) end end Base.Cartesian.@nexprs $(U-1) u -> begin add!(acc_1, acc_{u+1}) end acc = sum(acc_1) if $rem_handling <: Val{:scalar} _offset = VectorizationBase.data(offset) while _offset < N _offset += 1 Base.Cartesian.@nexprs $A a -> begin @inbounds xi_a = getindex(x[a], _offset) end Base.Cartesian.@ncall $A add! acc xi end end sum(acc) end end # Default values for unrolling @inline default_ushift(::SumAcc) = Val(3) @inline default_ushift(::CompSumAcc) = Val(2) @inline default_ushift(::MixedSumAcc) = Val(3) @inline default_ushift(::DotAcc) = Val(3) @inline default_ushift(::CompDotAcc) = Val(2) @inline default_ushift(::MixedDotAcc) = Val(3) # dispatch # either default_ushift(x, acc) # or default_ushift((x,), acc) @inline default_ushift(x::AbstractArray, acc) = default_ushift(acc(eltype(x))) @inline default_ushift(x::NTuple, acc) = default_ushift(first(x), acc) # Default values for cache prefetching @inline default_prefetch(::SumAcc) = Val(0) @inline default_prefetch(::CompSumAcc) = Val(35) @inline default_prefetch(::MixedSumAcc) = Val(0) @inline default_prefetch(::DotAcc) = Val(0) @inline default_prefetch(::CompDotAcc) = Val(20) @inline default_prefetch(::MixedDotAcc) = Val(0) # dispatch # either default_prefetch(x, acc) # or default_prefetch((x,), acc) @inline default_prefetch(x::AbstractArray, acc) = default_prefetch(acc(eltype(x))) @inline default_prefetch(x::NTuple, acc) = default_prefetch(first(x), acc) @inline _sum(x, acc) = if length(x) < 500 # no cache prefetching for small vectors accumulate((x,), acc, Val(:scalar), default_ushift(x, acc), Val(0)) else accumulate((x,), acc, Val(:scalar), default_ushift(x, acc), default_prefetch(x, acc)) end sum_naive(x) = _sum(x, sumAcc) sum_kbn(x) = _sum(x, compSumAcc(fast_two_sum)) sum_oro(x) = _sum(x, compSumAcc(two_sum)) sum_mixed(x) = _sum(x, mixedSumAcc) @inline _dot(x, y, acc) = if length(x) < 500 # no cache prefetching for small vectors accumulate((x,y), acc, Val(:scalar), default_ushift(x, acc), Val(0)) else accumulate((x,y), acc, Val(:scalar), default_ushift(x, acc), default_prefetch(x, acc)) end dot_naive(x, y) = _dot(x, y, dotAcc) dot_oro(x, y) = _dot(x, y, compDotAcc) dot_mixed(x, y) = _dot(x, y, mixedDotAcc) end
AccurateArithmetic
https://github.com/JuliaMath/AccurateArithmetic.jl.git
[ "MIT" ]
0.3.8
07af26e8d08c211ef85918f3e25d4c0990d20d70
code
3140
module Test export generate_dot, generate_sum using LinearAlgebra, Random using ..EFT: two_prod """ (x, y, d, c) = generate_dot(n, c) Generate two Float64 vectors whose dot product is ill-conditioned. Inputs: n -- vectors size c -- target condition number (must be >1) rng -- (pseudo-)random number generator Results: x, y -- vectors of size n d -- accurate dot product, rounded to nearest c -- actual condition number of the dot product """ function generate_dot(n, c::T; rng=Random.GLOBAL_RNG) where {T} generate(c, 100, "dot product") do c1 generate_dot_(n, T(c1), rng) end end """ (x, s, c) = generate_sum(n, c) Generate a Float64 vectors whose sum is ill-conditioned. Inputs: n -- vectors size c -- target condition number (must be >1) rng -- (pseudo-)random number generator Results: x -- vector of size n s -- accurate sum, rounded to nearest c -- actual condition number of the sum """ function generate_sum(n, c::T; rng=Random.GLOBAL_RNG) where {T} generate(c, 10, "sum") do c1 generate_sum_(n, T(c1), rng) end end function generate(f, c, cmin, title) c1 = c c = max(c, cmin) for i in 1:100 res = f(c1) c_ = last(res) # println("$i -> $c1 \t $c_") if c_ > 3*c c1 = max(1.01, 0.8*c1) elseif c_ < c/3 c1 *= 1.1 else return res end end @error "Could not generate $title with requested condition number" end function generate_dot_(n, c::T, rng) where {T} R = Rational{BigInt} # Initialization x = zeros(T, n) y = zeros(T, n) # First half of the vectors: # random numbers within a large exponent range n2 = div(n, 2) b = log2(c) e = rand(rng, n2) .* b/2 e[1] = b/2 + 1 # Make sure exponents b/2 e[n2] = 0 # and 0 actually occur for i in 1:n2 x[i] = (2*rand(rng, T)-1) * 2^(e[i]) y[i] = (2*rand(rng, T)-1) * 2^(e[i]) end # Second half of the vectors such that # (*) log2( dot (x[1:i], y[1:i]) ) decreases from b/2 to 0 δe = -b/(2*(n-n2-1)) e = b/2:δe:0 for i in eachindex(e) # Random x[i] cx = (2*rand(rng)-1) * 2^(e[i]) x[i+n2] = cx # y[i] chosen according to (*) cy = (2*rand(rng)-1) * 2^(e[i]) y[i+n2] = (cy - T(dot(R.(x), R.(y)))) / cx end # Random permutation of x and y perm = randperm(rng, n) X = x[perm] Y = y[perm] # Dot product, rounded to nearest d = T(dot(R.(X), R.(Y))) # Actual condition number c_ = 2 * dot(abs.(X), abs.(Y)) / abs(d) (X,Y,d,c_) end function generate_sum_(n, c::T, rng) where {T} R = Rational{BigInt} (x, y, _, _) = generate_dot_(n÷2, c, rng) z = (two_prod.(x, y) |> Iterators.flatten |> collect) # Complete if necessary if length(z) < n push!(z, rand(rng)) end z = shuffle(z) # Sum, rounded to nearest s = T(sum(R.(z))) # Actual condition number c_ = sum(abs.(z)) / abs(s) (z, s, c_) end end
AccurateArithmetic
https://github.com/JuliaMath/AccurateArithmetic.jl.git
[ "MIT" ]
0.3.8
07af26e8d08c211ef85918f3e25d4c0990d20d70
code
1337
@inline function two_inv(b::T) where {T} hi = inv(b) lo = fma(-hi, b, one(T)) lo /= b return hi, lo end @inline function two_div(a::T, b::T) where {T} hi = a / b lo = fma(-hi, b, a) lo /= b return hi, lo end @inline function two_sqrt(a::T) where {T} hi = sqrt(a) lo = fma(-hi, hi, a) lo /= 2 lo /= hi return hi, lo end """ ad_minus_bc(a, b, c, d) Computes the determinant of a 2x2 matrix. """ function ad_minus_bc(a::T, b::T, c::T, d::T) where {T} adhi, adlo = two_prod(a,d) bchi, bclo = two_prod(b,c) return four_sum(adhi, adlo, -bchi, -bclo) end #= "Concerning the division, the elementary rounding error is generally not a floating point number, so it cannot be computed exactly. Hence we cannot expect to obtain an error free transformation for the xdivision. ... This means that the computed approximation is as good as we can expect in the working precision." -- http://perso.ens-lyon.fr/nicolas.louvet/LaLo05.pdf While the sqrt algorithm is not strictly an errorfree transformation, it is known to be reliable and is recommended for general use. "Augmented precision square roots, 2-D norms and discussion on correctly reounding xsqrt(x^2 + y^2)" by Nicolas Brisebarre, Mioara Joldes, Erik Martin-Dorel, Hean-Michel Muller, Peter Kornerup =#
AccurateArithmetic
https://github.com/JuliaMath/AccurateArithmetic.jl.git
[ "MIT" ]
0.3.8
07af26e8d08c211ef85918f3e25d4c0990d20d70
code
9665
""" two_sum(a, b) Computes `hi = fl(a+b)` and `lo = err(a+b)`, using the algorithm by D. E. Knuth, "The Art of Computer Programming: Seminumerical Algorithms", 1969. This algorithm does not use any branch. See also `fast_two_sum` for an alternative algorithm which branches but does fewer arithmetic operations. """ @inline function two_sum(a::T, b::T) where {T} @fastmath hi = a + b v = hi - a lo = (a - (hi - v)) + (b - v) return hi, lo end """ fast_two_sum(a, b) Computes `hi = fl(a+b)` and `lo = err(a+b)`, using the algorithm by T. J. Dekker, "A Floating-Point Technique for Extending the Available Precision", 1971 Despite its name, this algorithm may not be as fast as expected on all hardware architectures because it branches. See also `two_sum` for an alternative algorithm which performs more arithmetic operations, but does not branch. """ @inline function fast_two_sum(a::T, b::T) where T <: Real x = a + b if abs(a) < abs(b) (a_,b_) = (b,a) else (a_,b_) = (a,b) end z = x - a_ e = b_ - z x, e end @inline function fast_two_sum(a::T, b::T) where T <: AbstractSIMD x = a + b t = abs(a) < abs(b) a_ = ifelse(t, b, a) b_ = ifelse(t, a, b) z = x - a_ e = b_ - z x, e end """ three_sum(a, b, c) Computes `hi = fl(a+b+c)` and `md = err(a+b+c), lo = err(md)`. """ function three_sum(a::T,b::T,c::T) where {T} s, t = two_sum(b, c) hi, u = two_sum(a, s) md, lo = two_sum(u, t) hi, md = two_hilo_sum(hi, md) return hi, md, lo end """ two_sum(a, b, c) Computes `hi = fl(a+b+c)` and `lo = err(a+b+c)`. """ function two_sum(a::T,b::T,c::T) where {T} s, t = two_sum(b, c) hi, u = two_sum(a, s) lo = u + t hi, lo = two_hilo_sum(hi, lo) return hi, lo end """ four_sum(a, b, c, d) Computes `s1 = fl(a+b+c+d)` and `s2 = err(a+b+c+d), s3 = err(himd), s4 = err(lomd)`. - Unchecked Precondition: !(isinf(a) | isinf(b) | isinf(c) | isinf(d)) """ function four_sum(a::T,b::T,c::T,d::T) where {T} t0, t1 = two_sum(a, b) t2, t3 = two_sum(c, d) hi, t4 = two_sum(t0, t2) t5, lo = two_sum(t1, t3) hm, ml = two_sum(t4, t5) ml, lo = two_hilo_sum(ml, lo) hm, ml = two_hilo_sum(hm, ml) hi, hm = two_hilo_sum(hi,hm) return hi, hm, ml, lo end """ three_sum(a, b, c, d) Computes `hi = fl(a+b+c+d)` and `md = err(a+b+c+d), lo = err(md)`. """ function three_sum(a::T,b::T,c::T,d::T) where {T} t0, t1 = two_sum(a , b) t0, t2 = two_sum(t0, c) hi, t3 = two_sum(t0, d) t0, t1 = two_sum(t1, t2) hm, t2 = two_sum(t0, t3) # here, t0 >= t3 ml = t1 + t2 return hi, hm, ml end """ two_sum(a, b, c, d) Computes `hi = fl(a+b+c+d)` and `lo = err(a+b+c+d)`. """ function two_sum(a::T,b::T,c::T,d::T) where {T} t0, t1 = two_sum(a , b) t0, t2 = two_sum(t0, c) hi, t3 = two_sum(t0, d) t0, t1 = two_sum(t1, t2) lo = t0 + t3 return hi, lo end """ five_sum(a, b, c, d, e) Computes `s = fl(a+b+c+d+e)` and `e1 = err(a+b+c+d), e2 = err(e1), e3 = err(e2), e4 = err(e3)`. """ function five_sum(v::T, w::T, x::T, y::T, z::T) where {T} t0, t4 = two_sum(y, z) t0, t3 = two_sum(x, t0) t0, t2 = two_sum(w, t0) a, t1 = two_sum(v, t0) t0, t3 = two_sum(t3, t4) t0, t2 = two_sum(t2, t0) b, t1 = two_sum(t1, t0) t0, t2 = two_sum(t2, t3) c, t1 = two_sum(t1, t0) d, e = two_sum(t1, t2) return a, b, c, d, e end """ two_diff(a, b) Computes `s = fl(a-b)` and `e = err(a-b)`. """ @inline function two_diff(a::T, b::T) where {T} hi = a - b a1 = hi + b b1 = hi - a1 lo = (a - a1) - (b + b1) return hi, lo end """ three_diff(a, b, c) Computes `s = fl(a-b-c)` and `e1 = err(a-b-c), e2 = err(e1)`. """ function three_diff(a::T,b::T,c::T) where {T} s, t = two_diff(-b, c) x, u = two_sum(a, s) y, z = two_sum(u, t) x, y = two_hilo_sum(x, y) return x, y, z end """ four_diff(a, b, c, d) Computes `hi = fl(a-b-c-d)` and `hm = err(a-b-c-d), ml = err(hm), lo = err(ml)`. """ function four_diff(a::T,b::T,c::T,d::T) where {T} t0, t1 = two_diff(a , b) t0, t2 = two_diff(t0, c) hi, t3 = two_diff(t0, d) t0, t1 = two_sum(t1, t2) hm, t2 = two_sum(t0, t3) # here, t0 >= t3 ml, lo = two_sum(t1, t2) return hi, hm, ml, lo end """ two_square(a) Computes `s = fl(a*a)` and `e = err(a*a)`. """ @inline function two_square(a::T) where {T} p = a * a e = fma(a, a, -p) p, e end """ two_prod(a, b) Computes `s = fl(a*b)` and `e = err(a*b)`. """ @inline function two_prod(a::T, b::T) where {T} p = a * b e = fma(a, b, -p) p, e end """ three_prod(a, b, c) Computes `hi = fl(a*b*c)` and `md = err(a*b*c), lo = err(md)`. """ function three_prod(a::T, b::T, c::T) where {T} abhi, ablo = two_prod(a, b) hi, abhiclo = two_prod(abhi, c) ablochi, abloclo = two_prod(ablo, c) md, lo, tmp = three_sum(ablochi, abhiclo, abloclo) return hi, md, lo end #= three_fma algorithm from Sylvie Boldo and Jean-Michel Muller Some Functions Computable with a Fused-mac =# """ three_fma(a, b, c) Computes `s = fl(fma(a,b,c))` and `e1 = err(fma(a,b,c)), e2 = err(e1)`. """ function three_fma(a::T, b::T, c::T) where {T} x = fma(a, b, c) y, z = two_prod(a, b) t, z = two_sum(c, z) t, u = two_sum(y, t) y = ((t - x) + u) y, z = two_hilo_sum(y, z) return x, y, z end # with arguments sorted by magnitude """ two_hilo_sum(a, b) *unchecked* requirement `|a| ≥ |b|` Computes `hi = fl(a+b)` and `lo = err(a+b)`. """ @inline function two_hilo_sum(a::T, b::T) where {T} hi = a + b lo = b - (hi - a) return hi, lo end """ two_lohi_sum(a, b) *unchecked* requirement `|b| ≥ |a|` Computes `hi = fl(a+b)` and `lo = err(a+b)`. """ @inline function two_lohi_sum(a::T, b::T) where {T} hi = b + a lo = a - (hi - b) return hi, lo end """ two_hilo_diff(a, b) *unchecked* requirement `|a| ≥ |b|` Computes `hi = fl(a-b)` and `lo = err(a-b)`. """ @inline function two_hilo_diff(a::T, b::T) where {T} hi = a - b lo = (a - hi) - b hi, lo end """ two_lohi_diff(a, b) *unchecked* requirement `|b| ≥ |a|` Computes `hi = fl(a-b)` and `lo = err(a-b)`. """ @inline function two_lohi_diff(a::T, b::T) where {T} hi = b - a lo = (b - hi) - a hi, lo end """ three_hilo_sum(a, b, c) *unchecked* requirement `|a| ≥ |b| ≥ |c|` Computes `x = fl(a+b+c)` and `y = err(a+b+c), z = err(y)`. """ function three_hilo_sum(a::T,b::T,c::T) where {T} s, t = two_hilo_sum(b, c) x, u = two_hilo_sum(a, s) y, z = two_hilo_sum(u, t) x, y = two_hilo_sum(x, y) return x, y, z end """ three_lohi_sum(a, b, c) *unchecked* requirement `|c| ≥ |b| ≥ |a|` Computes `x = fl(a+b+c)` and `y = err(a+b+c), z = err(y)`. """ function three_lohi_sum(a::T,b::T,c::T) where {T} s, t = two_hilo_sum(b, a) x, u = two_hilo_sum(c, s) y, z = two_hilo_sum(u, t) x, y = two_hilo_sum(x, y) return x, y, z end """ three_hilo_diff(a, b, c) *unchecked* requirement `|a| ≥ |b| ≥ |c|` Computes `x = fl(a-b-c)` and `y = err(a-b-c), z = err(y)`. """ function three_hilo_diff(a::T,b::T,c::T) where {T} s, t = two_hilo_diff(b, -c) x, u = two_hilo_sum(a, s) y, z = two_hilo_sum(u, t) x, y = two_hilo_sum(x, y) return x, y, z end """ three_lohi_diff(a, b, c) *unchecked* requirement `|c| ≥ |b| ≥ |a|` Computes `x = fl(a-b-c)` and `y = err(a-b-c), z = err(y)`. """ function three_lohi_diff(c::T,b::T,a::T) where {T} s, t = two_hilo_diff(b, -c) x, u = two_hilo_sum(a, s) y, z = two_hilo_sum(u, t) x, y = two_hilo_sum(x, y) return x, y, z end """ four_hilo_sum(a, b, c, d) *unchecked* requirement `|a| ≥ |b| ≥ |c| ≥ |d|` Computes `hi = fl(a+b+c+d)` and `hm = err(a+b+c+d), ml = err(hm), lo = err(ml)`. """ function four_hilo_sum(a::T,b::T,c::T,d::T) where {T} t0, t1 = two_hilo_sum(a , b) t0, t2 = two_hilo_sum(t0, c) hi, t3 = two_hilo_sum(t0, d) t0, t1 = two_hilo_sum(t1, t2) hm, t2 = two_hilo_sum(t0, t3) # here, t0 >= t3 ml, lo = two_hilo_sum(t1, t2) return hi, hm, ml, lo end """ four_lohi_sum(a, b, c, d) *unchecked* requirement `|d| ≥ |c| ≥ |b| ≥ |a|` Computes `hi = fl(a+b+c+d)` and `hm = err(a+b+c+d), ml = err(hm), lo = err(ml)`. """ function four_lohi_sum(d::T,c::T,b::T,a::T) where {T} t0, t1 = two_hilo_sum(a , b) t0, t2 = two_hilo_sum(t0, c) hi, t3 = two_hilo_sum(t0, d) t0, t1 = two_hilo_sum(t1, t2) hm, t2 = two_hilo_sum(t0, t3) ml, lo = two_hilo_sum(t1, t2) return hi, hm, ml, lo end """ four_hilo_diff(a, b, c, d) *unchecked* requirement `|a| ≥ |b| ≥ |c| ≥ |d|` Computes `hi = fl(a-b-c-d)` and `hm = err(a-b-c-d), ml = err(hm), lo = err(ml)`. """ function four_hilo_diff(a::T,b::T,c::T,d::T) where {T} t0, t1 = two_hilo_diff(a, b) t0, t2 = two_hilo_diff(t0, c) hi, t3 = two_hilo_diff(t0, d) t0, t1 = two_hilo_sum(t1, t2) hm, t2 = two_hilo_sum(t0, t3) # here, t0 >= t3 ml, lo = two_hilo_sum(t1, t2) return hi, hm, ml, lo end """ four_hilo_diff(a, b, c, d) *unchecked* requirement `|d| ≥ |c| ≥ |b| ≥ |a|` Computes `hi = fl(a-b-c-d)` and `hm = err(a-b-c-d), ml = err(hm), lo = err(ml)`. """ function four_lohi_diff(d::T,c::T,b::T,a::T) where {T} t0, t1 = two_hilo_diff(a, b) t0, t2 = two_hilo_diff(t0, c) hi, t3 = two_hilo_diff(t0, d) t0, t1 = two_hilo_sum(t1, t2) hm, t2 = two_hilo_sum(t0, t3) # here, t0 >= t3 ml, lo = two_hilo_sum(t1, t2) return hi, hm, ml, lo end
AccurateArithmetic
https://github.com/JuliaMath/AccurateArithmetic.jl.git
[ "MIT" ]
0.3.8
07af26e8d08c211ef85918f3e25d4c0990d20d70
code
1316
@inline function signbit(x::Tuple{T,T}) where T<:AbstractFloat return signbit(x[1]) end @inline function (-)(x::Tuple{T,T}) where T<:AbstractFloat return -x[1], -x[2] end @inline function abs(x::Tuple{T,T}) where T<:AbstractFloat return signbit(x[1]) ? -x : x end @inline function flipsign(x::Tuple{T,T}, y::Tuple{T,T}) where T<:AbstractFloat return signbit(y[1]) ? -x : x end @inline function copysign(x::Tuple{T,T}, y::Tuple{T,T}) where T<:AbstractFloat return signbit(y[1]) ? -abs(x) : abs(x) end function (+)(x::Tuple{T,T}, y::Tuple{T,T}) where T<:AbstractFloat hi, lo = two_sum(x[1], y[1]) lohi, lolo = two_sum(x[2], y[2]) lohi += lo hi, lo = fast_two_sum(hi, lohi) lolo += lo hi, lo = fast_two_sum(hi, lolo) return hi, lo end function (-)(x::Tuple{T,T}, y::Tuple{T,T}) where T<:AbstractFloat hi, lo = two_diff(x[1], y[1]) lohi, lolo = two_diff(x[2], y[2]) lohi += lo hi, lo = fast_two_sum(hi, lohi) lolo += lo hi, lo = fast_two_sum(hi, lolo) return hi, lo end function (*)(x::Tuple{T,T}, y::Tuple{T,T}) where T<:AbstractFloat lo = two_prod(x[2], y[2]) hi = two_prod(x[1], y[2]) hilo = lo + hi hi = two_prod(x[2], y[1]) hilo = hilo + hi hi = two_prod(x[1], y[1]) hilo = hilo + hi return hilo end
AccurateArithmetic
https://github.com/JuliaMath/AccurateArithmetic.jl.git
[ "MIT" ]
0.3.8
07af26e8d08c211ef85918f3e25d4c0990d20d70
code
729
mutable struct CompDotAcc{T} s :: T e :: T end compDotAcc(T) = CompDotAcc{T}(vzero(T), vzero(T)) @inline function add!(acc::CompDotAcc{T}, x::T, y::T) where {T} p, ep = two_prod(x, y) acc.s, es = two_sum(acc.s, p) @fastmath acc.e += ep + es end @inline function add!(acc::A, x::A) where {A<:CompDotAcc} acc.s, e = two_sum(acc.s, x.s) @fastmath acc.e += x.e + e end @inline function Base.sum(acc::CompDotAcc{T}) where {W, T<:Vec{W}} acc_r = compDotAcc(fptype(T)) acc_r.e = vsum(acc.e) for w in 1:W acc_r.s, ei = two_sum(acc_r.s, acc.s(w)) acc_r.e += ei end acc_r end @inline function Base.sum(acc::CompDotAcc{T}) where {T<:Real} acc.s + acc.e end
AccurateArithmetic
https://github.com/JuliaMath/AccurateArithmetic.jl.git
[ "MIT" ]
0.3.8
07af26e8d08c211ef85918f3e25d4c0990d20d70
code
796
mutable struct CompSumAcc{T, EFT} s :: T e :: T end @inline compSumAcc(EFT) = T->compSumAcc(EFT, T) @inline compSumAcc(EFT, T) = CompSumAcc{T, EFT}(vzero(T), vzero(T)) @inline function add!(acc::CompSumAcc{T, EFT}, x::T) where {T, EFT} acc.s, e = EFT(acc.s, x) @fastmath acc.e += e end @inline function add!(acc::A, x::A) where {A<:CompSumAcc{T, EFT}} where {T, EFT} acc.s, e = EFT(acc.s, x.s) @fastmath acc.e += x.e + e end @inline function Base.sum(acc::CompSumAcc{T, EFT}) where {W, T<:Vec{W}, EFT} acc_r = compSumAcc(EFT, fptype(T)) acc_r.e = vsum(acc.e) for w in 1:W acc_r.s, ei = EFT(acc_r.s, acc.s(w)) acc_r.e += ei end acc_r end @inline function Base.sum(acc::CompSumAcc{T, EFT}) where {T<:Real, EFT} acc.s + acc.e end
AccurateArithmetic
https://github.com/JuliaMath/AccurateArithmetic.jl.git
[ "MIT" ]
0.3.8
07af26e8d08c211ef85918f3e25d4c0990d20d70
code
339
mutable struct DotAcc{T} s :: T end dotAcc(T) = DotAcc{T}(vzero(T)) function add!(acc::DotAcc, x, y) @fastmath acc.s += x * y end function add!(acc::DotAcc{T}, x::DotAcc{T}) where {T} @fastmath acc.s += x.s end Base.sum(acc::DotAcc{T}) where {T<:Vec} = DotAcc(vsum(acc.s)) Base.sum(acc::DotAcc{T}) where {T<:Real} = acc.s
AccurateArithmetic
https://github.com/JuliaMath/AccurateArithmetic.jl.git
[ "MIT" ]
0.3.8
07af26e8d08c211ef85918f3e25d4c0990d20d70
code
510
mutable struct MixedDotAcc{T} s :: T end mixedDotAcc(::Type{Float32}) = MixedDotAcc(Float64(0)) mixedDotAcc(::Type{Vec{N, Float32}}) where {N} = MixedDotAcc(vzero(Vec{N, Float64})) function add!(acc::MixedDotAcc, x, y) @fastmath acc.s += f64(x) * f64(y) end function add!(acc::MixedDotAcc{T}, x::MixedDotAcc{T}) where {T} @fastmath acc.s += x.s end Base.sum(acc::MixedDotAcc{T}) where {T<:Vec} = MixedDotAcc(vsum(acc.s)) Base.sum(acc::MixedDotAcc{T}) where {T<:Real} = acc.s
AccurateArithmetic
https://github.com/JuliaMath/AccurateArithmetic.jl.git
[ "MIT" ]
0.3.8
07af26e8d08c211ef85918f3e25d4c0990d20d70
code
498
mutable struct MixedSumAcc{T} s :: T end mixedSumAcc(::Type{Float32}) = MixedSumAcc(Float64(0)) mixedSumAcc(::Type{Vec{N, Float32}}) where {N} = MixedSumAcc(vzero(Vec{N, Float64})) function add!(acc::MixedSumAcc, x) @fastmath acc.s += f64(x) end function add!(acc::MixedSumAcc{T}, x::MixedSumAcc{T}) where {T} @fastmath acc.s += x.s end Base.sum(acc::MixedSumAcc{T}) where {T<:Vec} = MixedSumAcc(vsum(acc.s)) Base.sum(acc::MixedSumAcc{T}) where {T<:Real} = acc.s
AccurateArithmetic
https://github.com/JuliaMath/AccurateArithmetic.jl.git
[ "MIT" ]
0.3.8
07af26e8d08c211ef85918f3e25d4c0990d20d70
code
329
mutable struct SumAcc{T} s :: T end sumAcc(T) = SumAcc(vzero(T)) function add!(acc::SumAcc, x) @fastmath acc.s += x end function add!(acc::SumAcc{T}, x::SumAcc{T}) where {T} @fastmath acc.s += x.s end Base.sum(acc::SumAcc{T}) where {T<:Vec} = SumAcc(vsum(acc.s)) Base.sum(acc::SumAcc{T}) where {T<:Real} = acc.s
AccurateArithmetic
https://github.com/JuliaMath/AccurateArithmetic.jl.git
[ "MIT" ]
0.3.8
07af26e8d08c211ef85918f3e25d4c0990d20d70
code
2019
println("Loading required packages...") using Plots, JSON function plot_results() println("Generating plots...") for filename in readdir() endswith(filename, ".json") || continue plot_results(replace(filename, ".json" => "")) end end function plot_results(filename) results = JSON.parsefile(filename*".json") if get(results, "type", nothing) == nothing @warn "Badly formatted file: `$filename.json'" return end println("-> $filename") plot_results(Val(Symbol(results["type"])), filename, results) end function plot_results(::Val{:accuracy}, filename, results) title = results["title"] labels = results["labels"] data = results["data"] scatter(title=title, xscale=:log10, yscale=:log10, xlabel="Condition number", ylabel="Relative error") markers = Symbol[:circle, :+, :rect, :x, :utriangle] for i in 1:length(labels) scatter!(Float64.(data[1]), Float64.(data[i+1]), label=labels[i], markershape=markers[i]) end savefig(filename*".pdf") savefig(filename*".svg") end function plot_results(::Val{:ushift}, filename, results) title = results["title"] labels = results["labels"] data = results["data"] p = plot(title=title, xlabel="log2(U)", ylabel="Time [ns/elem]") for i in 1:length(labels) plot!(Float64.(data[1]), Float64.(data[i+1]), label="2^$(Int(round(log2(labels[i])))) elems") end savefig(filename*".pdf") savefig(filename*".svg") end function plot_results(::Val{:performance}, filename, results) title = results["title"] labels = results["labels"] data = results["data"] p = plot(title=title, xscale=:log10, xlabel="Vector size", ylabel="Time [ns/elem]") for i in 1:length(labels) plot!(Float64.(data[1]), Float64.(data[i+1]), label=labels[i]) end savefig(filename*".pdf") savefig(filename*".svg") end
AccurateArithmetic
https://github.com/JuliaMath/AccurateArithmetic.jl.git
[ "MIT" ]
0.3.8
07af26e8d08c211ef85918f3e25d4c0990d20d70
code
11164
import Pkg Pkg.activate(joinpath(@__DIR__, "..")) println("Loading required packages...") using LinearAlgebra, Random, Printf, Statistics using BenchmarkTools, JSON using AccurateArithmetic using AccurateArithmetic.Summation: accumulate, two_sum, fast_two_sum using AccurateArithmetic.Summation: sumAcc, compSumAcc, mixedSumAcc using AccurateArithmetic.Summation: dotAcc, compDotAcc, mixedDotAcc using AccurateArithmetic.Summation: default_ushift using AccurateArithmetic.Test output(x) = @printf "%.2e " x err(val, ref::T) where {T} = min(1, max(eps(T), abs((val-ref)/ref))) FAST_TESTS = false FLOAT_TYPE = Float64 # * Accuracy cond_max(::Type{Float64}) = 1e45 cond_max(::Type{Float32}) = 1f21 function run_accuracy(gen, funs, labels, title, filename) println("-> $title") n = 100 # Vector size c1 = FLOAT_TYPE(2) # Condition number (min) c2 = cond_max(FLOAT_TYPE) # - (max) logstep = 2 # Step for condition number increase (log scale) data = [FLOAT_TYPE[] for _ in 1:(1+length(funs))] c = c1 while c < c2 i = 1 (x, d, C) = gen(rand(n:n+10), c) output(C) push!(data[i], C) for fun in funs i += 1 r = fun(x...) ε = err(r, d) output(ε) push!(data[i], ε) end println() c *= logstep end open(filename*".json", "w") do f JSON.print(f, Dict( :type => :accuracy, :title => title, :labels => labels, :data => data)) end end function run_accuracy() println("Running accuracy tests...") function gen_sum(n, c) (x, d, c) = generate_sum(n, c) ((x,), d, c) end funs = [sum, sum_naive, sum_oro, sum_kbn] labels = ["pairwise", "naive", "oro", "kbn"] if FLOAT_TYPE === Float32 push!(funs, sum_mixed) push!(labels, "mixed") end run_accuracy(gen_sum, funs, labels, "Error of summation algorithms", "sum_accuracy") function gen_dot(n, c) (x, y, d, c) = generate_dot(n, c) ((x, y), d, c) end funs = [dot, dot_naive, dot_oro] labels = ["blas", "naive", "oro"] if FLOAT_TYPE === Float32 push!(funs, dot_mixed) push!(labels, "mixed") end run_accuracy(gen_dot, funs, labels, "Error of dot product algorithms", "dot_accuracy") end # * Optimal u_shift function run_ushift(gen, acc, title, filename) println("-> $title") if FAST_TESTS title *= " [FAST]" sizes = [2^(3*i) for i in 3:4] ushifts = (0,2) BenchmarkTools.DEFAULT_PARAMETERS.evals = 1 BenchmarkTools.DEFAULT_PARAMETERS.seconds = 0.5 else sizes = [2^(3*i) for i in 2:6] ushifts = 0:4 BenchmarkTools.DEFAULT_PARAMETERS.evals = 2 BenchmarkTools.DEFAULT_PARAMETERS.seconds = 5.0 end data = [[] for _ in 1:(1+length(sizes))] for ushift in ushifts i = 1 print(ushift, " ") push!(data[i], ushift) for n in sizes i += 1 x = gen(n) b = @benchmark accumulate($x, $acc, $(Val(:scalar)), $(Val(ushift))) t = minimum(b.times) / n output(t) push!(data[i], t) end println() end open(filename*".json", "w") do f JSON.print(f, Dict( :type => :ushift, :title => title, :labels => sizes, :data => data)) end end function run_ushift() BenchmarkTools.DEFAULT_PARAMETERS.evals = 2 println("Finding optimal ushift...") gen_sum(n) = (rand(FLOAT_TYPE, n),) run_ushift(gen_sum, sumAcc, "Performance of naive summation", "sum_naive_ushift") run_ushift(gen_sum, compSumAcc(two_sum), "Performance of ORO summation", "sum_oro_ushift") run_ushift(gen_sum, compSumAcc(fast_two_sum), "Performance of KBN summation", "sum_kbn_ushift") if FLOAT_TYPE === Float32 run_ushift(gen_sum, mixedSumAcc, "Performance of mixed summation", "sum_mixed_ushift") end gen_dot(n) = (rand(FLOAT_TYPE, n), rand(FLOAT_TYPE, n)) run_ushift(gen_dot, dotAcc, "Performance of naive dot product", "dot_naive_ushift") run_ushift(gen_dot, compDotAcc, "Performance of compensated dot product", "dot_oro_ushift") if FLOAT_TYPE === Float32 run_ushift(gen_dot, mixedDotAcc, "Performance of mixed dot product", "dot_mixed_ushift") end end # * Optimal prefetch function run_prefetch(gen, acc, title, filename) println("-> $title") if FAST_TESTS title *= " [FAST]" sizes = [2^(3*i) for i in (3,5,7)] prefetch = [0, 20, 40] BenchmarkTools.DEFAULT_PARAMETERS.evals = 1 BenchmarkTools.DEFAULT_PARAMETERS.seconds = 0.5 else sizes = [2^(3*i) for i in 2:8] prefetch = 0:4:60 BenchmarkTools.DEFAULT_PARAMETERS.evals = 2 BenchmarkTools.DEFAULT_PARAMETERS.seconds = 5.0 end println(" sizes: $sizes") data = [[] for _ in 1:(1+length(sizes))] for pref in prefetch i = 1 print(pref, " ") push!(data[i], pref) for n in sizes i += 1 x = gen(n) ushift = AccurateArithmetic.Summation.default_ushift(x, acc) b = @benchmark accumulate($x, $acc, $(Val(:scalar)), $ushift, $(Val(pref))) t = minimum(b.times) / n output(t) push!(data[i], t) end println() end open(filename*".json", "w") do f JSON.print(f, Dict( :type => :prefetch, :title => title, :labels => sizes, :data => data)) end end function run_prefetch() BenchmarkTools.DEFAULT_PARAMETERS.evals = 2 println("Finding optimal prefetch...") gen_sum(n) = (rand(FLOAT_TYPE, n),) run_prefetch(gen_sum, sumAcc, "Performance of naive summation", "sum_naive_prefetch") run_prefetch(gen_sum, compSumAcc(two_sum), "Performance of ORO summation", "sum_oro_prefetch") run_prefetch(gen_sum, compSumAcc(fast_two_sum), "Performance of KBN summation", "sum_kbn_prefetch") if FLOAT_TYPE === Float32 run_prefetch(gen_sum, mixedSumAcc, "Performance of mixed summation", "sum_mixed_prefetch") end gen_dot(n) = (rand(FLOAT_TYPE, n), rand(FLOAT_TYPE, n)) run_prefetch(gen_dot, dotAcc, "Performance of naive dot product", "dot_naive_prefetch") run_prefetch(gen_dot, compDotAcc, "Performance of compensated dot product", "dot_oro_prefetch") if FLOAT_TYPE === Float32 run_prefetch(gen_dot, mixedDotAcc, "Performance of mixed dot product", "dot_mixed_prefetch") end end # * Performance comparisons function run_performance(n2, gen, funs, labels, title, filename) println("-> $title") if FAST_TESTS title *= " [FAST]" logstep = 100. BenchmarkTools.DEFAULT_PARAMETERS.evals = 1 BenchmarkTools.DEFAULT_PARAMETERS.seconds = 0.5 else logstep = 1.1 BenchmarkTools.DEFAULT_PARAMETERS.evals = 2 BenchmarkTools.DEFAULT_PARAMETERS.seconds = 5.0 end data = [Float64[] for _ in 1:(1+length(funs))] n = 32 while n < n2 i = 1 x = gen(n) output(n) push!(data[i], n) for fun in funs i += 1 b = @benchmark $fun($(x)...) t = minimum(b.times) / n output(t) push!(data[i], t) end println() N = Int(round(n*logstep)) N = 32*div(N, 32) n = max(N, n+32) end elemsize = sizeof.(eltype.(gen(1))) |> sum open(filename*".json", "w") do f JSON.print(f, Dict( :type => :performance, :title => title, :labels => labels, :elem_size => elemsize, :data => data)) end end function run_performance() println("Running performance tests...") gen_sum(n) = (rand(FLOAT_TYPE, n),) funs = [sum, sum_naive, sum_oro, sum_kbn] labels = ["pairwise", "naive", "oro", "kbn"] if FLOAT_TYPE === Float32 push!(funs, sum_mixed) push!(labels, "mixed") end run_performance(1e8, gen_sum, funs, labels, "Performance of summation implementations", "sum_performance") BLAS.set_num_threads(1) gen_dot(n) = (rand(FLOAT_TYPE, n), rand(FLOAT_TYPE, n)) funs = [dot, dot_naive, dot_oro] labels = ["blas", "naive", "oro"] if FLOAT_TYPE === Float32 push!(funs, dot_mixed) push!(labels, "mixed") end run_performance(3e7, gen_dot, funs, labels, "Performance of dot product implementations", "dot_performance") end # * All tests function run_tests(fast=false, precision=64) global FAST_TESTS = fast global FLOAT_TYPE = if precision==64 Float64 else Float32 end print("Running tests") FAST_TESTS && print(" in FAST mode") println("...\n") run_accuracy() sleep(5) run_ushift() sleep(5) run_prefetch() sleep(5) run_performance() println("Normal end of the performance tests") end if abspath(PROGRAM_FILE) == @__FILE__ fast = get(ARGS, 1, "")=="fast" prec = parse(Int, get(ARGS, 2, "64")) date = open(readline, `git show --no-patch --pretty="%cd" --date="format:%Y-%m-%d.%H%M%S" HEAD`) sha1 = open(readline, `git show --no-patch --pretty="%h" HEAD`) |> String cpu = open(read, `lscpu`) |> String cpu = match(r"Model name:\s*(.*)\s+CPU", cpu)[1] cpu = replace(cpu, r"\(\S+\)" => "") cpu = replace(strip(cpu), r"\s+" => ".") blas = BLAS.vendor() |> String jobname = "$(date)_$(sha1)_$(VERSION)_$(cpu)_$(blas)_F$(prec)" open("jobname", "w") do f write(f, jobname) end open("info.json", "w") do f JSON.print(f, Dict( :job => jobname, :date => date, :sha1 => sha1, :julia => string(VERSION), :cpu => cpu, :blas => blas, :prec => prec)) end println("\nJob name: $jobname") println("\nGit commit: $sha1 ($date)"); run(`git show --no-patch --oneline HEAD`) println("\nJulia version: $VERSION"); println(Base.julia_cmd()) println("\nCPU: $cpu"); run(`lscpu`) println("\nBLAS vendor: $blas") println("\nFP precision: $prec bits") run_tests(fast, prec) end
AccurateArithmetic
https://github.com/JuliaMath/AccurateArithmetic.jl.git
[ "MIT" ]
0.3.8
07af26e8d08c211ef85918f3e25d4c0990d20d70
code
10527
using AccurateArithmetic using Test using AccurateArithmetic.Summation: accumulate using AccurateArithmetic.Summation: sumAcc, compSumAcc, mixedSumAcc using AccurateArithmetic.Summation: dotAcc, compDotAcc, mixedDotAcc using AccurateArithmetic.Test: generate_sum, generate_dot using LinearAlgebra using StableRNGs @testset "AccurateArithmetic" begin rng = StableRNG(42) @testset "Tests" begin @testset "generate_sum" begin @testset "vector length" begin @testset "F64" begin for n in 100:110 let (x, s, c_) = generate_sum(n, 1e10; rng=rng) @test eltype(x) === Float64 @test s isa Float64 @test length(x) == n end end end @testset "F32" begin for n in 100:110 let (x, s, c_) = generate_sum(n, 1f5; rng=rng) @test eltype(x) === Float32 @test s isa Float32 @test length(x) == n end end end end @testset "condition number" begin @testset "F64" begin for c in (1e10, 1e20) let (x, s, c_) = generate_sum(101, c; rng=rng) @test eltype(x) === Float64 @test s isa Float64 @test c/3 < c_ < 3c end end end @testset "F32" begin for c in (1f5, 1f10) let (x, s, c_) = generate_sum(101, c; rng=rng) @test eltype(x) === Float32 @test s isa Float32 @test c/3 < c_ < 3c end end end end end @testset "generate_dot" begin @testset "vector length" begin @testset "F64" begin for n in 100:110 let (x, y, s, c_) = generate_dot(n, 1e10; rng=rng) @test eltype(x) === Float64 @test s isa Float64 @test length(x) == n @test length(y) == n end end end @testset "F32" begin for n in 100:110 let (x, y, s, c_) = generate_dot(n, 1f5; rng=rng) @test eltype(x) === Float32 @test s isa Float32 @test length(x) == n @test length(y) == n end end end end @testset "condition number" begin @testset "F64" begin for c in (1e10, 1e20) let (x, y, s, c_) = generate_dot(101, c; rng=rng) @test s isa Float64 @test c/3 < c_ < 3c end end end @testset "F32" begin for c in (1f5, 1f10) let (x, y, s, c_) = generate_dot(101, c; rng=rng) @test s isa Float32 @test c/3 < c_ < 3c end end end end end end @testset "summation" begin @testset "naive" begin @testset "F64" begin for N in 100:110 x = rand(rng, N) ref = sum(x) @test ref isa Float64 @test ref ≈ sum_naive(x) acc = sumAcc @test ref ≈ accumulate((x,), acc, Val(:scalar), Val(2)) @test ref ≈ accumulate((x,), acc, Val(:mask), Val(2)) end end @testset "F32" begin for N in 100:110 x = rand(rng, Float32, N) ref = sum(x) @test ref isa Float32 @test ref ≈ sum_naive(x) acc = sumAcc @test ref ≈ accumulate((x,), acc, Val(:scalar), Val(2)) @test ref ≈ accumulate((x,), acc, Val(:mask), Val(2)) end end end @testset "compensated" begin @testset "F64" begin for N in 100:110 x, ref, _ = generate_sum(N, 1e10; rng=rng) @test ref isa Float64 @test ref == sum_oro(x) @test ref == sum_kbn(x) acc = compSumAcc(two_sum) @test ref == accumulate((x,), acc, Val(:scalar), Val(2)) @test ref == accumulate((x,), acc, Val(:mask), Val(2)) end end @testset "F32" begin for N in 100:110 x, ref, _ = generate_sum(N, 1f5; rng=rng) @test ref isa Float32 @test ref == sum_oro(x) @test ref == sum_kbn(x) acc = compSumAcc(two_sum) @test ref == accumulate((x,), acc, Val(:scalar), Val(2)) @test ref == accumulate((x,), acc, Val(:mask), Val(2)) end end end @testset "mixed" begin for N in 100:110 # Only test for approximate equality here, since sum_mixed # returns a Float64 whereas the reference value is a Float32 x, ref, _ = generate_sum(N, 1f7; rng=rng) @test ref isa Float32 @test ref ≈ sum_mixed(x) acc = mixedSumAcc @test ref ≈ accumulate((x,), acc, Val(:scalar), Val(2)) @test ref ≈ accumulate((x,), acc, Val(:mask), Val(2)) end end end @testset "dot product" begin @testset "naive" begin @testset "F64" begin for N in 100:110 x = rand(rng, N) y = rand(rng, N) ref = dot(x, y) @test ref isa Float64 @test ref ≈ dot_naive(x, y) acc = dotAcc @test ref ≈ accumulate((x,y), acc, Val(:scalar), Val(2)) @test ref ≈ accumulate((x,y), acc, Val(:mask), Val(2)) end end @testset "F32" begin for N in 100:110 x = rand(rng, Float32, N) y = rand(rng, Float32, N) ref = dot(x, y) @test ref isa Float32 @test ref ≈ dot_naive(x, y) acc = dotAcc @test ref ≈ accumulate((x,y), acc, Val(:scalar), Val(2)) @test ref ≈ accumulate((x,y), acc, Val(:mask), Val(2)) end end end @testset "compensated" begin @testset "F64" begin for N in 100:110 x, y, ref, _ = generate_dot(N, 1e10; rng=rng) @test ref isa Float64 @test ref == dot_oro(x, y) acc = compDotAcc @test ref == accumulate((x,y), acc, Val(:scalar), Val(2)) @test ref == accumulate((x,y), acc, Val(:mask), Val(2)) end end @testset "F32" begin for N in 100:110 x, y, ref, _ = generate_dot(N, 1f5; rng=rng) @test ref isa Float32 @test ref == dot_oro(x, y) acc = compDotAcc @test ref == accumulate((x,y), acc, Val(:scalar), Val(2)) @test ref == accumulate((x,y), acc, Val(:mask), Val(2)) end end end @testset "mixed" begin for N in 100:110 # Only test for approximate equality here, since dot_mixed # returns a Float64 whereas the reference value is a Float32 x, y, ref, _ = generate_dot(N, 1f7; rng=rng) @test ref isa Float32 @test ref ≈ dot_mixed(x, y) acc = mixedDotAcc @test ref ≈ accumulate((x,y), acc, Val(:scalar), Val(2)) @test ref ≈ accumulate((x,y), acc, Val(:mask), Val(2)) end end end end using BenchmarkTools BLAS.set_num_threads(1) BenchmarkTools.DEFAULT_PARAMETERS.evals = 1000 println("\nsize 32") x = rand(32) y = rand(32) print(" sum_kbn "); @btime sum_kbn($x) print(" sum_oro "); @btime sum_oro($x) print(" sum_naive"); @btime sum_naive($x) print(" sum "); @btime sum($x) println() print(" dot_oro "); @btime dot_oro($x, $y) print(" dot_naive"); @btime dot_naive($x, $y) print(" dot "); @btime dot($x, $y) println("\nsize 10_000") x = rand(10_000) y = rand(10_000) print(" sum_kbn "); @btime sum_kbn($x) print(" sum_oro "); @btime sum_oro($x) print(" sum_naive"); @btime sum_naive($x) print(" sum "); @btime sum($x) println() print(" dot_oro "); @btime dot_oro($x, $y) print(" dot_naive"); @btime dot_naive($x, $y) print(" dot "); @btime dot($x, $y) BenchmarkTools.DEFAULT_PARAMETERS.evals = 10 println("\nsize 1_000_000") x = rand(1_000_000) y = rand(1_000_000) print(" sum_kbn "); @btime sum_kbn($x) print(" sum_oro "); @btime sum_oro($x) print(" sum_naive"); @btime sum_naive($x) print(" sum "); @btime sum($x) println() print(" dot_oro "); @btime dot_oro($x, $y) print(" dot_naive"); @btime dot_naive($x, $y) print(" dot "); @btime dot($x, $y) println("\nsize 100_000_000") x = rand(100_000_000) y = rand(100_000_000) print(" sum_kbn "); @btime sum_kbn($x) print(" sum_oro "); @btime sum_oro($x) print(" sum_naive"); @btime sum_naive($x) print(" sum "); @btime sum($x) println() print(" dot_oro "); @btime dot_oro($x, $y) print(" dot_naive"); @btime dot_naive($x, $y) print(" dot "); @btime dot($x, $y)
AccurateArithmetic
https://github.com/JuliaMath/AccurateArithmetic.jl.git
[ "MIT" ]
0.3.8
07af26e8d08c211ef85918f3e25d4c0990d20d70
docs
8717
# AccurateArithmetic.jl ## Floating point math with error-free, faithful, and compensated transforms. [travis-img]: https://travis-ci.org/JuliaMath/AccurateArithmetic.jl.svg?branch=master [travis-url]: https://travis-ci.org/JuliaMath/AccurateArithmetic.jl [pkgeval-img]: https://juliaci.github.io/NanosoldierReports/pkgeval_badges/A/AccurateArithmetic.svg [pkgeval-url]: https://juliaci.github.io/NanosoldierReports/pkgeval_badges/report.html ![Lifecycle](https://img.shields.io/badge/lifecycle-maturing-blue.svg) [![Build Status][travis-img]][travis-url] [![PkgEval][pkgeval-img]][pkgeval-url] ### Error-free and faithful transforms `AccurateArithmetic.jl` provides a set of error-free transforms (EFTs), which allow getting not only the rounded result of a floating-point computation, but also the accompanying rounding error: ```julia julia> using AccurateArithmetic # WARNING: a is not really 1/10, as this value is not representable as a Float64 # (and similarly for b) julia> (a, b) = (0.1, 0.2) julia> (s, e) = AccurateArithmetic.two_sum(a, b) (0.30000000000000004, -2.7755575615628914e-17) ``` In the above example, `s` is the result of the floating-point addition `0.1+0.2`, rounded to the nearest representable floating-point number, exactly what you would get from a standard addition. `e` is the rounding error associated to `s`. In other words, it is guaranteed that a + b = s + e, in a strict mathematical sense (i.e. when the `+` operate on real numbers and are not rounded). Similar EFTs are provided for the binary subtraction (`two_diff`) and multiplication (`two_prod`). Some operations of higher arity are also supported, such as `three_sum`, `four_sum` or `three_prod`. ### Compensated algorithms EFTs can be leveraged to build "compensated algorithms", which compute a result as if the basic algorithm had been run using a higher precision. ```julia # By construction, this vector sums to 1 julia> x = 5000 |> N->randn(N) .* exp.(10 .* randn(N)) |> x->[x;-x;1.0] |> x->x[sortperm(rand(length(x)))]; julia> sum(big.(x)) 1.0 # But the standard summation algorithms computes this sum very inaccurately # (not even the sign is correct) julia> sum(x) -8.0 # Compensated summation algorithms should compute this more accurately julia> using AccurateArithmetic # Algorithm by Ogita, Rump and Oishi julia> sum_oro(x) 1.0000000000000084 # Algorithm by Kahan, Babuska and Neumaier julia> sum_kbn(x) 1.0000000000000084 ``` ![](test/figs/sum_accuracy.svg) ![](test/figs/dot_accuracy.svg) In the graphs above, we see the relative error vary as a function of the condition number, in a log-log scale. Errors lower than ϵ are arbitrarily set to ϵ; conversely, when the relative error is more than 100% (i.e no digit is correctly computed anymore), the error is capped there in order to avoid affecting the scale of the graph too much. What we see on the left is that the pairwise summation algorithm (as implemented in Base.sum) starts losing accuracy as soon as the condition number increases, computing only noise when the condition number exceeds 1/ϵ≃10¹⁶. The same goes for the naive summation algorithm. In contrast, both compensated algorithms (Kahan–Babuska–Neumaier and Ogita–Rump–Oishi) still accurately compute the result at this point, and start losing accuracy there, computing meaningless results when the condition nuber reaches 1/ϵ²≃10³². In effect these (simply) compensated algorithms produce the same results as if a naive summation had been performed with twice the working precision (128 bits in this case), and then rounded to 64-bit floats. The same comments can be made for the dot product implementations shown on the right. Uncompensated algorithms, as implemented in `AccurateArithmetic.dot_naive` or `Base.dot` (which internally calls BLAS in this case) exhibit typical loss of accuracy. In contrast, the implementation of Ogita, Rump & Oishi's compentated algorithm effectively doubles the working precision. <br/> Performancewise, compensated algorithms perform a lot better than alternatives such as arbitrary precision (`BigFloat`) or rational arithmetic (`Rational`) : ```julia julia> using BenchmarkTools julia> length(x) 10001 julia> @btime sum($x) 1.320 μs (0 allocations: 0 bytes) -8.0 julia> @btime sum_naive($x) 1.026 μs (0 allocations: 0 bytes) -1.121325337906356 julia> @btime sum_oro($x) 3.348 μs (0 allocations: 0 bytes) 1.0000000000000084 julia> @btime sum_kbn($x) 3.870 μs (0 allocations: 0 bytes) 1.0000000000000084 julia> @btime sum($(big.(x))) 437.495 μs (2 allocations: 112 bytes) 1.0 julia> @btime sum($(Rational{BigInt}.(x))) 10.894 ms (259917 allocations: 4.76 MiB) 1//1 ``` However, compensated algorithms perform a larger number of elementary operations than their naive floating-point counterparts. As such, they usually perform worse. However, leveraging the power of modern architectures via vectorization, the slow down can be kept to a small value. ![](test/figs/sum_performance.svg) ![](test/figs/dot_performance.svg) Benchmarks presented in the above graphs were obtained in an Intel® Xeon® Gold 6128 CPU @ 3.40GHz. The time spent in the summation (renormalized per element) is plotted against the vector size. What we see with the standard summation is that, once vectors start having significant sizes (say, more than a few thousands of elements), the implementation is memory bound (as expected of a typical BLAS1 operation). Which is why we see significant decreases in the performance when the vector can’t fit into the L1, L2 or L3 cache. On this AVX512-enabled system, the Kahan–Babuska–Neumaier implementation tends to be a little more efficient than the Ogita–Rump–Oishi algorithm (this would generally the opposite for AVX2 systems). When implemented with a suitable unrolling level and cache prefetching, these implementations are CPU-bound when vectors fit inside the L1 or L2 cache. However, when vectors are too large to fit into the L2 cache, the implementation becomes memory-bound again (on this system), which means we get the same performance as the standard summation. Again, the same could be said as well for dot product calculations (graph on the right), where the implementations from `AccurateArithmetic.jl` compete against MKL's dot product. In other words, the improved accuracy is free for sufficiently large vectors. For smaller vectors, the accuracy comes with a slow-down by a factor of approximately 3 in the L2 cache. ### Mixed-precision algorithms When working with single-precision floating-point numbers (`Float32`), it is far more efficient to rely on the possibility to internally use double-precision numbers in places where more accuracy is needed. Such mixed-precision implementations are also provided in this package for convenience: ``` # Generate an ill-conditioned sum of 100 Float32 numbers # (requested condition number 1f10) julia> (x, _, _) = generate_sum(100, 1f10); # Reference result julia> sum(big.(x)) -0.784491270104194171608469332568347454071044921875 # Standard algorithm -> 100% error julia> sum(x) 42.25f0 # Mixed-precision implementation julia> sum_mixed(x) -0.7844913924050729 ``` Mixed-precision summation implementations should perform approximately as well as naive ones: ``` julia> x = rand(Float32, 10_000); julia> @btime sum($x) 1.273 μs (0 allocations: 0 bytes) 5022.952f0 julia> using AccurateArithmetic julia> @btime sum_mixed($x) 1.109 μs (0 allocations: 0 bytes) 5022.952363848686 ``` Depending on the system, mixed-precision implementations of the dot product might not be as competitive (especially on AVX2 systems; this is much better on AVX512 CPUs), but are still faster than compensated algorithms: ``` julia> x = rand(Float32, 10_000); julia> y = rand(Float32, 10_000); julia> using LinearAlgebra julia> @btime dot($x, $y) 1.178 μs (0 allocations: 0 bytes) 2521.3572f0 julia> using AccurateArithmetic julia> @btime dot_mixed($x, $y) 2.027 μs (0 allocations: 0 bytes) 2521.356998107087 julia> @btime dot_oro($x, $y) 3.402 μs (0 allocations: 0 bytes) 2521.357f0 ``` ### Tests The graphs above can be reproduced using the `test/perftests.jl` script in this repository. Before running them, be aware that it takes a few hours to generate the performance graphs, during which the benchmark machine should be as low-loaded as possible in order to avoid perturbing performance measurements. ### References - C. Elrod and F. Févotte, "Accurate and Efficient Sums and Dot Products in Julia". [preprint](https://hal.archives-ouvertes.fr/hal-02265534) - T. Ogita, S. Rump and S. Oishi, "Accurate sum and dot product", SIAM Journal on Scientific Computing, 6(26), 2005. DOI: 10.1137/030601818
AccurateArithmetic
https://github.com/JuliaMath/AccurateArithmetic.jl.git
[ "MIT" ]
0.3.8
07af26e8d08c211ef85918f3e25d4c0990d20d70
docs
859
## References ``` [Building Blocks] M. Joldes, V. Popescu, and J.-M. Muller. Tight and rigourous error bounds for basic building blocks of double-word arithmetic 2016, working paper. ``` &nbsp; &nbsp; &rarr; https://hal.archives-ouvertes.fr/hal-013515 ``` [Multiple Precision] V. Popescu. Towards fast and certified multiple-precision librairies. 2017, thesis. ``` &nbsp; &nbsp; &rarr; https://hal.archives-ouvertes.fr/tel-01534090/document ``` [Faithful Floats] M. Lange and S.M. Rump. Faithfully Rounded Floating-point Computations 2017, preprint. ``` &nbsp; &nbsp; &rarr; http://www.ti3.tu-harburg.de/paper/rump/LaRu2017b.pdf ``` J.-M. Muller, N. Brisebarre, F. de Dinechin, C.-P. Jeannerod, V. Lefevre, G. Melquiond, N. Revol, D. Stehle, and S. Torres. Handbook of Floating-Point Arithmetic Birkhauser Boston, 2010, book ``` &nbsp;
AccurateArithmetic
https://github.com/JuliaMath/AccurateArithmetic.jl.git
[ "MIT" ]
1.4.0
ef85ef8b9985f2f9245fad4bea24e6a8b85f4dd8
code
456
using Documenter using PolynomialGTM makedocs( sitename = "PolynomialGTM", format = Documenter.HTML(), modules = [PolynomialGTM], pages = [ "Quick Start" => "index.md", "Docstrings" => "docstrings.md" ] ) deploydocs( target = "build", repo = "github.com/cadojo/PolynomialGTM.jl.git", branch = "gh-pages", devbranch = "main", versions = ["stable" => "v^", "manual", "v#.#", "v#.#.#"], )
PolynomialGTM
https://github.com/cadojo/PolynomialGTM.jl.git
[ "MIT" ]
1.4.0
ef85ef8b9985f2f9245fad4bea24e6a8b85f4dd8
code
7724
""" Provides unofficial implementations (in the form of `ODESystem` and `ODEFunction` instances) of a polynomial approximation for longitudinal aircraft dynamics. Specifically, these models approximate NASA's Generic Transport Model – a radio-controlled, sub-scale model aircraft which is used flight control research. These publicly available equations were published by [Chakraborty et al](https://www.sciencedirect.com/science/article/abs/pii/S0967066110002595). # Extended help ## License $(LICENSE) ## Exports $(EXPORTS) ## Imports $(IMPORTS) """ module PolynomialGTM using Memoize using Symbolics using LinearAlgebra using ModelingToolkit using DocStringExtensions @template (FUNCTIONS, METHODS, MACROS) = """ $(SIGNATURES) $(DOCSTRING) """ @template (TYPES, CONSTANTS) = """ $(TYPEDEF) $(DOCSTRING) """ export GTM, GTMFunction """ NASA's Generic Transport Model can be approximated (near select flight conditions) as a polynomial model. Here, `GTM` is a `ModelingToolkit.ODESystem` which provides publicly available polynomial approximations for GTM longitudinal flight dynamics. # Extended Help ## Initial Conditions The default initial conditions are one trim condition. Two trim conditions for these polynomial-approximated dynamics are shown below. ```julia trim₁ = [[29.6, deg2rad(9), 0.0, deg2rad(9)], [deg2rad(0.68), 12.7]] trim₂ = [[25.0, deg2rad(18), 0.0, deg2rad(18)], [deg2rad(-7.2), 59]] ``` ## Usage ```julia model = GTM() ``` ## References: - [Chakraborty et al](https://www.sciencedirect.com/science/article/abs/pii/S0967066110002595) - [Joe Carpinelli](https://github.com/cadojo/Replicated-ROA-Analysis) """ @memoize function GTM(; stm=false, name=:GTM) # First, let's define the necessary parameters # and variables for modeling the longitudinal # dynamics for NASA's Generic Transport Model @parameters t δₑ δₜ @variables V(t) α(t) q(t) θ(t) δ = Differential(t) x = [V, α, q, θ] p = [δₑ, δₜ] # Great! Now, we'll need to hard-code in the polynomial # approximations the longitudinal dynamics. eqs = [ # Damn Unicode and its variable character font width!!! δ(V) ~ 1.233e-8 * V^4 * q^2 + 4.853e-9 * α^3 * δₜ^3 + 3.705e-5 * V^3 * α * q - 2.184e-6 * V^3 * q^2 + 2.203e-2 * V^2 * α^3 - 2.836e-6 * α^3 * δₜ^2 + 3.885e-7 * α^2 * δₜ^3 - 1.069e-6 * V^3 * q - 4.517e-2 * V^2 * α^2 - 2.140e-3 * V^2 * α * δₑ - 3.282e-3 * V^2 * α * q - 8.901e-4 * V^2 * δₑ^2 + 9.677e-5 * V^2 * q^2 - 2.037e-4 * α^3 * δₜ - 2.270e-4 * α^2 * δₜ^2 - 2.912e-8 * α * δₜ^3 + 1.591e-3 * V^2 * α - 4.077e-4 * V^2 * δₑ + 9.475e-5 * V^2 * q - 1.637 * α^3 - 1.631e-2 * α^2 * δₜ + 4.903 * α^2 * θ - 4.903 * α * θ^2 + 1.702e-5 * α * δₜ^2 - 7.771e-7 * δₜ^3 + 1.634 * θ^3 - 4.319e-4 * V^2 - 2.142e-1 * α^2 + 1.222e-3 * α * δₜ + 4.541e-4 * δₜ^2 + 9.823 * α + 3.261e-2 * δₜ - 9.807 * θ + 4.282e-1, δ(α) ~ -3.709e-11 * V^5 * q^2 + 6.869e-11 * V * α^3 * δₜ^3 + 7.957e-10 * V^4 * α * q + 9.860e-9 * V^4 * q^2 + 1.694e-5 * V^3 * α^3 - 4.015e-8 * V * α^3 * δₜ^2 - 7.722e-12 * V * α^2 * δₜ^3 - 6.086e-9 * α^3 * δₜ^3 - 2.013e-8 * V^4 * q - 5.180e-5 * V^3 * α^2 - 2.720e-6 * V^3 * α * δₑ - 1.410e-7 * V^3 * α * q + 7.352e-7 * V^3 * δₑ^2 - 8.736e-7 * V^3 * q^2 - 1.501e-3 * V^2 * α^3 - 2.883e-6 * V * α^3 * δₜ + 4.513e-9 * V * α^2 * δₜ^2 - 4.121e-10 * V * α * δₜ^3 + 3.557e-6 * α^3 * δₜ^2 + 6.841e-10 * α^2 * δₜ^3 + 4.151e-5 * V^3 * α + 3.648e-6 * V^3 * δₑ + 3.566e-6 * V^3 * q + 6.246e-6 * V^2 * α * q + 4.589e-3 * V^2 * α^2 + 2.410e-74 * V^2 * α * δₑ - 6.514e-5 * V^2 * δₑ^2 + 2.580e-5 * V^2 * q^2 - 3.787e-5 * V * α^3 + 3.241e-7 * V * α^2 * δₜ + 2.409e-7 * V * α * δₜ^2 + 1.544e-11 * V * δₜ^3 + 2.554e-4 * α^3 * δₜ - 3.998e-7 * α^2 * δₜ^2 + 3.651e-8 * α * δₜ^3 + 4.716e-7 * V^3 - 3.677e-3 * V^2 * α - 3.231e-4 * V^2 * δₑ - 1.579e-4 * V^2 * q + 2.605e-3 * V * α^2 + 1.730e-5 * V * α * δₜ - 5.201e-3 * V * α * θ - 9.026e-9 * V * δₜ^2 + 2.601e-3 * V * θ^2 + 3.355e-3 * α^3 - 2.872e-5 * α^2 * δₜ - 2.134e-5 * α * δₜ^2 - 1.368e-9 * δₜ^3 - 4.178e-5 * V^2 + 2.272e-4 * V * α - 6.483e-7 * V * δₜ - 2.308e-1 * α^2 - 1.532e-3 * α * δₜ + 4.608e-1 * α * θ - 2.304e-1 * θ^2 + 7.997e-7 * δₜ^2 - 5.210e-3 * V - 2.013e-2 * α + 5.744e-5 * δₜ + q + 4.616e-1, δ(q) ~ -6.573e-9 * V^5 * q^3 + 1.747e-6 * V^4 * q^3 - 1.548e-4 * V^3 * q^3 - 3.569e-3 * V^2 * α^3 + 4.571e-3 * V^2 * q^3 + 4.953e-5 * V^3 * q + 9.596e-3 * V^2 * α^2 + 2.049e-2 * V^2 * α * δₑ - 2.431e-2 * V^2 * α - 3.063e-2 * V^2 * δₑ - 4.388e-3 * V^2 * q - 2.594e-7 * δₜ^3 + 2.461e-3 * V^2 + 1.516e-4 * δₜ^2 + 1.089e-2 * δₜ + 1.430e-1, δ(θ) ~ q ] # Let's set some default values, so we can plug this system directly # into `ODEProblem` and perform quick analysis. Note that what we're # doing here is setting one equilibrium position as a default # initial condition if no arguments are provided to `ODEProblem`! defaults = Dict( V => 29.6, α => deg2rad(9), q => 0.0, θ => deg2rad(0), δₑ => deg2rad(0.68), δₜ => 12.7 ) # If state transition matrix dynamics are enabled, append # the dynamics to our equations of motion, append the # state variables to our state vector, and append default # values (the identity matrix) to the defaults field! if stm @variables (Φ(t))[1:4, 1:4] Φ = Symbolics.scalarize(Φ) A = Symbolics.jacobian(map(el -> el.rhs, eqs), x) LHS = map(δ, Φ) RHS = map(simplify, A * Φ) eqs = vcat(eqs, [LHS[i] ~ RHS[i] for i in 1:length(LHS)]) for ϕ in vec(Φ) push!(x, ϕ) end for (ϕ, i) in zip(vec(Φ), vec(Matrix(I(4)))) defaults[ϕ] = i end end # Model name if string(name) == "GTM" && stm modelname = Symbol("GTMWithSTM") else modelname = name end # Make the model and return return ODESystem(eqs, t, x, p; defaults=defaults, name=Symbol(modelname)) end """ Returns a `DifferentialEquations`-compatible `ODEFunction` for GTM dynamics. The `stm`, and `name` keyword arguments are passed to `GTM`. All other keyword arguments are passed directly to `ODEFunction`. # Extended Help ## Usage Note that this `ODEFunction` output has several methods, including an in-place method! Function signatures follow `ModelingToolkit` and `DifferentialEquations` conventions. ```julia f = GTMFunction() let u = randn(4), p = randn(2), t = rand() f(u,p,t) end ``` """ @memoize function GTMFunction(; stm=false, name=:GTM, kwargs...) defaults = (; jac=true) options = merge(defaults, kwargs) model = complete(GTM(; stm=stm, name=name); split=false) return ODEFunction(model, unknowns(model), ModelingToolkit.parameters(model); options...) end end # module
PolynomialGTM
https://github.com/cadojo/PolynomialGTM.jl.git
[ "MIT" ]
1.4.0
ef85ef8b9985f2f9245fad4bea24e6a8b85f4dd8
code
799
module PolynomialGTMTests using PolynomialGTM, Test @testset "Constructors" begin try GTM() @test true catch e @test throw(e) end try GTM(; stm=true) @test true catch e @test throw(e) end end @testset "Functions" begin try f = GTMFunction() f(randn(4), randn(2), NaN) @test true catch e @test throw(e) end try f = GTMFunction(; stm=true) f(randn(20), randn(2), NaN) @test true catch e @test throw(e) end end @testset "Regression" begin f = GTMFunction() let u = [0.1, 0.2, 0.3, 0.4], p = [0.1, 0.1], t = NaN @test f(u, p, t) ≈ [-1.522331443175375, 0.7478311441572367, 0.14403160747471513, 0.3] end end end
PolynomialGTM
https://github.com/cadojo/PolynomialGTM.jl.git
[ "MIT" ]
1.4.0
ef85ef8b9985f2f9245fad4bea24e6a8b85f4dd8
docs
1982
[![Tests](https://github.com/cadojo/PolynomialGTM.jl/workflows/UnitTests/badge.svg)](https://github.com/cadojo/PolynomialGTM.jl/actions?query=workflow%3AUnitTests) [![Docs](https://github.com/cadojo/PolynomialGTM.jl/workflows/Documentation/badge.svg)](https://cadojo.github.io/PolynomialGTM.jl) # PolynomialGTM.jl _An unofficial implementation of publicly available approximated polynomial models for NASA's Generic Transport Model aircraft._ ## Overview NASA Langley has developed a scaled-down radio-controlled aircraft called the Generic Transport Model (GTM). This model is physically similar to a typical commercial plane (think 737, etc.), and is used for off-nominal flight control research. [Chakraborty et al](https://www.sciencedirect.com/science/article/abs/pii/S0967066110002595) published a polynomial approximation for longitudinal GTM dynamics (near select flight conditions). Joe Carpinelli (me!) wrote these dynamics in Python, and [replicated and summarized](https://github.com/cadojo/Replicated-ROA-Analysis) parts of Chakraborty et al's region of attraction analysis for the polynomial-approximated GTM dynamics. This Julia package extends [ModelingToolkit.jl](https://github.com/SciML/ModelingToolkit.jl) to provide this polynomial-approximated model of longitudinal GTM flight dynamics to the Julia ecosystem! ## Installation You can install `PolynomialGTM` from Julia's General Registry using `Pkg`, or `]install PolynomialGTM` in Julia's REPL. ```julia import Pkg Pkg.install("PolynomialGTM") ``` ## Usage See the [ModelingToolkit documentation](http://mtk.sciml.ai/stable/) for more usage examples! ```julia using PolynomialGTM, ModelingToolkit # Get the model model = GTM() # Get the equations equations(model) # Print the equations to LaTeX using Latexify latexify(equations(model)) # Get an `ODEFunction` which implements the dynamics f = GTMFunction() # Execute the function let x = randn(4), p = randn(2), t = rand() f(x,p,t) end ```
PolynomialGTM
https://github.com/cadojo/PolynomialGTM.jl.git
[ "MIT" ]
1.4.0
ef85ef8b9985f2f9245fad4bea24e6a8b85f4dd8
docs
119
# Documentation _All docstrings!_ ```@autodocs Modules = [ PolynomialGTM ] Order = [:module, :type, :function] ```
PolynomialGTM
https://github.com/cadojo/PolynomialGTM.jl.git
[ "MIT" ]
1.4.0
ef85ef8b9985f2f9245fad4bea24e6a8b85f4dd8
docs
2403
# PolynomialGTM.jl _Longitudinal flight dynamics, approximated with polynomials!_ ## Overview This is an unofficial implementation of publicly available approximated polynomial models for NASA's Generic Transport Model aircraft. NASA Langley has developed a scaled-down radio-controlled aircraft called the Generic Transport Model (GTM). This model is physically similar to a typical commercial plane (think 737, etc.), and is used for off-nominal flight control research. [Chakraborty et al](https://www.sciencedirect.com/science/article/abs/pii/S0967066110002595) published a polynomial approximation for longitudinal GTM dynamics (near select flight conditions). Joe Carpinelli (me!) wrote these dynamics in Python, and [replicated and summarized](https://github.com/cadojo/Replicated-ROA-Analysis) parts of Chakraborty et al's region of attraction analysis for the polynomial-approximated GTM dynamics. This Julia package extends [ModelingToolkit.jl](https://github.com/SciML/ModelingToolkit.jl) to provide this polynomial-approximated model of longitudinal GTM flight dynamics to the Julia ecosystem! ## Usage This package exports two functions: `GTM`, and `GTMFunction`. The former constructs an `ODESystem`, and the latter returns an `ODEFunction` associated with the model produced by `GTM`. Both functions cache all outputs using `Memoize.jl`. Some `PolynomialGTM`-specific documentation can be found here, and in the [docstrings](docstrings.md). See the [ModelingToolkit documentation](http://mtk.sciml.ai/stable/) for more usage examples! ### Installation and Startup You can install this package from Julia's [General](https://juliahub.com) package registry with `import Pkg; Pkg.install("PolynomialGTM")`, or with `julia> ]install PolynomialGTM` in Julia's REPL. ```@repl main using PolynomialGTM ``` ### Constructing the Model Generally, you'll just want to call `GTM` with no arguments. ```@repl main model = GTM() ``` If you'd like to append state transition matrix dynamics, use `stm=true`. This appends state transition matrix dynamics to the model's equations of motion. ```@repl main model = GTM(; stm=true) ``` ### Constructing the Vector Field As before, you can optionally append state transition matrix dynamics using `stm=true`. ```@repl main f = GTMFunction() # or, with `stm=true` let u = randn(4), p = randn(2), t = rand() f(u,p,t) end ```
PolynomialGTM
https://github.com/cadojo/PolynomialGTM.jl.git
[ "BSD-3-Clause" ]
0.1.5
e57b9894ce0f47f3b346d4a375203084085e90c7
code
836
module StackedHourglass using CUDA, Knet const KnetMoment = Knet.Ops20.BNMoments using Knet.CuArrays #standard Library using Distributed, Random using Images, MAT, FFTW #exported types export HG2 #exported methods export subpixel, set_testing, save_hourglass, load_hourglass, features abstract type NN end; const HGType = Union{KnetArray{Float32,4},AutoGrad.Result{KnetArray{Float32,4}},Array{Float32,4},AutoGrad.Result{Array{Float32,4}}} const PType1 = Union{Param{KnetArray{Float32,1}},Param{Array{Float32,1}}} const PType4 = Union{Param{KnetArray{Float32,4}},Param{Array{Float32,4}}} include("residual.jl") include("hourglass.jl") include("cuda_resizing.jl") include("gaussian_pyramids.jl") include("cuda_files.jl") include("helper.jl") include("load.jl") include("subpixel.jl") include("image_preprocessing.jl") end
StackedHourglass
https://github.com/paulmthompson/StackedHourglass.jl.git
[ "BSD-3-Clause" ]
0.1.5
e57b9894ce0f47f3b346d4a375203084085e90c7
code
5631
#adapted from https://stackoverflow.com/questions/51038294/resize-image-using-nearest-neighborhood-with-cuda function _CUDA_resize(pIn,pOut) _CUDA_resize(pIn,pOut,size(pIn,1),size(pIn,2),size(pOut,1),size(pOut,2)) end function _CUDA_resize(pIn,pOut,w_in,h_in,w_out,h_out) index_i = blockDim().y * (blockIdx().y-1) + threadIdx().y index_j = blockDim().x * (blockIdx().x-1) + threadIdx().x stride_i = blockDim().y * gridDim().y stride_j = blockDim().x * gridDim().x for j=index_j:stride_j:h_out for i=index_i:stride_i:w_out jIn = div(j*h_in, h_out) iIn = div(i*w_in, w_out) @inbounds pOut[i,j] = pIn[iIn,jIn] end end return end function CUDA_resize(pIn,pOut) CUDA.@sync @cuda threads=(16,16) _CUDA_resize(pIn,pOut) end function _CUDA_resize4(pIn,pOut,w_in,h_in,w_out,h_out,n) c = blockIdx().y b = blockIdx().x a = threadIdx().x if ((a <= h_out)&&(b <= w_out))&&(c <=n) jIn = div(b*h_in, h_out) iIn = div(a*w_in, w_out) @inbounds pOut[a,b,1,c] = pIn[iIn,jIn,1,c] end return end function _CUDA_resize4(pIn,pOut) _CUDA_resize4(pIn,pOut,size(pIn,1),size(pIn,2),size(pOut,1),size(pOut,2),size(pIn,4)) end function CUDA_resize4(pIn,pOut) numblocks_x = size(pOut,2) numblocks_y = size(pOut,4) CUDA.@sync @cuda threads=256 blocks=(numblocks_x,numblocks_y) _CUDA_resize4(pIn,pOut) end function _CUDA_normalize_images(pIn,meanImg,h_out,w_out,n) index_i = blockDim().y * (blockIdx().y-1) + threadIdx().y index_j = blockDim().x * (blockIdx().x-1) + threadIdx().x stride_i = blockDim().y * gridDim().y stride_j = blockDim().x * gridDim().x for k=1:n for j=index_j:stride_j:h_out for i=index_i:stride_i:w_out @inbounds pIn[i,j,1,k] = pIn[i,j,1,k] / 255 @inbounds pIn[i,j,1,k] = pIn[i,j,1,k] - meanImg[i,j] end end end return end function _CUDA_normalize_images(pIn,meanImg) _CUDA_normalize_images(pIn,meanImg,size(pIn,1),size(pIn,2),size(pIn,4)) end function CUDA_normalize_images(pIn,meanImg) CUDA.@sync @cuda threads=256 _CUDA_normalize_images(pIn,meanImg) end function CUDA_preprocess(pIn,pOut) n = size(pIn,4) w_in=size(pIn,1) h_in=size(pIn,2) w_out=size(pOut,1) h_out=size(pOut,2) CUDA.@sync @cuda threads=(16,16) _CUDA_preprocess(pIn,pOut,w_in,h_in,w_out,h_out,n) end function _CUDA_preprocess(pIn,pOut,w_in,h_in,w_out,h_out,n) index_i = blockDim().y * (blockIdx().y-1) + threadIdx().y index_j = blockDim().x * (blockIdx().x-1) + threadIdx().x stride_i = blockDim().y * gridDim().y stride_j = blockDim().x * gridDim().x for k=1:n for j=index_j:stride_j:h_out for i=index_i:stride_i:w_out jIn = div(j*h_in, h_out) iIn = div(i*w_in, w_out) @inbounds pOut[j,i,1,k] = Float32(pIn[iIn,jIn,1,k]) end end end return end function _CUDA_blur_x(pIn,pOut,w_in,h_in,gauss,n) c = blockIdx().z b = blockIdx().y a = threadIdx().x while (a<=w_in) if ((a <= w_in)&&(b <= h_in))&&(c <=n) temp = 0.0 for yy = 1:9 new_y = yy-5 + a if new_y<1 new_y=abs(new_y)+1 end if new_y>w_in new_y = w_in - (new_y - w_in) end @inbounds temp = temp + Float32(pIn[new_y,b,1,c]) * gauss[yy] end @inbounds pOut[a,b,1,c] = temp end a += blockDim().x*blockIdx().x end return nothing end function _CUDA_blur_x(pIn,pOut,gauss) _CUDA_blur_x(pIn,pOut,size(pIn,1),size(pIn,2),gauss,size(pIn,4)) end function CUDA_blur_x(pIn,pOut,gauss) numblocks_x = ceil(Int,size(pOut,1)/ 256) numblocks_y = size(pOut,2) numblocks_z = size(pOut,4) CUDA.@sync @cuda threads=256 blocks=(numblocks_x,numblocks_y,numblocks_z) _CUDA_blur_x(pIn,pOut,gauss) end function _CUDA_blur_y(pIn,pOut,gauss) _CUDA_blur_y(pIn,pOut,size(pIn,1),size(pIn,2),gauss,size(pIn,4)) end function CUDA_blur_y(pIn,pOut,gauss) numblocks_x = ceil(Int,size(pOut,2)/ 256) numblocks_y = size(pOut,1) numblocks_z = size(pOut,4) CUDA.@sync @cuda threads=256 blocks=(numblocks_x,numblocks_y,numblocks_z) _CUDA_blur_y(pIn,pOut,gauss) end function _CUDA_blur_y(pIn,pOut,w_in,h_in,gauss,n) c = blockIdx().z b = blockIdx().y a = threadIdx().x while (a<=h_in) if ((a <= h_in)&&(b <= w_in))&&(c <=n) temp = 0.0 for yy = 1:9 new_y = yy-5 + a if new_y<1 new_y=abs(new_y)+1 end if new_y>h_in new_y = h_in - (new_y - h_in) end @inbounds temp = temp + Float32(pIn[b,new_y,1,c]) * gauss[yy] end @inbounds pOut[b,a,1,c] = temp end a += blockDim().x*blockIdx().x end return nothing end function _CUDA_flip_xy(pIn,pOut,w_in,h_in,n) c = blockIdx().y b = blockIdx().x a = threadIdx().x if ((a <= h_in)&&(b <= w_in))&&(c <=n) @inbounds pOut[a,b,1,c] = pIn[b,a,1,c] end return end function _CUDA_flip_xy(pIn,pOut) _CUDA_flip_xy(pIn,pOut,size(pIn,1),size(pIn,2),size(pIn,4)) end function CUDA_flip_xy(pIn,pOut) numblocks_x = size(pOut,2) numblocks_y = size(pOut,4) CUDA.@sync @cuda threads=256 blocks=(numblocks_x,numblocks_y) _CUDA_flip_xy(pIn,pOut) end
StackedHourglass
https://github.com/paulmthompson/StackedHourglass.jl.git
[ "BSD-3-Clause" ]
0.1.5
e57b9894ce0f47f3b346d4a375203084085e90c7
code
1152
mutable struct CUDA_Resize input::CuArray{Float32,4} xpass::CuArray{Float32,4} ypass::CuArray{Float32,4} gauss_x::CuArray{Float32,1} gauss_y::CuArray{Float32,1} resized::CuArray{Float32,4} flip_xy::Bool output::CuArray{Float32,4} end function CUDA_Resize(in_w,in_h,out_w,out_h,n,flip_xy=true) input = convert(CuArray,zeros(Float32,in_w,in_h,1,n)) xpass = convert(CuArray,zeros(Float32,in_w,in_h,1,n)) ypass = convert(CuArray,zeros(Float32,in_w,in_h,1,n)) (gauss_x,gauss_y) = get_xy_gauss_cu((in_w,in_h),(out_w,out_h)) resized = convert(CuArray,zeros(Float32,out_w,out_h,1,n)) output = convert(CuArray,zeros(Float32,out_w,out_h,1,n)) CUDA_Resize(input,xpass,ypass,gauss_x,gauss_y,resized,flip_xy,output) end function lowpass_resize(cr::CUDA_Resize,input::AbstractArray{T,4}) where T cr.input[:] = convert(CuArray,input) CUDA_blur_x(cr.input,cr.xpass,cr.gauss_x) CUDA_blur_y(cr.xpass,cr.ypass,cr.gauss_y) CUDA_resize4(cr.ypass,cr.resized) if cr.flip_xy CUDA_flip_xy(cr.resized,cr.output) else cr.output[:] = cr.resized end nothing end
StackedHourglass
https://github.com/paulmthompson/StackedHourglass.jl.git
[ "BSD-3-Clause" ]
0.1.5
e57b9894ce0f47f3b346d4a375203084085e90c7
code
2561
mutable struct Gaussian_Pyramid dims::Array{Tuple{Int64,Int64},1} imgs::Array{Array{Float64,2},1} kerns::Array{Tuple{KernelFactors.ReshapedOneD,KernelFactors.ReshapedOneD},1} end function Gaussian_Pyramid(in_sz::Tuple) Gaussian_Pyramid([in_sz],[zeros(Float64,in_sz)], Array{Tuple{KernelFactors.ReshapedOneD,KernelFactors.ReshapedOneD},1}()) end function Gaussian_Pyramid(in_sz::Tuple,out_sz::Tuple) mygauss=Gaussian_Pyramid(in_sz) if (in_sz[1] * in_sz[2]) > (out_sz[1] * out_sz[2]) println("Downsampling pyramid") new_sz = (div(in_sz[1],2),div(in_sz[2],2)) #push!(mygauss.dims,new_sz) #push!(mygauss.imgs,zeros(Float64,new_sz)) #push!(mygauss.kerns,make_gaussian_kernel(in_sz,new_sz)) old_sz = in_sz while ((new_sz[1] > out_sz[1])&&(new_sz[2] > out_sz[2])) push!(mygauss.dims,new_sz) push!(mygauss.imgs,zeros(Float64,new_sz)) push!(mygauss.kerns,make_gaussian_kernel(old_sz,new_sz)) old_sz = new_sz new_sz = (div(new_sz[1],2),div(new_sz[2],2)) end if mygauss.dims[end] != out_sz push!(mygauss.dims,out_sz) push!(mygauss.imgs,zeros(Float64,out_sz)) push!(mygauss.kerns,make_gaussian_kernel(new_sz,out_sz)) end else println("Upsampling pyramid") new_sz = (in_sz[1]*2,in_sz[2]*2) old_sz = in_sz #push!(mygauss.dims,new_sz) #push!(mygauss.imgs,zeros(Float64,new_sz)) #push!(mygauss.kerns,make_gaussian_kernel(in_sz,new_sz)) while ((new_sz[1] <= out_sz[1]) && (new_sz[2] <= out_sz[2])) push!(mygauss.dims,new_sz) push!(mygauss.imgs,zeros(Float64,new_sz)) push!(mygauss.kerns,make_gaussian_kernel(old_sz,new_sz)) old_sz = new_sz new_sz = (new_sz[1]*2,new_sz[2]*2) end if mygauss.dims[end] != out_sz push!(mygauss.dims,out_sz) push!(mygauss.imgs,zeros(Float64,out_sz)) push!(mygauss.kerns,make_gaussian_kernel(new_sz,out_sz)) end end mygauss end function lowpass_filter_resize(gauss::Gaussian_Pyramid) for k=1:length(gauss.kerns) lowpass_filter_resize!(gauss.imgs[k],gauss.imgs[k+1],gauss.kerns[k]) end end function lowpass_filter_resize(gauss::Gaussian_Pyramid,input::AbstractArray{Float64,2},output::AbstractArray{Float64,2}) gauss.imgs[1][:] = input lowpass_filter_resize(gauss) output[:] = gauss.imgs[end] nothing end
StackedHourglass
https://github.com/paulmthompson/StackedHourglass.jl.git
[ "BSD-3-Clause" ]
0.1.5
e57b9894ce0f47f3b346d4a375203084085e90c7
code
5976
function pixel_mse(truth::Union{KnetArray{Float32,4},CuArray{Float32,4}},pred::HGType) loss = sum((pred .- truth).^2) loss / (size(pred,3) * size(pred,4)) end function myfree(x::AutoGrad.Result) #myfree(x.value) end function myfree(x::KnetArray) Knet.KnetArrays.freeKnetPtr(x.ptr) end function myfree(x::CuArray) end function myfree(x::Array) end function gaussian_2d(x,y,x0,y0,sig_x=1,sig_y=1) out=[exp.(-1/2 .* ((xi .- x0).^2 ./sig_x^2 + (yi .- y0).^2 ./sig_y^2)) for xi in x, yi in y] out./sum(out) end function gaussian_1d(x,x0,sig) [1/(sig*sqrt(2*pi))*exp.(-1/2 .* ((xi .- x0).^2 ./sig^2)) for xi in x] end function calculate_sigma((in_x,in_y),(out_x,out_y)) (0.75 * in_x/out_x , 0.75 * in_y/out_y) end function get_xy_gauss_cu((in_w,in_h),(out_w,out_h)) (sig_x,sig_y) = StackedHourglass.calculate_sigma((in_w,in_h),(out_w,out_h)) gauss_x = StackedHourglass.gaussian_1d(collect(-4:4),0,sig_x) gauss_x_cu = convert(CuArray,gauss_x); gauss_y = StackedHourglass.gaussian_1d(collect(-4:4),0,sig_y) gauss_y_cu = convert(CuArray,gauss_y); (gauss_x_cu, gauss_y_cu) end function create_padded_kernel(size_x,size_y,kl) kernel = gaussian_2d(collect(-kl:1:kl),collect(-kl:1:kl),0,0) kernel = kernel ./ maximum(kernel) kernel_pad = zeros(Float32,size_x,size_y) kernel_pad[(div(size_x,2)-kl):(div(size_x,2)+kl),(div(size_y,2)-kl):(div(size_y,2)+kl)] = kernel kernel_pad end #https://github.com/JuliaImages/ImageTransformations.jl/blob/master/src/resizing.jl#L239 function lowpass_filter_resize(img::AbstractArray{T,2},sz::Tuple) where T kern = make_gaussian_kernel(size(img),sz) imgr = imresize(imfilter(img, kern, NA()), sz) #Can include method here in newest ImageTransformations end function lowpass_filter_resize!(img::AbstractArray{T,2},output::AbstractArray{T,2},kern) where T imfilter!(img, img,kern, NA()) ImageTransformations.imresize!(output, img) #Can include method here in newest ImageTransformations nothing end function make_gaussian_kernel(in_sz::Tuple,out_sz::Tuple) σ = map((o,n)->0.75*o/n, in_sz, out_sz) KernelFactors.gaussian(σ) end function low_pass_pyramid(im::AbstractArray{T,2},sz::Tuple) where T new_sz = (div(size(im,1),2),div(size(im,2),2)) im2 = deepcopy(im) while ((new_sz[1] > sz[1])&&(new_sz[2] > sz[2])) im2=lowpass_filter_resize(im2,(new_sz)) #im2 = im2 ./ maximum(im2) new_sz = (div(new_sz[1],2),div(new_sz[2],2)) end im2=lowpass_filter_resize(im2,(sz)) end function upsample_pyramid(im::AbstractArray{T,2},sz::Tuple) where T new_sz = (size(im,1)*2,size(im,2)*2) im2 = deepcopy(im) while ((new_sz[1] <= sz[1])&&(new_sz[2] <= sz[2])) im2=lowpass_filter_resize(im2,(new_sz)) new_sz = (new_sz[1]*2,new_sz[2]*2) end im2=lowpass_filter_resize(im2,(sz)) end function predict_single_frame(hg,img::AbstractArray{T,2},atype=KnetArray) where T temp_frame = convert(Array{Float32,2},img) temp_frame = convert(Array{Float32,2},lowpass_filter_resize(temp_frame,(256,256))) temp_frame = convert(atype,reshape(temp_frame,(256,256,1,1))) my_features = features(hg) set_testing(hg,false) #Turn off batch normalization for prediction myout=hg(temp_frame)[4] set_testing(hg,true) #Turn back on myout=convert(Array{Float32,4},myout) end #= Convert Discrete points to heatmap for deep learning =# function make_heatmap_labels(han,real_w=640,real_h=480,label_img_size=64) d_points=make_discrete_all_whiskers(han) labels=zeros(Float32,label_img_size,label_img_size,size(d_points,1),size(han.woi,1)) for i=1:size(labels,4) for j=1:size(labels,3) this_x = d_points[j,1,i] / real_w * label_img_size this_y = d_points[j,2,i] / real_h * label_img_size if (this_x !=0.0)&(this_y != 0.0) labels[:,:,j,i] = WhiskerTracking.gaussian_2d(1.0:1.0:label_img_size,1.0:1.0:label_img_size,this_y,this_x) labels[:,:,j,i] = labels[:,:,j,i] ./ maximum(labels[:,:,j,i]) end end end labels end function make_heatmap_labels_keypoints(points::Array{Tuple,1},input_hw::Tuple,labels=zeros(Float32,64,64,length(points),1)) for j=1:size(points,1) this_x = points[j][1] / input_hw[1] * size(labels,1) this_y = points[j][2] / input_hw[2] * size(labels,2) if (this_x !=0.0)&(this_y != 0.0) labels[:,:,j,1] = gaussian_2d(1.0:1.0:size(labels,1),1.0:1.0:size(labels,2),this_x,this_y) end end end function get_labeled_frames(han,out_hw=256,h=480,w=640,frame_rate=25) imgs=zeros(Float32,out_hw,out_hw,1,length(han.frame_list)) temp=zeros(UInt8,w,h) for i=1:length(han.frame_list) frame_time = han.frame_list[i] / frame_rate WhiskerTracking.load_single_frame(frame_time,temp,han.wt.vid_name) imgs[:,:,1,i]=Images.imresize(temp',(out_hw,out_hw)) end imgs end function batch_predict(hg::StackedHourglass.NN,input_images::CuArray{T,4},sub_input_images, input_f,return_ind=4,batch_size=32,batch_per_load=4) where T batch_predict(hg,KnetArray(input_images),sub_input_images,input_f,return_ind,batch_size,batch_per_load) end function batch_predict(hg::StackedHourglass.NN,input_images::KnetArray{T,4},sub_input_images::KnetArray{T,4}, input_f::KnetArray{T,4},return_ind=4,batch_size=32,batch_per_load=4) where T input_hw=size(input_images,1) output_hw=size(input_f,1) my_features=size(input_f,3) for k=0:(batch_per_load-1) copyto!(sub_input_images,1,input_images,k*input_hw*input_hw*batch_size+1,input_hw*input_hw*batch_size) myout=hg(sub_input_images) copyto!(input_f,k*output_hw*output_hw*my_features*batch_size+1,myout[return_ind],1,length(myout[return_ind])) for kk=1:length(myout) Knet.KnetArrays.freeKnetPtr(myout[kk].ptr) end end nothing end
StackedHourglass
https://github.com/paulmthompson/StackedHourglass.jl.git
[ "BSD-3-Clause" ]
0.1.5
e57b9894ce0f47f3b346d4a375203084085e90c7
code
4622
mutable struct Out_Layer <: NN r1::Residual w::PType4 #weights b::PType4#biases ms::KnetMoment #batch norm moments bn_p::PType1 #batch norm parameters training::Bool end function (c::Out_Layer)(x::HGType) r1=c.r1(x) out1 = conv4(c.w,r1); myfree(r1); out2 = out1 .+ c.b; myfree(out1); bn=batchnorm(out2,c.ms,c.bn_p,training=c.training); myfree(out2); out3 = relu.(bn); myfree(bn) out3 end function Out_Layer(in_dim::Int,atype=KnetArray) r1=Residual(in_dim,in_dim,atype) bn_p = bnparams(Float32,in_dim) bn_p = Param(convert(atype{Float32,1},bn_p)) ms = bnmoments() w = xavier_normal(Float32,1,1,in_dim,in_dim) b = xavier_normal(Float32,1,1,in_dim,1) w = Param(convert(atype,w)) b = Param(convert(atype,b)) Out_Layer(r1,w,b,ms,bn_p,true) end function set_testing(f::Out_Layer,training=false) set_testing(f.r1,training) f.training=training nothing end struct FirstBlock <: NN c1::Conv1 r1::Residual_skip p1::Pool r2::Residual r3::Residual_skip end FirstBlock(N::Int,atype=KnetArray)=FirstBlock(Conv1(3,64,7,2,3,atype),Residual_skip(64,128,atype),Pool(),Residual(128,128,atype),Residual_skip(128,N,atype)) function (f::FirstBlock)(x::HGType) c1=f.c1(x) r1=f.r1(c1); myfree(c1); p1=f.p1(r1); myfree(r1); r2=f.r2(p1); myfree(p1); r3=f.r3(r2); myfree(r2) r3 end function set_testing(f::FirstBlock,training=false) set_testing(f.c1,training) set_testing(f.r1,training) set_testing(f.r2,training) set_testing(f.r3,training) nothing end struct Hourglass <: NN n::Int64 up1::Residual pool1::Pool low1::Residual low2::Union{Hourglass,Residual} #This could be a residual or another Hourglass low3::Residual up2::Unpool end function Hourglass(n::Int,f_num::Int,atype=KnetArray) up1 = Residual(f_num,f_num,atype) pool1 = Pool() low1 = Residual(f_num,f_num,atype) if n > 1 low2 = Hourglass(n-1,f_num,atype) else low2 = Residual(f_num,f_num,atype) end low3 = Residual(f_num,f_num,atype) up2 = Unpool() Hourglass(n,up1,pool1,low1,low2,low3,up2) end function (h::Hourglass)(x::HGType) up1 = h.up1(x) pool1 = h.pool1(x) low1 = h.low1(pool1); myfree(pool1); low2 = h.low2(low1); myfree(low1); low3 = h.low3(low2); myfree(low2); up2 = h.up2(low3); myfree(low3); out = up1 .+ up2 myfree(up1); myfree(up2) out end function set_testing(f::Hourglass,training=false) set_testing(f.up1,training) set_testing(f.low1,training) set_testing(f.low2,training) set_testing(f.low3,training) nothing end struct HG2 <: NN nstack::Int64 fb::FirstBlock hg::Array{Hourglass,1} o1::Array{Out_Layer,1} c1::Array{Conv0,1} merge_features::Array{Conv0,1} merge_preds::Array{Conv0,1} end #= N = Number of Channels (64 default) K = number of features for prediction nstack = number of hourglasses =# function HG2(N::Int,K::Int,nstack::Int,atype=KnetArray) fb = FirstBlock(N,atype) hg=[Hourglass(4,N,atype) for i=1:nstack]; o1=[Out_Layer(N,atype) for i=1:nstack]; c1=[Conv0(N,K,1,1,0,atype) for i=1:nstack]; merge_features=[Conv0(N,N,1,1,0,atype) for i=1:(nstack-1)] merge_preds=[Conv0(K,N,1,1,0,atype) for i=1:(nstack-1)] HG2(nstack,fb,hg,o1,c1,merge_features,merge_preds) end features(hg::HG2)=size(hg.merge_preds[1].w,3) function (h::HG2)(x::HGType) temp=h.fb(x) preds=Array{typeof(temp),1}() #Can this be typed to be the same as input? temps=Array{typeof(temp),1}(undef,h.nstack) #Can this be typed to be the same as input? temps[1]=temp for i=1:h.nstack hg=h.hg[i](temps[i]) features=h.o1[i](hg) pred=h.c1[i](features) push!(preds,pred) if i<h.nstack m_features = h.merge_features[i](features) m_preds = h.merge_preds[i](pred) temp1 = m_features + m_preds temps[i+1] = temp1 + temps[i] myfree(m_features); myfree(m_preds); myfree(temp1) end myfree(hg); myfree(features); end myfree(temp) for i=1:h.nstack myfree(temps[i]) end preds end function (h::HG2)(x,y) preds=h(x) loss=0.0f0 for i=1:h.nstack loss += pixel_mse(y,preds[i]) end loss end (h::HG2)(d::Knet.Data) = mean(h(x,y) for (x,y) in d) function set_testing(f::HG2,training=false) set_testing(f.fb,training) for i=1:f.nstack set_testing(f.hg[i],training) set_testing(f.o1[i],training) end nothing end
StackedHourglass
https://github.com/paulmthompson/StackedHourglass.jl.git
[ "BSD-3-Clause" ]
0.1.5
e57b9894ce0f47f3b346d4a375203084085e90c7
code
4071
#= Image augmentation will apply various transformations to the training images and accompanying labels =# mutable struct ImageAugmentation rotation::Bool rotation_angles::Array{Float64,1} flip_x::Bool flip_y::Bool set_bw::Bool end function ImageAugmentation() default_rotations = [pi/6, pi/2, pi, 3*pi/2, -pi/6] ImageAugmentation(true,default_rotations,true,true,true) end function rotation_augmentation(im,ll,im_out,l_out,ind,aug::ImageAugmentation,count) for j in aug.rotation_angles for k=1:size(im,3) im_out[:,:,k,count] = imrotate(im[:,:,k,ind],j,ImageTransformations.Flat())[1:size(im,1),1:size(im,2)] end for k=1:size(ll,3) l_out[:,:,k,count] = imrotate(ll[:,:,k,ind],j,0)[1:size(ll,1),1:size(ll,2)] end count += 1 end count end function flip_x_augmentation(im,ll,im_out,l_out,ind,aug::ImageAugmentation,count) im_out[:,:,:,count] = reverse(im[:,:,:,ind],dims=1) l_out[:,:,:,count] = reverse(ll[:,:,:,ind],dims=1) count+=1 end function flip_y_augmentation(im,ll,im_out,l_out,ind,aug::ImageAugmentation,count) im_out[:,:,:,count] = reverse(im[:,:,:,ind],dims=2) l_out[:,:,:,count] = reverse(ll[:,:,:,ind],dims=2) count+=1 end function random_block(xdim,ydim,max_length) x1 = rand(1:div(xdim,2)) x2 = rand(x1:(x1+max_length)) y1 = rand(1:div(ydim,2)) y2 = rand(y1:(y1+max_length)) (x1,x2,y1,y2) end function flip_bw_augmentation(im,ll,im_out,l_out,ind,aug::ImageAugmentation,count) #Random Black (x1,x2,y1,y2) = random_block(size(im,1),size(im,2),5) im_out[:,:,:,count] = im[:,:,:,ind] l_out[:,:,:,count] = ll[:,:,:,ind] im_out[x1:x2,y1:y2,:,count] .= 0.0 count+=1 #Random White (x1,x2,y1,y2) = random_block(size(im,1),size(im,2),5) im_out[:,:,:,count] = im[:,:,:,ind] l_out[:,:,:,count] = ll[:,:,:,ind] im_out[x1:x2,y1:y2,:,count] .= 1.0 count+=1 end function image_augmentation(im,ll,aug::ImageAugmentation) rot_size = 0 flip_x_size = 0 flip_y_size = 0 set_bw_size = 0 if aug.rotation rot_size += length(aug.rotation_angles) end if aug.flip_x flip_x_size = 1 end if aug.flip_y flip_y_size = 1 end if aug.set_bw set_bw_size = 2 end array_size = rot_size + flip_x_size + flip_y_size + set_bw_size + 1 im_out = zeros(Float32,size(im,1),size(im,2),size(im,3),size(im,4) * array_size) l_out = zeros(Float32,size(ll,1),size(ll,2),size(ll,3),size(ll,4) * array_size) count=1 for i=1:size(im,4) im_out[:,:,:,count] = im[:,:,:,i] l_out[:,:,:,count] = ll[:,:,:,i] count += 1 #rotations if aug.rotation count = rotation_augmentation(im,ll,im_out,l_out,i,aug,count) end #Flip x if aug.flip_x count = flip_x_augmentation(im,ll,im_out,l_out,i,aug,count) end #Flip Y if aug.flip_y count = flip_y_augmentation(im,ll,im_out,l_out,i,aug,count) end if aug.set_bw count = flip_bw_augmentation(im,ll,im_out,l_out,i,aug,count) end # 0.75 Scale (zoom in) #1.25 Scale (Reflect around places where image is empty) end #Shuffle Positions myinds=Random.shuffle(collect(1:size(im_out,4))); im_out=im_out[:,:,:,myinds] l_out=l_out[:,:,:,myinds] (im_out,l_out) end function normalize_images(ii) mean_img = mean(ii,dims=4)[:,:,:,1] std_img = std(ii,dims=4)[:,:,:,1] std_img[std_img .== 0.0] .= 1 ii = (ii .- mean_img) ./ std_img min_ref = minimum(ii) ii = ii .- min_ref max_ref = maximum(ii) ii = ii ./ max_ref (mean_img,std_img,min_ref,max_ref) end function normalize_new_images(ii::KnetArray,mean_img::Array,std_img,min_ref,max_ref) normalize_new_images(ii,convert(KnetArray,mean_img),convert(KnetArray,std_img),min_ref,max_ref) end function normalize_new_images(ii,mean_img) ii = ii ./ 255 ii = ii .- mean_img end
StackedHourglass
https://github.com/paulmthompson/StackedHourglass.jl.git
[ "BSD-3-Clause" ]
0.1.5
e57b9894ce0f47f3b346d4a375203084085e90c7
code
5470
#= Loads a single image from a filename and converts to the expected 256x256 size =# function load_single_image(filename::String,imgs,ii,x_off,y_off) this_img=load(filename) x_off[ii] = 256 / size(this_img,2) y_off[ii] = 256 / size(this_img,1) new_img=imresize(this_img,(256,256)) for i=1:size(imgs,2) for j=1:size(imgs,1) imgs[i,j,1,ii]=convert(Float32,new_img[j,i].r) imgs[i,j,2,ii]=convert(Float32,new_img[j,i].g) imgs[i,j,3,ii]=convert(Float32,new_img[j,i].b) end end nothing end function make_all_labels(ll,xo,yo,j_a) for i=1:size(ll,4) add_single_label(ll,i,xo,yo,j_a); end end function add_single_label(ll,ii,x_off,y_off,j_a,ds=4) for i=1:size(ll,3) xo=round(Int64,x_off[ii] * j_a[1,i,ii]/ds) yo=round(Int64,y_off[ii] * j_a[2,i,ii]/ds) ll[:,:,i,ii] = gaussian_2d(1.0:1.0:size(ll,1),1.0:1.0:size(ll,2),xo,yo) if maximum(ll[:,:,i,ii])>0 ll[:,:,i,ii] = ll[:,:,i,ii] ./ maximum(ll[:,:,i,ii]) end end end #= Saving Hourglass Model =# function save_hourglass(name,x) count=[1]; file=matopen(name,"w") save_nn(x,file,count) close(file) end function save_nn(x,file,count) for f in fieldnames(typeof(x)) f1=getfield(x,f) if typeof(f1) <: NN save_nn(f1,file,count) elseif eltype(f1) <: NN for i=1:length(f1) save_nn(f1[i],file,count) end else if f == :w write(file,string("w_",count[1]),convert(Array,f1.value)) count[1]+=1 elseif f == :b write(file,string("b_",count[1]),convert(Array,f1.value)) count[1]+=1 elseif f == :ms write(file,string("ms_mo_",count[1]),f1.momentum) write(file,string("ms_mean_",count[1]),convert(Array,f1.mean)) write(file,string("ms_var_",count[1]),convert(Array,f1.var)) count[1]+=1 elseif f == :bn_p write(file,string("bn_p_",count[1]),convert(Array,f1.value)) count[1]+=1 end end end end #= Loading Hourglass Model =# function load_hourglass(name,x,atype=KnetArray) count=[1]; file=matopen(name,"r") load_nn(x,file,count,atype) close(file) end function load_nn(x,file,count,atype=KnetArray) for f in fieldnames(typeof(x)) f1=getfield(x,f) if typeof(f1) <: NN load_nn(f1,file,count,atype) elseif eltype(f1) <: NN for i=1:length(f1) load_nn(f1[i],file,count,atype) end else if f == :w setfield!(x,f,Param(convert(atype,read(file,string("w_",count[1]))))) count[1]+=1 elseif f == :b xx = read(file,string("b_",count[1])) if typeof(xx) == Float32 xxx = zeros(Float32,1,1,1,1) xxx[1] = xx setfield!(x,f,Param(convert(atype,xxx))) else setfield!(x,f,Param(convert(atype,xx))) end count[1]+=1 elseif f == :ms x.ms.momentum=read(file,string("ms_mo_",count[1])) xx=read(file,string("ms_mean_",count[1])) if typeof(xx) == Float32 x.ms.mean = convert(atype,[xx]) else x.ms.mean = convert(atype,xx) end xx=read(file,string("ms_var_",count[1])) if typeof(xx) == Float32 x.ms.var = convert(atype,[xx]) else x.ms.var = convert(atype,xx) end count[1]+=1 elseif f == :bn_p xx = read(file,string("bn_p_",count[1])) if typeof(xx) == Float32 x.bn_p = Param(convert(atype,[xx])) else x.bn_p = Param(convert(atype,xx)) end count[1]+=1 end end end end #= Change the number of input or output features or dimensions for hourglass model =# function change_hourglass(hg::HG2,feature_num::Int,input_dim::Int,output_dim::Int,atype=KnetArray) change_hourglass_input(hg,feature_num,input_dim,atype) change_hourglass_output(hg,feature_num,output_dim,atype) nothing end function change_hourglass_input(hg::HG2,feature_num::Int,input_dim::Int,atype=KnetArray) #Input transform hg.fb.c1.w = Param(convert(atype,xavier_normal(Float32,7,7,input_dim,64))) hg.fb.c1.b = Param(convert(atype,xavier_normal(Float32,1,1,64,1))) hg.fb.c1.bn_p = Param(convert(atype{Float32,1},bnparams(input_dim))) hg.fb.c1.ms = bnmoments() nothing end function change_hourglass_output(hg::HG2,feature_num::Int,output_dim::Int,atype=KnetArray) for i=1:length(hg.c1) hg.c1[i].w = Param(convert(atype,xavier_normal(Float32,1,1,feature_num,output_dim))) hg.c1[i].b = Param(convert(atype,xavier_normal(Float32,1,1,output_dim,1))) end for i=1:length(hg.merge_preds) hg.merge_preds[i].w = Param(convert(atype,xavier_normal(Float32,1,1,output_dim,feature_num))) hg.merge_preds[i].b = Param(convert(atype,xavier_normal(Float32,1,1,feature_num,1))) end nothing end
StackedHourglass
https://github.com/paulmthompson/StackedHourglass.jl.git
[ "BSD-3-Clause" ]
0.1.5
e57b9894ce0f47f3b346d4a375203084085e90c7
code
3155
mutable struct Conv1 <: NN w::PType4 #weights b::PType4 #biases ms::KnetMoment #batch norm moments bn_p::PType1 #batch norm parameters stride::Int64 padding::Int64 training::Bool end function (c::Conv1)(x::HGType) bn = batchnorm(x,c.ms,c.bn_p,training=c.training) relu_out = relu.(bn) output1 = conv4(c.w,relu_out,stride=c.stride,padding=c.padding) output2 = output1 .+ c.b myfree(bn); myfree(relu_out); myfree(output1) output2 end function Conv1(in_dim::Int,out_dim::Int,k_s,stride,padding,atype=KnetArray) bn_p = bnparams(Float32,in_dim) bn_p = Param(convert(atype{Float32,1},bn_p)) ms = bnmoments() w = xavier_normal(Float32,k_s,k_s,in_dim,out_dim) b = xavier_normal(Float32,1,1,out_dim,1) w = Param(convert(atype,w)) b = Param(convert(atype,b)) Conv1(w,b,ms,bn_p,stride,padding,true) end function set_testing(f::Conv1,training=false) f.training=training nothing end mutable struct Conv0 <: NN w::PType4 #weights b::PType4 #biases stride::Int64 padding::Int64 end function (c::Conv0)(x::HGType) out1=conv4(c.w,x,stride=c.stride,padding=c.padding) out2 = out1 .+ c.b myfree(out1) out2 end function Conv0(in_dim::Int,out_dim::Int,k_s,stride,padding,atype=KnetArray) w = xavier_normal(Float32,k_s,k_s,in_dim,out_dim) b = xavier_normal(Float32,1,1,out_dim,1) w = Param(convert(atype,w)) b = Param(convert(atype,b)) Conv0(w,b,stride,padding) end struct Residual <: NN c1::Conv1 c2::Conv1 c3::Conv1 end function (r::Residual)(x::HGType) c1=r.c1(x) c2=r.c2(c1) output = r.c3(c2) .+ x myfree(c1); myfree(c2) output end function Residual(in_dim::Int,out_dim::Int,atype=KnetArray) c1=Conv1(in_dim,div(out_dim,2),1,1,0,atype) c2=Conv1(div(out_dim,2),div(out_dim,2),3,1,1,atype) c3=Conv1(div(out_dim,2),out_dim,1,1,0,atype) Residual(c1,c2,c3) end function set_testing(f::Residual,training=false) set_testing(f.c1,training) set_testing(f.c2,training) set_testing(f.c3,training) nothing end mutable struct Residual_skip <: NN w::PType4 b::PType4 c1::Conv1 c2::Conv1 c3::Conv1 end function (r::Residual_skip)(x::HGType) residual1 = conv4(r.w,x,stride=1) residual2 = residual1 .+ r.b c1=r.c1(x) c2=r.c2(c1) output = r.c3(c2) .+ residual2 myfree(c1); myfree(c2); myfree(residual1); myfree(residual2); output end function Residual_skip(in_dim::Int,out_dim::Int,atype=KnetArray) c1=Conv1(in_dim,div(out_dim,2),1,1,0,atype) c2=Conv1(div(out_dim,2),div(out_dim,2),3,1,1,atype) c3=Conv1(div(out_dim,2),out_dim,1,1,0,atype) w = xavier_normal(Float32,1,1,in_dim,out_dim) b = xavier_normal(Float32,1,1,out_dim,1) w=Param(convert(atype,w)) b=Param(convert(atype,b)) Residual_skip(w,b,c1,c2,c3) end function set_testing(f::Residual_skip,training=false) set_testing(f.c1,training) set_testing(f.c2,training) set_testing(f.c3,training) nothing end struct Pool end (p::Pool)(x::HGType) = pool(x) struct Unpool end (u::Unpool)(x::HGType) = unpool(x)
StackedHourglass
https://github.com/paulmthompson/StackedHourglass.jl.git
[ "BSD-3-Clause" ]
0.1.5
e57b9894ce0f47f3b346d4a375203084085e90c7
code
3804
#= Modified from SubpixelRegistration.jl https://github.com/romainFr/SubpixelRegistration.jl Copyright (c) 2016: Romain Franconville. Under MIT "Expat" License Original Publication: =# function subpixel(imgRef::AbstractArray{T,N},imgF::AbstractArray{T,N},usfac) where {T,N} if usfac==1 ## Whole-pixel shift - Compute crosscorrelation by an IFFT and locate the peak L = length(imgRef) CC = ifft(imgRef.*conj(imgF)) loc = argmax(abs.(CC)) CCmax=CC[loc] indi = size(imgRef) ind2 = tuple([div(x,2) for x in indi]...) #locI = [ind2sub(indi,loc)...] locI = [Tuple(loc)...] shift = zeros(size(locI)) for i in eachindex(locI) if locI[i]>ind2[i] shift[i]=locI[i]-indi[i]-1 else shift[i]=locI[i]-1 end end shift else ## Partial pixel shift ##First upsample by a factor of 2 to obtain initial estimate ##Embed Fourier data in a 2x larger array dimR = [size(imgRef)...] ranges = [(x+1-div(x,2)):(x+1+div(x-1,2)) for x in dimR] dimRL = map(x -> x*2, dimR) CC = zeros(Complex{Float32},tuple(dimRL...)) #CC = convert(CuArray,CC) CC[ranges...] = fftshift(imgRef).*conj(fftshift(imgF)) ## Compute crosscorrelation and locate the peak CC = ifft(ifftshift(CC)) loc = argmax(abs.(CC)) indi = size(CC) #locI = [ind2sub(indi,loc)...] locI = [Tuple(loc)...] CCmax = CC[loc] ## Obtain shift in original pixel grid from the position of the crosscorrelation peak ind2 = tuple([div(x,2) for x in indi]...) shift = zeros(size(locI)) for i in eachindex(locI) if locI[i]>ind2[i] shift[i]=locI[i]-indi[i]-1 else shift[i]=locI[i]-1 end end shift = shift/2 ## If upsampling > 2, then refine estimate with matrix multiply DFT if usfac > 2 ### DFT Computation ### # Initial shift estimate in upsampled grid shift = round.(Integer,shift*usfac)/usfac dftShift = div(ceil(usfac*1.5),2) ## center of output array at dftshift+1 ## Matrix multiplies DFT around the current shift estimate CC = conj(dftups(imgF.*conj(imgRef),ceil(Integer,usfac*1.5),usfac,dftShift.-shift*usfac))/(prod(ind2)*usfac^2) ## Locate maximum and map back to original pixel grid loc = argmax(abs.(CC)) locI = Tuple(loc) CCmax = CC[loc] locI = map((x) -> x - dftShift - 1,locI) for i in eachindex(shift) shift[i]=shift[i]+locI[i]/usfac end end ## If its only one row or column the shift along that dimension has no effect. Set to zero. shift[[div(x,2) for x in size(imgRef)].==1].=0 end reverse(shift) end function dftups(inp::AbstractArray{T,N},no,usfac::Int=1,offset=zeros(N)) where {T,N} sz = [size(inp)...] permV = 1:N for i in permV inp = permutedims(inp,[i;deleteat!(collect(permV),i)]) kern = exp.(Complex{Float32}(-1im*2*pi/(sz[i]*usfac))*((0:(no-1)).-offset[i])*transpose(ifftshift(0:(sz[i]-1)).-floor(sz[i]/2))) #kern = convert(CuArray{Complex{Float32}},kern) d = size(inp)[2:N] inp = kern * reshape(inp, Val(2)) inp = reshape(inp,(no,d...)) end permutedims(inp,collect(ndims(inp):-1:1)) end function calculate_subpixel(preds,offset,input,k_fft) @distributed for jj=1:size(input,4) for kk=1:size(input,3) preds[kk,1:2,jj+offset] = convert(Array{Float32,1},subpixel(input[:,:,kk,jj],k_fft,4)) .+ 32.0f0 end end nothing end
StackedHourglass
https://github.com/paulmthompson/StackedHourglass.jl.git
[ "BSD-3-Clause" ]
0.1.5
e57b9894ce0f47f3b346d4a375203084085e90c7
docs
320
# StackedHourglass.jl This is a Julia implementation of a stacked hourglass neural network for pose detection. This model was first described in Newell et al 2016: <br> https://arxiv.org/abs/1603.06937 An excellent PyTorch implemention can be found here: <br> https://github.com/princeton-vl/pytorch_stacked_hourglass
StackedHourglass
https://github.com/paulmthompson/StackedHourglass.jl.git
[ "MIT" ]
0.1.1
7e2ddf219f42be2d7ab61f5d6f21ac5cadc78efb
code
376
export GaltonWatson # Dist = Distribution of generation # Len = Number of generations function GaltonWatson(; Dist = Poisson(1.1), Len = 30) # Declaring serie Population = ones(Len + 1) # Generatting serie for i in 1:Len Population[i+1] = sum(rand(Dist, trunc(Int, Population[i]))) end # Return serie return Population end
RandomProcesses
https://github.com/joaquimbermudes/RandomProcesses.jl.git
[ "MIT" ]
0.1.1
7e2ddf219f42be2d7ab61f5d6f21ac5cadc78efb
code
770
export MarkovChain # Alphabet = Values oc chain # Init = Initial Value # MProb = Probability Matix # Len = lenght of serie function MarkovChain(; Alphabet = ["A", "B", "C"], Init = "A" , MProb = [0.5 0.3 0.2; 0.1 0.7 0.2; 0.6 0.35 0.05], Len = 100) # Declaring the output array vecAlph = [Init] # Declaring a index that I will use in loop indice = 0 # Getting the lenght of alphabet l = length(Alphabet) # Generatting the Markov Chain for i in 1:Len for state in Alphabet indice = (indice % l) + 1 if state == vecAlph[i] append!(vecAlph, wsample(Alphabet, MProb[indice,:], 1)) end end end # Return Markov Chain return vecAlph end
RandomProcesses
https://github.com/joaquimbermudes/RandomProcesses.jl.git
[ "MIT" ]
0.1.1
7e2ddf219f42be2d7ab61f5d6f21ac5cadc78efb
code
321
export Martingale # Dist = Ditribution of increments # Mean = Mean of distribution # Len = Lenght of simulating serie function Martingale(;Dist = Chisq(1), Mean = 1, Len = 1000) # Declaring the increments dM = rand(Dist, Len) .- Mean # Return Martingale return cumsum(dM)/std(cumsum(dM)) end
RandomProcesses
https://github.com/joaquimbermudes/RandomProcesses.jl.git
[ "MIT" ]
0.1.1
7e2ddf219f42be2d7ab61f5d6f21ac5cadc78efb
code
884
export NeuralProcess # Activate = list of activate function # Initial = initial values # Matrix = matrix of weights list # Bias = Bias # distErro = Error distribution # Len = Lenght of serie function NeuralProcess(;Activate, Initial = [0.5, 0.75], Matrix = [[2 0.2; -0.8 0.3], [-1 2]], Bias = [[0; 0], [0]], distErro = Normal(0, 0.2), Len = 100) # initing serie NeuralSerie = zeros(Len) # generating serie for j in 1:Len # Loop of serie lenght for i in 1:length(Matrix) # loop for creante serie[j] value function FunctionActvation(x; FunctionXYZ = Activate[i]) return FunctionXYZ(x) end Initial = FunctionActvation(Matrix[i] * Initial .+ Bias[i]) end Initial = Initial + rand(distErro) NeuralSerie[j] = Initial end # return serie return NeuralSerie end
RandomProcesses
https://github.com/joaquimbermudes/RandomProcesses.jl.git
[ "MIT" ]
0.1.1
7e2ddf219f42be2d7ab61f5d6f21ac5cadc78efb
code
301
export PoissonProcess # Len = Lenght of sumullating serie # lambda = Lambda parameter of Poisson distribution function PoissonProcess(;Len = 1000, lambda = 0.01) # Generatting Poisson increments dP = rand(Poisson(lambda), Len) # Return Poisson process return cumsum(dP) end
RandomProcesses
https://github.com/joaquimbermudes/RandomProcesses.jl.git
[ "MIT" ]
0.1.1
7e2ddf219f42be2d7ab61f5d6f21ac5cadc78efb
code
281
module RandomProcesses using Random using Distributions using Statistics include("GaltonWatson.jl") include("MarkovChain.jl") include("Martingale.jl") include("NeuralProcess.jl") include("PoissonProcess.jl") include("RandomWalk.jl") include("SARMA.jl") include("Wiener.jl") end
RandomProcesses
https://github.com/joaquimbermudes/RandomProcesses.jl.git
[ "MIT" ]
0.1.1
7e2ddf219f42be2d7ab61f5d6f21ac5cadc78efb
code
306
export RandomWalk # Len = Lenght of simulatting serie # p = Probability of increment 1 function RandomWalk(;Len = 1000, p = 0.5) # Generatting increment of serie (1 or -1) dRW = (rand(Binomial(1, p), Len) .- 0.5) .* 2 # Return Random Walk return cumsum(dRW)/std(cumsum(dRW)) end
RandomProcesses
https://github.com/joaquimbermudes/RandomProcesses.jl.git
[ "MIT" ]
0.1.1
7e2ddf219f42be2d7ab61f5d6f21ac5cadc78efb
code
1630
export SARMA # InItialValues = Serie values for initialize the process # InitialErrors = Serie errors for initialize the process # AR = Autoregressive parameters [AR_n, AR_{n-1}, ..., AR_1] # MA = Moving average parameters [MA_n, MA_{n-1}, ..., MA_1] # SAR = Seasonal autorregressive parameters [AR_{seasonal * n}, AR_{seasonal * (n-1)}, ..., AR_{seasonal}] # SMA = Seasonal moving average parameters [MA_{seasonal * n}, MA_{seasonal * (n-1)}, ..., MA_{seasonal}] # Seasonal = Lenght of seasonal lag # Mean = Serie mean # Std_Error = Standard desvio of generate error # len = Simulatio lenght function SARMA(;InitialVlues = [], InitialErrors = [], AR = [0], MA = [0], SAR = [0], SMA = [0], Seasonal = 1, Mean = 0, Std_Error = 1, Len = 12) # Getting lenght of parameters lenAR = length(AR) lenMA = length(MA) lenSAR = length(SAR) lenSMA = length(SMA) # Getting maximum lenght of parameters lenMax = max(lenAR, lenMA, lenSAR * Seasonal, lenSMA * Seasonal) # Initializing error serie error = append!(InitialErrors, Std_Error .* Random.randn(Len)) # Initializing serie if length(InitialValues) > 0 serie = InitialValues .- Mean else serie = error[1:len] end # Generating simulating serie for i in (lenMax+1):Len append!(serie, sum(MA .* error[(i-lenMA):(i-1)]) + sum(SMA .* error[(i-lenSMA*Seasonal):Seasonal:(i-Seasonal)]) + sum(SAR .* serie[(i-lenSAR*Seasonal):Seasonal:(i-Seasonal)]) + error[i] + sum(AR .* serie[(i-lenAR):(i-1)])) end # Return serie with mean return serie .+ Mean end
RandomProcesses
https://github.com/joaquimbermudes/RandomProcesses.jl.git
[ "MIT" ]
0.1.1
7e2ddf219f42be2d7ab61f5d6f21ac5cadc78efb
code
229
export Wiener # Len = lenght of simulatting serie function Wiener(Len = 1000) # Generatting normal random increments dW = Random.randn(Len) # Return Wiener process return cumsum(dW)/std(cumsum(dW)) end
RandomProcesses
https://github.com/joaquimbermudes/RandomProcesses.jl.git
[ "MIT" ]
0.1.1
7e2ddf219f42be2d7ab61f5d6f21ac5cadc78efb
docs
1468
# RandomProcesses.jl ## Introduction RandomProcesses.jl is a package for simulling stochastics processes in Julia in a easy way. At the moment the package has 8 functions that simulling the following stochastic processes: - SARMA - Ramdom Walk - Weiner - Martingale - Galton Watson - Markov Chain - Poisson - Neural (simuling the results of neural network) ## Exemples Importing RandomProcesses and PyPlot ```Julia using RandomProcesses, PyPlot, Distributions ``` ### Random Walk ```Julia for _ in 1:5 plot(RandomWalk()) end ``` ![RW.png](https://github.com/joaquimbermudes/RandomProcesses.jl/blob/main/Imgs/RW.png) ### Poisson Process ```Julia for _ in 1:5 plot(PoissonProcess()) end ``` ![Poisson.png](https://github.com/joaquimbermudes/RandomProcesses.jl/blob/main/Imgs/Poisson.png) ### Neural Process ```Julia function f(x) return exp.(x)./(1 .+ exp.(x)) end function g(x) return sum(x) end for _ in 1:5 plot(NeuralProcess(Activate = [f, g], Len = 30)) end ``` ![Neural.png](https://github.com/joaquimbermudes/RandomProcesses.jl/blob/main/Imgs/Neural.png) ## Coments 1. Almost functions need the package "Distribution" for execute. 2. You has that declare a vector of functions in each leyaer for neural process execute. 3. This is my first package, please have pacience. Send criticisms and suggestions to joaquimacbermudes@gmail.com. I would also like to know out of curiosity in which projects the patent is being used.
RandomProcesses
https://github.com/joaquimbermudes/RandomProcesses.jl.git